KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openide > filesystems > Utilities


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 package org.openide.filesystems;
20
21 import java.io.IOException JavaDoc;
22 import java.io.File JavaDoc;
23 import java.io.FileInputStream JavaDoc;
24 import java.io.FileOutputStream JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import java.io.PrintStream JavaDoc;
27 import java.io.InputStreamReader JavaDoc;
28 import java.io.BufferedReader JavaDoc;
29 import java.io.DataOutput JavaDoc;
30 import java.io.DataInput JavaDoc;
31 import java.util.HashMap JavaDoc;
32 import java.util.List JavaDoc;
33 import java.util.ArrayList JavaDoc;
34
35 /**
36  * A set of utility methods.
37  */

38 public abstract class Utilities {
39
40     /** Counts padding size from given size, i.e. 1 for less than 10, 3 for 100 - 999, etc. */
41     public static int expPaddingSize(int size) {
42         int ret = 0;
43         
44         while (size > 0) {
45             size /= 10;
46             ret++;
47         }
48         return ret;
49     }
50     
51     /** Appends paddingSize number of digits e.g. 00digit */
52     public static void appendNDigits(int digit, int paddingSize, StringBuffer JavaDoc buffer) {
53         int localLength = paddingSize - 1;
54         int exp[] = new int[] { 0, 10, 100, 1000, 10000, 100000, 1000000 };
55
56         while (digit < exp[localLength--]) {
57             buffer.append('0');
58         }
59
60         buffer.append(String.valueOf(digit));
61     }
62     
63     /** Creates jar file
64      * @param srcdir which folder to be zipped
65      * @param <tt>name</tt> name of the jar
66      */

67     public static File JavaDoc createJar(File JavaDoc srcdir, String JavaDoc name) throws Exception JavaDoc {
68         Process JavaDoc proc = Runtime.getRuntime().exec("jar cf " + name + " .", null, srcdir);
69         proc.waitFor();
70         copyIS(proc.getErrorStream(), System.out);
71         
72         return new File JavaDoc(srcdir, name);
73     }
74     
75     /** Copy content of a stream to a PrintStream */
76     public static void copyIS(InputStream JavaDoc is, PrintStream JavaDoc out) throws Exception JavaDoc {
77         BufferedReader JavaDoc reader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(is));
78         String JavaDoc str;
79         while ((str = reader.readLine()) != null) {
80             out.println(str);
81         }
82     }
83     
84     /** Writes a file to DataOutput */
85     public static void writeFile(File JavaDoc src, DataOutput JavaDoc dest) throws IOException JavaDoc {
86         FileInputStream JavaDoc fis = new FileInputStream JavaDoc(src);
87         long len = src.length();
88         dest.writeUTF(src.getName());
89         dest.writeLong(len);
90                 
91         byte[] buffer = new byte[5000];
92         int read;
93         for (;;) {
94             read = fis.read(buffer);
95             if (read < 0) {
96                 break;
97             }
98             dest.write(buffer, 0, read);
99         }
100         
101         fis.close();
102     }
103     
104     /** Reads a file from DataInput */
105     public static File JavaDoc readFile(File JavaDoc dest, DataInput JavaDoc src) throws IOException JavaDoc {
106         File JavaDoc ret = new File JavaDoc(dest, src.readUTF());
107         FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(ret);
108         long len = src.readLong();
109         final int BUF_SIZE = 5000;
110         byte[] buffer = new byte[BUF_SIZE];
111         
112         int read;
113         int shouldRead;
114         for (;;) {
115             read = (int) Math.min(BUF_SIZE, len);
116             src.readFully(buffer, 0, read);
117             fos.write(buffer, 0, read);
118             len -= read;
119             if (len <= 0) {
120                 break;
121             }
122         }
123         
124         fos.close();
125         return ret;
126     }
127
128     /**
129      * Simple grep
130      */

