Source Code Cross Referenced for FileUtil.java in  » Portal » Open-Portal » com » sun » portal » fabric » util » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Portal » Open Portal » com.sun.portal.fabric.util 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /**
002:         * $Id: FileUtil.java,v 1.34 2007/01/26 03:48:34 portalbld Exp $
003:         * Copyright 2004 Sun Microsystems, Inc. All
004:         * rights reserved. Use of this product is subject
005:         * to license terms. Federal Acquisitions:
006:         * Commercial Software -- Government Users
007:         * Subject to Standard License Terms and
008:         * Conditions.
009:         *
010:         * Sun, Sun Microsystems, the Sun logo, and Sun ONE
011:         * are trademarks or registered trademarks of Sun Microsystems,
012:         * Inc. in the United States and other countries.
013:         */package com.sun.portal.fabric.util;
014:
015:        import java.io.BufferedReader;
016:        import java.io.BufferedWriter;
017:        import java.io.ByteArrayOutputStream;
018:        import java.io.File;
019:        import java.io.FileInputStream;
020:        import java.io.FileNotFoundException;
021:        import java.io.FileOutputStream;
022:        import java.io.FileReader;
023:        import java.io.FileWriter;
024:        import java.io.FilenameFilter;
025:        import java.io.IOException;
026:        import java.io.InputStream;
027:        import java.io.InputStreamReader;
028:        import java.io.OutputStreamWriter;
029:        import java.io.UnsupportedEncodingException;
030:        import java.util.ArrayList;
031:        import java.util.Enumeration;
032:        import java.util.Iterator;
033:        import java.util.List;
034:        import java.util.Random;
035:        import java.util.jar.JarFile;
036:        import java.util.logging.Level;
037:        import java.util.logging.Logger;
038:        import java.util.regex.Matcher;
039:        import java.util.regex.Pattern;
040:        import java.util.zip.ZipEntry;
041:
042:        import org.jdom.Document;
043:        import org.jdom.Element;
044:        import org.jdom.input.SAXBuilder;
045:
046:        import com.sun.portal.log.common.PortalLogger;
047:        import com.sun.portal.util.FileWildFilter;
048:        import com.sun.portal.util.Platform;
049:
050:        public class FileUtil {
051:            public static final int DELETE_FIRST_OCCURANCE = 1;
052:            public static final int DELETE_ALL_OCCURANCES = 2;
053:            public static final int DELETE_FIRST_OCCURANCE_STARTING_WITH = 3;
054:            public static final int DELETE_ALL_OCCURANCES_STARTING_WITH = 4;
055:
056:            public static final int APPEND_FIRST_OCCURANCE = 5;
057:            public static final int APPEND_ALL_OCCURANCES = 6;
058:            public static final int APPEND_FIRST_OCCURANCE_STARTING_WITH = 7;
059:            public static final int APPEND_ALL_OCCURANCES_STARTING_WITH = 8;
060:
061:            public static final int REPLACE_FIRST_OCCURANCE = 9;
062:            public static final int REPLACE_ALL_OCCURANCES = 10;
063:            public static final int REPLACE_FIRST_OCCURANCE_STARTING_WITH = 11;
064:            public static final int REPLACED_ALL_OCCURANCES_STARTING_WITH = 12;
065:
066:            private static Logger logger = PortalLogger
067:                    .getLogger(FileUtil.class);
068:
069:            private static boolean isWinOS = System.getProperty("os.name")
070:                    .indexOf("indows") > 0;
071:            private static ExecuteUtil execUtil = new ExecuteUtil();
072:
073:            /**
074:             * Public methods
075:             */
076:
077:            public static void debug(String str) {
078:                System.out.println(str);
079:            }
080:
081:            public static FilenameFilter getExtensionFilter(String ext) {
082:                FileWildFilter filter = FileWildFilter.getExtensionFilter(ext,
083:                        FileWildFilter.ALL);
084:                return (FilenameFilter) filter;
085:            }
086:
087:            public static boolean getFiles(File dir, List files) {
088:
089:                return getFiles(dir, files, null);
090:            }
091:
092:            public static boolean getFiles(File dir, List files, String ext) {
093:
094:                if ((dir == null) || !dir.exists() || (files == null)) {
095:
096:                    return false;
097:                }
098:
099:                FilenameFilter sExtFilter = FileWildFilter.getExtensionFilter(
100:                        ext, FileWildFilter.ONLY_FILE);
101:
102:                File[] fFileList = dir.listFiles(sExtFilter);
103:
104:                for (int i = 0; i < fFileList.length; i++) {
105:
106:                    File file = (File) fFileList[i];
107:                    if (file.isFile()) {
108:                        files.add(file);
109:                    }
110:                }
111:
112:                FilenameFilter sDirFilter = FileWildFilter.getDirectoryFilter();
113:                File[] fDirList = dir.listFiles(sDirFilter);
114:                boolean bRetCode = true;
115:                for (int i = 0; i < fDirList.length; i++) {
116:
117:                    File file = (File) fDirList[i];
118:                    bRetCode = getFiles(file, files, ext);
119:                    if (!bRetCode) {
120:
121:                        break;
122:                    }
123:                }
124:
125:                return bRetCode;
126:            }
127:
128:            public static boolean copyFile(String fromFilename,
129:                    String toFilename) {
130:                return copyFile(new File(fromFilename), new File(toFilename),
131:                        false);
132:            }
133:
134:            public static boolean copyFile(File fromFile, File toFile) {
135:                return copyFile(fromFile, toFile, false);
136:            }
137:
138:            public static boolean fileExists(String fileName) {
139:                try {
140:                    File file = new File(fileName);
141:                    return file.isFile();
142:                } catch (Exception e) {
143:                    return false;
144:                }
145:            }
146:
147:            public static boolean directoryExists(String dirName) {
148:                try {
149:                    File file = new File(dirName);
150:                    return file.isDirectory();
151:                } catch (Exception e) {
152:                    return false;
153:                }
154:            }
155:
156:            public static boolean makeDir(String dirName) {
157:                File dir = new File(dirName);
158:                return dir.exists() ? true : dir.mkdirs();
159:            }
160:
161:            public static boolean copyDir(String fromDirName, String toDirName) {
162:                return copyDir(fromDirName, toDirName, true);
163:            }
164:
165:            public static boolean copyDir(String fromDirName, String toDirName,
166:                    boolean resolveLinks) {
167:                try {
168:                    File fromDir = new File(fromDirName);
169:                    fromDirName = fromDir.getCanonicalPath();
170:
171:                    File toDir = new File(toDirName);
172:                    toDirName = toDir.getCanonicalPath();
173:
174:                    List files = new ArrayList();
175:                    if (!getFiles(fromDir, files)) {
176:                        return false;
177:                    }
178:
179:                    if (!makeDir(toDirName)) {
180:                        return false;
181:                    }
182:
183:                    for (int i = 0; i < files.size(); i++) {
184:                        File from = (File) files.get(i);
185:                        String fromName = null;
186:                        //if links have to be resolved use getCanonicalPath else use getAbsolutePath
187:                        if (resolveLinks == true)
188:                            fromName = from.getCanonicalPath();
189:                        if (resolveLinks == false)
190:                            fromName = from.getAbsolutePath();
191:
192:                        String relativeName = fromName.substring(fromDirName
193:                                .length(), fromName.length());
194:                        String destName = toDirName + relativeName;
195:
196:                        if (from.isFile()) {
197:                            if (!copyFile(from, new File(destName), false)) {
198:                                return false;
199:                            }
200:                        } else if (from.isDirectory()) {
201:                            if (!makeDir(destName)) {
202:                                return false;
203:                            }
204:                        }
205:                    }
206:                    return true;
207:                } catch (Exception e) {
208:                    return false;
209:                }
210:            }
211:
212:            public static boolean deleteDir(String dirName) {
213:                return deleteDir(new File(dirName));
214:            }
215:
216:            public static boolean deleteDir(File dir) {
217:                if (dir.isDirectory()) {
218:                    File[] files = dir.listFiles();
219:                    for (int i = 0; i < files.length; i++) {
220:                        File file = (File) files[i];
221:                        if (file.isFile()) {
222:                            if (!file.delete()) {
223:                                return false;
224:                            }
225:                        } else if (file.isDirectory()) {
226:                            if (!deleteDir(file)) {
227:                                return false;
228:                            }
229:                        }
230:                    }
231:                }
232:
233:                return dir.delete();
234:            }
235:
236:            public static boolean appendLineInFile(File file, String pattern,
237:                    String text) {
238:                return appendLineInFile(file, pattern, text,
239:                        APPEND_ALL_OCCURANCES);
240:            }
241:
242:            public static boolean appendLineInFile(File file, String pattern,
243:                    String text, int mode) {
244:                boolean appendDone = false;
245:
246:                try {
247:                    File tmpFile = File.createTempFile("appendlineinfile",
248:                            ".tmp");
249:
250:                    BufferedReader in = getUTF8BufferedReader(file);
251:                    BufferedWriter out = getUTF8BufferedWriter(tmpFile);
252:
253:                    String line = null;
254:                    while ((line = in.readLine()) != null) {
255:                        out.write(line);
256:                        out.newLine();
257:
258:                        int index = line.indexOf(pattern);
259:                        boolean startsWithIndex = line.trim().startsWith(
260:                                pattern);
261:                        if (index >= 0) {
262:                            switch (mode) {
263:                            case APPEND_FIRST_OCCURANCE:
264:                                if (appendDone == false) {
265:                                    out.write(text.toString());
266:                                    out.newLine();
267:                                    appendDone = true;
268:                                }
269:                                ;
270:                                break;
271:                            case APPEND_ALL_OCCURANCES:
272:                                out.write(text.toString());
273:                                out.newLine();
274:                                break;
275:                            case APPEND_FIRST_OCCURANCE_STARTING_WITH:
276:                                if (appendDone == false
277:                                        && startsWithIndex == true) {
278:                                    out.write(text.toString());
279:                                    out.newLine();
280:                                    appendDone = true;
281:                                }
282:                                ;
283:                                break;
284:                            case APPEND_ALL_OCCURANCES_STARTING_WITH:
285:                                if (startsWithIndex == true) {
286:                                    out.write(text.toString());
287:                                    out.newLine();
288:                                }
289:                                ;
290:                                break;
291:                            }
292:                        }
293:                    }
294:
295:                    in.close();
296:                    out.close();
297:
298:                    return copyFile(tmpFile, file, true);
299:                } catch (Exception e) {
300:                    return false;
301:                }
302:            }
303:
304:            public static boolean replaceLineInFile(File file, String pattern,
305:                    String text) {
306:                try {
307:                    File tmpFile = File.createTempFile("replacelineinfile",
308:                            ".tmp");
309:
310:                    BufferedReader in = getUTF8BufferedReader(file);
311:                    BufferedWriter out = getUTF8BufferedWriter(tmpFile);
312:
313:                    boolean replaced = false;
314:                    String line = null;
315:                    while ((line = in.readLine()) != null) {
316:                        if (line.indexOf(pattern) >= 0) {
317:                            out.write(text.toString());
318:                            out.newLine();
319:                            replaced = true;
320:                        } else {
321:                            out.write(line);
322:                            out.newLine();
323:                        }
324:                    }
325:
326:                    in.close();
327:                    out.close();
328:
329:                    if (replaced)
330:                        copyFile(tmpFile, file, true);
331:                    else
332:                        tmpFile.delete();
333:
334:                    return replaced;
335:                } catch (Exception e) {
336:                    return false;
337:                }
338:            }
339:
340:            public static boolean deleteLineInFile(File file, String pattern) {
341:                return deleteLineInFile(file, pattern, DELETE_ALL_OCCURANCES);
342:            }
343:
344:            public static boolean deleteLineInFile(File file, String pattern,
345:                    int mode) {
346:                boolean deleteDone = false;
347:
348:                try {
349:                    File tmpFile = File.createTempFile("deletelineinfile",
350:                            ".tmp");
351:
352:                    BufferedReader in = getUTF8BufferedReader(file);
353:                    BufferedWriter out = getUTF8BufferedWriter(tmpFile);
354:
355:                    String line = null;
356:                    while ((line = in.readLine()) != null) {
357:
358:                        int index = line.indexOf(pattern);
359:                        boolean startsWithIndex = line.trim().startsWith(
360:                                pattern);
361:                        switch (mode) {
362:                        case DELETE_FIRST_OCCURANCE:
363:                            if (deleteDone || index == -1) {
364:                                out.write(line);
365:                                out.newLine();
366:                            } else {
367:                                deleteDone = true;
368:                            }
369:                            ;
370:                            break;
371:                        case DELETE_ALL_OCCURANCES:
372:                            if (index == -1) {
373:                                out.write(line);
374:                                out.newLine();
375:                            }
376:                            ;
377:                            break;
378:                        case DELETE_FIRST_OCCURANCE_STARTING_WITH:
379:                            if (deleteDone || startsWithIndex == false) {
380:                                out.write(line);
381:                                out.newLine();
382:                            } else {
383:                                deleteDone = true;
384:                            }
385:                            ;
386:                            break;
387:                        case DELETE_ALL_OCCURANCES_STARTING_WITH:
388:                            if (startsWithIndex == false) {
389:                                out.write(line);
390:                                out.newLine();
391:                            }
392:                            ;
393:                            break;
394:                        }
395:                    }
396:
397:                    in.close();
398:                    out.close();
399:
400:                    return copyFile(tmpFile, file, true);
401:                } catch (Exception e) {
402:                    return false;
403:                }
404:            }
405:
406:            /**
407:             * Delete section from start token to end token in file.
408:             * If start token is not found, so not delete anything.
409:             * If start token is found, delete every line till end token is found.
410:             * If end token is not found, do not delete anything.
411:             * If token is found in line, the entire line is deleted
412:             * Assume that start and end tokens are in different lines, and end token
413:             * always appears after start token.
414:             * Assume that the section appears only once in the file
415:             * @param file
416:             * @param start - Start token of section.
417:             * @param end - End token of section
418:             * @return true if section found and deleted. false otherwise.
419:             */
420:            public static boolean deleteSectionInFile(File file, String start,
421:                    String end) {
422:                try {
423:                    File tmpFile = File.createTempFile("deletesectioninfile",
424:                            ".tmp");
425:
426:                    BufferedReader in = getUTF8BufferedReader(file);
427:                    BufferedWriter out = getUTF8BufferedWriter(tmpFile);
428:
429:                    String line = null;
430:                    boolean isSection = false;
431:                    boolean isSectionValid = false;
432:
433:                    while ((line = in.readLine()) != null) {
434:                        if (!isSection && line.indexOf(start) >= 0) {
435:                            //found start token
436:                            isSection = true;
437:                        }
438:
439:                        if (!isSection) {
440:                            out.write(line);
441:                            out.newLine();
442:                        }
443:
444:                        if (isSection && line.indexOf(end) >= 0) {
445:                            //found end token
446:                            //the section is valid since we have already found start token
447:                            isSectionValid = true;
448:                            isSection = false;
449:                        }
450:                    }
451:                    in.close();
452:                    out.close();
453:
454:                    if (isSectionValid) {
455:                        return copyFile(tmpFile, file, true);
456:                    }
457:                } catch (Exception e) {
458:                    return false;
459:                }
460:                return false;
461:            }
462:
463:            public static boolean appendToFile(File file, String text,
464:                    boolean checkIfExists) {
465:                try {
466:                    File tmpFile = File.createTempFile("appendlineeof", ".tmp");
467:
468:                    BufferedReader in = getUTF8BufferedReader(file);
469:                    BufferedWriter out = getUTF8BufferedWriter(tmpFile);
470:
471:                    boolean found = false;
472:
473:                    String line;
474:                    while ((line = in.readLine()) != null) {
475:                        if (checkIfExists) {
476:                            if (line.equals(text)) {
477:                                found = true;
478:                            }
479:                        }
480:                        out.write(line);
481:                        out.newLine();
482:                    }
483:                    in.close();
484:
485:                    if (!found) {
486:                        out.write(text);
487:                        out.newLine();
488:                    }
489:
490:                    out.close();
491:
492:                    return copyFile(tmpFile, file, true);
493:                } catch (Exception e) {
494:                    return false;
495:                }
496:            }
497:
498:            public static String findTextInFile(File file, String text) {
499:                try {
500:                    BufferedReader in = new BufferedReader(
501:                            new InputStreamReader(new FileInputStream(file),
502:                                    "UTF-8"));
503:
504:                    String line;
505:                    while ((line = in.readLine()) != null) {
506:                        if (line.indexOf(text) >= 0) {
507:                            in.close();
508:                            return line;
509:                        }
510:                    }
511:                    in.close();
512:                    return "";
513:                } catch (Exception e) {
514:                    return "";
515:                }
516:            }
517:
518:            /**
519:             * Returns first line in file that matches pattern
520:             * If pattern not found  returns null
521:             * @param file
522:             * @param pattern - regex defining pattern to be matched
523:             * @return
524:             */
525:            public static String findPatternInFile(File file, String pattern) {
526:                try {
527:                    BufferedReader in = new BufferedReader(
528:                            new InputStreamReader(new FileInputStream(file),
529:                                    "UTF-8"));
530:
531:                    String line;
532:                    while ((line = in.readLine()) != null) {
533:                        if (line.matches(pattern)) {
534:                            in.close();
535:                            return line;
536:                        }
537:                    }
538:                    in.close();
539:                } catch (Exception e) {
540:                    logger.log(Level.SEVERE, "PSFB_CSPFU0050", e);
541:                }
542:                return null;
543:            }
544:
545:            public static boolean replaceTokenInFile(File origFile,
546:                    File newFile, String token, String value) {
547:                return replaceTokensInFile(origFile, newFile,
548:                        new String[] { token }, new String[] { value });
549:            }
550:
551:            public static boolean replaceTokenInFile(File file, String token,
552:                    String value) {
553:                return replaceTokensInFile(file, file, new String[] { token },
554:                        new String[] { value });
555:            }
556:
557:            public static boolean replaceTokensInFile(File file,
558:                    String[] tokens, String[] values) {
559:                return replaceTokensInFile(file, file, tokens, values);
560:            }
561:
562:            private static boolean replaceTokensInFile(File origFile,
563:                    File newFile, String[] tokens, String[] values) {
564:                try {
565:                    File tmpFile = File.createTempFile("replacetokeninfile",
566:                            ".tmp");
567:
568:                    BufferedReader in = getUTF8BufferedReader(origFile);
569:                    BufferedWriter out = getUTF8BufferedWriter(tmpFile);
570:
571:                    Pattern[] p = new Pattern[tokens.length];
572:                    for (int i = 0; i < tokens.length; ++i) {
573:                        p[i] = Pattern.compile(tokens[i]);
574:                    }
575:
576:                    String line;
577:                    while ((line = in.readLine()) != null) {
578:                        for (int i = 0; i < tokens.length; ++i) {
579:                            Matcher m = p[i].matcher(line);
580:                            if (m.find()) {
581:                                line = m.replaceAll(values[i]);
582:                            }
583:                        }
584:                        out.write(line);
585:                        out.newLine();
586:                    }
587:
588:                    in.close();
589:                    out.close();
590:
591:                    return copyFile(tmpFile, newFile, true);
592:                } catch (Exception e) {
593:                    return false;
594:                }
595:            }
596:
597:            public static String replaceToken(String str, String token,
598:                    String value) {
599:                Pattern p = Pattern.compile(token);
600:                Matcher m = p.matcher(str);
601:                if (m.find()) {
602:                    str = m.replaceAll(value);
603:                }
604:                return str;
605:            }
606:
607:            public static String decoratePath(String path) {
608:                if (System.getProperty("os.name").indexOf("indows") != -1) {
609:                    if (path != null && path.indexOf(' ') >= 0) {
610:                        StringBuffer quotedPath = new StringBuffer("\"" + path
611:                                + "\"");
612:                        return quotedPath.toString();
613:                    }
614:                }
615:                return path;
616:            }
617:
618:            /**
619:             * @return a random number string which is 8 digits or less in length
620:             */
621:            public static String getRandomDirName() {
622:                Random random = new Random();
623:                String name = "" + Math.abs(random.nextInt());
624:                return name.substring(0, Math.min(8, name.length()));
625:            }
626:
627:            /**
628:             * @return a random number string which is 8 digits or less in length
629:             */
630:            public static String getRandomString() {
631:                Random random = new Random();
632:                String name = "" + Math.abs(random.nextInt());
633:                return name.substring(0, Math.min(8, name.length()));
634:            }
635:
636:            /*
637:             ** Private methods
638:             */
639:
640:            private static byte[] getByteData(InputStream is) {
641:                ByteArrayOutputStream os = new ByteArrayOutputStream();
642:                try {
643:                    byte[] byteBuf = new byte[1024];
644:                    int num = 0;
645:                    while ((num = is.read(byteBuf)) != -1) {
646:                        os.write(byteBuf, 0, num);
647:                    }
648:                } catch (Exception e) {
649:                    logger.log(Level.SEVERE, "PSFB_CSPFU0052", e);
650:                }
651:                return os.toByteArray();
652:            }
653:
654:            public static boolean copyFile(File fromFile, File toFile,
655:                    boolean deleteSourceFile) {
656:
657:                try {
658:
659:                    File parent = toFile.getParentFile();
660:                    if (parent != null) {
661:                        parent.mkdirs();
662:                    }
663:
664:                    FileInputStream fis = new FileInputStream(fromFile);
665:                    byte[] b = getByteData(fis);
666:                    fis.close();
667:
668:                    FileOutputStream fout = new FileOutputStream(toFile);
669:                    fout.write(b);
670:                    fout.close();
671:
672:                    return deleteSourceFile ? fromFile.delete() : true;
673:                } catch (Exception e) {
674:                    return false;
675:                }
676:            }
677:
678:            public static File extractFileFromJar(String jarPath,
679:                    String filePath) throws IOException, FileNotFoundException {
680:                return extractFileFromJar(jarPath, filePath, true);
681:            }
682:
683:            public static File extractFileFromJar(String jarPath,
684:                    String filePath, boolean keepFileAfterExist)
685:                    throws IOException, FileNotFoundException {
686:                JarFile jar = new JarFile(jarPath);
687:                ZipEntry entry = jar.getEntry(filePath);
688:                if (null == entry)
689:                    throw new FileNotFoundException("file:" + filePath
690:                            + " not in jar file:" + jarPath);
691:                InputStream inputstream = jar.getInputStream(entry);
692:                int leafIdx = filePath.lastIndexOf(Platform.fs);
693:                if (leafIdx < 0)
694:                    leafIdx = -1;
695:
696:                String fileName = filePath.substring(leafIdx + 1);
697:                int extIdx = fileName.indexOf('.');
698:                String pfx = (extIdx > 0) ? fileName.substring(0, extIdx)
699:                        : fileName;
700:                String sfx = (extIdx > 0) ? fileName.substring(extIdx + 1)
701:                        : null;
702:                File extract = File.createTempFile(pfx, sfx);
703:                if (!keepFileAfterExist)
704:                    extract.deleteOnExit();
705:                FileOutputStream fileoutputstream = new FileOutputStream(
706:                        extract);
707:                int length = 0;
708:                byte buffer[] = new byte[2048];
709:                while (-1 != length) {
710:                    length = inputstream.read(buffer);
711:                    if (length > 0)
712:                        fileoutputstream.write(buffer, 0, length);
713:                }
714:                inputstream.close();
715:                fileoutputstream.close();
716:                jar.close();
717:                return extract;
718:            }
719:
720:            public static void extractJar(String jarPath, String targetPath)
721:                    throws IOException {
722:                JarFile jar = new JarFile(jarPath);
723:
724:                for (Enumeration e = jar.entries(); e.hasMoreElements();) {
725:                    ZipEntry entry = (ZipEntry) e.nextElement();
726:                    if (entry.isDirectory()) {
727:                        FileUtil.makeDir(targetPath + Platform.fs
728:                                + entry.getName());
729:                    } else {
730:                        InputStream inputstream = jar.getInputStream(entry);
731:                        File extract = new File(targetPath + Platform.fs
732:                                + entry.getName());
733:                        FileOutputStream fileoutputstream = new FileOutputStream(
734:                                extract);
735:                        int length = 0;
736:                        byte buffer[] = new byte[2048];
737:                        while (-1 != length) {
738:                            length = inputstream.read(buffer);
739:                            if (length > 0)
740:                                fileoutputstream.write(buffer, 0, length);
741:                        }
742:                        inputstream.close();
743:                        fileoutputstream.close();
744:                    }
745:                }
746:                jar.close();
747:            }
748:
749:            public static String extractPatternTillEOL(File file, String key,
750:                    String separator) {
751:                String rline = "";
752:                String answer = "";
753:                try {
754:
755:                    BufferedReader inBuff = getUTF8BufferedReader(file);
756:
757:                    while ((rline = inBuff.readLine()) != null) {
758:                        if (rline.indexOf(key) >= 0) {
759:                            answer = rline
760:                                    .substring(rline.indexOf(separator) + 1);
761:                            answer = answer.trim();
762:                            break;
763:                        }
764:                    }
765:                } catch (Exception e) {
766:                    debug("Error in extracting pattern.");
767:                }
768:                return answer;
769:            }
770:
771:            /**
772:             * Read an xml file into an xml document (org.jdom.Document) and return
773:             * the request attribute value, given an xpath.
774:             */
775:            public static String getAttributeValue(final File sXMLFile,
776:                    String xpath, String attr) {
777:                String attrValue = "";
778:                String[] childElements = xpath.split(Platform.fs);
779:                try {
780:                    SAXBuilder builder = new SAXBuilder();
781:                    builder.setValidation(false);
782:                    Document doc = builder.build(sXMLFile);
783:
784:                    Element current = doc.getRootElement();
785:
786:                    String name = "";
787:                    List children = null;
788:                    Iterator iterator = null;
789:
790:                    for (int i = 0; i < childElements.length; i++) {
791:                        children = current.getChildren();
792:                        iterator = children.iterator();
793:                        while (iterator.hasNext()) {
794:                            Element child = (Element) iterator.next();
795:                            name = child.getName();
796:                            if (name.equals(childElements[i])) {
797:                                current = child;
798:                                break;
799:                            }
800:                        }
801:                    }
802:                    attrValue = current.getAttributeValue(attr);
803:                } catch (IOException e) {
804:                    //Do something...
805:                } catch (org.jdom.JDOMException e) {
806:                    //Do something...
807:                }
808:                return attrValue;
809:            }
810:
811:            /**
812:             * Creates a file of random name after writing the data
813:             */
814:
815:            public static String createPasswordFile(String data) {
816:
817:                File passwordFile;
818:                String passwordFilePath = null;
819:
820:                Random randomNo = new Random();
821:                StringBuffer fileData = new StringBuffer();
822:                fileData.append(data);
823:
824:                try {
825:                    passwordFile = File.createTempFile(
826:                            "" + randomNo.nextLong(), "" + randomNo.nextLong());
827:                    passwordFilePath = passwordFile.getAbsolutePath();
828:                    FileWriter fwriter = new FileWriter(passwordFile);
829:                    fwriter.write(fileData.toString());
830:                    fwriter.close();
831:                } catch (IOException ioe) {
832:                    logger.log(Level.INFO, "PSFB_CSPFU0051", ioe);
833:                }
834:                return passwordFilePath;
835:            }
836:
837:            /**
838:             * Searches for key with quoted value in text and returns value
839:             * @param key
840:             * @param text
841:             * @return value without quotes
842:             */
843:            public static String getQuotedKeyValueInText(String key, String text) {
844:                //if text is null return null
845:                if (text == null || text.equals("")) {
846:                    return null;
847:                }
848:                int idx = text.indexOf(key);
849:                if (idx >= 0) {
850:                    String keyValStr = text.substring(idx);
851:                    String keyQuotedValSepRegex = "=\\s*\"|\"\\s+";
852:                    String[] tokens = keyValStr.split(keyQuotedValSepRegex, 3);
853:                    if (tokens.length >= 2) {
854:                        //return value
855:                        return tokens[1];
856:                    }
857:                }
858:                //if key is not not found in text return null
859:                return null;
860:            }
861:
862:            /**
863:             * Changes the permissions of the given file to the given
864:             * permissions.  On UNIX systems, permissions can either be in
865:             * string (symbolic) mode or octal numbers.  However, on Microsoft
866:             * Windows systems, permissions must be in octal numbers.  In
867:             * addition, group and other permissions must not be set
868:             * (i.e. permssions must be in the form "x00").
869:             *
870:             * @param  file  the file where its permssions are to be changed.
871:             * @param  permissions  the permssions of the file to be changed to.
872:             */
873:            public static void changeFilePermissions(String file,
874:                    String permissions) {
875:                if (!isWinOS) {
876:                    execUtil.exec("chmod", new String[] { permissions, file });
877:                } else if (permissions.endsWith("00")) {
878:                    String permission = "n";
879:
880:                    if (permissions.startsWith("2")
881:                            || permissions.startsWith("3")) {
882:                        permission = "c";
883:                    } else if (permissions.startsWith("4")
884:                            || permissions.startsWith("5")) {
885:                        permission = "r";
886:                    } else if (permissions.startsWith("6")
887:                            || permissions.startsWith("7")) {
888:                        permission = "f";
889:                    }
890:
891:                    execUtil.exec("echo y| cacls", new String[] { file, "/c",
892:                            "/p", "Administrators:" + permission,
893:                            "SYSTEM:" + permission });
894:                }
895:            }
896:
897:            /**
898:             * Changes the permissions of the given file to the given
899:             * permissions.  On UNIX systems, permissions can either be in
900:             * string (symbolic) mode or octal numbers.  However, on Microsoft
901:             * Windows systems, permissions must be in octal numbers.  In
902:             * addition, group and other permissions must not be set
903:             * (i.e. permssions must be in the form "x00").
904:             *
905:             * @param  file  the file where its permssions are to be changed.
906:             * @param  permissions  the permssions of the file to be changed to.
907:             */
908:            public static void changeFilePermissions(File file,
909:                    String permissions) {
910:                changeFilePermissions(file.getAbsolutePath(), permissions);
911:            }
912:
913:            /* Start - L10N Code Change */
914:
915:            /**
916:             * Gets Buffered Reader initialized with UTF-8 encoding
917:             * @param File Object from which data needs to be read.
918:             * @return BufferedReader Object initialized with UTF-8 encoding
919:             */
920:            public static BufferedReader getUTF8BufferedReader(File fileName) {
921:                try {
922:                    return new BufferedReader(new InputStreamReader(
923:                            new FileInputStream(fileName), "UTF-8"));
924:                } catch (UnsupportedEncodingException ex) {
925:                    logger.log(Level.INFO, ex.getMessage());
926:                    ex.printStackTrace();
927:                } catch (FileNotFoundException ex) {
928:                    logger.log(Level.INFO, ex.getMessage());
929:                    ex.printStackTrace();
930:                }
931:                return null;
932:            }
933:
934:            /**
935:             * Gets Buffered Writer intialized UTF-8 encoding
936:             * @param File Object to which data needs to be read.
937:             * @return BufferedWriter Object initialized with UTF-8 encoding
938:             */
939:            public static BufferedWriter getUTF8BufferedWriter(File fileName) {
940:                try {
941:                    return new BufferedWriter(new OutputStreamWriter(
942:                            new FileOutputStream(fileName), "UTF-8"));
943:                } catch (UnsupportedEncodingException ex) {
944:                    logger.log(Level.INFO, ex.getMessage());
945:                    ex.printStackTrace();
946:                } catch (FileNotFoundException ex) {
947:                    logger.log(Level.INFO, ex.getMessage());
948:                    ex.printStackTrace();
949:                }
950:                return null;
951:            }
952:
953:            /* End - L10N Code Change */
954:
955:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.