KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ejbca > core > model > hardtoken > profiles > SVGImageManipulator


1 /*************************************************************************
2  * *
3  * EJBCA: The OpenSource Certificate Authority *
4  * *
5  * This software is free software; you can redistribute it and/or *
6  * modify it under the terms of the GNU Lesser General Public *
7  * License as published by the Free Software Foundation; either *
8  * version 2.1 of the License, or any later version. *
9  * *
10  * See terms of license at gnu.org. *
11  * *
12  *************************************************************************/

13  
14 package org.ejbca.core.model.hardtoken.profiles;
15
16
17 import java.awt.image.BufferedImage JavaDoc;
18 import java.awt.image.RenderedImage JavaDoc;
19 import java.awt.print.Printable JavaDoc;
20 import java.awt.print.PrinterException JavaDoc;
21 import java.io.ByteArrayOutputStream JavaDoc;
22 import java.io.FileNotFoundException JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.Reader JavaDoc;
25 import java.text.DateFormat JavaDoc;
26 import java.util.ArrayList JavaDoc;
27 import java.util.Collection JavaDoc;
28 import java.util.Date JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.regex.Pattern JavaDoc;
31
32 import org.apache.batik.dom.GenericText;
33 import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
34 import org.apache.batik.dom.svg.SVGDOMImplementation;
35 import org.apache.batik.dom.svg.SVGOMDocument;
36 import org.apache.batik.dom.svg.SVGOMImageElement;
37 import org.apache.batik.dom.svg.SVGOMTSpanElement;
38 import org.apache.batik.svggen.ImageHandlerBase64Encoder;
39 import org.apache.batik.svggen.SVGGeneratorContext;
40 import org.apache.batik.svggen.SimpleImageHandler;
41 import org.apache.batik.transcoder.TranscoderInput;
42 import org.apache.batik.transcoder.TranscoderOutput;
43 import org.apache.batik.transcoder.print.PrintTranscoder;
44 import org.apache.batik.util.XMLResourceDescriptor;
45 import org.apache.commons.lang.StringUtils;
46 import org.apache.log4j.Logger;
47 import org.ejbca.core.model.ra.UserDataVO;
48 import org.ejbca.util.dn.DNFieldExtractor;
49 import org.w3c.dom.Document JavaDoc;
50 import org.w3c.dom.Node JavaDoc;
51 import org.w3c.dom.NodeList JavaDoc;
52 import org.w3c.dom.svg.SVGDocument;
53 import org.w3c.dom.svg.SVGRectElement;
54 import org.w3c.dom.svg.SVGTextElement;
55
56
57
58
59
60 /**
61  * This is a help class used to manipulate SVG images.
62  * It replaces all occurrenses of specified variables in the images
63  * with the corresponding userdata.
64  *
65  * @version $Id: SVGImageManipulator.java,v 1.7 2006/12/02 11:17:34 anatom Exp $
66  */

