Java Code Examples for java.util.zip.ZipEntry

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project aws-toolkit-for-eclipse, under directory /com.amazonaws.eclipse.sdk.ui/src/com/amazonaws/eclipse/sdk/ui/.

Source file: SdkInstall.java

  33 
vote

/** 
 * Returns version release notes pertaining to this particular version of the SDK
 * @return The version notes pertaining to this SDK install.
 */
public String getVersionNotes(){
  try {
    JarFile jarFile=new JarFile(getSdkJar());
    ZipEntry zipEntry=jarFile.getEntry(VERSION_INFO_PROPERTIES_PATH);
    Properties properties=new Properties();
    properties.load(jarFile.getInputStream(zipEntry));
    if (properties.containsKey("notes")) {
      return properties.getProperty("notes");
    }
  }
 catch (  IOException e) {
  }
  return "Could not find any version notes for this version of the SDK.";
}
 

Example 2

From project apb, under directory /modules/apb-base/src/apb/tasks/.

Source file: JarTask.java

  32 
vote

private void writeManifest(JarOutputStream jarOut) throws IOException {
  ZipEntry e=new ZipEntry(JarFile.MANIFEST_NAME);
  jarOut.putNextEntry(e);
  manifest.write(new BufferedOutputStream(jarOut));
  jarOut.closeEntry();
}
 

Example 3

From project Application-Builder, under directory /src/main/java/org/silverpeas/applicationbuilder/.

Source file: WriteOnlyArchive.java

  32 
vote

/** 
 * Adds an XML file in the archive by the means of streams.
 * @param xmlDoc the XML document to add in the archive
 * @since 1.0
 * @roseuid 3AAF4D630303
 */
public void add(XmlDocument xmlDoc) throws AppBuilderException {
  try {
    addDirectory(xmlDoc.getLocation());
    ZipEntry entry=getNormalizedEntry(xmlDoc.getArchivePath());
    entry.setSize(xmlDoc.getDocumentSize());
    jarOut.putNextEntry(entry);
    xmlDoc.saveTo(getOutputStream());
    getOutputStream().flush();
    getOutputStream().closeEntry();
  }
 catch (  Exception e) {
    throw new AppBuilderException(getName() + " : impossible to add the document \"" + xmlDoc.getArchivePath()+ "\"",e);
  }
}
 

Example 4

From project as3-commons-jasblocks, under directory /src/test/java/org/as3commons/asblocks/impl/.

Source file: TestSWCResourceRoot.java

  32 
vote

private void createTextSWC(File file) throws FileNotFoundException, IOException {
  ZipEntry catalogEntry=new ZipEntry("catalog.xml");
  FileOutputStream out=new FileOutputStream(file);
  file.deleteOnExit();
  ZipOutputStream zip=new ZipOutputStream(out);
  zip.putNextEntry(catalogEntry);
  OutputStreamWriter writer=new OutputStreamWriter(zip);
  writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<swc xmlns=\"http://www.adobe.com/flash/swccatalog/9\">" + "  <versions>"+ "    <swc version=\"1.0\"/>"+ "    <flex version=\"2.0\" build=\"0\"/>"+ "  </versions>"+ "  <features>"+ "    <feature-script-deps/>"+ "    <feature-components/>"+ "    <feature-files/>"+ "  </features>"+ "  <libraries>"+ "    <library path=\"library.swf\">"+ "      <script name=\"EventWrecker\" mod=\"1234567890123\">"+ "        <def id=\"flashy.events:EventWrecker\"/>"+ "        <def id=\"NoPackage\"/>"+ "        <dep id=\"Object\" type=\"i\"/>"+ "      </script>"+ "    </library>"+ "  </libraries>"+ "  <files>"+ "  </files>"+ "</swc>");
  writer.flush();
  zip.close();
}
 

Example 5

From project Baseform-Epanet-Java-Library, under directory /src/org/addition/epanet/util/.

Source file: XLSXWriter.java

  32 
vote

private void createWorksheet(Spreadsheet sheet,int pos) throws IOException {
  sheet.close();
  ZipEntry entry=new ZipEntry("xl/worksheets/sheet" + pos + ".xml");
  zos.putNextEntry(entry);
  zos.write(("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + "<worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">\n" + "<sheetData>\n").getBytes("UTF-8"));
  BufferedInputStream bis=new BufferedInputStream(new FileInputStream(sheet.getTmpFile()));
  IOUtils.copy(bis,zos);
  bis.close();
  zos.write(("</sheetData>\n" + "</worksheet>\n").getBytes("UTF-8"));
  zos.closeEntry();
}
 

Example 6

From project bndtools, under directory /bndtools.jareditor/src/bndtools/jareditor/internal/.

Source file: JAREntryPart.java

  32 
vote

public void selectionChanged(IFormPart part,ISelection selection){
  if (selection instanceof IStructuredSelection) {
    Object element=((IStructuredSelection)selection).getFirstElement();
    ZipEntry entry=null;
    if (element instanceof ZipEntry)     entry=(ZipEntry)element;
 else     if (element instanceof ZipTreeNode)     entry=((ZipTreeNode)element).getZipEntry();
    this.zipEntry=entry;
  }
 else {
    this.zipEntry=null;
  }
  loadContent();
}
 

Example 7

From project bundlemaker, under directory /main/org.bundlemaker.core.osgi/src/org/bundlemaker/core/osgi/utils/.

Source file: ManifestUtils.java

  32 
vote

/** 
 * <p> </p>
 * @param jarFile
 * @return
 * @throws IOException
 */
public static ManifestContents readManifestContents(JarFile jarFile) throws IOException {
  ZipEntry zipEntry=jarFile.getEntry("META-INF/MANIFEST.MF");
  if (zipEntry != null) {
    InputStream inputStream=jarFile.getInputStream(zipEntry);
    RecoveringManifestParser recoveringManifestParser=new RecoveringManifestParser();
    recoveringManifestParser.parse(new InputStreamReader(inputStream));
    return recoveringManifestParser.getManifestContents();
  }
 else {
    return toManifestContents(BundleManifestFactory.createBundleManifest());
  }
}
 

Example 8

From project Catroid-maven-playground, under directory /src/main/java/at/tugraz/ist/catroid/utils/.

Source file: UtilZip.java

  32 
vote

private static void writeFileToZip(File file,String zipEntryPath) throws IOException {
  byte[] readBuffer=new byte[Constants.BUFFER_8K];
  int bytesIn=0;
  FileInputStream fis=new FileInputStream(file);
  ZipEntry anEntry=new ZipEntry(zipEntryPath + file.getName());
  zipOutputStream.putNextEntry(anEntry);
  while ((bytesIn=fis.read(readBuffer)) != -1) {
    zipOutputStream.write(readBuffer,0,bytesIn);
  }
  zipOutputStream.closeEntry();
  fis.close();
}
 

Example 9

From project cdk, under directory /maven-resources-plugin/src/main/java/org/richfaces/cdk/vfs/zip/.

Source file: ZipVFSFile.java

  32 
vote

@Override public InputStream getInputStream() throws IOException {
  ZipEntry entry=zipNode.getZipEntry();
  if (entry != null) {
    return zipFile.getInputStream(entry);
  }
  throw new IOException("Input stream isn't available!");
}
 

Example 10

From project ceres, under directory /ceres-core/src/main/java/com/bc/ceres/core/.

Source file: VirtualDir.java

  32 
vote

private ZipEntry getEntry(String path) throws FileNotFoundException {
  ZipEntry zipEntry=zipFile.getEntry(path);
  if (zipEntry == null) {
    throw new FileNotFoundException(zipFile.getName() + "!" + path);
  }
  return zipEntry;
}
 

Example 11

From project cloudbees-api-client, under directory /cloudbees-api-client/src/main/java/com/cloudbees/upload/.

Source file: ArchiveUtils.java

  32 
vote

public static Map<String,Long> getCheckSums(String archiveFile) throws IOException {
  Map<String,Long> checkSums=new HashMap<String,Long>();
  ZipFile zipFile=new ZipFile(archiveFile);
  Enumeration<? extends ZipEntry> e=zipFile.entries();
  while (e.hasMoreElements()) {
    ZipEntry entry=e.nextElement();
    checkSums.put(entry.getName(),entry.getCrc());
  }
  return checkSums;
}
 

Example 12

From project core_3, under directory /src/main/java/org/animotron/bridge/.

Source file: AbstractZipBridge.java

  32 
vote

public void load(File file) throws IOException {
  if (!file.exists()) {
    return;
  }
  FileInputStream fis=new FileInputStream(file);
  ZipInputStream zis=new ZipInputStream(new BufferedInputStream(fis));
  ZipEntry entry;
  while ((entry=zis.getNextEntry()) != null) {
    loadEntry(zis,entry);
  }
  zis.close();
}
 

Example 13

From project discovery, under directory /src/main/java/com/tacitknowledge/util/discovery/.

Source file: ArchiveResourceListSource.java

  32 
vote

/** 
 * Returns a list of file resources contained in the specified directory within a given Zip'd archive file.
 * @param file the zip file containing the resources to return
 * @param root the directory within the zip file containing the resources
 * @return a list of file resources contained in the specified directorywithin a given Zip'd archive file
 */
private List getResources(ZipFile file,String root){
  List resourceNames=new ArrayList();
  Enumeration e=file.entries();
  while (e.hasMoreElements()) {
    ZipEntry entry=(ZipEntry)e.nextElement();
    String name=entry.getName();
    if (name.startsWith(root) && !(name.indexOf('/') > root.length()) && !entry.isDirectory()) {
      name=new File(name).getPath();
      resourceNames.add(name);
    }
  }
  return resourceNames;
}
 

Example 14

From project droid-comic-viewer, under directory /src/net/robotmedia/acv/comic/.

Source file: ACVComic.java

  32 
vote

@Override protected void setZip(ZipFile zip){
  super.setZip(zip);
  ZipEntry entry=zip.getEntry(METADATA_FILE);
  if (entry == null) {
    entry=zip.getEntry(LEGACY_METADATA_FILE);
  }
  if (entry != null) {
    processMetadata(entry);
  }
}
 

Example 15

From project droidparts, under directory /extra/src/org/droidparts/util/.

Source file: AppUtils2.java

  32 
vote

public long getClassesDexCrc(){
  ZipFile zf;
  try {
    zf=new ZipFile(ctx.getPackageCodePath());
  }
 catch (  IOException e) {
    L.e(e);
    return -1;
  }
  ZipEntry ze=zf.getEntry("classes.dex");
  long crc=ze.getCrc();
  return crc;
}
 

Example 16

From project erjang, under directory /src/main/java/erjang/driver/efile/.

Source file: ClassPathResource.java

  32 
vote

