001: package org.contineo.core;
002:
003: import java.io.BufferedInputStream;
004: import java.io.BufferedOutputStream;
005: import java.io.File;
006: import java.io.FileOutputStream;
007: import java.util.Enumeration;
008: import java.util.jar.JarEntry;
009: import java.util.jar.JarFile;
010:
011: import org.apache.commons.logging.Log;
012: import org.apache.commons.logging.LogFactory;
013:
014: /**
015: * This class is for handling with jar-files.
016: *
017: * @author Michael Scholz
018: * @version 1.0
019: */
020: public class JarBean {
021: /**
022: * This method extracts all entries of a jar-file.
023: *
024: * @param jarsource Path of the jar-file.
025: * @param target Path of the extracted files.
026: * @return True if successfully extracted.
027: */
028: public static boolean unjar(String jarsource, String target) {
029: boolean result = true;
030:
031: try {
032: if (!target.endsWith("/")) {
033: target = target + "/";
034: }
035:
036: JarFile jar = new JarFile(jarsource);
037: JarEntry jare;
038:
039: for (Enumeration enum1 = jar.entries(); enum1
040: .hasMoreElements(); saveEntry(jar, jare, target)) {
041: jare = (JarEntry) enum1.nextElement();
042: }
043: } catch (Exception e) {
044: result = false;
045: logError(e.getMessage());
046: }
047:
048: return result;
049: } // end method unjar
050:
051: /**
052: * This method extracts one entry of a jar-file.
053: *
054: * @param jarsource Path of the jar-file.
055: * @param target Path of the extracted files.
056: * @param entry Name of the entry to be extracted.
057: * @return True if successfully extracted.
058: */
059: public static boolean unjar(String jarsource, String target,
060: String entry) {
061: boolean result = true;
062:
063: try {
064: if (!target.endsWith("/")) {
065: target = target + "/";
066: }
067:
068: JarFile jar = new JarFile(jarsource);
069: JarEntry jare = new JarEntry(entry);
070: saveEntry(jar, jare, target);
071: } catch (Exception e) {
072: result = false;
073: logError(e.getMessage());
074: }
075:
076: return result;
077: } // end method unjar
078:
079: private static void saveEntry(JarFile jar, JarEntry jare,
080: String target) throws Exception {
081: File file = new File(target + jare.getName());
082:
083: if (jare.isDirectory()) {
084: file.mkdirs();
085: } else {
086: java.io.InputStream is = jar.getInputStream(jare);
087: BufferedInputStream bis = new BufferedInputStream(is);
088: File dir = new File(file.getParent());
089: dir.mkdirs();
090:
091: FileOutputStream fos = new FileOutputStream(file);
092: BufferedOutputStream bos = new BufferedOutputStream(fos);
093:
094: for (int letter = 0; (letter = bis.read()) != -1;) {
095: bos.write((byte) letter);
096: }
097:
098: bos.close();
099: fos.close();
100: bis.close();
101: }
102: }
103:
104: private static void logError(String message) {
105: Log logger = LogFactory.getLog(JarBean.class);
106: logger.error(message);
107: }
108: }
|