67 public class SVGImageManipulator {
68     /**
69      * For logging
70      */

71     private static final Logger log = Logger.getLogger(SVGImageManipulator.class);
72     
73     /**
74      * Availabe vairables used to replace text in a printlayout
75      * Variable text are case-insensitive.
76      */

77     private static final Pattern JavaDoc USERNAME = Pattern.compile("\\$USERNAME", Pattern.CASE_INSENSITIVE);
78     private static final Pattern JavaDoc UID = Pattern.compile("\\$UID", Pattern.CASE_INSENSITIVE);
79     private static final Pattern JavaDoc CN = Pattern.compile("\\$CN", Pattern.CASE_INSENSITIVE);
80     private static final Pattern JavaDoc SN = Pattern.compile("\\$SN", Pattern.CASE_INSENSITIVE);
81     private static final Pattern JavaDoc GIVENNAME= Pattern.compile("\\$GIVENNAME", Pattern.CASE_INSENSITIVE);
82     private static final Pattern JavaDoc INITIALS = Pattern.compile("\\$INITIALS", Pattern.CASE_INSENSITIVE);
83     private static final Pattern JavaDoc SURNAME = Pattern.compile("\\$SURNAME", Pattern.CASE_INSENSITIVE);
84     private static final Pattern JavaDoc O = Pattern.compile("\\$O", Pattern.CASE_INSENSITIVE);
85     private static final Pattern JavaDoc OU = Pattern.compile("\\$OU", Pattern.CASE_INSENSITIVE);
86     private static final Pattern JavaDoc C = Pattern.compile("\\$C", Pattern.CASE_INSENSITIVE);
87     private static final Pattern JavaDoc LOCATION = Pattern.compile("\\$LOCATION", Pattern.CASE_INSENSITIVE);
88     private static final Pattern JavaDoc TITLE = Pattern.compile("\\$TITLE", Pattern.CASE_INSENSITIVE);
89     
90     /**
91      * Indicates the start date of the tokens validity.
92      */

93     private static final Pattern JavaDoc STARTDATE = Pattern.compile("\\$STARTDATE", Pattern.CASE_INSENSITIVE);
94     /**
95      * Indicates the end date of the tokens validity.
96      */

97     private static final Pattern JavaDoc ENDDATE = Pattern.compile("\\$ENDDATE", Pattern.CASE_INSENSITIVE);
98     
99     private static final Pattern JavaDoc HARDTOKENSN = Pattern.compile("\\$HARDTOKENSN", Pattern.CASE_INSENSITIVE);
100
101     private static final Pattern JavaDoc HARDTOKENSNWITHOUTPREFIX = Pattern.compile("\\$HARDTOKENSNWITHOUTPREFIX", Pattern.CASE_INSENSITIVE);
102
103     /**
104      * Constants used for pin and puk codes.
105      */

106     private static final Pattern JavaDoc[] PINS;
107     private static final Pattern JavaDoc[] PUKS;
108
109     /**
110      * Constants reserved for future use.
111      */

112 // private static final Pattern CUSTOMTEXTROW1 = Pattern.compile("\\$CUSTOMTEXTROW1", Pattern.CASE_INSENSITIVE);
113
// private static final Pattern CUSTOMTEXTROW2 = Pattern.compile("\\$CUSTOMTEXTROW2", Pattern.CASE_INSENSITIVE);
114
// private static final Pattern CUSTOMTEXTROW3 = Pattern.compile("\\$CUSTOMTEXTROW3", Pattern.CASE_INSENSITIVE);
115
// private static final Pattern CUSTOMTEXTROW4 = Pattern.compile("\\$CUSTOMTEXTROW4", Pattern.CASE_INSENSITIVE);
116
// private static final Pattern CUSTOMTEXTROW5 = Pattern.compile("\\$CUSTOMTEXTROW5", Pattern.CASE_INSENSITIVE);
117
// private static final Pattern COPYOFSN = Pattern.compile("\\$COPYOFSN", Pattern.CASE_INSENSITIVE);
118
// private static final Pattern COPYOFSNWITHOUTPREFIX = Pattern.compile("\\$COPYOFSNWITHOUTPREFIX", Pattern.CASE_INSENSITIVE);
119

120     static {
121         PINS = new Pattern JavaDoc[0x50];
122         PUKS = new Pattern JavaDoc[PINS.length];
123         for (int i=0; i<PINS.length; i++) {
124             final int pinNr = i+1;
125             PINS[i] = Pattern.compile("\\$PIN"+pinNr, Pattern.CASE_INSENSITIVE);
126             PUKS[i] = Pattern.compile("\\$PUK"+pinNr, Pattern.CASE_INSENSITIVE);
127         }
128     }
129
130     /**
131      * Constructor for the SVGImageManipulator object
132      *
133      * @param svgdata the xlm data to parse
134      * @param validity the validity of the card i days.
135      * @param hardtokensnprefix the prefix of all hard tokens generated with this profile.
136      * @param imagex x-position for image, reserved for future use
137      * @param imagey y-position for image, reserved for future use
138      * @param imageheight heigth of image, reserved for future use
139      * @param imagewidth width of image, reserved for future use
140      * @param unit units used, reserved for future use
141      * @throws IOException
142      */

143     
144     public SVGImageManipulator(Reader JavaDoc svgdata,
145                         int validity,
146                          String JavaDoc hardtokensnprefix) throws IOException JavaDoc {
147       this.validityms = ( ((long)validity) * 1000 * 3600 * 24); // Validity i ms
148
this.hardtokensnprefix = hardtokensnprefix;
149
150       String JavaDoc parser = XMLResourceDescriptor.getXMLParserClassName();
151       SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
152       String JavaDoc svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
153       Document doc = f.createDocument(svgNS, svgdata);
154
155       svgdoc = ((SVGOMDocument) doc);
156     }
157     
158     /**
159      * Returns the message with userspecific data replaced.
160      *
161      *
162      * @return A processed notification message.
163      *
164      */

165     public Printable JavaDoc print(UserDataVO userdata,
166                       String JavaDoc[] pincodes, String JavaDoc[] pukcodes,
167                       String JavaDoc hardtokensn, String JavaDoc copyoftokensn) throws IOException JavaDoc, PrinterException JavaDoc {
168       // Initialize
169
DNFieldExtractor dnfields = new DNFieldExtractor(userdata.getDN(), DNFieldExtractor.TYPE_SUBJECTDN);
170       // DNFieldExtractor subaltnamefields = new DNFieldExtractor(dn,DNFieldExtractor.TYPE_SUBJECTALTNAME);
171
Date JavaDoc currenttime = new Date JavaDoc();
172       String JavaDoc startdate = DateFormat.getDateInstance(DateFormat.SHORT).format(currenttime);
173       
174       String JavaDoc enddate = DateFormat.getDateInstance(DateFormat.SHORT).format(new Date JavaDoc(currenttime.getTime() + (this.validityms)));
175       String JavaDoc hardtokensnwithoutprefix = hardtokensn.substring(this.hardtokensnprefix.length());
176       String JavaDoc copyoftokensnwithoutprefix = copyoftokensn.substring(this.hardtokensnprefix.length());
177
178       final SVGOMDocument clone = (SVGOMDocument)svgdoc.cloneNode(true);
179       // Get Text rows
180
process( "text", userdata, dnfields, pincodes, pukcodes,
181                 hardtokensn, hardtokensnwithoutprefix,
182                 copyoftokensn, copyoftokensnwithoutprefix,
183                 startdate, enddate, clone);
184       process( "svg:text", userdata, dnfields, pincodes, pukcodes,
185                 hardtokensn, hardtokensnwithoutprefix,
186                 copyoftokensn, copyoftokensnwithoutprefix,
187                 startdate, enddate, clone);
188                        
189       // Add Image
190
/**
191       if(userdata.hasimage()){
192         addImage(userdata);
193       }
194        */

195       insertImage(userdata, clone); // special dravel for demo
196

197       PrintTranscoder t = new PrintTranscoder();
198       TranscoderInput input = new TranscoderInput(clone);
199       TranscoderOutput output = new TranscoderOutput(new ByteArrayOutputStream JavaDoc());
200       t.transcode(input, output);
201       {
202           final String JavaDoc aDoNot = clone.getRootElement().getAttribute("doNotScaleToPage");
203           t.addTranscodingHint( PrintTranscoder.KEY_SCALE_TO_PAGE,
204                                 new Boolean JavaDoc(aDoNot==null||aDoNot.trim().length()<=0) );
205       }
206       return t;
207     }
208
209     private void process(String JavaDoc tagName, UserDataVO userdata,
210             DNFieldExtractor dnfields, String JavaDoc[] pincodes, String JavaDoc[] pukcodes,
211             String JavaDoc hardtokensn, String JavaDoc hardtokensnwithoutprefix,
212             String JavaDoc copyoftokensn, String JavaDoc copyoftokensnwithoutprefix,
213             String JavaDoc startdate, String JavaDoc enddate, SVGDocument clone){
214         Collection JavaDoc texts = new ArrayList JavaDoc();
215         NodeList JavaDoc list = clone.getDocumentElement().getElementsByTagName(tagName);
216         int numberofelements = list.getLength();
217         for(int i=0; i<numberofelements; i++){
218             Node JavaDoc node = list.item(i);
219             if(node instanceof SVGTextElement){
220                 NodeList JavaDoc list2 = ((SVGTextElement) node).getChildNodes();
221                 int numberofelements2 = list2.getLength();
222                 for(int j=0;j<numberofelements2;j++){
223                     Node JavaDoc node2 = list2.item(j);
224                     if(node2 instanceof GenericText)
225                         texts.add(node2);
226                     if(node2 instanceof SVGOMTSpanElement){
227                         SVGOMTSpanElement tspan = (SVGOMTSpanElement) node2;
228                         NodeList JavaDoc list3 = tspan.getChildNodes();
229                         int numberofelements3 = list3.getLength();
230                         for(int k=0;k<numberofelements3;k++){
231                             Node JavaDoc node3 = list3.item(k);
232                             if(node3 instanceof GenericText)
233                                 texts.add(node3);
234                         }
235                     }
236                 }
237             }
238         }
239       Iterator JavaDoc iter = texts.iterator();
240       String JavaDoc data = "";
241       while(iter.hasNext()){
242         GenericText text = (GenericText) iter.next();
243         data = text.getData();
244         data = processString(data, userdata, dnfields, pincodes, pukcodes,
245                 hardtokensn, hardtokensnwithoutprefix,
246                 copyoftokensn, copyoftokensnwithoutprefix,
247                 startdate, enddate);
248         text.setData(data);
249       }
250     }
251     
252
253     private String JavaDoc processString(String JavaDoc text, UserDataVO userdata, DNFieldExtractor dnfields,
254                                  String JavaDoc[] pincodes, String JavaDoc[] pukcodes,
255                                  String JavaDoc hardtokensn, String JavaDoc hardtokensnwithoutprefix,
256                                  String JavaDoc copyoftokensn, String JavaDoc copyoftokensnwithoutprefix,
257                                  String JavaDoc startdate, String JavaDoc enddate){
258  
259  
260       text = USERNAME.matcher(text).replaceAll(userdata.getUsername());
261       text = UID.matcher(text).replaceAll(dnfields.getField(DNFieldExtractor.UID, 0));
262       text = CN.matcher(text).replaceAll(dnfields.getField(DNFieldExtractor.CN, 0));
263       text = OU.matcher(text).replaceAll(dnfields.getField(DNFieldExtractor.OU, 0));
264       text = O.matcher(text).replaceAll(dnfields.getField(DNFieldExtractor.O, 0));
265       text = C.matcher(text).replaceAll(dnfields.getField(DNFieldExtractor.C, 0));
266       text = LOCATION.matcher(text).replaceAll(dnfields.getField(DNFieldExtractor.L, 0));
267       text = TITLE.matcher(text).replaceAll(dnfields.getField(DNFieldExtractor.T, 0));
268       text = INITIALS.matcher(text).replaceAll(dnfields.getField(DNFieldExtractor.INITIALS, 0));
269       text = SN.matcher(text).replaceAll(dnfields.getField(DNFieldExtractor.SN, 0));
270       text = SURNAME.matcher(text).replaceAll(dnfields.getField(DNFieldExtractor.SURNAME, 0));
271       text = GIVENNAME.matcher(text).replaceAll(dnfields.getField(DNFieldExtractor.GIVENNAME, 0));
272
273       text = STARTDATE.matcher(text).replaceAll(startdate);
274       text = ENDDATE.matcher(text).replaceAll(enddate);
275       text = HARDTOKENSN.matcher(text).replaceAll(hardtokensn);
276       text = HARDTOKENSNWITHOUTPREFIX.matcher(text).replaceAll(hardtokensnwithoutprefix);
277
278       for(int i=Math.min(PINS.length, pincodes.length)-1; i>=0; i--){
279         text = PINS[i].matcher(text).replaceAll(pincodes[i]);
280       }
281
282       for(int i=Math.min(PUKS.length, pukcodes.length)-1; i>=0; i--){
283         text = PUKS[i].matcher(text).replaceAll(pukcodes[i]);
284       }
285
286       //text = CUSTOMTEXTROW1.matcher(text).replaceAll(?);
287
//text = CUSTOMTEXTROW2.matcher(text).replaceAll(?);
288
//text = CUSTOMTEXTROW3.matcher(text).replaceAll(?);
289
//text = CUSTOMTEXTROW4.matcher(text).replaceAll(?);
290
//text = CUSTOMTEXTROW5.matcher(text).replaceAll(?);
291
if (StringUtils.isNotEmpty(copyoftokensn) || StringUtils.isNotEmpty(copyoftokensnwithoutprefix)) {
292           log.debug("copyoftokensn: "+copyoftokensn+" and/or copyoftokensnwithoutprefix: "+copyoftokensnwithoutprefix+" is not used.");
293       }
294       //text = COPYOFSN.matcher(text).replaceAll(copyoftokensn);
295
//text = COPYOFSNWITHOUTPREFIX.matcher(text).replaceAll(copyoftokensnwithoutprefix);
296

297         
298       return text;
299     }
300
301
302     // Private Methods
303
private void insertImage(UserDataVO userdata, SVGOMDocument clone) throws FileNotFoundException JavaDoc, IOException JavaDoc{
304         log.debug(">insertImage("+userdata != null ? userdata.getUsername() : "null"+")");
305         int imgx = 0;
306         int imgy = 0;
307         int imgwidth = 0;
308         int imgheight = 0;
309         
310         String JavaDoc transform = null;
311         // Get image info from template
312
NodeList JavaDoc list = clone.getDocumentElement().getElementsByTagName("rect");
313         int numberofelements = list.getLength();
314         for(int i=0; i<numberofelements; i++){
315             Node JavaDoc node = list.item(i);
316             if(node instanceof SVGRectElement){
317                 SVGRectElement rectnode = (SVGRectElement) node;
318                 if(rectnode.getId().equalsIgnoreCase("USERPICTURE")){
319                     transform = rectnode.getAttribute("transform");
320                     imgx = (int) rectnode.getX().getBaseVal().getValue();
321                     imgy = (int) rectnode.getY().getBaseVal().getValue();
322                     imgwidth = (int) rectnode.getWidth().getBaseVal().getValue();
323                     imgheight = (int) rectnode.getHeight().getBaseVal().getValue();
324                     
325                 }
326             }
327         }
328         
329         if(imgwidth != 0 && imgheight != 0){
330             // Special dravel for demo remove
331
// BufferedImage image = ImageIO.read(new FileInputStream("c:\\userpicture.jpg"));
332
// TODO: get image.
333
BufferedImage JavaDoc image = null;
334             
335             SVGOMImageElement imageelement = new SVGOMImageElement("", clone);
336             SimpleImageHandler imagehandler = new SimpleImageHandler(new ImageHandlerBase64Encoder());
337             
338             SVGGeneratorContext svgcxt = SVGGeneratorContext.createDefault(clone);
339             
340             imagehandler.handleImage((RenderedImage JavaDoc) image, imageelement,
341                     imgx, imgy,
342                     imgwidth, imgheight,
343                     svgcxt);
344             
345             if(transform != null && !transform.equals(""))
346                 imageelement.setAttribute("transform", transform);
347             
348             clone.getRootElement().appendChild(imageelement);
349         }
350         
351     }
352
353     // Private Variables
354
final private SVGOMDocument svgdoc;
355     final private long validityms;
356     final private String JavaDoc hardtokensnprefix;
357
358     
359 }
360
Popular Tags