static ZipEntry get_entry(String path) throws IOException {
  String fileName=getResourceName(path);
  Enumeration<URL> out=ClassPathResource.class.getClassLoader().getResources(fileName);
  while (out.hasMoreElements()) {
    URL u=out.nextElement();
    ZipEntry result=get_entry(u);
    if (result != null)     return result;
  }
  return null;
}
 

Example 17

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/generic/.

Source file: FileUtils.java

  31 
vote

public static void unJar(String path,String to,boolean verbose){
  File file=new File(path);
  Utils.console("Starting unjar of: " + file.getAbsolutePath() + File.separator+ "*.jar");
  if (file.exists()) {
    File[] files;
    if (file.isFile()) {
      files=new File[]{file};
    }
 else {
      files=file.listFiles();
    }
    for (int i=0; i < files.length; i++) {
      if (!files[i].isDirectory() && files[i].getName().endsWith("jar")) {
        Utils.console("unJar file: " + files[i].getName() + " ("+ (i + 1)+ "/"+ files.length+ ")");
        try {
          FileInputStream fis=new FileInputStream(files[i]);
          JarInputStream zis=new JarInputStream(new BufferedInputStream(fis));
          ZipEntry entry;
          while ((entry=zis.getNextEntry()) != null) {
            writejarEntry(zis,entry,to,false);
          }
          zis.close();
        }
 catch (        IOException e) {
          Utils.log("unJar error:",e);
        }
      }
    }
  }
 else {
    System.err.println("Failed to create: " + file.getAbsolutePath());
  }
}
 

Example 18

From project activejdbc, under directory /activejdbc-instrumentation/src/main/java/org/javalite/instrumentation/.

Source file: InstrumentationModelFinder.java

  31 
vote

/** 
 * Finds and processes property files inside zip or jar files.
 * @param file zip or jar file.
 */
