KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > nbbuild > CopyIcons


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.nbbuild;
21
22 import java.awt.Dimension JavaDoc;
23 import java.io.BufferedOutputStream JavaDoc;
24 import java.io.ByteArrayInputStream JavaDoc;
25 import java.io.File JavaDoc;
26 import java.io.FileFilter JavaDoc;
27 import java.io.FileInputStream JavaDoc;
28 import java.io.FileNotFoundException JavaDoc;
29 import java.io.FileOutputStream JavaDoc;
30 import java.io.FilenameFilter JavaDoc;
31 import java.io.IOException JavaDoc;
32 import java.io.InputStream JavaDoc;
33 import java.io.PrintWriter JavaDoc;
34 import java.util.ArrayList JavaDoc;
35 import java.util.Iterator JavaDoc;
36 import java.util.List JavaDoc;
37 import java.util.StringTokenizer JavaDoc;
38
39 import org.apache.tools.ant.BuildException;
40 import org.apache.tools.ant.DirectoryScanner;
41 import org.apache.tools.ant.Project;
42 import org.apache.tools.ant.taskdefs.Copy;
43 import org.apache.tools.ant.taskdefs.MatchingTask;
44 import org.apache.tools.ant.types.FileSet;
45
46 /**
47  * Task for copying out icons from NetBeans projects. It creates paralel directory
48  * structure in destdir with only copied icons. It creates index.html page that
49  * lists all found icons and group them according to nb modules. Icons are considered
50  * images with dimensions 8x8, 16x16, 24x24, 32x32 of type PNG or GIF.
51  * Inclusion filter for images in each module is given by attribute 'iconincludes',
52  * default inclusion filter is all gifs and pngs under src folder. Exclusion filter
53  * is defined by attribute 'iconexcludes'. Filters are regular ant inclusion and
54  * exclusion filters. Task tries to find all nb modules up to depth defined by
55  * 'depth' attribute (default is 4) in the nbsrcroot. Modules without icons are
56  * not listed by default, they can be shown by setting attribute 'showempty' to true.
57  *
58  * Required attributes are:
59  * nbsrcroot ... root of NetBeans CVS checkout
60  * destdir ... dir for copying icons
61  *
62  * @author Milan Kubec
63  */