131     public static final class Matcher {
132         private State first;
133
134         /** new Matcher */
135         public Matcher(String JavaDoc[] patterns) {
136             first = new State(null);
137             initStates(patterns);
138         }
139
140         /** Inits this Matcher */
141         private void initStates(String JavaDoc[] patterns) {
142             List JavaDoc groups = createGroups(patterns, 0);
143             StringGroup.resolveGroups(groups);
144             StringGroup.fillState(first, groups);
145             createDG(first);
146         }
147
148         /** Creates directed graph of States */
149         private static void createDG(State state) {
150             Transition[] ts = state.getTransitions();
151             for (int i = 0; i < ts.length; i++) {
152                 createDG(ts[i].getState(), ts);
153             }
154         }
155
156         /** Creates directed cycled graph of States*/
157         private static void createDG(State state, Transition[] ts) {
158             Transition[] myts = state.getTransitions();
159
160             for (int j = 0; j < myts.length; j++) {
161                 createDG(myts[j].getState(), ts);
162             }
163
164             mergeTransitions(state, ts);
165         }
166
167         /** Creates cycles in a graph of States
168          * Adds given Transitions to given state.
169          */

170         private static void mergeTransitions(State state, Transition[] ts) {
171             for (int i = 0; i < ts.length; i++) {
172                 State istate = ts[i].getState();
173                 if (istate == state) {
174                     continue;
175                 }
176
177                 if (state.isDefined(ts[i].getChar())) {
178                     State tmp = state.getNext(ts[i].getChar());
179                     if (tmp != istate) {
180                         makePtr(tmp, istate);
181                     }
182                 } else {
183                     state.addTransition(ts[i]);
184                 }
185             }
186         }
187
188         /** Links one state to another state */
189         private static void makePtr(State from, State to) {
190             Transition[] tots = to.getTransitions();
191             mergeTransitions(from, tots);
192
193             if (to.isTerminal()) {
194                 String JavaDoc[] matches = to.getMatches();
195                 from.markAsTerminal(matches[0]);
196                 for (int i = 1; i < matches.length; i++) {
197                     from.addMatch(matches[i]);
198                 }
199             }
200         }
201
202         /** Creates groups for patterns */
203         static List JavaDoc createGroups(String JavaDoc[] patterns, int level) {
204             HashMap JavaDoc map = new HashMap JavaDoc();
205
206             for (int i = 0; i < patterns.length; i++) {
207                 Character JavaDoc divider = new Character JavaDoc(patterns[i].charAt(level));
208                 StringGroup grp = (StringGroup) map.get(divider);
209                 if (grp == null) {
210                     grp = new StringGroup(level);
211                     map.put(divider, grp);
212                 }
213                 grp.addString(patterns[i]);
214             }
215
216             return new ArrayList JavaDoc(map.values());
217         }
218
219         /** @return initial state for this Matcher */
220         public State getInitState() {
221             return first;
222         }
223
224         /** Encapsulates a group of strings with a common prefix */
225         static final class StringGroup {
226             private List JavaDoc strings;
227             private final int startIndex;
228             private List JavaDoc subGroups;
229             private int minIdx;
230             private int endIndex;
231             private boolean terminal;
232
233             /** New group */
234             public StringGroup(int idx) {
235                 this.startIndex = idx;
236                 minIdx = Integer.MAX_VALUE;
237                 strings = new ArrayList JavaDoc();
238                 this.terminal = false;
239             }
240
241             /** Adds a String to this group */
242             public void addString(String JavaDoc s) {
243                 strings.add(s);
244                 minIdx = Math.min(minIdx, s.length());
245             }
246
247             /** @return true if this group contains only one String */
248             private boolean isTerminal() {
249                 if (strings.size() <= 1 || terminal) {
250                     return true;
251                 } else {
252                     return false;
253                 }
254             }
255
256             private boolean hasSubGroups() {
257                 return (subGroups != null) && (subGroups.size() > 0);
258             }
259
260             /** @return first char for this group */
261             private char getFirstChar() {
262                 return ((String JavaDoc) strings.get(0)).charAt(startIndex);
263             }
264
265             /** Resolves this group and all its sub groups */
266             private void resolve() {
267                 if (isTerminal()) {
268                     endIndex = minIdx;
269                     return;
270                 }
271
272                 subGroups = new ArrayList JavaDoc();
273                 int i = startIndex + 1;
274 out: for (; i < minIdx; i++) {
275                     char c = ((String JavaDoc) strings.get(0)).charAt(i);
276
277                     for (int j = 1; j < strings.size(); j++) {
278                         char c2 = ((String JavaDoc) strings.get(j)).charAt(i);
279                         if (c2 != c) {
280                             String JavaDoc[] arr = (String JavaDoc[]) strings.toArray(new String JavaDoc[strings.size()]);
281                             subGroups = createGroups(arr, endIndex = i);
282                             break out;
283                         }
284                     }
285                 }
286
287                 if (i == minIdx) {
288                     endIndex = minIdx;
289                     List JavaDoc longStrings = new ArrayList JavaDoc();
290                     for (int j = 0; j < strings.size(); j++) {
291                         String JavaDoc str = (String JavaDoc) strings.get(j);
292                         if (str.length() > minIdx) {
293                             longStrings.add(str);
294                         }
295                     }
296
297                     String JavaDoc[] arr = (String JavaDoc[]) longStrings.toArray(new String JavaDoc[longStrings.size()]);
298                     subGroups = createGroups(arr, minIdx);
299                     terminal = true;
300                 }
301
302                 resolveGroups(subGroups);
303             }
304
305             /** @return a String that */
306             private String JavaDoc getShortOrAny() {
307                 for (int j = 0; j < strings.size(); j++) {
308                     String JavaDoc str = (String JavaDoc) strings.get(j);
309                     if (str.length() == minIdx) {
310                         return str;
311                     }
312                 }
313
314                 return (String JavaDoc) strings.get(0);
315             }
316
317             /** @return initial State for this group */
318             private State createEntryState(State firstState) {
319                 State entry = new State(firstState);
320                 String JavaDoc any = getShortOrAny();
321                 State iter = entry;
322
323                 for (int i = startIndex + 1; i < endIndex; i++) {
324                     char c = any.charAt(i);
325                     State state = new State(firstState);
326                     Transition t = new Transition(c, state);
327                     iter.addTransition(t);
328                     iter = state;
329                 }
330
331                 if (isTerminal()) {
332                     iter.markAsTerminal(any);
333                 }
334
335                 if (hasSubGroups()) {
336                     fillState(iter, firstState, subGroups);
337                 }
338
339                 return entry;
340             }
341
342             /** Joins given groups to state with a given firstState */
343             public static void fillState(State state, List JavaDoc groups) {
344                 fillState(state, state, groups);
345             }
346
347             /** Joins given groups to state with a given firstState */
348             private static void fillState(State state, State firstState, List JavaDoc groups) {
349                 Transition[] tmp = new Transition[1];
350                 for (int i = 0; i < groups.size(); i++) {
351                     StringGroup grp = (StringGroup) groups.get(i);
352                     State xstate = grp.createEntryState(firstState);
353                     tmp[0] = new Transition(grp.getFirstChar(), xstate);
354                     mergeTransitions(state, tmp);
355                 }
356             }
357
358             /** Resolves all groups */
359             static void resolveGroups(List JavaDoc groups) {
360                 int len = groups.size();
361
362                 for (int i = 0; i < len; i++) {
363                     StringGroup grp = (StringGroup) groups.get(i);
364                     grp.resolve();
365                 }
366             }
367         }
368
369         /** Represents state of the automata */
370         public static final class State {
371             private HashMap JavaDoc transitions;
372             private State first;
373             private boolean terminal;
374             private List JavaDoc matches;
375
376             /** New State */
377             public State(State first) {
378                 this.transitions = new HashMap JavaDoc();
379                 this.matches = new ArrayList JavaDoc();
380                 this.terminal = false;
381                 if (first == null) {
382                     this.first = this;
383                 } else {
384                     this.first = first;
385                 }
386             }
387
388             /** Adds on Transition */
389             void addTransition(Transition t) {
390                 transitions.put(t.getHashKey(), t);
391             }
392
393             /** @return next State for the given char */
394             public State getNext(char c) {
395                 Transition t = (Transition) transitions.get(new Character JavaDoc(c));
396                 if (t != null) {
397                     return t.getState();
398                 } else {
399                     return first;
400                 }
401             }
402
403             /** @return true iff there exists a Transition for given char */
404             boolean isDefined(char c) {
405                 return (transitions.get(new Character JavaDoc(c)) != null);
406             }
407
408             /** This is a match */
409             void markAsTerminal(String JavaDoc match) {
410                 terminal = true;
411                 addMatch(match);
412             }
413
414             /** Adds this String to its matches */
415             void addMatch(String JavaDoc match) {
416                 matches.add(match);
417             }
418
419             /** @return matches */
420             public String JavaDoc[] getMatches() {
421                 return (String JavaDoc[]) matches.toArray(new String JavaDoc[matches.size()]);
422             }
423
424             /** @return true iff it is a match */
425             public boolean isTerminal() {
426                 return terminal;
427             }
428
429             /** @return all transitions for this State */
430             Transition[] getTransitions() {
431                 return (Transition[]) transitions.values().toArray(new Transition[transitions.size()]);
432             }
433         }
434
435         /** Bound to State - represents mapping of a char to next State */
436         static final class Transition {
437             private char c;
438             private State nextState;
439
440             /** New Transition */
441             public Transition(char c, State nextState) {
442                 this.c = c;
443                 this.nextState = nextState;
444             }
445
446             /** Hash key for this Transition */
447             public Object JavaDoc getHashKey() {
448                 return new Character JavaDoc(c);
449             }
450
451             /** @return char */
452             public char getChar() {
453                 return c;
454             }
455
456             /** @return State for this Transition */
457             public State getState() {
458                 return nextState;
459             }
460         }
461     }
462     
463 }
464
Popular Tags