private void processFilePath(File file){
  try {
    if (file.getCanonicalPath().toLowerCase().endsWith(".jar") || file.getCanonicalPath().toLowerCase().endsWith(".zip")) {
      ZipFile zip=new ZipFile(file);
      Enumeration<? extends ZipEntry> entries=zip.entries();
      while (entries.hasMoreElements()) {
        ZipEntry entry=entries.nextElement();
        if (entry.getName().endsWith("class")) {
          InputStream zin=zip.getInputStream(entry);
          classFound(entry.getName().replace(File.separatorChar,'.').substring(0,entry.getName().length() - 6));
          zin.close();
        }
      }
    }
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
catch (  ClassNotFoundException ignore) {
  }
}
 

Example 19

From project adt-maven-plugin, under directory /src/main/java/com/yelbota/plugins/adt/model/.

Source file: AneModel.java

  31 
vote

public AneModel(File file) throws MojoFailureException {
  this.file=file;
  try {
    ZipInputStream zip=new ZipInputStream(new FileInputStream(file));
    ZipEntry entry=zip.getNextEntry();
    byte[] buf=new byte[1024];
    while (entry != null) {
      if (entry.getName().endsWith("extension.xml")) {
        ByteArrayOutputStream out=new ByteArrayOutputStream();
        int n;
        while ((n=zip.read(buf,0,1024)) > -1)         out.write(buf,0,n);
        parseXml(out.toByteArray());
        break;
      }
      zip.closeEntry();
      entry=zip.getNextEntry();
    }
  }
 catch (  FileNotFoundException e) {
    throw new MojoFailureException(this,"Cant open ANE file " + file.getPath(),e.getLocalizedMessage());
  }
catch (  IOException e) {
    throw new MojoFailureException(this,"Cant read ANE file " + file.getPath(),e.getLocalizedMessage());
  }
}
 

Example 20

From project ALP, under directory /workspace/alp-utils/src/main/java/com/lohika/alp/utils/zip/.

Source file: Zip.java

  31 
vote

/** 
 * Adds file to Zip.
 * @param filePath the file path
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void add(String filePath) throws IOException {
  byte data[]=new byte[BUFFER];
  File f=new File(filePath);
  if (f.isDirectory()) {
    File files[]=f.listFiles();
    for (int i=0; i < files.length; i++) {
      add(files[i].getAbsolutePath());
    }
  }
 else {
    logger.debug("Adding: " + filePath);
    FileInputStream fi=new FileInputStream(filePath);
    BufferedInputStream origin=new BufferedInputStream(fi,BUFFER);
    ZipEntry entry=new ZipEntry(filePath);
    out.putNextEntry(entry);
    int count;
    while ((count=origin.read(data,0,BUFFER)) != -1) {
      out.write(data,0,count);
    }
    origin.close();
  }
  logger.debug("checksum: " + checksum.getChecksum().getValue());
}
 

Example 21

From project and-bible, under directory /jsword-tweaks/src/util/java/net/andbible/util/.

Source file: MJDIndexAll.java

  31 
vote

private void createZipFile(File jarFile,File sourceDir){
  try {
    BufferedInputStream origin=null;
    FileOutputStream dest=new FileOutputStream(jarFile);
    ZipOutputStream out=new ZipOutputStream(new BufferedOutputStream(dest));
    byte data[]=new byte[JAR_BUFFER_SIZE];
    File files[]=sourceDir.listFiles();
    for (int i=0; i < files.length; i++) {
      System.out.println("Adding: " + files[i]);
      FileInputStream fi=new FileInputStream(files[i]);
      origin=new BufferedInputStream(fi,JAR_BUFFER_SIZE);
      ZipEntry entry=new ZipEntry(files[i].getName());
      out.putNextEntry(entry);
      int count;
      while ((count=origin.read(data,0,JAR_BUFFER_SIZE)) != -1) {
        out.write(data,0,count);
      }
      origin.close();
    }
    out.close();
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 22

From project andlytics, under directory /src/com/github/andlyticsproject/io/.

Source file: ImportService.java

  31 
vote

private boolean importStats(){
  String message=getApplicationContext().getString(R.string.import_started);
  sendNotification(message);
  ContentAdapter db=new ContentAdapter(ImportService.this);
  try {
    StatsCsvReaderWriter statsWriter=new StatsCsvReaderWriter(ImportService.this);
    ZipInputStream inzip=new ZipInputStream(new FileInputStream(zipFilename));
    ZipEntry entry=null;
    while ((entry=inzip.getNextEntry()) != null) {
      String filename=entry.getName();
      if (!fileNames.contains(filename)) {
        continue;
      }
      List<AppStats> stats=statsWriter.readStats(inzip);
      if (!stats.isEmpty()) {
        String packageName=stats.get(0).getPackageName();
        message=getApplicationContext().getString(R.string.importing) + " " + packageName;
        sendNotification(message);
        for (        AppStats appStats : stats)         db.insertOrUpdateAppStats(appStats,packageName);
      }
    }
  }
 catch (  Exception e) {
    Log.e(TAG,"Error importing stats: " + e.getMessage());
    error=e;
    errors=true;
  }
  message=getResources().getString(R.string.app_name) + ": " + getApplicationContext().getString(R.string.import_finished);
  sendNotification(message);
  return !errors;
}
 

Example 23

From project Android-FFXIEQ, under directory /ffxieq/src/com/github/kanata3249/ffxieq/android/db/.

Source file: FFXIDatabase.java

  31 
vote

public long getLastModifiedFromAssets() throws IOException {
  InputStream in=mContext.getAssets().open(DB_NAME_ASSET,AssetManager.ACCESS_STREAMING);
  ZipInputStream zipIn=new ZipInputStream(in);
  ZipEntry zipEntry=zipIn.getNextEntry();
  long result;
  result=0;
  while (zipEntry != null) {
    if (zipEntry.getName().equalsIgnoreCase(DB_NAME)) {
      result=zipEntry.getTime();
    }
    zipIn.closeEntry();
    zipEntry=zipIn.getNextEntry();
  }
  zipIn.close();
  in.close();
  return result;
}
 

Example 24

From project Android-File-Manager, under directory /src/com/nexes/manager/.

Source file: FileManager.java

  31 
vote

private void zip_folder(File file,ZipOutputStream zout) throws IOException {
  byte[] data=new byte[BUFFER];
  int read;
  if (file.isFile()) {
    ZipEntry entry=new ZipEntry(file.getName());
    zout.putNextEntry(entry);
    BufferedInputStream instream=new BufferedInputStream(new FileInputStream(file));
    while ((read=instream.read(data,0,BUFFER)) != -1)     zout.write(data,0,read);
    zout.closeEntry();
    instream.close();
  }
 else   if (file.isDirectory()) {
    String[] list=file.list();
    int len=list.length;
    for (int i=0; i < len; i++)     zip_folder(new File(file.getPath() + "/" + list[i]),zout);
  }
}
 

Example 25

From project Android-File-Manager-Tablet, under directory /src/com/nexes/manager/tablet/.

Source file: FileManager.java

  31 
vote

private void zip_folder(File file,ZipOutputStream zout) throws IOException {
  byte[] data=new byte[BUFFER];
  int read;
  if (file.isFile()) {
    ZipEntry entry=new ZipEntry(file.getName());
    zout.putNextEntry(entry);
    BufferedInputStream instream=new BufferedInputStream(new FileInputStream(file));
    Log.e("File Manager","zip_folder file name = " + entry.getName());
    while ((read=instream.read(data,0,BUFFER)) != -1)     zout.write(data,0,read);
    zout.closeEntry();
    instream.close();
  }
 else   if (file.isDirectory()) {
    Log.e("File Manager","zip_folder dir name = " + file.getPath());
    String[] list=file.list();
    int len=list.length;
    for (int i=0; i < len; i++)     zip_folder(new File(file.getPath() + "/" + list[i]),zout);
  }
}
 

Example 26

From project android_packages_apps_FileManager, under directory /src/org/openintents/filemanager/util/.

Source file: ExtractManager.java

  31 
vote

/** 
 * Recursively extract file or directory
 */
public boolean extract(File archive,String destinationPath){
  try {
    ZipFile zipfile=new ZipFile(archive);
    int fileCount=zipfile.size();
    for (Enumeration e=zipfile.entries(); e.hasMoreElements(); ) {
      ZipEntry entry=(ZipEntry)e.nextElement();
      unzipEntry(zipfile,entry,destinationPath);
      isExtracted++;
      progressDialog.setProgress((isExtracted * 100) / fileCount);
    }
    return true;
  }
 catch (  Exception e) {
    Log.e(TAG,"Error while extracting file " + archive,e);
    return false;
  }
}
 

Example 27

From project Anki-Android, under directory /src/com/ichi2/anki/services/.

Source file: DownloadManagerService.java

  31 
vote

private String unzipSharedDeckFile(String zipFilename,String title){
  ZipInputStream zipInputStream=null;
  Log.i(AnkiDroidApp.TAG,"unzipSharedDeckFile");
  if (zipFilename.endsWith(".zip")) {
    Log.i(AnkiDroidApp.TAG,"zipFilename ends with .zip");
    try {
      zipInputStream=new ZipInputStream(new FileInputStream(new File(zipFilename)));
      title=title.replace("^","");
      title=title.substring(0,java.lang.Math.min(title.length(),40));
      if (new File(mDestination + "/" + title+ ".anki").exists()) {
        title+=System.currentTimeMillis();
      }
      String partialDeckPath=mDestination + "/tmp/" + title;
      String deckFilename=partialDeckPath + ".anki.updating";
      ZipEntry zipEntry=null;
      while ((zipEntry=zipInputStream.getNextEntry()) != null) {
        Log.i(AnkiDroidApp.TAG,"zipEntry = " + zipEntry.getName());
        if ("shared.anki".equalsIgnoreCase(zipEntry.getName())) {
          Utils.writeToFile(zipInputStream,deckFilename);
        }
 else         if (zipEntry.getName().startsWith("shared.media/",0)) {
          Log.i(AnkiDroidApp.TAG,"Folder created = " + new File(partialDeckPath + ".media/").mkdir());
          Log.i(AnkiDroidApp.TAG,"Destination = " + AnkiDroidApp.getStorageDirectory() + "/"+ title+ ".media/"+ zipEntry.getName().replace("shared.media/",""));
          Utils.writeToFile(zipInputStream,partialDeckPath + ".media/" + zipEntry.getName().replace("shared.media/",""));
        }
      }
      zipInputStream.close();
      new File(zipFilename).delete();
    }
 catch (    FileNotFoundException e) {
      Log.e(AnkiDroidApp.TAG,"FileNotFoundException = " + e.getMessage());
      e.printStackTrace();
    }
catch (    IOException e) {
      Log.e(AnkiDroidApp.TAG,"IOException = " + e.getMessage());
      e.printStackTrace();
    }
  }
  return title;
}
 

Example 28

From project anode, under directory /app/src/org/meshpoint/anode/util/.

Source file: ZipExtractor.java

  31 
vote

public void unpack(File src,File dest) throws IOException {
  int count;
  byte[] buf=new byte[1024];
  ZipInputStream zis=null;
  ZipEntry zipentry;
  zis=new ZipInputStream(new FileInputStream(src));
  while ((zipentry=zis.getNextEntry()) != null) {
    String entryName=zipentry.getName();
    File entryFile=new File(dest,entryName);
    File parentDir=new File(entryFile.getParent());
    if (!parentDir.isDirectory() && !parentDir.mkdirs())     throw new IOException("ZipExtractor.unpack(): unable to create directory");
    if (zipentry.isDirectory()) {
      if (!entryFile.mkdir())       throw new IOException("ZipExtractor.unpack(): unable to create directory entry");
    }
 else {
      FileOutputStream fos=new FileOutputStream(entryFile);
      while ((count=zis.read(buf,0,1024)) != -1)       fos.write(buf,0,count);
      fos.close();
    }
    zis.closeEntry();
  }
  zis.close();
}
 

Example 29

From project ant4eclipse, under directory /org.ant4eclipse.lib.core/src/org/ant4eclipse/lib/core/util/.

Source file: Utilities.java

  31 
vote

/** 
 * Unpacks the content from the supplied zip file into the supplied destination directory.
 * @todo [11-Dec-2009:KASI] This should be merged with {@link #expandJarFile(JarFile,File)}
 * @param zipfile The zip file which has to be unpacked. Not <code>null</code> and must be a file.
 * @param destdir The directory where the content shall be written to. Not <code>null</code>.
 */
public static final void unpack(File zipfile,File destdir){
  Assure.notNull("zipfile",zipfile);
  Assure.notNull("destdir",destdir);
  byte[] buffer=new byte[16384];
  try {
    if (!destdir.isAbsolute()) {
      destdir=destdir.getAbsoluteFile();
    }
    ZipFile zip=new ZipFile(zipfile);
    Enumeration<? extends ZipEntry> entries=zip.entries();
    while (entries.hasMoreElements()) {
      ZipEntry zentry=entries.nextElement();
      if (zentry.isDirectory()) {
        mkdirs(new File(destdir,zentry.getName()));
      }
 else {
        File destfile=new File(destdir,zentry.getName());
        mkdirs(destfile.getParentFile());
        copy(zip.getInputStream(zentry),new FileOutputStream(destfile),buffer);
      }
    }
  }
 catch (  IOException ex) {
    throw new Ant4EclipseException(ex,CoreExceptionCode.UNPACKING_FAILED,zipfile);
  }
}
 

Example 30

From project any23, under directory /core/src/test/java/org/apache/any23/plugin/.

Source file: Any23PluginManagerTest.java

  31 
vote

private void decompressJar(File jarFile,File destination) throws IOException {
  final int BUFFER=1024 * 1024;
  BufferedOutputStream dest=null;
  FileOutputStream fos=null;
  ZipInputStream zis=null;
  final byte data[]=new byte[BUFFER];
  try {
    FileInputStream fis=new FileInputStream(jarFile);
    zis=new ZipInputStream(new BufferedInputStream(fis));
    ZipEntry entry;
    while ((entry=zis.getNextEntry()) != null) {
      int count;
      final File destinationFile=new File(destination,entry.getName());
      if (entry.getName().endsWith("/")) {
        destinationFile.mkdirs();
      }
 else {
        fos=new FileOutputStream(destinationFile);
        dest=new BufferedOutputStream(fos,BUFFER);
        while ((count=zis.read(data,0,BUFFER)) != -1) {
          dest.write(data,0,count);
          dest.flush();
        }
        dest.close();
        fos.close();
      }
    }
  }
  finally {
    if (zis != null)     zis.close();
    if (dest != null)     dest.close();
    if (fos != null)     fos.close();
  }
}
 

Example 31

From project Apertiurm-Androind-app-devlopment, under directory /ApertiumAndroid/src/org/apertium/android/filemanager/.

Source file: FileManager.java

  31 
vote

static public void unzip(String zipFile,String to) throws ZipException, IOException {
  Log.i(TAG,zipFile);
  int BUFFER=2048;
  File file=new File(zipFile);
  ZipFile zip=new ZipFile(file);
  String newPath=to;
  Log.i(TAG,"new path =" + newPath);
  new File(newPath).mkdir();
  Enumeration<? extends ZipEntry> zipFileEntries=zip.entries();
  while (zipFileEntries.hasMoreElements()) {
    ZipEntry entry=(ZipEntry)zipFileEntries.nextElement();
    String currentEntry=entry.getName();
    File destFile=new File(newPath,currentEntry);
    File destinationParent=destFile.getParentFile();
    destinationParent.mkdirs();
    if (!entry.isDirectory()) {
      BufferedInputStream is=new BufferedInputStream(zip.getInputStream(entry));
      int currentByte;
      byte data[]=new byte[BUFFER];
      FileOutputStream fos=new FileOutputStream(destFile);
      BufferedOutputStream dest=new BufferedOutputStream(fos,BUFFER);
      while ((currentByte=is.read(data,0,BUFFER)) != -1) {
        dest.write(data,0,currentByte);
      }
      dest.flush();
      dest.close();
      is.close();
    }
  }
}
 

Example 32

From project apps-for-android, under directory /CLiCkin2DaBeaT/src/com/google/clickin2dabeat/.

Source file: Unzipper.java

  31 
vote

public static void unzip(String fileUrl){
  try {
    String filename=download(fileUrl);
    ZipFile zip=new ZipFile(filename);
    Enumeration<? extends ZipEntry> zippedFiles=zip.entries();
    while (zippedFiles.hasMoreElements()) {
      ZipEntry entry=zippedFiles.nextElement();
      InputStream is=zip.getInputStream(entry);
      String name=entry.getName();
      File outputFile=new File("/sdcard/c2b/" + name);
      String outputPath=outputFile.getCanonicalPath();
      name=outputPath.substring(outputPath.lastIndexOf("/") + 1);
      outputPath=outputPath.substring(0,outputPath.lastIndexOf("/"));
      File outputDir=new File(outputPath);
      outputDir.mkdirs();
      outputFile=new File(outputPath,name);
      outputFile.createNewFile();
      FileOutputStream out=new FileOutputStream(outputFile);
      byte buf[]=new byte[16384];
      do {
        int numread=is.read(buf);
        if (numread <= 0) {
          break;
        }
 else {
          out.write(buf,0,numread);
        }
      }
 while (true);
      is.close();
      out.close();
    }
    File theZipFile=new File(filename);
    theZipFile.delete();
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 33

From project Arecibo, under directory /util/src/main/java/com/ning/arecibo/util/.

Source file: ZipUtils.java

  31 
vote

public static byte[] unzip(byte[] input) throws IOException {
  byte b[]=buf.get();
  ByteArrayOutputStream o=out.get();
  o.reset();
  ZipInputStream z=null;
  try {
    z=new ZipInputStream(new ByteArrayInputStream(input));
    ZipEntry ze=z.getNextEntry();
    int read=0;
    while ((read=z.read(b)) > 0) {
      o.write(b,0,read);
    }
    o.flush();
  }
  finally {
    if (z != null) {
      z.close();
    }
  }
  return o.toByteArray();
}
 

Example 34

From project aviator, under directory /src/main/java/com/googlecode/aviator/asm/optimizer/.

Source file: JarOptimizer.java

  31 
vote

static void optimize(final File f) throws IOException {
  if (f.isDirectory()) {
    File[] files=f.listFiles();
    for (int i=0; i < files.length; ++i) {
      optimize(files[i]);
    }
  }
 else   if (f.getName().endsWith(".jar")) {
    File g=new File(f.getParentFile(),f.getName() + ".new");
    ZipFile zf=new ZipFile(f);
    ZipOutputStream out=new ZipOutputStream(new FileOutputStream(g));
    Enumeration e=zf.entries();
    byte[] buf=new byte[10000];
    while (e.hasMoreElements()) {
      ZipEntry ze=(ZipEntry)e.nextElement();
      if (ze.isDirectory()) {
        continue;
      }
      out.putNextEntry(ze);
      InputStream is=zf.getInputStream(ze);
      int n;
      do {
        n=is.read(buf,0,buf.length);
        if (n != -1) {
          out.write(buf,0,n);
        }
      }
 while (n != -1);
      out.closeEntry();
    }
    out.close();
    zf.close();
    f.delete();
    g.renameTo(f);
  }
}
 

Example 35

From project azkaban, under directory /azkaban-common/src/java/azkaban/common/utils/.

Source file: Utils.java

  31 
vote

private static void zipFile(String path,File input,ZipOutputStream zOut) throws IOException {
  if (input.isDirectory()) {
    File[] files=input.listFiles();
    if (files != null) {
      for (      File f : files) {
        String childPath=path + input.getName() + (f.isDirectory() ? "/" : "");
        zipFile(childPath,f,zOut);
      }
    }
  }
 else {
    String childPath=path + (path.length() > 0 ? "/" : "") + input.getName();
    ZipEntry entry=new ZipEntry(childPath);
    zOut.putNextEntry(entry);
    InputStream fileInputStream=new BufferedInputStream(new FileInputStream(input));
    IOUtils.copy(fileInputStream,zOut);
    fileInputStream.close();
  }
}
 

Example 36

From project b3log-solo, under directory /core/src/main/java/org/b3log/solo/processor/.

Source file: CaptchaProcessor.java

  31 
vote

/** 
 * Loads captcha.
 */
private static void loadCaptchas(){
  LOGGER.info("Loading captchas....");
  try {
    final URL captchaURL=SoloServletListener.class.getClassLoader().getResource("captcha.zip");
    final ZipFile zipFile=new ZipFile(captchaURL.getFile());
    final Set<String> imageNames=new HashSet<String>();
    for (int row=0; row < MAX_CAPTCHA_ROW; row++) {
      for (int column=0; column < MAX_CAPTCHA_COLUM; column++) {
        imageNames.add(row + "/" + column+ ".png");
      }
    }
    final ImageService imageService=ImageServiceFactory.getImageService();
    final Iterator<String> i=imageNames.iterator();
    while (i.hasNext()) {
      final String imageName=i.next();
      final ZipEntry zipEntry=zipFile.getEntry(imageName);
      final BufferedInputStream bufferedInputStream=new BufferedInputStream(zipFile.getInputStream(zipEntry));
      final byte[] captchaCharData=new byte[bufferedInputStream.available()];
      bufferedInputStream.read(captchaCharData);
      bufferedInputStream.close();
      final Image captchaChar=imageService.makeImage(captchaCharData);
      CAPTCHAS.put(imageName,captchaChar);
    }
    zipFile.close();
  }
 catch (  final Exception e) {
    LOGGER.severe("Can not load captchs!");
    throw new IllegalStateException(e);
  }
  LOGGER.info("Loaded captch images");
}
 

Example 37

From project backend-update-center2, under directory /src/main/java/org/jvnet/hudson/update_center/.

Source file: MavenArtifact.java

  31 
vote

public Manifest getManifest() throws IOException {
  if (manifest == null) {
    File f=resolve();
    try {
      JarFile jar=new JarFile(f);
      ZipEntry e=jar.getEntry("META-INF/MANIFEST.MF");
      timestamp=e.getTime();
      manifest=jar.getManifest();
      jar.close();
    }
 catch (    IOException x) {
      throw (IOException)new IOException("Failed to open " + f).initCause(x);
    }
  }
  return manifest;
}
 

Example 38

From project BeeQueue, under directory /src/org/beequeue/launcher/.

Source file: JarUnpacker.java

  31 
vote

public static void unpack(Class<?> searchJar,EntryFilter filter,File destination) throws IOException {
  CodeSource src=searchJar.getProtectionDomain().getCodeSource();
  if (src != null) {
    URL jar=src.getLocation();
    ZipInputStream zip=new ZipInputStream(jar.openStream());
    ZipEntry ze=null;
    while ((ze=zip.getNextEntry()) != null) {
      if (filter.include(ze)) {
        String entryName=ze.getName();
        File f=new File(destination,entryName);
        if (ze.isDirectory()) {
          f.mkdirs();
        }
 else {
          FileOutputStream out=new FileOutputStream(f);
          copy(zip,out,4096);
        }
      }
    }
  }
 else {
    throw new RuntimeException("cannot uppack jar specified by class:" + searchJar);
  }
}
 

Example 39

From project behemoth, under directory /gate/src/test/java/com/digitalpebble/behemoth/gate/.

Source file: GATEProcessorTest.java

  31 
vote

/** 
 * Unzips the argument into the temp directory and returns the unzipped location.
 */
public static File unzip(File inputZip){
  File rootDir=null;
  try {
    BufferedOutputStream dest=null;
    BufferedInputStream is=null;
    ZipEntry entry;
    ZipFile zipfile=new ZipFile(inputZip);
    String zipname=inputZip.getName().replaceAll("\\.zip","");
    File test=File.createTempFile("aaa","aaa");
    String tempDir=test.getParent();
    test.delete();
    rootDir=new File(tempDir,zipname);
    rootDir.mkdir();
    Enumeration e=zipfile.entries();
    while (e.hasMoreElements()) {
      entry=(ZipEntry)e.nextElement();
      is=new BufferedInputStream(zipfile.getInputStream(entry));
      int count;
      byte data[]=new byte[BUFFER];
      File target=new File(rootDir,entry.getName());
      if (entry.getName().endsWith("/")) {
        target.mkdir();
        continue;
      }
      FileOutputStream fos=new FileOutputStream(target);
      dest=new BufferedOutputStream(fos,BUFFER);
      while ((count=is.read(data,0,BUFFER)) != -1) {
        dest.write(data,0,count);
      }
      dest.flush();
      dest.close();
      is.close();
    }
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return rootDir;
}
 

Example 40

From project BibleQuote-for-Android, under directory /src/com/BibleQuote/utils/.

Source file: FsUtils.java

  31 
vote

public static BufferedReader getTextFileReaderFromZipArchive(String archivePath,String textFileInArchive,String textFileEncoding) throws FileAccessException {
  File zipFile=new File(archivePath);
  try {
    InputStream moduleStream=new FileInputStream(zipFile);
    ZipInputStream zStream=new ZipInputStream(moduleStream);
    ZipEntry entry;
    while ((entry=zStream.getNextEntry()) != null) {
      String entryName=entry.getName().toLowerCase();
      if (entryName.contains(File.separator)) {
        entryName=entryName.substring(entryName.lastIndexOf(File.separator) + 1);
      }
      String fileName=textFileInArchive.toLowerCase();
      if (entryName.equals(fileName)) {
        InputStreamReader iReader=new InputStreamReader(zStream,textFileEncoding);
        return new BufferedReader(iReader);
      }
      ;
    }
    String message=String.format("File %1$s in zip-arhive %2$s not found",textFileInArchive,archivePath);
    Log.e(TAG,message);
    throw new FileAccessException(message);
  }
 catch (  UTFDataFormatException e) {
    String message=String.format("Archive %1$s contains the file names not in the UTF format",zipFile.getName());
    Log.e(TAG,message);
    throw new FileAccessException(message);
  }
catch (  IOException e) {
    Log.e(TAG,String.format("getTextFileReaderFromZipArchive(%1$s, %2$s, %3$s)",archivePath,textFileInArchive,textFileEncoding),e);
    throw new FileAccessException(e);
  }
}
 

Example 41

From project blacktie, under directory /utils/cpp-plugin/src/main/java/org/jboss/narayana/blacktie/plugins/.

Source file: AddCommonSources.java

  31 
vote

private static void unzip(InputStream from,String to,String pattern){
  if (from == null || to == null)   return;
  try {
    ZipInputStream zs=new ZipInputStream(from);
    ZipEntry ze;
    while ((ze=zs.getNextEntry()) != null) {
      String fname=to + '/' + ze.getName();
      boolean match=(pattern == null || ze.getName().matches(pattern));
      if (ze.isDirectory())       new File(fname).mkdirs();
 else       if (match)       externalizeFile(fname,zs);
 else       readFile(fname,zs);
      zs.closeEntry();
    }
    zs.close();
  }
 catch (  IOException e) {
    e.printStackTrace();
    throw new RuntimeException("Unable to unpack archive: " + e.getMessage());
  }
}
 

Example 42

From project bpelunit, under directory /net.bpelunit.framework.control.deploy.activevos9/src/main/java/net/bpelunit/util/.

Source file: ZipUtil.java

  31 
vote

public static void unzipFile(File zip,File dir) throws IOException {
  InputStream in=null;
  OutputStream out=null;
  ZipFile zipFile=new ZipFile(zip);
  Enumeration<? extends ZipEntry> entries=zipFile.entries();
  while (entries.hasMoreElements()) {
    ZipEntry entry=entries.nextElement();
    if (!entry.getName().endsWith("/")) {
      File unzippedFile=new File(dir,entry.getName());
      try {
        in=zipFile.getInputStream(entry);
        unzippedFile.getParentFile().mkdirs();
        out=new FileOutputStream(unzippedFile);
        IOUtils.copy(in,out);
      }
  finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
      }
    }
  }
}
 

Example 43

From project c24-spring, under directory /c24-spring-batch/src/main/java/biz/c24/io/spring/batch/reader/source/.

Source file: ZipFileSource.java

  31 
vote

public void initialise(StepExecution stepExecution){
  try {
    File source=null;
    if (resource != null) {
      name=resource.getDescription();
      source=resource.getFile();
    }
 else {
      name=stepExecution.getJobParameters().getString("input.file");
      if (name.startsWith("file://")) {
        name=name.substring("file://".length());
      }
      source=new File(name);
    }
    zipFile=new ZipFile(source);
    zipEntries=zipFile.entries();
    ZipEntry entry=null;
    if (zipEntries.hasMoreElements()) {
      entry=zipEntries.nextElement();
      reader=getReader(entry);
    }
    if (entry != null && zipFile.size() > 20 && (entry.getSize() == -1 || entry.getSize() < 10000)) {
      useMultipleThreadsPerReader=false;
    }
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
}
 

Example 44

From project Cafe, under directory /webapp/src/org/openqa/selenium/io/.

Source file: Zip.java

  31 
vote

private void addToZip(String basePath,ZipOutputStream zos,File toAdd) throws IOException {
  if (toAdd.isDirectory()) {
    for (    File file : toAdd.listFiles()) {
      addToZip(basePath,zos,file);
    }
  }
 else {
    FileInputStream fis=new FileInputStream(toAdd);
    String name=toAdd.getAbsolutePath().substring(basePath.length() + 1);
    ZipEntry entry=new ZipEntry(name);
    zos.putNextEntry(entry);
    int len;
    byte[] buffer=new byte[4096];
    while ((len=fis.read(buffer)) != -1) {
      zos.write(buffer,0,len);
    }
    fis.close();
    zos.closeEntry();
  }
}
 

Example 45

From project candlepin, under directory /src/main/java/org/candlepin/sync/.

Source file: Exporter.java

  31 
vote

private void addFileToArchive(ZipOutputStream out,int charsToDropFromName,File file) throws IOException, FileNotFoundException {
  log.debug("Adding file to archive: " + file.getAbsolutePath().substring(charsToDropFromName));
  out.putNextEntry(new ZipEntry(file.getAbsolutePath().substring(charsToDropFromName)));
  FileInputStream in=new FileInputStream(file);
  byte[] buf=new byte[1024];
  int len;
  while ((len=in.read(buf)) > 0) {
    out.write(buf,0,len);
  }
  out.closeEntry();
  in.close();
}
 

Example 46

From project ceylon-ide-eclipse, under directory /plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/editor/.

Source file: SourceArchiveDocumentProvider.java

  31 
vote

private String getZipEntryContents(IURIEditorInput uriEditorInput,String encoding){
  String path=uriEditorInput.getURI().getPath();
  int lastColonIdx=path.lastIndexOf('!');
  if (lastColonIdx < 0)   return null;
  String jarPath=path.substring(0,lastColonIdx);
  String entryPath=path.substring(lastColonIdx + 2);
  try {
    ZipFile zipFile=new ZipFile(new File(jarPath));
    try {
      ZipEntry entry=zipFile.getEntry(entryPath);
      return encoding == null ? readStreamContents(zipFile.getInputStream(entry)) : readStreamContents(zipFile.getInputStream(entry),encoding);
    }
  finally {
      zipFile.close();
    }
  }
 catch (  IOException e) {
    e.printStackTrace();
    return null;
  }
}
 

Example 47

From project ceylon-module-resolver, under directory /impl/src/main/java/com/redhat/ceylon/cmr/impl/.

Source file: IOUtils.java

  31 
vote

private static void zipInternal(String path,File file,ZipOutputStream os) throws IOException {
  String filePath=path + "/" + file.getName();
  if (file.isDirectory()) {
    for (    File f : file.listFiles())     zipInternal(filePath,f,os);
  }
 else {
    ZipEntry entry=new ZipEntry(filePath);
    os.putNextEntry(entry);
    FileInputStream in=new FileInputStream(file);
    try {
      copyStreamNoClose(in,os);
    }
  finally {
      in.close();
    }
    os.closeEntry();
  }
}
 

Example 48

From project ceylon-runtime, under directory /bootstrap/src/main/java/ceylon/modules/bootstrap/loader/.

Source file: DistributionModuleLoader.java

  31 
vote

/** 
 * Unzip bootstrap distrubution if not already present.
 * @param dir the unzip destination
 * @param zip the zipped bootstrap distribution
 * @return unziped root directory
 */
protected File unzipDistribution(File dir,File zip){
  File exploded=new File(dir,BOOTSTRAP_DISTRIBUTION + "-exploded");
  if (exploded.exists()) {
    if (forceBootstrapUpdate() == false)     return exploded;
 else     delete(exploded);
  }
  try {
    final ZipFile zipFile=new ZipFile(zip);
    try {
      final Enumeration<? extends ZipEntry> entries=zipFile.entries();
      while (entries.hasMoreElements()) {
        final ZipEntry ze=entries.nextElement();
        final File file=new File(exploded,ze.getName());
        if (ze.isDirectory()) {
          if (file.mkdirs() == false)           throw new IllegalArgumentException("Cannot create dir: " + file);
        }
 else {
          final FileOutputStream fos=new FileOutputStream(file);
          copyStream(zipFile.getInputStream(ze),fos);
        }
      }
    }
  finally {
      zipFile.close();
    }
  }
 catch (  IOException e) {
    throw new IllegalArgumentException(e);
  }
  return exploded;
}
 

Example 49

From project ChkBugReport, under directory /src/com/sonyericsson/chkbugreport/.

Source file: Main.java

  31 
vote

protected int loadReportFrom(Module report,String fileName,int mode) throws IOException {
  for (  Extension ext : mExtensions) {
    int ret=ext.loadReportFrom(report,fileName,mode);
    if (ret != RET_NOP) {
      return ret;
    }
  }
  File f=new File(fileName);
  InputStream is=null;
  if (!f.exists()) {
    onPrint(1,TYPE_ERR,"File " + fileName + " does not exists!");
    return RET_FALSE;
  }
  try {
    ZipFile zip=new ZipFile(fileName);
    Enumeration<? extends ZipEntry> entries=zip.entries();
    while (entries.hasMoreElements()) {
      ZipEntry entry=entries.nextElement();
      if (!entry.isDirectory()) {
        if (!mSilent)         System.out.println("Trying to parse zip entry: " + entry.getName() + " ...");
        if (loadFrom(report,fileName,zip.getInputStream(entry))) {
          return RET_TRUE;
        }
      }
    }
  }
 catch (  IOException e) {
  }
  try {
    is=new FileInputStream(f);
  }
 catch (  IOException e) {
    onPrint(1,TYPE_ERR,"Error opening file " + fileName + "!");
    return RET_FALSE;
  }
  if (!loadFrom(report,fileName,is)) {
    return RET_FALSE;
  }
  return RET_TRUE;
}
 

Example 50

From project cilia-workbench, under directory /cilia-workbench-common/src/fr/liglab/adele/cilia/workbench/common/xml/.

Source file: XMLHelpers.java

  31 
vote

/** 
 * Gets an Input stream from a file embedded in a jar archive.
 * @param jarFile the jar archive file, on the hard disk.
 * @param fileName the file name, in the archive. The file must be located at the archive root.
 * @return the input stream
 * @throws CiliaException if any error.
 */
public static InputStream inputStreamFromFileInJarArchive(File jarFile,String fileName) throws CiliaException {
  JarFile file;
  try {
    file=new JarFile(jarFile);
  }
 catch (  IOException e) {
    throw new CiliaException("Can't open jar file " + jarFile.getAbsolutePath(),e);
  }
  ZipEntry entry=file.getEntry(fileName);
  if (entry == null)   throw new CiliaException("File " + fileName + " not found in "+ jarFile.getAbsolutePath());
  BufferedInputStream is;
  try {
    is=new BufferedInputStream(file.getInputStream(entry));
  }
 catch (  IOException e) {
    throw new CiliaException("Can't access file " + fileName + " in jar file "+ jarFile.getAbsolutePath(),e);
  }
  return is;
}
 

Example 51

From project cipango, under directory /cipango-console/src/main/java/org/cipango/console/.

Source file: Deployer.java

  31 
vote

private void assertValidArchive(byte[] sarContent){
  try {
    JarInputStream is=new JarInputStream(new ByteArrayInputStream(sarContent));
    ZipEntry entry;
    if ((entry=is.getNextEntry()) == null)     throw new IllegalArgumentException("Not a JAR archive format");
    do {
      if (!entry.isDirectory() && (entry.getName().equals("WEB-INF/sip.xml") || entry.getName().equals("WEB-INF/web.xml")))       return;
    }
 while ((entry=is.getNextEntry()) != null);
  }
 catch (  IOException e) {
    throw new IllegalArgumentException("Not a JAR archive format: " + e.getMessage());
  }
  throw new IllegalArgumentException("Missing WEB-INF/sip.xml or WEB-INF/web.xml in archive");
}
 

Example 52

From project CircDesigNA, under directory /src/circdesigna/energy/.

Source file: ExperimentalDuplexParams.java

  31 
vote

public ExperimentalDuplexParams(CircDesigNAConfig config){
  super(config);
  ZipInputStream paramZip=ZipExtractor.getFile("parameters.zip");
  ZipEntry nextEntry;
  String dG=null, dH=null;
  try {
    while ((nextEntry=paramZip.getNextEntry()) != null) {
      if (nextEntry.getName().startsWith(config.getParameterName())) {
        ByteArrayOutputStream baos=ZipExtractor.readFully(paramZip);
        if (nextEntry.getName().endsWith(".dG")) {
          dG=baos.toString();
        }
        if (nextEntry.getName().endsWith(".dH")) {
          dH=baos.toString();
        }
      }
    }
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
  StandardizedThermoFileLoader.makeTable(this,dG,dH);
}
 

Example 53

From project CIShell, under directory /core/org.cishell.utilities/src/org/cishell/utilities/.

Source file: ZipUtilities.java

  31 
vote

public static void writeFileToZipFile(File file,String zippedName,ZipOutputStream zipOut) throws ZipIOException {
  try {
    byte data[]=new byte[BUFFER_SIZE];
    BufferedInputStream fileInput=new BufferedInputStream(new FileInputStream(file),BUFFER_SIZE);
    ZipEntry entry=new ZipEntry(zippedName);
    zipOut.putNextEntry(entry);
    int count;
    while ((count=fileInput.read(data,0,BUFFER_SIZE)) != -1) {
      zipOut.write(data,0,count);
    }
    fileInput.close();
  }
 catch (  FileNotFoundException e) {
    throw new ZipIOException(e.getMessage(),e);
  }
catch (  IOException e) {
    throw new ZipIOException(e.getMessage(),e);
  }
}
 

Example 54

From project cloudbees-deployer-plugin, under directory /src/test/java/org/jenkins/plugins/cloudbees/.

Source file: CloudbeesDeployWarTest.java

  31 
vote

public void assertOnArchive(InputStream inputStream) throws IOException {
  List<String> fileNames=new ArrayList<String>();
  ZipInputStream zipInputStream=null;
  try {
    zipInputStream=new ZipInputStream(inputStream);
    ZipEntry zipEntry=zipInputStream.getNextEntry();
    while (zipEntry != null) {
      fileNames.add(zipEntry.getName());
      zipEntry=zipInputStream.getNextEntry();
    }
  }
  finally {
    IOUtils.closeQuietly(zipInputStream);
  }
  assertTrue(fileNames.contains("META-INF/maven/org.olamy.puzzle.translate/translate-puzzle-webapp/pom.xml"));
  assertTrue(fileNames.contains("WEB-INF/lib/javax.inject-1.jar"));
}
 

Example 55

From project cloudhopper-commons-util, under directory /src/main/java/com/cloudhopper/commons/util/.

Source file: CompressionUtil.java

  31 
vote

@Override public void uncompress(InputStream srcIn,OutputStream destOut) throws IOException {
  ZipInputStream in=null;
  try {
    in=new ZipInputStream(srcIn);
    ZipEntry ze=in.getNextEntry();
    byte[] buf=new byte[1024];
    int len;
    while ((len=in.read(buf)) > 0) {
      destOut.write(buf,0,len);
    }
    if (in.getNextEntry() != null) {
      throw new IOException("Zip file/inputstream contained more than one entry (this method cannot support)");
    }
    in.closeEntry();
    in.close();
    in=null;
    destOut.close();
    destOut=null;
  }
  finally {
    if (in != null) {
      try {
        in.close();
      }
 catch (      Exception e) {
      }
    }
    if (destOut != null) {
      try {
        destOut.close();
      }
 catch (      Exception e) {
      }
    }
  }
}
 

Example 56

From project cloudify, under directory /CLI/src/main/java/org/cloudifysource/shell/commands/.

Source file: TestRecipe.java

  31 
vote

/** 
 * Unzips a given file.
 * @param inputFile The zip file to extract
 * @return The new folder, containing the extracted content of the zip file
 * @throws IOException Reporting a failure to extract the zipped file or close it afterwards
 */
private static File unzipFile(final File inputFile) throws IOException {
  ZipFile zipFile=null;
  try {
    final File baseDir=TestRecipe.createTempDir();
    zipFile=new ZipFile(inputFile);
    final Enumeration<? extends ZipEntry> entries=zipFile.entries();
    while (entries.hasMoreElements()) {
      final ZipEntry entry=entries.nextElement();
      if (entry.isDirectory()) {
        logger.fine("Extracting directory: " + entry.getName());
        final File dir=new File(baseDir,entry.getName());
        dir.mkdir();
        continue;
      }
      logger.finer("Extracting file: " + entry.getName());
      final File file=new File(baseDir,entry.getName());
      file.getParentFile().mkdirs();
      ServiceReader.copyInputStream(zipFile.getInputStream(entry),new BufferedOutputStream(new FileOutputStream(file)));
    }
    return baseDir;
  }
  finally {
    if (zipFile != null) {
      try {
        zipFile.close();
      }
 catch (      final IOException e) {
        logger.log(Level.SEVERE,"Failed to close zip file after unzipping zip contents",e);
      }
    }
  }
}
 

Example 57

From project clustermeister, under directory /integration-tests/src/main/java/com/github/nethad/clustermeister/integration/.

Source file: JPPFTestNode.java

  31 
vote

private void unzipNode(InputStream fileToUnzip,File targetDir){
  ZipInputStream zipFile;
  try {
    zipFile=new ZipInputStream(fileToUnzip);
    ZipEntry entry;
    while ((entry=zipFile.getNextEntry()) != null) {
      if (entry.isDirectory()) {
        System.err.println("Extracting directory: " + entry.getName());
        (new File(targetDir,entry.getName())).mkdir();
        continue;
      }
      System.err.println("Extracting file: " + entry.getName());
      File targetFile=new File(targetDir,entry.getName());
      copyInputStream_notClosing(zipFile,new BufferedOutputStream(new FileOutputStream(targetFile)));
    }
    zipFile.close();
  }
 catch (  IOException ioe) {
    System.err.println("Unhandled exception:");
    ioe.printStackTrace();
  }
}
 

Example 58

From project coffeescript-netbeans, under directory /src/coffeescript/nb/project/sample/.

Source file: CoffeeScriptApplicationWizardIterator.java

  31 
vote

private static void unZipFile(InputStream source,FileObject projectRoot) throws IOException {
  try {
    ZipInputStream str=new ZipInputStream(source);
    ZipEntry entry;
    while ((entry=str.getNextEntry()) != null) {
      if (entry.isDirectory()) {
        FileUtil.createFolder(projectRoot,entry.getName());
      }
 else {
        FileObject fo=FileUtil.createData(projectRoot,entry.getName());
        if ("nbproject/project.xml".equals(entry.getName())) {
          filterProjectXML(fo,str,projectRoot.getName());
        }
 else {
          writeFile(str,fo);
        }
      }
    }
  }
  finally {
    source.close();
  }
}
 

Example 59

From project core_1, under directory /common/src/main/java/org/switchyard/common/type/classpath/.

Source file: ClasspathScanner.java

  31 
vote

private void handleArchive(File file) throws IOException {
  if (_logger.isDebugEnabled()) {
    _logger.debug("Scanning archive: " + file.getAbsolutePath());
  }
  ZipFile zip=new ZipFile(file);
  Enumeration<? extends ZipEntry> entries=zip.entries();
  while (entries.hasMoreElements()) {
    if (!_filter.continueScanning()) {
      break;
    }
    ZipEntry entry=entries.nextElement();
    String name=entry.getName();
    _filter.filter(name);
  }
}
 

Example 60

From project Core_2, under directory /shell-api/src/main/java/org/jboss/forge/shell/util/.

Source file: Files.java

  31 
vote

/** 
 * Unzips a specific file into a target directory
 */
public static void unzip(File zipFile,File targetDirectory) throws IOException {
  OutputStream dest=null;
  ZipInputStream zis=new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile)));
  ZipEntry entry;
  try {
    while ((entry=zis.getNextEntry()) != null) {
      File file=new File(targetDirectory,entry.getName());
      if (entry.isDirectory()) {
        file.mkdirs();
        continue;
      }
      try {
        dest=new BufferedOutputStream(new FileOutputStream(file));
        Streams.write(zis,dest);
      }
  finally {
        dest.flush();
        Streams.closeQuietly(dest);
      }
    }
  }
  finally {
    Streams.closeQuietly(zis);
  }
}
 

Example 61

From project cp-common-utils, under directory /src/com/clarkparsia/common/io/.

Source file: Files2.java

  31 
vote

/** 
 * Zip the given directory.
 * @param theDir the directory to zip
 * @param theOutputFile the zip file to write to
 * @throws IOException thrown if there is an error while zipping the directory or while saving the results.
 */
public static void zipDirectory(File theDir,File theOutputFile) throws IOException {
  ZipOutputStream aZipOut=new ZipOutputStream(new FileOutputStream(theOutputFile));
  try {
    Collection<File> aFileList=listFiles(theDir);
    String aPathToRemove=theDir.getAbsolutePath().substring(0,theDir.getAbsolutePath().lastIndexOf(File.separator));
    for (    File aFile : aFileList) {
      FileInputStream aFileIn=new FileInputStream(aFile);
      try {
        ZipEntry aZipEntry=new ZipEntry(aFile.getAbsolutePath().substring(aFile.getAbsolutePath().indexOf(aPathToRemove) + aPathToRemove.length() + 1));
        aZipOut.putNextEntry(aZipEntry);
        ByteStreams.copy(aFileIn,aZipOut);
      }
  finally {
        Closeables.closeQuietly(aFileIn);
        aZipOut.closeEntry();
      }
    }
  }
  finally {
    Closeables.closeQuietly(aZipOut);
  }
}
 

Example 62

From project cpp-maven-plugins, under directory /cpp-compiler-maven-plugin/src/main/java/com/ericsson/tools/cpp/compiler/dependencies/.

Source file: DependencyExtractor.java

  31 
vote

private void extractDependency(final DependencyIdentifier dep) throws MojoExecutionException {
  int extractedFiles=0;
  try {
    final ZipFile zipFile=new ZipFile(dep.getArtifact().getFile());
    final Enumeration<? extends ZipEntry> entriesEnum=zipFile.entries();
    while (entriesEnum.hasMoreElements()) {
      final ZipEntry entry=entriesEnum.nextElement();
      if (entryMatchesDependency(entry,dep)) {
        extractEntry(entry,zipFile,dep.getDestination());
        extractedFiles++;
      }
    }
    zipFile.close();
  }
 catch (  IOException e) {
    throw new MojoExecutionException("Failed to extract " + dep.getArtifact() + ".",e);
  }
  if (extractedFiles > 0)   log.debug("Extracted " + extractedFiles + " files from \""+ dep+ "\" to "+ dep.getDestination());
}
 

Example 63

From project cw-omnibus, under directory /EmPubLite/T16-Update/src/com/commonsware/empublite/.

Source file: DownloadInstallService.java

  31 
vote

private static void unzip(File src,File dest) throws IOException {
  InputStream is=new FileInputStream(src);
  ZipInputStream zis=new ZipInputStream(new BufferedInputStream(is));
  ZipEntry ze;
  dest.mkdirs();
  while ((ze=zis.getNextEntry()) != null) {
    byte[] buffer=new byte[8192];
    int count;
    FileOutputStream fos=new FileOutputStream(new File(dest,ze.getName()));
    BufferedOutputStream out=new BufferedOutputStream(fos);
    try {
      while ((count=zis.read(buffer)) != -1) {
        out.write(buffer,0,count);
      }
      out.flush();
    }
  finally {
      fos.getFD().sync();
      out.close();
    }
    zis.closeEntry();
  }
  zis.close();
}
 

Example 64

From project datasalt-utils, under directory /src/contrib/java/org/apache/solr/hadoop/.

Source file: SolrOutputFormat.java

  31 
vote

private static void createZip(File dir,File out) throws IOException {
  HashSet<File> files=new HashSet<File>();
  for (  String allowedDirectory : SolrRecordWriter.getAllowedConfigDirectories()) {
    File configDir=new File(dir,allowedDirectory);
    boolean configDirExists;
    if (!(configDirExists=configDir.exists()) && SolrRecordWriter.isRequiredConfigDirectory(allowedDirectory)) {
      throw new IOException(String.format("required configuration directory %s is not present in %s",allowedDirectory,dir));
    }
    if (!configDirExists) {
      continue;
    }
    listFiles(configDir,files);
  }
  out.delete();
  int subst=dir.toString().length();
  ZipOutputStream zos=new ZipOutputStream(new FileOutputStream(out));
  byte[] buf=new byte[1024];
  for (  File f : files) {
    ZipEntry ze=new ZipEntry(f.toString().substring(subst));
    zos.putNextEntry(ze);
    InputStream is=new FileInputStream(f);
    int cnt;
    while ((cnt=is.read(buf)) >= 0) {
      zos.write(buf,0,cnt);
    }
    is.close();
    zos.flush();
    zos.closeEntry();
  }
  zos.close();
}
 

Example 65

From project dawn-common, under directory /org.dawb.common.util/src/org/dawb/common/util/io/.

Source file: ZipUtils.java

  31 
vote

public static void unzip(final File zip,final File dir) throws Exception {
  if (!zip.exists())   throw new FileNotFoundException("Cannot find " + zip);
  if (!dir.exists())   throw new FileNotFoundException("Cannot find " + dir);
  if (!zip.isFile())   throw new FileNotFoundException("Zip file must be a file " + zip);
  if (!dir.isDirectory())   throw new FileNotFoundException("Dir argument must be a directory " + dir);
  final ZipInputStream zis=new ZipInputStream(new BufferedInputStream(new FileInputStream(zip)));
  try {
    ZipEntry entry;
    while ((entry=zis.getNextEntry()) != null) {
      int count;
      byte data[]=new byte[BUFFER];
      final String path=dir.getAbsolutePath() + "/" + entry.getName();
      final File out=new File(path);
      if (entry.isDirectory()) {
        out.mkdirs();
        continue;
      }
 else {
        out.getParentFile().mkdirs();
        out.createNewFile();
      }
      final FileOutputStream fos=new FileOutputStream(out);
      final BufferedOutputStream dest=new BufferedOutputStream(fos,BUFFER);
      try {
        while ((count=zis.read(data,0,BUFFER)) != -1) {
          dest.write(data,0,count);
        }
        dest.flush();
      }
  finally {
        dest.close();
      }
    }
  }
  finally {
    zis.close();
  }
}
 

Example 66

From project dawn-isencia, under directory /com.isencia.passerelle.commons/src/main/java/com/isencia/util/.

Source file: FileLocator.java

  31 
vote

private static NamedDataInputStream locateInZipFile(String zipFileName,String fileName,boolean wantClass,boolean buffered) throws ZipException, IOException {
  ZipFile zf;
  ZipEntry ze;
  zf=new ZipFile(zipFileName);
  if (zf == null)   return null;
  String zeName=wantClass ? fileName.replace('.','/') + ".class" : fileName;
  ze=zf.getEntry(zeName);
  if (ze == null) {
    zf.close();
    zf=null;
    return null;
  }
  InputStream istream=zf.getInputStream(ze);
  if (buffered)   istream=new BufferedInputStream(istream);
  return new NamedDataInputStream(istream,zipFileName + '(' + zeName+ ')',true);
}
 

Example 67

From project des, under directory /daemon/lib/apache-log4j-1.2.16/tests/src/java/org/apache/log4j/.

Source file: PropertyConfiguratorTest.java

  31 
vote

/** 
 * Test for bug 47465. configure(URL) did not close opened JarURLConnection.
 * @throws IOException if IOException creating properties jar.
 */
public void testJarURL() throws IOException {
  File dir=new File("output");
  dir.mkdirs();
  File file=new File("output/properties.jar");
  ZipOutputStream zos=new ZipOutputStream(new FileOutputStream(file));
  zos.putNextEntry(new ZipEntry(LogManager.DEFAULT_CONFIGURATION_FILE));
  zos.write("log4j.rootLogger=debug".getBytes());
  zos.closeEntry();
  zos.close();
  URL url=new URL("jar:" + file.toURL() + "!/"+ LogManager.DEFAULT_CONFIGURATION_FILE);
  PropertyConfigurator.configure(url);
  assertTrue(file.delete());
  assertFalse(file.exists());
}
 

Example 68

From project dolphin, under directory /com.sysdeo.eclipse.tomcat/src/com/sysdeo/eclipse/tomcat/.

Source file: Zipper.java

  31 
vote

private void zipDir(File dir) throws IOException {
  if (!dir.getPath().equals(currentDirName)) {
    String entryName=dir.getPath().substring(currentDirName.length() + 1);
    entryName=entryName.replace('\\','/');
    ZipEntry ze=new ZipEntry(entryName + "/");
    if (dir != null && dir.exists()) {
      ze.setTime(dir.lastModified());
    }
 else {
      ze.setTime(System.currentTimeMillis());
    }
    ze.setSize(0);
    ze.setMethod(ZipEntry.STORED);
    ze.setCrc(EMPTY_CRC);
    zos.putNextEntry(ze);
  }
  if (dir.exists() && dir.isDirectory()) {
    File[] fileList=dir.listFiles();
    for (int i=0; i < fileList.length; i++) {
      if (fileList[i].isDirectory() && this.acceptDir(fileList[i])) {
        zipDir(fileList[i]);
      }
      if (fileList[i].isFile() && this.acceptFile(fileList[i])) {
        zipFile(fileList[i]);
      }
    }
  }
}
 

Example 69

From project EasySOA, under directory /easysoa-registry/easysoa-registry-api/easysoa-registry-api-frascati/src/main/java/org/easysoa/registry/frascati/.

Source file: FileUtils.java

  31 
vote

/** 
 * Unzips the given jar in a temp file and returns its files' URLs Inspired from AssemblyFactoryManager.processContribution() (though doesn't add it to the classloader or parse composites) TODO move to util TODO better : delete temp files afterwards (or mark them so) OR rather use jar:url ?
 * @param SCA zip or jar
 * @return unzipped composites URLs
 * @throws ManagerException
 */
public static final Set<URL> unzipAndGetFileUrls(File file){
  try {
    ZipFile zipFile=new ZipFile(file);
    final String folder=zipFile.getName().substring(zipFile.getName().lastIndexOf(File.separator),zipFile.getName().length() - ".zip".length());
    Set<URL> fileURLSet=new HashSet<URL>();
    final String tempDir=System.getProperty("java.io.tmpdir") + File.separator + folder+ File.separator;
    Enumeration<? extends ZipEntry> entries=zipFile.entries();
    while (entries.hasMoreElements()) {
      ZipEntry entry=entries.nextElement();
      log.info("ZIP entry: " + entry.getName());
      if (entry.isDirectory()) {
        log.info("create directory : " + tempDir + entry.getName());
        new File(tempDir,entry.getName()).mkdirs();
      }
 else {
        File f=new File(tempDir,File.separator + entry.getName());
        int idx=entry.getName().lastIndexOf(File.separator);
        if (idx != -1) {
          String tmp=entry.getName().substring(0,idx);
          log.info("create directory : " + tempDir + tmp);
          new File(tempDir,tmp).mkdirs();
        }
        copy(zipFile.getInputStream(entry),new BufferedOutputStream(new FileOutputStream(f)));
        fileURLSet.add(f.toURI().toURL());
      }
    }
    return fileURLSet;
  }
 catch (  IOException e) {
    log.error(e);
    return new HashSet<URL>(0);
  }
}
 

Example 70

From project Eclipse, under directory /com.mobilesorcery.sdk.core/src/com/mobilesorcery/sdk/core/.

Source file: Util.java

  31 
vote

private static void zip(File sourceDir,File targetZip,boolean isJar) throws IOException {
  ZipOutputStream output=createZipOutputStream(new FileOutputStream(targetZip),isJar);
  try {
    for (    File file : listFiles(sourceDir,true)) {
      if (!file.isDirectory()) {
        String relativePath=file.getAbsolutePath().substring(sourceDir.getAbsolutePath().length());
        ZipEntry entry=createZipEntry(relativePath,isJar);
        output.putNextEntry(entry);
        FileInputStream fileInput=new FileInputStream(file);
        try {
          transfer(fileInput,output);
        }
  finally {
          Util.safeClose(fileInput);
          output.closeEntry();
        }
      }
    }
  }
  finally {
    Util.safeClose(output);
  }
}
 

Example 71

From project eclipse-integration-cloudfoundry, under directory /org.cloudfoundry.ide.eclipse.server.core/src/org/cloudfoundry/ide/eclipse/internal/server/core/.

Source file: ModuleResourceApplicationArchive.java

  31 
vote

public void generatePartialWarFile(Set<String> knownResourceNames){
  Iterable<Entry> localEntries=getEntries();
  Map<String,AbstractModuleResourceEntryAdapter> missingChangedEntries=new HashMap<String,AbstractModuleResourceEntryAdapter>();
  Set<IModuleResource> missingChangedResources=new HashSet<IModuleResource>();
  for (  Entry entry : localEntries) {
    if (entry.isDirectory() || !knownResourceNames.contains(entry.getName())) {
      missingChangedEntries.put(entry.getName(),(AbstractModuleResourceEntryAdapter)entry);
      missingChangedResources.add(((AbstractModuleResourceEntryAdapter)entry).getResource());
    }
  }
  try {
    File partialWar=CloudUtil.createWarFile(getModuleResources(),getModule(),missingChangedResources,null);
    if (partialWar.exists()) {
      fileName=partialWar.getName();
      ZipFile zipPartialWar=new ZipFile(partialWar);
      Enumeration<? extends ZipEntry> zipEntries=zipPartialWar.entries();
      List<Entry> toDeploy=new ArrayList<ApplicationArchive.Entry>();
      while (zipEntries.hasMoreElements()) {
        ZipEntry zipEntry=zipEntries.nextElement();
        AbstractModuleResourceEntryAdapter archiveEntry=missingChangedEntries.get(zipEntry.getName());
        if (archiveEntry != null) {
          DeployedResourceEntry deployedResourcesEntry=archiveEntry instanceof ZipModuleFileEntryAdapter ? ((ZipModuleFileEntryAdapter)archiveEntry).getDeployedResourcesEntry() : null;
          toDeploy.add(new PartialZipEntryAdapter(deployedResourcesEntry,zipEntry,zipPartialWar));
        }
      }
      entries=toDeploy;
    }
  }
 catch (  CoreException e) {
    CloudFoundryPlugin.logError(e);
  }
catch (  ZipException e) {
    CloudFoundryPlugin.logError(e);
  }
catch (  IOException e) {
    CloudFoundryPlugin.logError(e);
  }
}
 

Example 72

From project eclipse.pde.build, under directory /org.eclipse.pde.build/src/org/eclipse/pde/internal/build/site/.

Source file: ProfileManager.java

  31 
vote

private InputStream getProfileListInputStream(Object container){
  if (container instanceof File) {
    File listFile=new File((File)container,PROFILE_LIST);
    if (listFile.exists())     try {
      return new BufferedInputStream(new FileInputStream(listFile));
    }
 catch (    FileNotFoundException e) {
      return null;
    }
  }
 else   if (container instanceof ZipFile) {
    ZipFile zipFile=(ZipFile)container;
    ZipEntry listEntry=((ZipFile)container).getEntry(PROFILE_LIST);
    if (listEntry != null)     try {
      return new BufferedInputStream(zipFile.getInputStream(listEntry));
    }
 catch (    IOException e) {
      return null;
    }
  }
 else   if (container instanceof Bundle) {
    Bundle systemBundle=(Bundle)container;
    URL url=systemBundle.getEntry(PROFILE_LIST);
    if (url != null) {
      try {
        return new BufferedInputStream(url.openStream());
      }
 catch (      IOException e) {
        return null;
      }
    }
  }
  return null;
}
 

Example 73

From project enclojure, under directory /org-enclojure-ide/src/main/java/org/enclojure/ide/asm/optimizer/.

Source file: JarOptimizer.java

  31 
vote

static void optimize(final File f) throws IOException {
  if (f.isDirectory()) {
    File[] files=f.listFiles();
    for (int i=0; i < files.length; ++i) {
      optimize(files[i]);
    }
  }
 else   if (f.getName().endsWith(".jar")) {
    File g=new File(f.getParentFile(),f.getName() + ".new");
    ZipFile zf=new ZipFile(f);
    ZipOutputStream out=new ZipOutputStream(new FileOutputStream(g));
    Enumeration e=zf.entries();
    byte[] buf=new byte[10000];
    while (e.hasMoreElements()) {
      ZipEntry ze=(ZipEntry)e.nextElement();
      if (ze.isDirectory()) {
        continue;
      }
      out.putNextEntry(ze);
      if (ze.getName().endsWith(".class")) {
        ClassReader cr=new ClassReader(zf.getInputStream(ze));
        cr.accept(new ClassVerifier(),0);
      }
      InputStream is=zf.getInputStream(ze);
      int n;
      do {
        n=is.read(buf,0,buf.length);
        if (n != -1) {
          out.write(buf,0,n);
        }
      }
 while (n != -1);
      out.closeEntry();
    }
    out.close();
    zf.close();
    f.delete();
    g.renameTo(f);
  }
}
 

Example 74

From project encog-java-core, under directory /src/main/java/org/encog/ml/data/buffer/codec/.

Source file: ExcelCODEC.java

  31 
vote

/** 
 * {@inheritDoc}
 */
@Override public void prepareRead(){
  try {
    this.readZipFile=new ZipFile(this.file);
    final Enumeration<? extends ZipEntry> entries=this.readZipFile.entries();
    this.entry=null;
    while (entries.hasMoreElements()) {
      final ZipEntry e=entries.nextElement();
      if (e.getName().equals("xl/worksheets/sheet1.xml")) {
        this.entry=e;
      }
    }
    if (this.entry == null) {
      this.readZipFile.close();
      this.readZipFile=null;
      throw new BufferedDataError("Could not find worksheet.");
    }
    final InputStream is=this.readZipFile.getInputStream(this.entry);
    this.xmlIn=new ReadXML(is);
  }
 catch (  final ZipException e) {
    throw new BufferedDataError("Not a valid Excel file.");
  }
catch (  final IOException e) {
    throw new BufferedDataError(e);
  }
}
 

Example 75

From project Extlet6, under directory /liferay-6.0.5-patch/portal-impl/src/com/liferay/portal/deploy/hot/.

Source file: ExtHotDeployListener.java

  31 
vote

private void zipWebInfJar(String zipName,File[] files) throws Exception {
  byte[] buffer=new byte[4096];
  int bytesRead;
  ZipOutputStream out=new ZipOutputStream(new FileOutputStream(zipName));
  try {
    for (int i=0; i < files.length; i++) {
      File f=files[i];
      if (f.isDirectory()) {
        continue;
      }
      String fileName="WEB-INF/" + f.getName();
      FileInputStream in=new FileInputStream(f);
      try {
        ZipEntry entry=new ZipEntry(fileName);
        out.putNextEntry(entry);
        while ((bytesRead=in.read(buffer)) != -1) {
          out.write(buffer,0,bytesRead);
        }
      }
  finally {
        in.close();
      }
    }
  }
  finally {
    out.close();
  }
}
 

Example 76

From project cargo-maven2-plugin-db, under directory /src/test/java/org/codehaus/cargo/maven2/configuration/.

Source file: ContainerTest.java

  30 
vote

public void testCreateEmbeddedContainerWithExtraClasspathDependency() throws Exception {
  String resourceValue="file in zip in dependency";
  String resourceName="maven-test-my-dependency.txt";
  File zipFile=File.createTempFile("maven2-plugin-test-dependency",".zip");
  zipFile.deleteOnExit();
  ZipOutputStream zip=new ZipOutputStream(new FileOutputStream(zipFile));
  zip.putNextEntry(new ZipEntry(resourceName));
  zip.write(resourceValue.getBytes());
  zip.close();
  DefaultArtifact artifact=new DefaultArtifact("customGroupId","customArtifactId",VersionRange.createFromVersion("0.1"),"compile","jar",null,new DefaultArtifactHandler());
  artifact.setFile(zipFile);
  Set artifacts=new HashSet();
  artifacts.add(artifact);
  Dependency dependencyElement=new Dependency();
  dependencyElement.setGroupId("customGroupId");
  dependencyElement.setArtifactId("customArtifactId");
  dependencyElement.setType("jar");
  org.codehaus.cargo.maven2.configuration.Container containerElement=setUpContainerElement(new EmbeddedLocalContainerStub());
  containerElement.setDependencies(new Dependency[]{dependencyElement});
  org.codehaus.cargo.container.EmbeddedLocalContainer container=(EmbeddedLocalContainer)containerElement.createContainer(new StandaloneLocalConfigurationStub("configuration/home"),new NullLogger(),createTestCargoProject("whatever",artifacts));
  assertEquals(resourceValue,getResource(container.getClassLoader(),resourceName));
  assertEquals(resourceValue,getResource(Thread.currentThread().getContextClassLoader(),resourceName));
}
 

Example 77

From project cider, under directory /src/net/yacy/cider/util/.

Source file: FileUtils.java

  30 
vote

public static void saveSet(final File file,final String format,final Set<byte[]> set,final String sep) throws IOException {
  final File tf=new File(file.toString() + ".prt" + (System.currentTimeMillis() % 1000));
  OutputStream os=null;
  if ((format == null) || (format.equals("plain"))) {
    os=new BufferedOutputStream(new FileOutputStream(tf));
  }
 else   if (format.equals("gzip")) {
    os=new GZIPOutputStream(new FileOutputStream(tf));
  }
 else   if (format.equals("zip")) {
    final ZipOutputStream zos=new ZipOutputStream(new FileOutputStream(file));
    String name=file.getName();
    if (name.endsWith(".zip"))     name=name.substring(0,name.length() - 4);
    zos.putNextEntry(new ZipEntry(name + ".txt"));
    os=zos;
  }
  if (os != null) {
    for (final Iterator<byte[]> i=set.iterator(); i.hasNext(); ) {
      os.write(i.next());
      if (sep != null)       os.write(sep.getBytes("UTF-8"));
    }
    os.close();
  }
  forceMove(tf,file);
}
 

Example 78

From project android-ocr, under directory /android/src/edu/sfsu/cs/orange/ocr/.

Source file: OcrInitAsyncTask.java

  29 
vote

/** 
 * Unzip the given Zip file, located in application assets, into the given destination file.
 * @param sourceFilename Name of the file in assets
 * @param destinationDir Directory to save the destination file in
 * @param destinationFile File to unzip into, excluding path
 * @return
 * @throws IOException
 * @throws FileNotFoundException
 */
private boolean installZipFromAssets(String sourceFilename,File destinationDir,File destinationFile) throws IOException, FileNotFoundException {
  publishProgress("Uncompressing data for " + languageName + "...","0");
  ZipInputStream inputStream=new ZipInputStream(context.getAssets().open(sourceFilename));
  for (ZipEntry entry=inputStream.getNextEntry(); entry != null; entry=inputStream.getNextEntry()) {
    destinationFile=new File(destinationDir,entry.getName());
    if (entry.isDirectory()) {
      destinationFile.mkdirs();
    }
 else {
      long zippedFileSize=entry.getSize();
      FileOutputStream outputStream=new FileOutputStream(destinationFile);
      final int BUFFER=8192;
      BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(outputStream,BUFFER);
      int unzippedSize=0;
      int count=0;
      Integer percentComplete=0;
      Integer percentCompleteLast=0;
      byte[] data=new byte[BUFFER];
      while ((count=inputStream.read(data,0,BUFFER)) != -1) {
        bufferedOutputStream.write(data,0,count);
        unzippedSize+=count;
        percentComplete=(int)((unzippedSize / (long)zippedFileSize) * 100);
        if (percentComplete > percentCompleteLast) {
          publishProgress("Uncompressing data for " + languageName + "...",percentComplete.toString(),"0");
          percentCompleteLast=percentComplete;
        }
      }
      bufferedOutputStream.close();
    }
    inputStream.closeEntry();
  }
  inputStream.close();
  return true;
}
 

Example 79

From project closure-templates, under directory /java/src/com/google/template/soy/javasrc/dyncompile/.

Source file: ClasspathUtils.java

  29 
vote

/** 
 * Iterates through the entries in a ZIP file to enumerate all the resources under a particular package tree.
 * @param pathInJar A package path like {@code "java/lang"}.
 * @param isRecursive True iff sub-packages should be included.
 * @param zipFileUrl A gettable URL to a ZIP file.
 * @param classResourcePaths Receives resource paths like {@code "java/lang/Object.class"}.
 */
private static void searchZipAtFileForPath(String pathInJar,boolean isRecursive,URL zipFileUrl,ImmutableList.Builder<? super String> classResourcePaths) throws IOException {
  InputStream in=zipFileUrl.openStream();
  try {
    ZipInputStream zipIn=new ZipInputStream(in);
    String prefix=pathInJar;
    if (pathInJar.startsWith("/")) {
      prefix=prefix.substring(1);
    }
    for (ZipEntry zipEntry; (zipEntry=zipIn.getNextEntry()) != null; ) {
      String zipEntryName=zipEntry.getName();
      if (!zipEntry.isDirectory() && zipEntryName.endsWith(".class") && zipEntryName.startsWith(prefix)) {
        if (zipEntryName.lastIndexOf('/') == prefix.length() || (isRecursive && (prefix.length() == 0 || zipEntryName.charAt(prefix.length()) == '/'))) {
          classResourcePaths.add(zipEntryName);
        }
      }
    }
  }
  finally {
    in.close();
  }
}
 

Example 80

From project commons-compress, under directory /src/main/java/org/apache/commons/compress/archivers/zip/.

Source file: ZipFile.java

  29 
vote

/** 
 * Returns an InputStream for reading the contents of the given entry.
 * @param ze the entry to get the stream for.
 * @return a stream to read the entry from.
 * @throws IOException if unable to create an input stream from the zipentry
 * @throws ZipException if the zipentry uses an unsupported feature
 */
public InputStream getInputStream(ZipArchiveEntry ze) throws IOException, ZipException {
  OffsetEntry offsetEntry=entries.get(ze);
  if (offsetEntry == null) {
    return null;
  }
  ZipUtil.checkRequestedFeatures(ze);
  long start=offsetEntry.dataOffset;
  BoundedInputStream bis=new BoundedInputStream(start,ze.getCompressedSize());
switch (ze.getMethod()) {
case ZipEntry.STORED:
    return bis;
case ZipEntry.DEFLATED:
  bis.addDummy();
final Inflater inflater=new Inflater(true);
return new InflaterInputStream(bis,inflater){
@Override public void close() throws IOException {
  super.close();
  inflater.end();
}
}
;
default :
throw new ZipException("Found unsupported compression method " + ze.getMethod());
}
}
 

Example 81

From project eclipse-integration-commons, under directory /org.springsource.ide.eclipse.commons.core/src/org/springsource/ide/eclipse/commons/core/.

Source file: ZipFileUtil.java

  29 
vote

/** 
 * Creates an executable permission setter based on a list of file extensions. <p> Any file ending with the extension will be made executable.
 */
public static PermissionSetter executableExtensions(final String... exts){
  if (OsUtils.isWindows()) {
    return NULL;
  }
 else {
    return new PermissionSetter(){
      @Override public void fileUnzipped(      ZipEntry entry,      File entryFile) throws IOException {
        for (        String ext : exts) {
          if (entryFile.getName().endsWith(ext)) {
            StandardProcessRunner runner=new StandardProcessRunner();
            try {
              runner.run(new File("."),"chmod","a+x",entryFile.toString());
            }
 catch (            InterruptedException e) {
              Thread.currentThread().interrupt();
            }
            return;
          }
        }
      }
    }
;
  }
}
 

Example 82

From project eclipse-integration-gradle, under directory /org.springsource.ide.eclipse.gradle.core/src/org/springsource/ide/eclipse/gradle/core/util/.

Source file: ZipFileUtil.java

  29 
vote

/** 
 * Creates an executable permission setter based on a list of file extensions. <p> Any file ending with the extension will be made executable.
 */
public static PermissionSetter executableExtensions(final String... exts){
  if (OsUtils.isWindows()) {
    return NULL;
  }
 else {
    return new PermissionSetter(){
      @Override public void fileUnzipped(      ZipEntry entry,      File entryFile) throws IOException {
        String name=entryFile.toString();
        for (        String ext : exts) {
          if (name.endsWith(ext)) {
            entryFile.setExecutable(true);
          }
        }
      }
    }
;
  }
}