64 public class CopyIcons extends MatchingTask {
65     
66     private int depth = 0;
67     private List JavaDoc<File JavaDoc> projectDirList = new ArrayList JavaDoc<File JavaDoc>();
68     private List JavaDoc<ProjectIconInfo> prjIconInfoList = new ArrayList JavaDoc<ProjectIconInfo>();
69     
70     File JavaDoc baseDir = null;
71     public void setNbsrcroot(File JavaDoc f) {
72         baseDir = f;
73     }
74     
75     File JavaDoc destDir = null;
76     public void setDestdir(File JavaDoc f) {
77         destDir = f;
78     }
79     
80     int userDepth = 4;
81     public void setDepth(String JavaDoc s) {
82         userDepth = Integer.parseInt(s);
83     }
84     
85     String JavaDoc iconIncludes = "src/**/*.png,src/**/*.gif";
86     public void setIconincludes(String JavaDoc s) {
87         iconIncludes = s;
88     }
89     
90     String JavaDoc iconExcludes = "";
91     public void setIconexcludes(String JavaDoc s) {
92         iconExcludes = s;
93     }
94     
95     String JavaDoc prjIncludes = "";
96     public void setPrjincludes(String JavaDoc s) {
97         prjIncludes = s;
98     }
99     
100     String JavaDoc prjExcludes = "";
101     public void setPrjExcludes(String JavaDoc s) {
102         prjExcludes = s;
103     }
104     
105     boolean showEmpty = false;
106     public void setShowempty(boolean b) {
107         showEmpty = b;
108     }
109     
110     public void execute() throws BuildException {
111         if (baseDir == null || destDir == null) {
112             log("Nbsrcroot or destdir are not specified.");
113             return;
114         }
115         scanForProjectDirs(baseDir);
116         for (Iterator JavaDoc<File JavaDoc> iter = projectDirList.iterator(); iter.hasNext(); ) {
117             File JavaDoc f = iter.next();
118             processProjectDir(f);
119         }
120         copyToDestDir(prjIconInfoList);
121         dumpListToHTML(prjIconInfoList);
122     }
123     
124     private ImageInfo readImageInfo(File JavaDoc fl) throws IOException JavaDoc {
125         Dimension JavaDoc dim = null;
126         ImageInfo imageInfo = null;
127         ByteArrayInputStream JavaDoc bais = null;
128         try {
129             bais = readSomeBytes(fl);
130             if (isGIF(bais)) {
131                 imageInfo = new ImageInfo(readGIFDimension(bais), ImageInfo.GIF);
132             } else if (isPNG(bais)) {
133                 imageInfo = new ImageInfo(readPNGDimension(bais), ImageInfo.PNG);
134             }
135         } catch (IOException JavaDoc ex) {
136             ex.printStackTrace();
137         } finally {
138             bais.close();
139         }
140         return imageInfo;
141     }
142     
143     private ByteArrayInputStream JavaDoc readSomeBytes(File JavaDoc fl) throws IOException JavaDoc {
144         byte buffer[] = new byte[30];
145         FileInputStream JavaDoc fis = null;
146         fis = new FileInputStream JavaDoc(fl);
147         fis.read(buffer);
148         fis.close();
149         return new ByteArrayInputStream JavaDoc(buffer);
150     }
151     
152     private boolean isGIF(InputStream JavaDoc is) throws IOException JavaDoc {
153         is.reset();
154         byte buf[];
155         is.read(buf = new byte[3]);
156         int signatureBuffer[] = parseUnsigned(buf);
157         if (((char) signatureBuffer[0] == 'G') &&
158             ((char) signatureBuffer[1] == 'I') &&
159             ((char) signatureBuffer[2] == 'F')) {
160             return true;
161         }
162         return false;
163     }
164     
165     private boolean isPNG(InputStream JavaDoc is) throws IOException JavaDoc {
166         is.reset();
167         byte buf[];
168         is.read(buf = new byte[8]);
169         int signatureBuffer[] = parseUnsigned(buf);
170         if ((signatureBuffer[0] == 137) && // PNG signature
171
(signatureBuffer[1] == 80) &&
172             (signatureBuffer[2] == 78) &&
173             (signatureBuffer[3] == 71) &&
174             (signatureBuffer[4] == 13) &&
175             (signatureBuffer[5] == 10) &&
176             (signatureBuffer[6] == 26) &&
177             (signatureBuffer[7] == 10)) {
178             return true;
179         }
180         return false;
181     }
182     
183     private Dimension JavaDoc readGIFDimension(InputStream JavaDoc is) throws IOException JavaDoc {
184         byte buf [];
185         is.read(new byte[3]); // GIF version
186
is.read(buf = new byte[2]); // width
187
int widthBuf[] = parseUnsigned(buf);
188         int width = (widthBuf[1] << 8) + widthBuf[0];
189         is.read(buf = new byte[2]); // height
190
int heightBuf[] = parseUnsigned(buf);
191         int height = (heightBuf[1] << 8) + heightBuf[0];
192         return new Dimension JavaDoc(width, height);
193     }
194     
195     private Dimension JavaDoc readPNGDimension(InputStream JavaDoc is) throws IOException JavaDoc {
196         byte buf[];
197         is.read(new byte[4]); // length
198
is.read(new byte[4]); // type
199
is.read(buf = new byte[4]); // width
200
int widthBuf[] = parseUnsigned(buf);
201         int width = (widthBuf[0] << 24) + (widthBuf[1] << 16) + (widthBuf[2] << 8) + widthBuf[3];
202         is.read(buf = new byte[4]); // height
203
int heightBuf[] = parseUnsigned(buf);
204         int height = (heightBuf[0] << 24) + (heightBuf[1] << 16) + (heightBuf[2] << 8) + heightBuf[3];
205         return new Dimension JavaDoc(width, height);
206     }
207     
208     private static int[] parseUnsigned(byte[] src) {
209         int[] val = new int[src.length];
210         for (int i = 0; i < src.length; i ++) {
211             val[i] = (src[i] < 0) && (src[i] >= -128) ? 256 + src[i] : src[i];
212         }
213         return val;
214     }
215     
216     // -------------------------------------------------------------------------
217

218 // public static void main(String[] args) {
219
// File buildFile = new File("e:/development/projects/CopyIcons/testscript.xml");
220
// Project p = new Project();
221
// p.setUserProperty("ant.file", buildFile.getAbsolutePath());
222
// p.init();
223
// ProjectHelper helper = ProjectHelper.getProjectHelper();
224
// p.addReference("ant.projectHelper", helper);
225
// helper.parse(p, buildFile);
226
// p.executeTarget(p.getDefaultTarget());
227
// }
228

229     // -------------------------------------------------------------------------
230

231     private static class ImageInfo {
232         
233         public static final int GIF = 1;
234         public static final int PNG = 2;
235         
236         private Dimension JavaDoc dim;
237         private int type;
238         private String JavaDoc path;
239         private String JavaDoc ext;
240         
241         public ImageInfo(Dimension JavaDoc dm, int tp) {
242             this(null, dm, tp);
243         }
244         
245         public ImageInfo(String JavaDoc pth, Dimension JavaDoc dm, int tp) {
246             path = pth;
247             dim = dm;
248             type = tp;
249         }
250         
251         public String JavaDoc getPath() {
252             return path;
253         }
254         
255         public void setPath(String JavaDoc pth) {
256             path = pth;
257         }
258         
259         public int getHeight() {
260             return dim.height;
261         }
262         
263         public int getWidth() {
264             return dim.width;
265         }
266         
267         public String JavaDoc getType() {
268             if (type == GIF) {
269                 return "GIF";
270             } else if (type == PNG) {
271                 return "PNG";
272             }
273             return "";
274         }
275         
276         public String JavaDoc getExt() {
277             return ext;
278         }
279         
280         public String JavaDoc setExt(String JavaDoc ex) {
281             return ext = ex;
282         }
283         
284     }
285     
286     private static class ProjectIconInfo {
287         
288         public String JavaDoc prjPath;
289         public List JavaDoc<ImageInfo> matchingIcons;
290         public List JavaDoc<ImageInfo> notmatchingIcons;
291         
292         public ProjectIconInfo(String JavaDoc pth, List JavaDoc<ImageInfo> mi, List JavaDoc<ImageInfo> nmi) {
293             prjPath = pth;
294             matchingIcons = mi;
295             notmatchingIcons = nmi;
296         }
297         
298     }
299     
300     // -------------------------------------------------------------------------
301

302     private void dumpListToHTML(List JavaDoc<ProjectIconInfo> lst) {
303         File JavaDoc reportFile = new File JavaDoc(destDir, "index.html");
304         FileOutputStream JavaDoc fos = null;
305         try {
306             fos = new FileOutputStream JavaDoc(reportFile);
307         } catch (FileNotFoundException JavaDoc ex) {
308             ex.printStackTrace();
309         }
310         PrintWriter JavaDoc pw = new PrintWriter JavaDoc(new BufferedOutputStream JavaDoc(fos));
311         pw.println("<html>");
312         pw.println("<head>");
313         pw.println("<style type=\"text/css\">\nbody { font-family: Tahoma, Verdana, sans-serif }\n</style>");
314         pw.println("</head>");
315         pw.println("<body>");
316         pw.println("<h2>List of icons in NetBeans projects</h2>");
317         pw.println("<h3>NetBeans Source Root: " + baseDir + "<br/>");
318         pw.println("Destination Directory: " + destDir + "</h3>");
319         pw.println("<p style=\"width: 70%\"><b>Description:</b><br/> New Image is image in the Destination Directory, Orig. Image is image in NetBeans Source Root. " +
320                 "By replacing the image in Destination Directory under coresponding module and path you can prepare rebranded " +
321                 "icons in paralel directory structure and then copy them over to NetBeans Source Root. Orig. Image is " +
322                 "in the table just for comparison and reference what image was already changed.</p>");
323         for (Iterator JavaDoc<ProjectIconInfo> iter = prjIconInfoList.iterator(); iter.hasNext(); ) {
324             ProjectIconInfo info = iter.next();
325             if (!showEmpty && info.matchingIcons.size() == 0) {
326                 continue;
327             }
328             pw.println("<p>Module name: <b>" + info.prjPath + "</b></p>");
329             pw.println("<p style=\"margin-left: 20px\">");
330             if (info.matchingIcons.size() == 0) {
331                 pw.println("<i>--- No icons ---</i>");
332                 pw.println("</p>");
333                 continue;
334             }
335             pw.println("<table width=\"80%\"border=\"1\" cellpadding=\"3\" cellspacing=\"0\">");
336             pw.println("<tr><td><b>Resource Path</b></td>" +
337                     "<td align=\"center\"><b>&nbsp;New Image&nbsp;</b></td>" +
338                     "<td align=\"center\"><b>&nbsp;Orig. image&nbsp;</b></td>" +
339                     "<td align=\"center\"><b>&nbsp;W x H&nbsp;</b></td>" +
340                     "<td align=\"center\"><b>&nbsp;Extension&nbsp;</b></td>" +
341                     "<td align=\"center\"><b>&nbsp;Real Type&nbsp;</b></td></tr>");
342             for (Iterator JavaDoc<ImageInfo> goodIter = info.matchingIcons.iterator(); goodIter.hasNext(); ) {
343                 ImageInfo goodInfo = goodIter.next();
344                 String JavaDoc iconPath = goodInfo.getPath();
345                 String JavaDoc copiedIconPath = info.prjPath + File.separator + iconPath;
346                 String JavaDoc originalIconPath = baseDir.getAbsolutePath() + File.separator + info.prjPath + File.separator + iconPath;
347                 pw.println("<tr>");
348                 pw.println("<td>");
349                 pw.println("<a HREF=\"" + copiedIconPath + "\">" + iconPath + "</a>");
350                 pw.println("</td>");
351                 pw.println("<td align=\"center\">");
352                 pw.println("<img SRC=\"" + copiedIconPath + "\"/>"); // copied image
353
pw.println("</td>");
354                 pw.println("<td align=\"center\">");
355                 pw.println("<img SRC=\"file://" + originalIconPath + "\"/>"); // original image
356
pw.println("</td>");
357                 pw.println("<td align=\"center\">" + goodInfo.getWidth() + " x " + goodInfo.getHeight() + "</td>");
358                 pw.println("<td align=\"center\">" + goodInfo.getExt().toUpperCase() + "</td>");
359                 if (!goodInfo.getExt().equalsIgnoreCase(goodInfo.getType())) {
360                     pw.println("<td align=\"center\"><font color=\"Orange\">" + goodInfo.getType() + "</font></td>");
361                 } else {
362                     pw.println("<td align=\"center\">" + goodInfo.getType() + "</td>");
363                 }
364                 pw.println("</tr>");
365             }
366             pw.println("</table>");
367             pw.println("</p>");
368         }
369         pw.println("</body>");
370         pw.println("</html>");
371         pw.flush();
372         pw.close();
373         log("---> Report was written to file: " + reportFile.getAbsolutePath());
374     }
375         
376     private void copyToDestDir(List JavaDoc<ProjectIconInfo> prjInfoList) {
377         FileSet fs = null;
378         for (Iterator JavaDoc<ProjectIconInfo> iter = prjInfoList.iterator(); iter.hasNext(); ) {
379             fs = new FileSet();
380             log("Setting basedir for fileset: " + baseDir, Project.MSG_VERBOSE);
381             ProjectIconInfo prjIconInfo = iter.next();
382             fs.setDir(new File JavaDoc(baseDir, prjIconInfo.prjPath));
383             int numFilesToCopy = prjIconInfo.matchingIcons.size() + prjIconInfo.notmatchingIcons.size();
384             for (Iterator JavaDoc<ImageInfo> matchInfoIter = prjIconInfo.matchingIcons.iterator(); matchInfoIter.hasNext(); ) {
385                 ImageInfo info = matchInfoIter.next();
386                 log("Adding file to matching fileset: " + info.getPath(), Project.MSG_VERBOSE);
387                 fs.setIncludes(info.getPath());
388             }
389             for (Iterator JavaDoc<ImageInfo> notmatchInfoIter = prjIconInfo.notmatchingIcons.iterator(); notmatchInfoIter.hasNext(); ) {
390                 ImageInfo info = notmatchInfoIter.next();
391                 log("Adding file to notmatching fileset: " + info.getPath(), Project.MSG_VERBOSE);
392                 fs.setIncludes(info.getPath());
393             }
394             if (numFilesToCopy > 0) {
395                 Copy copy = (Copy) getProject().createTask("copy");
396                 copy.addFileset(fs);
397                 File JavaDoc dest = new File JavaDoc(destDir, prjIconInfo.prjPath);
398                 dest.mkdir();
399                 copy.setTodir(dest);
400                 copy.init();
401                 copy.setLocation(getLocation());
402                 copy.execute();
403             }
404         }
405     }
406     
407     // -------------------------------------------------------------------------
408

409     private void scanForProjectDirs(File JavaDoc fl) {
410         if (depth > userDepth) return;
411         //if (isProjectDir(fl)) {
412
// projectDirList.add(fl);
413
//}
414
File JavaDoc allFiles[] = fl.listFiles(new FileFilter JavaDoc() {
415             public boolean accept(File JavaDoc pathname) {
416                 if (pathname.isDirectory()) {
417                     return true;
418                 }
419                 return false;
420             }
421         });
422         depth++;
423         for (File JavaDoc f : allFiles) {
424             if (isProjectDir(f)) {
425                 // here could be some project exclusion logic
426
projectDirList.add(f);
427                 log(f.toString(), Project.MSG_VERBOSE);
428                 scanForProjectDirs(f);
429             } else {
430                 scanForProjectDirs(f);
431             }
432         }
433         depth--;
434     }
435     
436     private boolean isProjectDir(File JavaDoc fl) {
437         File JavaDoc prjDirs[] = fl.listFiles(new FilenameFilter JavaDoc() {
438             public boolean accept(File JavaDoc dir, String JavaDoc name) {
439                 if ("nbproject".equals(name)) {
440                     return true;
441                 }
442                 return false;
443             }
444         });
445         if (prjDirs.length != 1) {
446             return false;
447         }
448         String JavaDoc prjFiles[] = prjDirs[0].list(new FilenameFilter JavaDoc() {
449             public boolean accept(File JavaDoc dir, String JavaDoc name) {
450                 if ("project.xml".equals(name)) {
451                     return true;
452                 }
453                 return false;
454             }
455         });
456         if (prjFiles.length != 1) {
457             return false;
458         }
459         return true;
460     }
461
462     private void processProjectDir(File JavaDoc f) {
463         String JavaDoc prjPath = null;
464         //if (f.getAbsolutePath().equals(baseDir.getAbsolutePath())) {
465
// prjPath = "";
466
//} else {
467
prjPath = f.getAbsolutePath().substring(baseDir.getAbsolutePath().length() + 1);
468         //}
469
log("Processing project dir: " + prjPath);
470         DirectoryScanner ds = new DirectoryScanner();
471         ds.setBasedir(f);
472         ds.setIncludes(getAsArray(iconIncludes));
473         ds.setExcludes(getAsArray(iconExcludes));
474         ds.setCaseSensitive(false);
475         ds.scan();
476         String JavaDoc[] files = ds.getIncludedFiles();
477         log(" Found " + files.length + " files in " + f);
478         List JavaDoc<ImageInfo> goodIcons = new ArrayList JavaDoc<ImageInfo>();
479         List JavaDoc<ImageInfo> badIcons = new ArrayList JavaDoc<ImageInfo>();
480         for (String JavaDoc file : files) {
481             String JavaDoc ext = file.substring(file.lastIndexOf('.') + 1);
482             if (ext.equalsIgnoreCase("gif") || ext.equalsIgnoreCase("png")) {
483                 File JavaDoc iconFile = new File JavaDoc(f, file);
484                 try {
485                     ImageInfo imageInfo = null;
486                     imageInfo = readImageInfo(iconFile);
487                     if (imageInfo != null) {
488                         imageInfo.setPath(file);
489                         imageInfo.setExt(ext);
490                         int w = imageInfo.getWidth();
491                         int h = imageInfo.getHeight();
492                         if ((w == 8 && h == 8) || (w == 16 && h == 16) ||
493                             (w == 24 && h == 24) || (w == 32 && h == 32)) {
494                             goodIcons.add(imageInfo);
495                         } else {
496                             badIcons.add(imageInfo);
497                         }
498                     }
499                 } catch (IOException JavaDoc ex) {
500                     ex.printStackTrace();
501                 }
502             }
503         }
504         ProjectIconInfo prjIconInfo = new ProjectIconInfo(prjPath, goodIcons, badIcons);
505         prjIconInfoList.add(prjIconInfo);
506     }
507     
508     private String JavaDoc[] getAsArray(String JavaDoc s) {
509         List JavaDoc<String JavaDoc> list = new ArrayList JavaDoc<String JavaDoc>();
510         for (StringTokenizer JavaDoc stok = new StringTokenizer JavaDoc(s, ","); stok.hasMoreTokens(); ) {
511           String JavaDoc token = stok.nextToken().trim();
512           list.add(token);
513         }
514         return list.toArray(new String JavaDoc[list.size()]);
515     }
516     
517 }
518
Popular Tags