Java Code Examples for java.util.zip.ZipInputStream

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 core_3, under directory /src/main/java/org/animotron/bridge/.

Source file: AbstractZipBridge.java

  33 
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 2

From project mylyn.docs.intent.main, under directory /plugins/org.eclipse.mylyn.docs.intent.exporter.ui/src/org/eclipse/mylyn/docs/intent/exporter/ui/popup/actions/.

Source file: ExportIntentDocumentationAction.java

  33 
vote

/** 
 * Copies in the given target folder all the files (css, javascript...) required by this HTML export
 * @param targetFolder
 * @throws IOException
 */
private void copyRequiredResourcesToGenerationFolder(File targetFolder) throws IOException {
  Bundle bundle=Platform.getBundle("org.eclipse.mylyn.docs.intent.exporter");
  Path path=new Path("resources/html_bootstrap/html_bootstrap.zip");
  ZipInputStream zipFileStream=new ZipInputStream(FileLocator.find(bundle,path,null).openStream());
  ZipEntry zipEntry=zipFileStream.getNextEntry();
  try {
    while (zipEntry != null) {
      final File file=new File(targetFolder.getAbsolutePath().toString(),zipEntry.getName());
      if (!zipEntry.isDirectory()) {
        final File parentFile=file.getParentFile();
        if (null != parentFile && !parentFile.exists()) {
          parentFile.mkdirs();
        }
        OutputStream os=null;
        try {
          os=new FileOutputStream(file);
          final int bufferSize=102400;
          final byte[] buffer=new byte[bufferSize];
          while (true) {
            final int len=zipFileStream.read(buffer);
            if (zipFileStream.available() == 0) {
              break;
            }
            os.write(buffer,0,len);
          }
        }
  finally {
          if (null != os) {
            os.close();
          }
        }
      }
      zipFileStream.closeEntry();
      zipEntry=zipFileStream.getNextEntry();
    }
  }
  finally {
    zipFileStream.close();
  }
}
 

Example 3

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

Source file: ZipHelper.java

  32 
vote

public static void unzipFile(InputStream fis,ZipEntryHandler zipHandler,boolean closeStream) throws IOException {
  ZipInputStream zis=new ZipInputStream(new BufferedInputStream(fis));
  ZipEntry entry;
  while ((entry=zis.getNextEntry()) != null) {
    zipHandler.unzip(entry,new NoCloseInputStream(zis));
  }
  if (closeStream)   zis.close();
}
 

Example 4

From project core_1, under directory /runtime/src/main/java/org/switchyard/internal/io/.

Source file: ZIPSerializer.java

  32 
vote

/** 
 * {@inheritDoc}
 */
@Override public <T>T deserialize(InputStream in,Class<T> type,int bufferSize) throws IOException {
  ZipInputStream zip=new ZipInputStream(in);
  try {
    zip.getNextEntry();
    return _serializer.deserialize(zip,type,bufferSize);
  }
  finally {
    if (isCloseEnabled()) {
      zip.close();
    }
  }
}
 

Example 5

From project gxa, under directory /atlas-loader/src/main/java/uk/ac/ebi/gxa/loader/datamatrix/.

Source file: DataMatrixFileBuffer.java

  32 
vote

/** 
 * Opens zip file and navigates to a proper entry. It's caller's responsibility to close the input stream.
 * @return an {@link InputStream} ready to read the entry's content
 * @throws FileNotFoundException in case there's no such entry
 * @throws IOException           in case of any I/O errors
 */
private InputStream openStream() throws IOException {
  if (fileName == null)   return dataMatrixURL.openStream();
  dataMatrixURL=new URL(DataUtils.fixZipURL(dataMatrixURL.toExternalForm()));
  ZipInputStream zistream=new ZipInputStream(new BufferedInputStream(dataMatrixURL.openStream()));
  ZipEntry zi;
  while ((zi=zistream.getNextEntry()) != null) {
    if (zi.getName().toLowerCase().endsWith(fileName.toLowerCase())) {
      return zistream;
    }
    zistream.closeEntry();
  }
  zistream.close();
  throw new FileNotFoundException("Can't find file " + fileName + " in archive "+ dataMatrixURL);
}
 

Example 6

From project jabox, under directory /jabox-persistence/src/main/java/org/jabox/utils/.

Source file: Unzip.java

  32 
vote

public static void unzip(File zipFile,File baseDir) throws IOException {
  InputStream in=new BufferedInputStream(new FileInputStream(zipFile));
  ZipInputStream zin=new ZipInputStream(in);
  ZipEntry e;
  while ((e=zin.getNextEntry()) != null) {
    if (!e.isDirectory()) {
      unzip(zin,baseDir,e.getName());
    }
  }
  zin.close();
}
 

Example 7

From project logback, under directory /logback-core/src/test/java/ch/qos/logback/core/util/.

Source file: Compare.java

  32 
vote

static BufferedReader zipFileToBufferedReader(String file) throws IOException {
  FileInputStream fis=new FileInputStream(file);
  ZipInputStream zis=new ZipInputStream(fis);
  zis.getNextEntry();
  return new BufferedReader(new InputStreamReader(zis));
}
 

Example 8

From project maven-shared, under directory /maven-jarsigner/src/main/java/org/apache/maven/shared/jarsigner/.

Source file: JarSignerUtil.java

  32 
vote

/** 
 * Checks whether the specified file is a JAR file. For our purposes, a ZIP file is a ZIP stream with at least one entry.
 * @param file The file to check, must not be <code>null</code>.
 * @return <code>true</code> if the file looks like a ZIP file, <code>false</code> otherwise.
 */
public static boolean isZipFile(final File file){
  try {
    ZipInputStream zis=new ZipInputStream(new FileInputStream(file));
    try {
      return zis.getNextEntry() != null;
    }
  finally {
      zis.close();
    }
  }
 catch (  Exception e) {
  }
  return false;
}
 

Example 9

From project mobilis, under directory /MobilisServer/src/de/tudresden/inf/rn/mobilis/server/deployment/helper/.

Source file: FileHelper.java

  32 
vote

/** 
 * Gets the a list of files in a jar file.
 * @param jarFile the jar file which should be queried
 * @return the packed files of the jar file as relative paths
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static List<String> getJarFiles(File jarFile) throws IOException {
  List<String> jarFiles=new ArrayList<String>();
  FileInputStream fileInputStream=new FileInputStream(jarFile);
  ZipInputStream zipInputStream=new ZipInputStream(fileInputStream);
  ZipEntry zipEntry;
  while ((zipEntry=zipInputStream.getNextEntry()) != null) {
    jarFiles.add(zipEntry.getName());
  }
  zipInputStream.close();
  fileInputStream.close();
  return jarFiles;
}
 

Example 10

From project nexus-obr-plugin, under directory /nexus-obr-plugin/src/main/java/org/sonatype/nexus/obr/metadata/.

Source file: AbstractObrSite.java

  32 
vote

public final InputStream openStream() throws IOException {
  if ("application/zip".equalsIgnoreCase(getContentType())) {
    final ZipInputStream zis=new ZipInputStream(openRawStream());
    for (ZipEntry e=zis.getNextEntry(); e != null; e=zis.getNextEntry()) {
      final String name=e.getName().toLowerCase();
      if (name.endsWith("repository.xml") || name.endsWith("obr.xml")) {
        return zis;
      }
    }
    throw new IOException("No repository.xml or obr.xml in zip: " + getMetadataUrl());
  }
  return openRawStream();
}
 

Example 11

From project nuxeo-common, under directory /src/main/java/org/nuxeo/common/utils/.

Source file: ZipUtils.java

  32 
vote

public static void unzip(String prefix,InputStream zipStream,File dir) throws IOException {
  ZipInputStream in=null;
  try {
    in=new ZipInputStream(new BufferedInputStream(zipStream));
    unzip(prefix,in,dir);
  }
  finally {
    if (in != null) {
      in.close();
    }
  }
}
 

Example 12

From project nuxeo-platform-rendering-templates, under directory /src/main/java/org/nuxeo/ecm/platform/template/processors/docx/.

Source file: WordXMLRawTemplateProcessor.java

  32 
vote

public String readPropertyFile(InputStream in) throws Exception {
  ZipInputStream zIn=new ZipInputStream(in);
  ZipEntry zipEntry=zIn.getNextEntry();
  String xmlContent=null;
  while (zipEntry != null) {
    if (zipEntry.getName().equals("docProps/custom.xml")) {
      StringBuilder sb=new StringBuilder();
      byte[] buffer=new byte[BUFFER_SIZE];
      int read;
      while ((read=zIn.read(buffer)) != -1) {
        sb.append(new String(buffer,0,read));
      }
      xmlContent=sb.toString();
      break;
    }
    zipEntry=zIn.getNextEntry();
  }
  zIn.close();
  return xmlContent;
}
 

Example 13

From project nuxeo-tycho-osgi, under directory /nuxeo-common/src/main/java/org/nuxeo/common/utils/.

Source file: ZipUtils.java

  32 
vote

public static void unzip(String prefix,InputStream zipStream,File dir) throws IOException {
  ZipInputStream in=null;
  try {
    in=new ZipInputStream(new BufferedInputStream(zipStream));
    unzip(prefix,in,dir);
  }
  finally {
    if (in != null) {
      in.close();
    }
  }
}
 

Example 14

From project nuxeo-webengine, under directory /nuxeo-webengine-core/src/main/java/.

Source file: Archetype.java

  32 
vote

public static void unzip(File zip,File dir) throws IOException {
  ZipInputStream in=null;
  try {
    in=new ZipInputStream(new BufferedInputStream(new FileInputStream(zip)));
    unzip(in,dir);
  }
  finally {
    if (in != null) {
      in.close();
    }
  }
}
 

Example 15

From project onebusaway-nyc, under directory /onebusaway-nyc-transit-data-manager/onebusaway-nyc-tdm-webapp/src/test/java/org/onebusaway/nyc/transit_data_manager/api/barcode/.

Source file: ZipFileTesterUtil.java

  32 
vote

public int getNumEntriesInZipInputStream(InputStream is) throws IOException {
  ZipInputStream zis=new ZipInputStream(is);
  int numFilesInZip=0;
  while (zis.getNextEntry() != null) {
    numFilesInZip++;
  }
  zis.close();
  return numFilesInZip;
}
 

Example 16

From project QuakeInjector, under directory /src/de/haukerehfeld/quakeinjector/.

Source file: InspectZipWorker.java

  32 
vote

@Override public List<ZipEntry> doInBackground() throws IOException, FileNotFoundException {
  ZipInputStream zis=new ZipInputStream(new BufferedInputStream(input));
  List<ZipEntry> entries=new ArrayList<ZipEntry>();
  ZipEntry entry;
  while ((entry=zis.getNextEntry()) != null) {
    entries.add(entry);
  }
  zis.close();
  return entries;
}
 

Example 17

From project RSB, under directory /src/it/java/eu/openanalytics/rsb/.

Source file: AbstractITCase.java

  32 
vote

public static void validateZipResult(final InputStream responseStream) throws IOException {
  final ZipInputStream result=new ZipInputStream(responseStream);
  ZipEntry ze=null;
  while ((ze=result.getNextEntry()) != null) {
    if (ze.getName().endsWith(".pdf")) {
      return;
    }
  }
  fail("No PDF file found in Zip result");
}
 

Example 18

From project rundeck, under directory /core/src/main/java/com/dtolabs/rundeck/core/plugins/.

Source file: ScriptPluginProviderLoader.java

  32 
vote

/** 
 * Get plugin metadatat from a zip file
 */
static PluginMeta loadMeta(final File jar) throws IOException {
  final ZipInputStream zipinput=new ZipInputStream(new FileInputStream(jar));
  final PluginMeta metadata=ScriptPluginProviderLoader.loadMeta(jar,zipinput);
  zipinput.close();
  return metadata;
}
 

Example 19

From project skalli, under directory /org.eclipse.skalli.maven.test/src/main/java/org/eclipse/skalli/model/ext/maven/internal/.

Source file: ZipHelperTest.java

  32 
vote

@Test public void testGetEntryAsInputStream_rootPom() throws Exception {
  URL url=this.getClass().getResource(RES_ZIP_PATH + "org.eclipse.skalli-pom.xml-HEAD.zip");
  InputStream openUrlStream=url.openStream();
  try {
    ZipInputStream zip=new ZipInputStream(openUrlStream);
    String fileName="pom.xml";
    InputStream inputStream=ZipHelper.getEntry(zip,fileName);
    String result=IOUtils.toString(inputStream);
    assertThat(result,is(getResourceAsString(RES_EXPECTED_PATH + "org.eclipse.skalli-pom.xml")));
  }
  finally {
    openUrlStream.close();
  }
}
 

Example 20

From project Supersonic, under directory /src/main/java/be/hehehe/supersonic/service/.

Source file: Library.java

  32 
vote

@PostConstruct public void loadFromFile(){
  File libraryFile=new File(LIBRARY_FILE);
  if (libraryFile.exists()) {
    try {
      ZipInputStream zip=new ZipInputStream(new FileInputStream(libraryFile));
      zip.getNextEntry();
      String content=IOUtils.toString(zip);
      albums=new JSONDeserializer<List<AlbumModel>>().deserialize(content);
    }
 catch (    IOException e) {
    }
  }
}
 

Example 21

From project teamcity-nuget-support, under directory /nuget-tests/src/jetbrains/buildServer/nuget/tests/integration/.

Source file: PackIntegrationTest.java

  32 
vote

@Test(dataProvider=NUGET_VERSIONS) public void test_vs_solution(@NotNull final NuGet nuget) throws IOException, RunBuildException {
  ZipUtil.extract(getTestDataPath("solution.zip"),myRoot,null);
  final File spec=new File(myRoot,"nuget-proj/nuget-proj.csproj");
  msbuild(new File(myRoot,"nuget-proj.sln"));
  callRunner(nuget,spec,false,false,false);
  Assert.assertTrue(nupkgs().length == 1,"There should be only one package created");
  final File nupkg=nupkgs()[0];
  ZipInputStream zis=new ZipInputStream(new BufferedInputStream(new FileInputStream(nupkg)));
  for (ZipEntry ze; (ze=zis.getNextEntry()) != null; ) {
    System.out.println(ze.getName());
  }
  zis.close();
  m.assertIsSatisfied();
}
 

Example 22

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 23

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 24

From project android-database-sqlcipher, under directory /src/net/sqlcipher/database/.

Source file: SQLiteDatabase.java

  31 
vote

private static void loadICUData(Context context,File workingDir){
  try {
    File icuDir=new File(workingDir,"icu");
    if (!icuDir.exists())     icuDir.mkdirs();
    File icuDataFile=new File(icuDir,"icudt46l.dat");
    if (!icuDataFile.exists()) {
      ZipInputStream in=new ZipInputStream(context.getAssets().open("icudt46l.zip"));
      in.getNextEntry();
      OutputStream out=new FileOutputStream(icuDataFile);
      byte[] buf=new byte[1024];
      int len;
      while ((len=in.read(buf)) > 0) {
        out.write(buf,0,len);
      }
      in.close();
      out.flush();
      out.close();
    }
  }
 catch (  Exception e) {
    Log.e(TAG,"Error copying icu data file" + e.getMessage());
  }
}
 

Example 25

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 26

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

Source file: OcrInitAsyncTask.java

  31 
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 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 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 30

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 31

From project aws-toolkit-for-eclipse, under directory /com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/webproject/.

Source file: CreateNewAwsJavaWebProjectRunnable.java

  31 
vote

private void unzipSampleAppTemplate(File file,File destination) throws FileNotFoundException, IOException {
  ZipInputStream zipInputStream=new ZipInputStream(new FileInputStream(file));
  ZipEntry zipEntry=null;
  while ((zipEntry=zipInputStream.getNextEntry()) != null) {
    IPath path=new Path(zipEntry.getName());
    path=path.removeFirstSegments(1);
    File destinationFile=new File(destination,path.toOSString());
    if (zipEntry.isDirectory()) {
      destinationFile.mkdirs();
    }
 else {
      FileOutputStream outputStream=new FileOutputStream(destinationFile);
      IOUtils.copy(zipInputStream,outputStream);
      outputStream.close();
    }
  }
  zipInputStream.close();
}
 

Example 32

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 33

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 34

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 35

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

Source file: Zip.java

  31 
vote

public void unzip(InputStream source,File outputDir) throws IOException {
  ZipInputStream zis=new ZipInputStream(source);
  try {
    ZipEntry entry;
    while ((entry=zis.getNextEntry()) != null) {
      File file=new File(outputDir,entry.getName());
      if (entry.isDirectory()) {
        FileHandler.createDir(file);
        continue;
      }
      unzipFile(outputDir,zis,entry.getName());
    }
  }
  finally {
    Closeables.closeQuietly(zis);
  }
}
 

Example 36

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

Source file: Importer.java

  31 
vote

/** 
 * Create a tar.gz archive of the exported directory.
 * @param exportDir Directory where Candlepin data was exported.
 * @return File reference to the new archive tar.gz.
 */
private File extractArchive(File tempDir,File exportFile) throws IOException {
  log.info("Extracting archive to: " + tempDir.getAbsolutePath());
  byte[] buf=new byte[1024];
  ZipInputStream zipinputstream=null;
  ZipEntry zipentry;
  zipinputstream=new ZipInputStream(new FileInputStream(exportFile));
  zipentry=zipinputstream.getNextEntry();
  while (zipentry != null) {
    String entryName=zipentry.getName();
    if (log.isDebugEnabled()) {
      log.debug("entryname " + entryName);
    }
    FileOutputStream fileoutputstream;
    File newFile=new File(entryName);
    String directory=newFile.getParent();
    if (directory != null) {
      new File(tempDir,directory).mkdirs();
    }
    fileoutputstream=new FileOutputStream(new File(tempDir,entryName));
    int n;
    while ((n=zipinputstream.read(buf,0,1024)) > -1) {
      fileoutputstream.write(buf,0,n);
    }
    fileoutputstream.close();
    zipinputstream.closeEntry();
    zipentry=zipinputstream.getNextEntry();
  }
  zipinputstream.close();
  return new File(tempDir.getAbsolutePath(),"export");
}
 

Example 37

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

Source file: UtilZip.java

  31 
vote

public static boolean unZipFile(String zipFile,String outDirectory){
  try {
    FileInputStream fin=new FileInputStream(zipFile);
    ZipInputStream zin=new ZipInputStream(fin);
    ZipEntry zipEntry=null;
    BufferedOutputStream dest=null;
    byte data[]=new byte[Constants.BUFFER_8K];
    while ((zipEntry=zin.getNextEntry()) != null) {
      if (zipEntry.isDirectory()) {
        File f=new File(Utils.buildPath(outDirectory,zipEntry.getName()));
        f.mkdir();
        zin.closeEntry();
        continue;
      }
      File f=new File(Utils.buildPath(outDirectory,zipEntry.getName()));
      f.getParentFile().mkdirs();
      FileOutputStream fos=new FileOutputStream(f);
      int count;
      dest=new BufferedOutputStream(fos,Constants.BUFFER_8K);
      while ((count=zin.read(data,0,Constants.BUFFER_8K)) != -1) {
        dest.write(data,0,count);
      }
      dest.flush();
      dest.close();
    }
    zin.close();
    return true;
  }
 catch (  FileNotFoundException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
  return false;
}
 

Example 38

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 39

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

Source file: ClasspathUtils.java

  31 
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 40

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 41

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 42

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 43

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 44

From project com.idega.content, under directory /src/java/com/idega/content/business/.

Source file: WebDAVUploadBean.java

  31 
vote

public boolean uploadZipFile(boolean uploadingTheme,String fileName,InputStream stream,IWSlideService slide) throws IOException {
  String resultInfo=null;
  boolean result=false;
  if (uploadingTheme) {
    String uploadFileName=fileName;
    if (uploadFileName == null) {
      uploadFileName=getUploadFileName();
    }
    if (!uploadFileName.equals(CoreConstants.EMPTY)) {
      uploadFilePath=getThemesHelper().changeFileUploadPath(getUploadFilePath() + uploadFileName);
    }
  }
  String path=getUploadFilePath();
  ZipInputStream zipStream=null;
  try {
    zipStream=new ZipInputStream(stream);
    if (slide.uploadZipFileContents(zipStream,path)) {
      resultInfo="Success uploading contents of file: " + path;
      result=true;
    }
 else {
      resultInfo="Unable to upload contents of file: " + path;
      result=false;
    }
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
 finally {
    IOUtil.close(stream);
    IOUtil.close(zipStream);
  }
  if (uploadingTheme) {
    getThemesHelper().removeThemeFromQueue(path);
  }
  LOGGER.info(resultInfo);
  return result;
}
 

Example 45

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 46

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 47

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 48

From project EasySOA, under directory /easysoa-proxy/easysoa-proxy-core/easysoa-proxy-core-httpdiscoveryproxy/src/main/java/org/easysoa/proxy/.

Source file: HttpResponseHandler.java

  31 
vote

public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
  Header contentEncodingHeader=response.getFirstHeader("Content-Encoding");
  StringBuffer responseBuffer=new StringBuffer();
  if (contentEncodingHeader != null) {
    byte[] buf=new byte[512];
    int len;
    ByteArrayOutputStream bos=new ByteArrayOutputStream();
    if ("gzip".equalsIgnoreCase(contentEncodingHeader.getValue())) {
      GZIPInputStream gzipInputStream=new GZIPInputStream(response.getEntity().getContent());
      while ((len=gzipInputStream.read(buf,0,512)) != -1) {
        bos.write(buf,0,len);
      }
      responseBuffer.append(new String(bos.toByteArray()));
    }
 else     if ("zip".equalsIgnoreCase(contentEncodingHeader.getValue())) {
      ZipInputStream zipInputStream=new ZipInputStream(response.getEntity().getContent());
      while ((len=zipInputStream.read(buf,0,512)) != -1) {
        bos.write(buf,0,len);
      }
      responseBuffer.append(new String(bos.toByteArray()));
    }
 else {
      logger.error("Unable to deflate this Content-Encoding : " + contentEncodingHeader.getValue());
      throw new IOException("Unable to deflate this Content-Encoding : " + contentEncodingHeader.getValue());
    }
  }
 else {
    InputStreamReader in=new InputStreamReader(response.getEntity().getContent());
    BufferedReader bin=new BufferedReader(in);
    String line;
    do {
      line=bin.readLine();
      if (line != null) {
        responseBuffer.append(line);
      }
    }
 while (line != null);
  }
  return responseBuffer.toString();
}
 

Example 49

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

Source file: Util.java

  31 
vote

private static void unzip(File zip,File targetDir,boolean isJar) throws IOException {
  ZipInputStream input=createZipInputStream(new FileInputStream(zip),isJar);
  OutputStream currentOutput=null;
  targetDir.mkdirs();
  try {
    for (ZipEntry entry=input.getNextEntry(); entry != null; entry=input.getNextEntry()) {
      File currentFile=new File(targetDir,entry.getName());
      if (!entry.isDirectory()) {
        int readBytes=0;
        byte[] buffer=new byte[512];
        currentFile.getParentFile().mkdirs();
        currentOutput=new FileOutputStream(currentFile);
        for (int read=input.read(buffer,0,buffer.length); read != -1; read=input.read(buffer,0,buffer.length)) {
          currentOutput.write(buffer,0,read);
          readBytes+=read;
        }
        currentOutput.close();
      }
 else {
        currentFile.mkdirs();
      }
      currentFile.setLastModified(entry.getTime());
    }
  }
  finally {
    Util.safeClose(input);
    Util.safeClose(currentOutput);
  }
}
 

Example 50

From project freemind, under directory /freemind/accessories/plugins/.

Source file: ImportMindmanagerFiles.java

  31 
vote

private void importMindmanagerFile(File file){
  try {
    ZipInputStream in=new ZipInputStream(new FileInputStream(file));
    while (in.available() != 0) {
      ZipEntry entry=in.getNextEntry();
      if (!entry.getName().equals("Document.xml")) {
        continue;
      }
      String xsltFileName="accessories/mindmanager2mm.xsl";
      URL xsltUrl=getResource(xsltFileName);
      if (xsltUrl == null) {
        logger.severe("Can't find " + xsltFileName + " as resource.");
        throw new IllegalArgumentException("Can't find " + xsltFileName + " as resource.");
      }
      InputStream xsltFile=xsltUrl.openStream();
      String xml=transForm(new StreamSource(in),xsltFile);
      if (xml != null) {
        File tempFile=File.createTempFile(file.getName(),freemind.main.FreeMindCommon.FREEMIND_FILE_EXTENSION,file.getParentFile());
        FileWriter fw=new FileWriter(tempFile);
        fw.write(xml);
        fw.close();
        getController().load(tempFile);
      }
      break;
    }
  }
 catch (  IOException e) {
    freemind.main.Resources.getInstance().logException(e);
  }
catch (  XMLParseException e) {
    freemind.main.Resources.getInstance().logException(e);
  }
}
 

Example 51

From project Game_3, under directory /core/tests/playn/core/json/.

Source file: InternalJsonParserTest.java

  31 
vote

/** 
 * Tests from json.org: http://www.json.org/JSON_checker/ Skips two tests that don't match reality (ie: Chrome).
 */
@Test public void jsonOrgTest() throws IOException {
  InputStream input=getClass().getResourceAsStream("json_org_test.zip");
  ZipInputStream zip=new ZipInputStream(input);
  ZipEntry ze;
  while ((ze=zip.getNextEntry()) != null) {
    if (ze.isDirectory())     continue;
    if (ze.getName().contains("fail1.json"))     continue;
    if (ze.getName().contains("fail18.json"))     continue;
    boolean positive=ze.getName().startsWith("test/pass");
    int offset=0;
    int size=(int)ze.getSize();
    byte[] buffer=new byte[size];
    while (size > 0) {
      int r=zip.read(buffer,offset,buffer.length - offset);
      if (r <= 0)       break;
      size-=r;
      offset+=r;
    }
    String testCase=new String(buffer,"ASCII");
    if (positive) {
      try {
        Object out=JsonParser.any().from(testCase);
        JsonStringWriter.toString(out);
      }
 catch (      JsonParserException e) {
        e.printStackTrace();
        fail("Should not have failed " + ze.getName() + ": "+ testCase);
      }
    }
 else {
      try {
        JsonParser.object().from(testCase);
        fail("Should have failed " + ze.getName() + ": "+ testCase);
      }
 catch (      JsonParserException e) {
      }
    }
  }
}
 

Example 52

From project GenericKnimeNodes, under directory /com.genericworkflownodes.knime.base_plugin/src/com/genericworkflownodes/util/.

Source file: ZipUtils.java

  31 
vote

/** 
 * Decompress the content of @p zipStream to the directory @p targetDir.
 * @param targetDir The directory where the zip should be extracted.
 * @param zipStream The zip file stream.
 */
public static void decompressTo(File targetDir,InputStream zipStream){
  targetDir.mkdirs();
  try {
    ZipInputStream zin=new ZipInputStream(zipStream);
    ZipEntry ze=null;
    byte[] buffer=new byte[2048];
    while ((ze=zin.getNextEntry()) != null) {
      File targetFile=new File(targetDir,ze.getName());
      if (ze.isDirectory()) {
        targetFile.mkdirs();
      }
 else {
        targetFile.getParentFile().mkdirs();
        FileOutputStream fout=new FileOutputStream(targetFile);
        int size;
        while ((size=zin.read(buffer,0,2048)) != -1) {
          fout.write(buffer,0,size);
        }
        zin.closeEntry();
        fout.flush();
        fout.close();
      }
    }
    zin.close();
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 53

From project geronimo-xbean, under directory /xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/.

Source file: BundleClassFinder.java

  31 
vote

private void scanZip(Collection<String> classes,Bundle bundle,String zipName){
  if (!discoveryFilter.jarFileDiscoveryRequired(zipName)) {
    return;
  }
  URL zipEntry=bundle.getEntry(zipName);
  if (zipEntry == null) {
    return;
  }
  ZipInputStream in=null;
  try {
    in=new ZipInputStream(zipEntry.openStream());
    ZipEntry entry;
    while ((entry=in.getNextEntry()) != null) {
      String name=entry.getName();
      if (name.endsWith(EXT) && discoveryFilter.packageDiscoveryRequired(toJavaStylePackageName(name))) {
        if (isClassAcceptable(name,in)) {
          classes.add(toJavaStyleClassName(name));
        }
      }
    }
  }
 catch (  IOException ignore) {
    logger.warn("Fail to check zip file " + zipName,ignore);
  }
 finally {
    if (in != null) {
      try {
        in.close();
      }
 catch (      IOException e) {
      }
    }
  }
}
 

Example 54

From project github-java-sdk, under directory /examples/src/java/com/github/api/v2/services/example/.

Source file: RepositoryApiSample.java

  31 
vote

/** 
 * The main method.
 * @param args the arguments
 * @throws Exception the exception
 */
public static void main(String[] args) throws Exception {
  GitHubServiceFactory factory=GitHubServiceFactory.newInstance();
  RepositoryService service=factory.createRepositoryService();
  List<Repository> repositories=service.searchRepositories("hadoop");
  for (  Repository repository : repositories) {
    printResult(repository);
  }
  Map<Language,Long> breakDown=service.getLanguageBreakdown("facebook","tornado");
  System.out.println(breakDown);
  ZipInputStream zip=service.getRepositoryArchive("nabeelmukhtar","github-java-sdk",Repository.MASTER);
  ZipEntry entry=null;
  while ((entry=zip.getNextEntry()) != null) {
    System.out.println(entry.getName());
  }
}
 

Example 55

From project gobandroid, under directory /src/org/ligi/gobandroid_hd/ui/.

Source file: UnzipSGFsDialog.java

  31 
vote

public void unzip(){
  try {
    InputStream fin=_zipFile;
    ZipInputStream zin=new ZipInputStream(fin);
    ZipEntry ze=null;
    byte[] readData=new byte[1024];
    while ((ze=zin.getNextEntry()) != null) {
      Log.i("Decompress" + "unzip" + ze.getName());
      if (ze.isDirectory()) {
        _dirChecker(ze.getName());
      }
 else {
        FileOutputStream fout=new FileOutputStream(_location + ze.getName());
        int i2=zin.read(readData);
        while (i2 != -1) {
          fout.write(readData,0,i2);
          i2=zin.read(readData);
        }
        zin.closeEntry();
        fout.close();
      }
    }
    zin.close();
  }
 catch (  Exception e) {
    Log.e("Decompress","unzip",e);
  }
}
 

Example 56

From project Hawksword, under directory /src/com/bw/hawksword/ocr/.

Source file: OcrInitAsyncTask.java

  31 
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));
  long totalSize=44479408, totalUncompression=0;
  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 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);
        totalUncompression+=count;
        percentComplete=(int)((totalUncompression * 100 / totalSize));
        if (totalSize / 100 < totalUncompression) {
          Log.i("%","okay");
        }
        if (percentComplete > percentCompleteLast) {
          publishProgress("Uncompressing data for " + languageName + "...",percentComplete.toString(),"0");
          percentCompleteLast=percentComplete;
        }
      }
      bufferedOutputStream.close();
    }
    inputStream.closeEntry();
  }
  inputStream.close();
  return true;
}
 

Example 57

From project Hesperid, under directory /server/src/main/java/ch/astina/hesperid/web/services/dbmigration/impl/.

Source file: ClasspathMigrationResolver.java

  31 
vote

public Set<Migration> resolve(){
  Set<Migration> migrations=new HashSet<Migration>();
  try {
    Enumeration<URL> enumeration=getClass().getClassLoader().getResources(classPath);
    while (enumeration.hasMoreElements()) {
      URL url=enumeration.nextElement();
      if (url.toExternalForm().startsWith("jar:")) {
        String file=url.getFile();
        file=file.substring(0,file.indexOf("!"));
        file=file.substring(file.indexOf(":") + 1);
        InputStream is=new FileInputStream(file);
        ZipInputStream zip=new ZipInputStream(is);
        ZipEntry ze;
        while ((ze=zip.getNextEntry()) != null) {
          if (!ze.isDirectory() && ze.getName().startsWith(classPath) && ze.getName().endsWith(".sql")) {
            Resource r=new UrlResource(getClass().getClassLoader().getResource(ze.getName()));
            String version=versionExtractor.extractVersion(r.getFilename());
            migrations.add(migrationFactory.create(version,r));
          }
        }
      }
 else {
        File file=new File(url.getFile());
        for (        String s : file.list()) {
          Resource r=new UrlResource(getClass().getClassLoader().getResource(classPath + "/" + s));
          String version=versionExtractor.extractVersion(r.getFilename());
          migrations.add(migrationFactory.create(version,r));
        }
      }
    }
  }
 catch (  Exception e) {
    logger.error("Error while resolving migrations",e);
  }
  return migrations;
}
 

Example 58

From project hoop, under directory /hoop-server/src/test/java/com/cloudera/lib/io/.

Source file: TestIOUtils.java

  31 
vote

@Test(dataProvider="zip") @TestDir public void zip(String base) throws IOException {
  File dir=getTestDir();
  File subdir=new File(dir,"bar");
  File subsubdir=new File(subdir,"woo");
  File file=new File(subdir,"file");
  Assert.assertTrue(subsubdir.mkdirs());
  OutputStream os=new FileOutputStream(file);
  os.write('a');
  os.close();
  Set<String> contents=new HashSet<String>();
  contents.add(base + "bar/woo/");
  contents.add(base + "bar/file");
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  ZipOutputStream zos=new ZipOutputStream(baos);
  IOUtils.zipDir(dir,base,zos);
  ZipInputStream zis=new ZipInputStream(new ByteArrayInputStream(baos.toByteArray()));
  Set<String> zipContents=new HashSet<String>();
  ZipEntry entry=zis.getNextEntry();
  while (entry != null) {
    zipContents.add(entry.getName());
    entry=zis.getNextEntry();
  }
  Assert.assertEquals(zipContents,contents);
}
 

Example 59

From project jbpm-plugin, under directory /jbpm/src/main/java/hudson/jbpm/.

Source file: PluginImpl.java

  31 
vote

/** 
 * Method supporting upload from the designer at /plugin/jbpm/upload
 */
public void doUpload(StaplerRequest req,StaplerResponse rsp) throws FileUploadException, IOException, ServletException {
  try {
    ServletFileUpload upload=new ServletFileUpload(new DiskFileItemFactory());
    FileItem fileItem=(FileItem)upload.parseRequest(req).get(0);
    if (fileItem.getContentType().indexOf("application/x-zip-compressed") == -1) {
      throw new IOException("Not a process archive");
    }
    log.fine("Deploying process archive " + fileItem.getName());
    ZipInputStream zipInputStream=new ZipInputStream(fileItem.getInputStream());
    JbpmContext jbpmContext=getCurrentJbpmContext();
    log.fine("Preparing to parse process archive");
    ProcessDefinition processDefinition=ProcessDefinition.parseParZipInputStream(zipInputStream);
    log.fine("Created a processdefinition : " + processDefinition.getName());
    jbpmContext.deployProcessDefinition(processDefinition);
    zipInputStream.close();
    rsp.forwardToPreviousPage(req);
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 60

From project jeppetto, under directory /jeppetto-test-support/src/main/java/org/iternine/jeppetto/testsupport/.

Source file: FileSystemFixtureSupport.java

  31 
vote

private void loadTestFixtureFromClasspath(String resourceName) throws IOException {
  ZipInputStream zipInputStream=null;
  FileOutputStream fileOutStream=null;
  try {
    zipInputStream=new ZipInputStream(ClassLoader.getSystemResourceAsStream(resourceName));
    ZipEntry nextEntry=null;
    while ((nextEntry=zipInputStream.getNextEntry()) != null) {
      String entryPath=nextEntry.getName();
      File outFile=new File(rootDir.getAbsolutePath() + File.separator + entryPath);
      if (!outFile.getParentFile().exists()) {
        createDirectoryOrThrow(outFile.getParentFile());
      }
      fileOutStream=new FileOutputStream(outFile);
      byte[] buffer=new byte[1024];
      int read=0;
      while ((read=zipInputStream.read(buffer,0,buffer.length)) != -1) {
        fileOutStream.write(buffer,0,read);
      }
      fileOutStream.close();
      fileOutStream=null;
      fixtureFiles.add(outFile);
    }
  }
  finally {
    if (zipInputStream != null) {
      zipInputStream.close();
    }
    if (fileOutStream != null) {
      fileOutStream.close();
    }
  }
}
 

Example 61

From project juzu, under directory /core/src/main/java/juzu/impl/fs/spi/classloader/.

Source file: URLCache.java

  31 
vote

private static void add(Trie<String,URL> root,URL url) throws IOException {
  if ("file".equals(url.getProtocol())) {
    try {
      File f=new File(url.toURI());
      ZipFile jarFile=new ZipFile(f);
      for (Enumeration<? extends ZipEntry> en=jarFile.entries(); en.hasMoreElements(); ) {
        ZipEntry entry=en.nextElement();
        add(root,url,entry);
      }
    }
 catch (    URISyntaxException e1) {
      throw new IOException("Could not access jar file " + url,e1);
    }
  }
 else {
    ZipInputStream in=new ZipInputStream(url.openStream());
    try {
      for (ZipEntry jarEntry=in.getNextEntry(); jarEntry != null; jarEntry=in.getNextEntry()) {
        add(root,url,jarEntry);
      }
    }
  finally {
      Tools.safeClose(in);
    }
  }
}
 

Example 62

From project kernel_1, under directory /exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/io/.

Source file: ZipUtil.java

  31 
vote

public void extractFromArchive(File input,String output) throws Exception {
  BufferedOutputStream dest=null;
  FileInputStream fileInput=new FileInputStream(input);
  ZipInputStream zipInput=new ZipInputStream(new BufferedInputStream(fileInput));
  ZipEntry entry;
  int count;
  FileOutputStream fileOuput=null;
  while ((entry=zipInput.getNextEntry()) != null) {
    if (entry.isDirectory())     createFile(new File(output + entry.getName()),true);
 else {
      if (output != null)       fileOuput=new FileOutputStream(createFile(new File(output + entry.getName()),false));
 else       fileOuput=new FileOutputStream(createFile(new File(entry.getName()),false));
      dest=new BufferedOutputStream(fileOuput,BUFFER);
      while ((count=zipInput.read(data,0,BUFFER)) != -1)       dest.write(data,0,count);
      dest.close();
    }
  }
  zipInput.close();
}
 

Example 63

From project kevoree-library, under directory /javase/org.kevoree.library.javase.webserver.wordpress/src/main/java/org/kevoree/library/javase/webserver/wordpress/.

Source file: ZipHelper.java

  31 
vote

public static File unzipToTempDir(InputStream res){
  try {
    File tempDir=File.createTempFile("tempDir","kevTemp");
    tempDir.delete();
    tempDir.mkdir();
    ZipInputStream zis=new ZipInputStream(res);
    ZipEntry entry;
    while ((entry=zis.getNextEntry()) != null) {
      if (entry.isDirectory()) {
        new File(tempDir.getAbsolutePath() + File.separator + entry.getName()).mkdirs();
      }
 else {
        BufferedOutputStream outputEntry=new BufferedOutputStream(new FileOutputStream(new File(tempDir + File.separator + entry.getName())));
        byte[] buffer=new byte[1024];
        int len=0;
        while (zis.available() > 0) {
          len=zis.read(buffer);
          if (len > 0) {
            outputEntry.write(buffer,0,len);
          }
        }
        outputEntry.flush();
        outputEntry.close();
      }
    }
    zis.close();
    return tempDir;
  }
 catch (  Exception e) {
    e.printStackTrace();
    return null;
  }
}
 

Example 64

From project lenya, under directory /org.apache.lenya.core.cocoon/src/main/java/org/apache/lenya/cms/cocoon/source/.

Source file: ZipSource.java

  31 
vote

public boolean exists(){
  if (!this.archive.exists()) {
    return false;
  }
  ZipInputStream zipStream=null;
  ZipEntry document=null;
  boolean found=false;
  try {
    zipStream=new ZipInputStream(this.archive.getInputStream());
    do {
      document=zipStream.getNextEntry();
      if (document != null) {
        if (document.getName().equals(this.documentName)) {
          found=true;
        }
 else {
          zipStream.closeEntry();
        }
      }
    }
 while (document != null && found == false);
  }
 catch (  IOException ioe) {
    return false;
  }
 finally {
    try {
      zipStream.close();
    }
 catch (    IOException ioe) {
      this.getLogger().error("Error while closing ZipInputStream: " + this.documentName);
    }
  }
  return found;
}
 

Example 65

From project m2eclipse-webby, under directory /org.sonatype.m2e.webby/src/org/sonatype/m2e/webby/internal/build/.

Source file: ArtifactResourceContributor.java

  31 
vote

private void processFile(WarAssembler assembler,IProgressMonitor monitor){
  boolean filtering=overlayConfig.isFiltering();
  String encoding=overlayConfig.getEncoding();
  PathSelector pathSelector=new PathSelector(overlayConfig.getIncludes(),overlayConfig.getExcludes());
  long lastModified=path.lastModified();
  try {
    ZipInputStream zis=new ZipInputStream(new FileInputStream(path));
    InputStream ncis=new NonClosingInputStream(zis);
    try {
      for (ZipEntry ze=zis.getNextEntry(); ze != null; ze=zis.getNextEntry()) {
        String path=ze.getName();
        if (ze.isDirectory() || !pathSelector.isSelected(path)) {
          continue;
        }
        String targetPath=overlayConfig.getTargetPath(path);
        if (assembler.registerTargetPath(targetPath,ordinal)) {
          try {
            assembler.copyResourceFile(ncis,targetPath,filtering,encoding,lastModified);
          }
 catch (          IOException e) {
            assembler.addError(this.path.getAbsolutePath() + "!/" + path,targetPath,e);
          }
        }
      }
    }
  finally {
      zis.close();
    }
  }
 catch (  IOException e) {
    assembler.addError(this.path.getAbsolutePath(),null,e);
  }
}
 

Example 66

From project magrit, under directory /installer/src/main/java/org/kercoin/magrit/.

Source file: Installer.java

  31 
vote

public static void inflate(File archive,File where){
  if (where.exists() && !where.isDirectory()) {
    throw new ExitException("Can't unzip file here because this isn't a directory: " + where.getAbsolutePath());
  }
  if (!where.exists()) {
    if (!where.mkdir()) {
      throw new ExitException("Couldn't create directory " + where.getAbsolutePath());
    }
  }
  if (where.list().length > 0) {
    throw new ExitException("Can't unzip file here: " + where.getAbsolutePath());
  }
  try {
    ZipInputStream zin=new ZipInputStream(new BufferedInputStream(new FileInputStream(archive)));
    ZipEntry entry;
    while ((entry=zin.getNextEntry()) != null) {
      File output=new File(where,entry.getName());
      output.getParentFile().mkdirs();
      if (!entry.isDirectory()) {
        FileOutputStream fos=new FileOutputStream(output.getAbsolutePath());
        BufferedOutputStream dest=new BufferedOutputStream(fos,BUFFER_SIZE);
        int count;
        byte data[]=new byte[BUFFER_SIZE];
        while ((count=zin.read(data,0,BUFFER_SIZE)) != -1) {
          dest.write(data,0,count);
        }
        dest.flush();
        dest.close();
      }
    }
    zin.close();
  }
 catch (  IOException e) {
    throw new ExitException(e.getMessage(),e);
  }
}
 

Example 67

From project mdk, under directory /service/core/src/main/java/uk/ac/ebi/mdk/service/loader/location/.

Source file: ZIPRemoteLocation.java

  31 
vote

/** 
 * Move the stream to the next zip entry
 * @return
 * @throws IOException
 */
public boolean hasNext(){
  try {
    if (stream == null) {
      stream=new ZipInputStream(super.open());
    }
    currentEntry=stream.getNextEntry();
  }
 catch (  IOException ex) {
    System.err.println("Could not open ZIP Stream: " + ex.getMessage());
  }
  return currentEntry != null;
}
 

Example 68

From project miso-lims, under directory /core/src/main/java/uk/ac/bbsrc/tgac/miso/core/util/.

Source file: LimsUtils.java

  31 
vote

public static boolean unzipFile(File source,File destination){
  final int BUFFER=2048;
  try {
    BufferedOutputStream dest=null;
    FileInputStream fis=new FileInputStream(source);
    ZipInputStream zis=new ZipInputStream(new BufferedInputStream(fis));
    ZipEntry entry;
    while ((entry=zis.getNextEntry()) != null) {
      File outputFile=null;
      if (destination != null && destination.exists() && destination.isDirectory()) {
        outputFile=new File(destination,entry.getName());
      }
 else {
        outputFile=new File(entry.getName());
      }
      if (entry.isDirectory()) {
        System.out.println("Extracting directory: " + entry.getName());
        LimsUtils.checkDirectory(outputFile,true);
      }
 else {
        System.out.println("Extracting file: " + entry.getName());
        int count;
        byte data[]=new byte[BUFFER];
        FileOutputStream fos=new FileOutputStream(outputFile);
        dest=new BufferedOutputStream(fos,BUFFER);
        while ((count=zis.read(data,0,BUFFER)) != -1) {
          dest.write(data,0,count);
        }
        dest.flush();
        dest.close();
      }
    }
    zis.close();
  }
 catch (  Exception e) {
    e.printStackTrace();
    return false;
  }
  return true;
}
 

Example 69

From project mylyn.context, under directory /org.eclipse.mylyn.context.tests/src/org/eclipse/mylyn/context/tests/support/.

Source file: DomContextReader.java

  31 
vote

public Document openAsDOM(File inputFile) throws IOException {
  DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
  DocumentBuilder builder=null;
  Document document=null;
  ZipInputStream zipInputStream=null;
  FileInputStream fileInputStream=null;
  try {
    fileInputStream=new FileInputStream(inputFile);
    zipInputStream=new ZipInputStream(fileInputStream);
    zipInputStream.getNextEntry();
    builder=factory.newDocumentBuilder();
    document=builder.parse(zipInputStream);
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
 finally {
    closeStream(zipInputStream);
    closeStream(fileInputStream);
  }
  return document;
}
 

Example 70

From project mylyn.docs, under directory /org.eclipse.mylyn.docs.epub.core/src/org/eclipse/mylyn/docs/epub/core/.

Source file: EPUB.java

  31 
vote

/** 
 * Used to verify that the given  {@link InputStream} contents is an EPUB. As per specification the first entry inthe file must be named "mimetype" and contain the string <i>application/epub+zip</i>. Further verification is not done at this stage.
 * @param inputStream the EPUB input stream
 * @return <code>true</code> if the file is an EPUB file
 * @throws IOException
 */
public static boolean isEPUB(InputStream inputStream) throws IOException {
  ZipInputStream in=new ZipInputStream(inputStream);
  try {
    byte[] buf=new byte[BUFFERSIZE];
    ZipEntry entry=null;
    if ((entry=in.getNextEntry()) != null) {
      String entryName=entry.getName();
      if (entryName.equals("mimetype")) {
        String type=new String();
        while ((in.read(buf,0,BUFFERSIZE)) > 0) {
          type=type + new String(buf);
        }
        if (type.trim().equals(EPUB.MIMETYPE_EPUB)) {
          return true;
        }
      }
    }
  }
 catch (  IOException e) {
    return false;
  }
 finally {
    in.close();
  }
  return false;
}
 

Example 71

From project OMS3, under directory /src/main/java/ngmfconsole/.

Source file: Utils.java

  31 
vote

static void unzip(File targetDir,File zipFile){
  int BUFFER=4096;
  try {
    FileInputStream fis=new FileInputStream(zipFile);
    ZipInputStream zis=new ZipInputStream(new BufferedInputStream(fis));
    ZipEntry entry;
    int count;
    byte data[]=new byte[BUFFER];
    while ((entry=zis.getNextEntry()) != null) {
      System.out.println("Extracting: " + entry);
      FileOutputStream fos=new FileOutputStream(new File(targetDir,entry.getName()));
      BufferedOutputStream dest=new BufferedOutputStream(fos,BUFFER);
      while ((count=zis.read(data,0,BUFFER)) != -1) {
        dest.write(data,0,count);
      }
      dest.flush();
      dest.close();
    }
    zis.close();
  }
 catch (  Exception e) {
    e.printStackTrace(System.err);
  }
}
 

Example 72

From project OpenMEAP, under directory /clients/java/openmeap-slic-android/src/com/openmeap/android/.

Source file: LocalStorageImpl.java

  31 
vote

public void unzipImportArchive(UpdateStatus update) throws LocalStorageException {
  ZipInputStream zis=null;
  String newPrefix="com.openmeap.storage." + update.getUpdateHeader().getHash().getValue();
  try {
    zis=new ZipInputStream(getImportArchiveInputStream());
    ZipEntry ze;
    while ((ze=zis.getNextEntry()) != null) {
      if (ze.isDirectory())       continue;
      OutputStream baos=openFileOutputStream(newPrefix,ze.getName());
      try {
        byte[] buffer=new byte[1024];
        int count;
        while ((count=zis.read(buffer)) != -1) {
          baos.write(buffer,0,count);
        }
      }
 catch (      Exception e) {
        ;
      }
 finally {
        baos.close();
      }
    }
  }
 catch (  Exception e) {
    throw new LocalStorageException(e);
  }
 finally {
    if (zis != null) {
      try {
        zis.close();
      }
 catch (      IOException e) {
        throw new GenericRuntimeException(e);
      }
    }
  }
}
 

Example 73

From project opennlp, under directory /opennlp-tools/src/main/java/opennlp/tools/util/model/.

Source file: BaseModel.java

  31 
vote

/** 
 * Initializes the current instance.
 * @param componentName the component name
 * @param in the input stream containing the model
 * @throws IOException
 * @throws InvalidFormatException
 */
protected BaseModel(String componentName,InputStream in) throws IOException, InvalidFormatException {
  if (componentName == null)   throw new IllegalArgumentException("componentName must not be null!");
  if (in == null)   throw new IllegalArgumentException("in must not be null!");
  this.componentName=componentName;
  artifactMap=new HashMap<String,Object>();
  createBaseArtifactSerializers(artifactSerializers);
  final ZipInputStream zip=new ZipInputStream(in);
  leftoverArtifacts=new HashMap<String,byte[]>();
  ZipEntry entry;
  while ((entry=zip.getNextEntry()) != null) {
    String extension=getEntryExtension(entry.getName());
    ArtifactSerializer factory=artifactSerializers.get(extension);
    if (factory == null) {
      byte[] bytes=toByteArray(zip);
      leftoverArtifacts.put(entry.getName(),bytes);
    }
 else {
      artifactMap.put(entry.getName(),factory.create(zip));
    }
    zip.closeEntry();
  }
  initializeFactory();
  loadArtifactSerializers();
  finishLoadingArtifacts();
  checkArtifactMap();
}
 

Example 74

From project orion.server, under directory /tests/org.eclipse.orion.server.tests/src/org/eclipse/orion/server/tests/servlets/xfer/.

Source file: TransferTest.java

  31 
vote

@Test public void testExportProject() throws CoreException, IOException, SAXException {
  String directoryPath="sample/directory/path" + System.currentTimeMillis();
  createDirectory(directoryPath);
  String fileContents="This is the file contents";
  createFile(directoryPath + "/file.txt",fileContents);
  GetMethodWebRequest export=new GetMethodWebRequest(getExportRequestPath(directoryPath));
  setAuthentication(export);
  WebResponse response=webConversation.getResponse(export);
  assertEquals(HttpURLConnection.HTTP_OK,response.getResponseCode());
  boolean found=false;
  ZipInputStream in=new ZipInputStream(response.getInputStream());
  ZipEntry entry;
  while ((entry=in.getNextEntry()) != null) {
    if (entry.getName().equals("file.txt")) {
      found=true;
      ByteArrayOutputStream bytes=new ByteArrayOutputStream();
      IOUtilities.pipe(in,bytes,false,false);
      assertEquals(fileContents,new String(bytes.toByteArray()));
    }
  }
  assertTrue(found);
}
 

Example 75

From project osgi-tests, under directory /test-support/glassfish/src/main/java/org/ancoron/osgi/test/glassfish/.

Source file: GlassfishHelper.java

  31 
vote

public static void unzip(String zipFile,String targetPath) throws IOException {
  log.log(Level.INFO,"Extracting {0} ...",zipFile);
  log.log(Level.INFO,"...target directory: {0}",targetPath);
  File path=new File(targetPath);
  path.delete();
  path.mkdirs();
  BufferedOutputStream dest=null;
  FileInputStream fis=new FileInputStream(zipFile);
  ZipInputStream zis=new ZipInputStream(new BufferedInputStream(fis));
  ZipEntry entry;
  while ((entry=zis.getNextEntry()) != null) {
    if (entry.isDirectory()) {
      File f=new File(targetPath + "/" + entry.getName());
      f.mkdirs();
      continue;
    }
    int count;
    byte data[]=new byte[BUFFER];
    FileOutputStream fos=new FileOutputStream(targetPath + "/" + entry.getName());
    dest=new BufferedOutputStream(fos,BUFFER);
    while ((count=zis.read(data,0,BUFFER)) != -1) {
      dest.write(data,0,count);
    }
    dest.flush();
    dest.close();
  }
  zis.close();
}
 

Example 76

From project PageTurner, under directory /src/main/java/net/nightwhistler/pageturner/epub/.

Source file: ResourceLoader.java

  31 
vote

public void load() throws IOException {
  ZipInputStream in=null;
  try {
    in=new ZipInputStream(new FileInputStream(this.fileName));
    for (ZipEntry zipEntry=in.getNextEntry(); zipEntry != null; zipEntry=in.getNextEntry()) {
      if (zipEntry.isDirectory()) {
        continue;
      }
      String href=zipEntry.getName();
      List<ResourceCallback> filteredCallbacks=findCallbacksFor(href);
      if (!filteredCallbacks.isEmpty()) {
        for (        ResourceCallback callBack : filteredCallbacks) {
          callBack.onLoadResource(href,in);
        }
      }
    }
  }
  finally {
    if (in != null) {
      in.close();
    }
    this.callbacks.clear();
  }
}
 

Example 77

From project pepe, under directory /pepe/src/edu/stanford/pepe/.

Source file: JREInstrumenter.java

  31 
vote

public static void main(String[] args) throws IOException {
  ZipInputStream is=new ZipInputStream(new FileInputStream(INPUT));
  ZipEntry je;
  ZipOutputStream os=new ZipOutputStream(new FileOutputStream(OUTPUT));
  while ((je=is.getNextEntry()) != null) {
    byte[] byteArray=read(is);
    if (je.getName().endsWith(".class")) {
      ClassNode cn=new ClassNode();
      ClassReader cr=new ClassReader(byteArray);
      cr.accept(cn,0);
      if (InstrumentationPolicy.isTypeInstrumentable(cn.name) || InstrumentationPolicy.isSpecialJavaClass(cn.name)) {
        byteArray=PepeAgent.instrumentClass(cn);
      }
 else {
        System.out.println("Skipping " + cn.name);
      }
    }
    JarEntry newJarEntry=new JarEntry(je.getName());
    os.putNextEntry(newJarEntry);
    os.write(byteArray);
  }
  is.close();
  os.close();
}
 

Example 78

From project platform_1, under directory /component/organization/src/main/java/org/exoplatform/platform/organization/injector/.

Source file: DataInjectorService.java

  31 
vote

public void readDataPlugins(String filePath) throws Exception {
  dataPlugins.clear();
  FileInputStream fin=new FileInputStream(filePath);
  ZipInputStream zin=new ZipInputStream(fin);
  ZipEntry ze=null;
  while ((ze=zin.getNextEntry()) != null) {
    if (ze.getName().equals("configuration.xml") || ze.getName().contains(CONFIGURATION_XML_SUFFIX)) {
      ByteArrayOutputStream fout=new ByteArrayOutputStream();
      for (int c=zin.read(); c != -1; c=zin.read()) {
        fout.write(c);
      }
      zin.closeEntry();
      Configuration tmpConfiguration=SerializationUtils.fromXML(fout.toByteArray(),Configuration.class);
      Component component=tmpConfiguration.getComponent(DataInjectorService.class.getName());
      ExternalComponentPlugins externalComponentPlugins=tmpConfiguration.getExternalComponentPlugins(DataInjectorService.class.getName());
      if (component != null && component.getComponentPlugins() != null && !component.getComponentPlugins().isEmpty()) {
        this.addComponentPlugins(component.getComponentPlugins());
      }
 else       if (externalComponentPlugins != null && externalComponentPlugins.getComponentPlugins() != null && !externalComponentPlugins.getComponentPlugins().isEmpty()) {
        this.addComponentPlugins(externalComponentPlugins.getComponentPlugins());
      }
    }
  }
  zin.close();
}
 

Example 79

From project playn, under directory /core/tests/playn/core/json/.

Source file: InternalJsonParserTest.java

  31 
vote

/** 
 * Tests from json.org: http://www.json.org/JSON_checker/ Skips two tests that don't match reality (ie: Chrome).
 */
@Test public void jsonOrgTest() throws IOException {
  InputStream input=getClass().getResourceAsStream("json_org_test.zip");
  ZipInputStream zip=new ZipInputStream(input);
  ZipEntry ze;
  while ((ze=zip.getNextEntry()) != null) {
    if (ze.isDirectory())     continue;
    if (ze.getName().contains("fail1.json"))     continue;
    if (ze.getName().contains("fail18.json"))     continue;
    boolean positive=ze.getName().startsWith("test/pass");
    int offset=0;
    int size=(int)ze.getSize();
    byte[] buffer=new byte[size];
    while (size > 0) {
      int r=zip.read(buffer,offset,buffer.length - offset);
      if (r <= 0)       break;
      size-=r;
      offset+=r;
    }
    String testCase=new String(buffer,"ASCII");
    if (positive) {
      try {
        Object out=JsonParser.any().from(testCase);
        JsonStringWriter.toString(out);
      }
 catch (      JsonParserException e) {
        e.printStackTrace();
        fail("Should not have failed " + ze.getName() + ": "+ testCase);
      }
    }
 else {
      try {
        JsonParser.object().from(testCase);
        fail("Should have failed " + ze.getName() + ": "+ testCase);
      }
 catch (      JsonParserException e) {
      }
    }
  }
}
 

Example 80

From project plexus-utils, under directory /src/main/java/org/codehaus/plexus/util/.

Source file: Expand.java

  31 
vote

/** 
 * Description of the Method
 */
protected void expandFile(File srcF,File dir) throws Exception {
  ZipInputStream zis=null;
  try {
    zis=new ZipInputStream(new FileInputStream(srcF));
    ZipEntry ze=null;
    while ((ze=zis.getNextEntry()) != null) {
      extractFile(srcF,dir,zis,ze.getName(),new Date(ze.getTime()),ze.isDirectory());
    }
  }
 catch (  IOException ioe) {
    throw new Exception("Error while expanding " + srcF.getPath(),ioe);
  }
 finally {
    if (zis != null) {
      try {
        zis.close();
      }
 catch (      IOException e) {
      }
    }
  }
}
 

Example 81

From project ps3mediaserver, under directory /src/main/java/net/pms/dlna/.

Source file: ZippedFile.java

  31 
vote

public InputStream getInputStream(){
  try {
    return new ZipInputStream(new FileInputStream(file));
  }
 catch (  FileNotFoundException e) {
    throw new RuntimeException(e);
  }
}
 

Example 82

From project PSXperia, under directory /src/com/yifanlu/PSXperiaTool/Extractor/.

Source file: CrashBandicootExtractor.java

  31 
vote

private void extractZip(File zipFile,File output,FileFilter filter) throws IOException {
  Logger.info("Extracting ZIP file: %s to: %s",zipFile.getPath(),output.getPath());
  if (!output.exists())   output.mkdirs();
  ZipInputStream zip=new ZipInputStream(new FileInputStream(zipFile));
  ZipEntry entry;
  while ((entry=zip.getNextEntry()) != null) {
    File file=new File(output,entry.getName());
    if (file.isDirectory())     continue;
    if (filter != null && !filter.accept(file))     continue;
    Logger.verbose("Unzipping %s",entry.getName());
    FileUtils.touch(file);
    FileOutputStream out=new FileOutputStream(file.getPath());
    int n;
    byte[] buffer=new byte[BLOCK_SIZE];
    while ((n=zip.read(buffer)) != -1) {
      out.write(buffer,0,n);
    }
    out.close();
    zip.closeEntry();
    Logger.verbose("Done extracting %s",entry.getName());
  }
  zip.close();
  Logger.debug("Done extracting ZIP.");
}
 

Example 83

From project rapid, under directory /rapid-generator/rapid-generator/src/main/java/cn/org/rapid_framework/generator/util/.

Source file: ZipUtils.java

  31 
vote

/** 
 * ????????????????????????(unzipDir)
 * @param unzipDir ??????
 * @param in ???????
 * @throws IOException
 */
public static void unzip(File unzipDir,InputStream in) throws IOException {
  unzipDir.mkdirs();
  ZipInputStream zin=new ZipInputStream(in);
  ZipEntry entry=null;
  while ((entry=zin.getNextEntry()) != null) {
    File path=new File(unzipDir,entry.getName());
    if (entry.isDirectory()) {
      path.mkdirs();
    }
 else {
      FileHelper.parentMkdir(path.getAbsoluteFile());
      IOHelper.saveFile(path,zin);
    }
  }
}
 

Example 84

From project recommenders, under directory /plugins/org.eclipse.recommenders.utils/src/org/eclipse/recommenders/utils/gson/.

Source file: GsonUtil.java

  31 
vote

public static <T>List<T> deserializeZip(File zip,Class<T> classOfT) throws IOException {
  List<T> res=Lists.newLinkedList();
  ZipInputStream zis=null;
  try {
    InputSupplier<FileInputStream> fis=Files.newInputStreamSupplier(zip);
    zis=new ZipInputStream(fis.getInput());
    ZipEntry entry;
    while ((entry=zis.getNextEntry()) != null) {
      if (!entry.isDirectory()) {
        final InputStreamReader reader=new InputStreamReader(zis);
        final T data=getInstance().fromJson(reader,classOfT);
        res.add(data);
      }
    }
  }
  finally {
    Closeables.closeQuietly(zis);
  }
  return res;
}
 

Example 85

From project SASAbus, under directory /src/it/sasabz/android/sasabus/classes/.

Source file: Decompress.java

  31 
vote

/** 
 * this method unzips the zip-file.
 */
public void unzip(){
  try {
    FileInputStream fin=new FileInputStream(zipFile);
    ZipInputStream zin=new ZipInputStream(fin);
    ZipEntry ze=null;
    byte[] buffer=new byte[1024];
    int length;
    while ((ze=zin.getNextEntry()) != null) {
      Log.v("Decompress","Unzipping " + ze.getName());
      if (ze.isDirectory()) {
        dirChecker(ze.getName());
      }
 else {
        FileOutputStream fout=new FileOutputStream(location + File.separator + ze.getName());
        while ((length=zin.read(buffer)) > 0) {
          fout.write(buffer,0,length);
        }
        zin.closeEntry();
        fout.close();
      }
    }
    zin.close();
  }
 catch (  Exception e) {
    Log.e("Decompress","unzip",e);
  }
}
 

Example 86

From project scufl2, under directory /scufl2-ucfpackage/src/main/java/uk/org/taverna/scufl2/ucfpackage/impl/odfdom/pkg/.

Source file: OdfPackage.java

  31 
vote

public Enumeration<? extends ZipEntry> entries() throws IOException {
  if (mZipFile != null) {
    return mZipFile.entries();
  }
 else {
    Vector<ZipEntry> list=new Vector<ZipEntry>();
    ZipInputStream inputStream=new ZipInputStream(new ByteArrayInputStream(mZipBuffer));
    ZipEntry zipEntry=inputStream.getNextEntry();
    while (zipEntry != null) {
      list.add(zipEntry);
      zipEntry=inputStream.getNextEntry();
    }
    inputStream.close();
    return list.elements();
  }
}
 

Example 87

From project SeriesGuide, under directory /SeriesGuide/src/com/battlelancer/thetvdbapi/.

Source file: TheTVDB.java

  31 
vote

/** 
 * Downloads the XML or ZIP file from the given URL, passing a valid response to {@link Xml#parse(InputStream,android.util.Xml.Encoding,ContentHandler)}using the given  {@link ContentHandler}.
 */
private static void downloadAndParse(String urlString,ContentHandler handler,boolean isZipFile) throws SAXException {
  try {
    final InputStream input=AndroidUtils.downloadUrl(urlString);
    if (isZipFile) {
      final ZipInputStream zipin=new ZipInputStream(input);
      zipin.getNextEntry();
      try {
        Xml.parse(zipin,Xml.Encoding.UTF_8,handler);
      }
  finally {
        if (zipin != null) {
          zipin.close();
        }
      }
    }
 else {
      try {
        Xml.parse(input,Xml.Encoding.UTF_8,handler);
      }
  finally {
        if (input != null) {
          input.close();
        }
      }
    }
  }
 catch (  SAXException e) {
    throw new SAXException("Malformed response for " + urlString,e);
  }
catch (  IOException e) {
    throw new SAXException("Problem reading remote response for " + urlString,e);
  }
catch (  AssertionError ae) {
    throw new SAXException("Problem reading remote response for " + urlString);
  }
catch (  Exception e) {
    throw new SAXException("Problem reading remote response for " + urlString,e);
  }
}
 

Example 88

From project ServalMaps, under directory /src/org/servalproject/maps/location/.

Source file: MockLocations.java

  31 
vote

/** 
 * create the MockLocations class and open the zip file for the required  location data
 * @param context the application context
 * @throws IllegalArgumentException if the context field is null
 * @throws IOException  if opening the zip file fails
 */
public MockLocations(Context context) throws IOException {
  if (V_LOG) {
    Log.v(TAG,"opening the zip file");
  }
  ZipInputStream mZipInput=new ZipInputStream(context.getAssets().open(LOCATION_ZIP_FILE));
  ZipEntry mZipEntry;
  while ((mZipEntry=mZipInput.getNextEntry()) != null) {
    if (V_LOG) {
      Log.v(TAG,"ZipEntry: " + mZipEntry.getName());
    }
    if (mZipEntry.getName().equals(LOCATION_FILE)) {
      if (V_LOG) {
        Log.v(TAG,"required file found inside zip file");
      }
      ByteArrayOutputStream mByteStream=new ByteArrayOutputStream();
      byte[] mBuffer=new byte[1024];
      int mCount;
      while ((mCount=mZipInput.read(mBuffer)) != -1) {
        mByteStream.write(mBuffer,0,mCount);
      }
      locations=new String(mByteStream.toByteArray(),"UTF-8");
    }
    if (V_LOG) {
      Log.v(TAG,"location file successfully read");
    }
    mZipInput.closeEntry();
  }
  mZipInput.close();
  if (locations == null) {
    throw new IOException("unable to read the required file from the zip file");
  }
  locationManager=(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
  locationManager.addTestProvider(LocationManager.GPS_PROVIDER,false,false,false,false,false,true,true,0,5);
}
 

Example 89

From project shrinkwrap, under directory /impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/importer/zip/.

Source file: ZipImporterImpl.java

  31 
vote

/** 
 * {@inheritDoc}
 * @see org.jboss.shrinkwrap.api.importer.StreamImporter#importFrom(java.io.InputStream)
 */
@Override public ZipImporter importFrom(final InputStream stream) throws ArchiveImportException {
  Validate.notNull(stream,"Stream must be specified");
  try {
    final ZipInputStream zipStream=new ZipInputStream(stream);
    ZipEntry entry;
    while ((entry=zipStream.getNextEntry()) != null) {
      final String entryName=entry.getName();
      final Archive<?> archive=this.getArchive();
      if (entry.isDirectory()) {
        archive.addAsDirectory(entryName);
        continue;
      }
      final ByteArrayOutputStream output=new ByteArrayOutputStream(8192);
      IOUtil.copy(zipStream,output);
      archive.add(new ByteArrayAsset(output.toByteArray()),entryName);
      zipStream.closeEntry();
    }
  }
 catch (  IOException e) {
    throw new ArchiveImportException("Could not import stream",e);
  }
  return this;
}
 

Example 90

From project skype-im-plugin, under directory /src/main/java/com/skype/connector/.

Source file: ConnectorUtils.java

  31 
vote

/** 
 * Search for a file in the jars of the classpath, return true if found.
 * @param searchString The path+filename to search for.
 * @return true if file could be found.
 */
public static boolean isInJar(String searchString){
  boolean found=false;
  String classpath=getExtendedClasspath();
  File jarfile=null;
  String jarFileName;
  StringTokenizer st=new StringTokenizer(classpath,File.pathSeparator);
  while (st.hasMoreTokens() && !found) {
    jarFileName=st.nextToken();
    jarfile=new File(jarFileName);
    if (jarfile.exists() && jarfile.isFile()) {
      FileInputStream fis=null;
      try {
        fis=new FileInputStream(jarFileName);
        BufferedInputStream bis=new BufferedInputStream(fis);
        ZipInputStream zis=new ZipInputStream(bis);
        ZipEntry ze=null;
        while ((ze=zis.getNextEntry()) != null) {
          if (ze.getName().endsWith(searchString)) {
            found=true;
          }
        }
      }
 catch (      Exception e) {
        found=false;
      }
    }
  }
  return found;
}
 

Example 91

From project SPaTo_Visual_Explorer, under directory /lib/src/WinRun4J/src/org/boris/winrun4j/classloader/.

Source file: EmbeddedClassLoader.java

  31 
vote

public InputStream getResourceAsStream(String name){
  for (int i=0; i < buffers.length; i++) {
    ByteBuffer bb=buffers[i];
    bb.position(0);
    ZipInputStream zis=new ZipInputStream(new ByteBufferInputStream(bb));
    ZipEntry ze=null;
    try {
      while ((ze=zis.getNextEntry()) != null) {
        if (name.equals(ze.getName())) {
          return zis;
        }
      }
    }
 catch (    IOException e) {
      return null;
    }
  }
  return null;
}
 

Example 92

From project spring-data-book, under directory /hadoop/batch-extract/src/main/java/com/manning/sbia/ch01/batch/.

Source file: DecompressTasklet.java

  31 
vote

public RepeatStatus execute(StepContribution contribution,ChunkContext chunkContext) throws Exception {
  ZipInputStream zis=new ZipInputStream(new BufferedInputStream(inputResource.getInputStream()));
  File targetDirectoryAsFile=new File(targetDirectory);
  if (!targetDirectoryAsFile.exists()) {
    FileUtils.forceMkdir(targetDirectoryAsFile);
  }
  File target=new File(targetDirectory,targetFile);
  BufferedOutputStream dest=null;
  while (zis.getNextEntry() != null) {
    if (!target.exists()) {
      target.createNewFile();
    }
    FileOutputStream fos=new FileOutputStream(target);
    dest=new BufferedOutputStream(fos);
    IOUtils.copy(zis,dest);
    dest.flush();
    dest.close();
  }
  zis.close();
  if (!target.exists()) {
    throw new IllegalStateException("Could not decompress anything from the archive!");
  }
  return RepeatStatus.FINISHED;
}
 

Example 93

From project SpringLS, under directory /src/main/java/com/springrts/springls/util/.

Source file: ZipUtil.java

  31 
vote

private static void unzip(File archive,File singleOutputFile) throws IOException {
  InputStream fin=null;
  InputStream bin=null;
  ZipInputStream zin=null;
  try {
    fin=new FileInputStream(archive);
    bin=new BufferedInputStream(fin);
    zin=new ZipInputStream(bin);
    ZipEntry zEntry=zin.getNextEntry();
    do {
      File toFile=(singleOutputFile == null) ? new File(zEntry.getName()) : singleOutputFile;
      unzipSingleEntry(zin,toFile);
      zEntry=zin.getNextEntry();
    }
 while ((singleOutputFile == null) && (zEntry != null));
  }
  finally {
    if (zin != null) {
      zin.close();
    }
 else     if (bin != null) {
      bin.close();
    }
 else     if (fin != null) {
      fin.close();
    }
  }
}
 

Example 94

From project srl-reflection, under directory /Development/java/Updater/src/smart/updater/.

Source file: Updater.java

  31 
vote

/** 
 * Creates an Updater instance by parsing the classes out of a byte[] from a runescape.jar. This constructor does not do any bytecode searching, it simply parses classes.
 * @param jar byte[] from a runescape.jar
 */
public Updater(byte[] jar){
  try {
    ZipInputStream in=new ZipInputStream(new ByteArrayInputStream(jar));
    ZipEntry entry=in.getNextEntry();
    byte[] buffer=new byte[1024];
    while (entry != null) {
      String entryName=entry.getName();
      if (entryName.endsWith(".class")) {
        ByteArrayOutputStream data=new ByteArrayOutputStream();
        int len;
        while ((len=in.read(buffer,0,1024)) > -1) {
          data.write(buffer,0,len);
        }
        rawclasses.put(entryName.replaceAll("\\\\",".").replace(".class",""),data.toByteArray());
        data.close();
      }
      in.closeEntry();
      entry=in.getNextEntry();
    }
    in.close();
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
  try {
    for (    Entry<String,byte[]> entry : rawclasses.entrySet()) {
      ByteArrayInputStream in=new ByteArrayInputStream(entry.getValue());
      ClassParser parser=new ClassParser(in,entry.getKey());
      javaclasses.put(entry.getKey(),new ClassGen(parser.parse()));
      in.close();
    }
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
}
 

Example 95

From project sveditor, under directory /sveditor/plugins/net.sf.sveditor.core.tests/src/net/sf/sveditor/core/tests/utils/.

Source file: BundleUtils.java

  31 
vote

public void unpackBundleZipToFS(String bundle_path,File fs_path){
  URL zip_url=fBundle.getEntry(bundle_path);
  TestCase.assertNotNull(zip_url);
  if (!fs_path.isDirectory()) {
    TestCase.assertTrue(fs_path.mkdirs());
  }
  try {
    InputStream in=zip_url.openStream();
    TestCase.assertNotNull(in);
    byte tmp[]=new byte[4 * 1024];
    int cnt;
    ZipInputStream zin=new ZipInputStream(in);
    ZipEntry ze;
    while ((ze=zin.getNextEntry()) != null) {
      File entry_f=new File(fs_path,ze.getName());
      if (ze.getName().endsWith("/")) {
        continue;
      }
      if (!entry_f.getParentFile().exists()) {
        TestCase.assertTrue(entry_f.getParentFile().mkdirs());
      }
      FileOutputStream fos=new FileOutputStream(entry_f);
      BufferedOutputStream bos=new BufferedOutputStream(fos,tmp.length);
      while ((cnt=zin.read(tmp,0,tmp.length)) > 0) {
        bos.write(tmp,0,cnt);
      }
      bos.flush();
      bos.close();
      fos.close();
      zin.closeEntry();
    }
    zin.close();
  }
 catch (  IOException e) {
    e.printStackTrace();
    TestCase.fail("Failed to unpack zip file: " + e.getMessage());
  }
}
 

Example 96

From project SWE12-Drone, under directory /catroid/src/at/tugraz/ist/catroid/utils/.

Source file: UtilZip.java

  31 
vote

public static boolean unZipFile(String zipFile,String outDirectory){
  try {
    FileInputStream fin=new FileInputStream(zipFile);
    ZipInputStream zin=new ZipInputStream(fin);
    ZipEntry zipEntry=null;
    BufferedOutputStream dest=null;
    byte data[]=new byte[Consts.BUFFER_8K];
    while ((zipEntry=zin.getNextEntry()) != null) {
      if (zipEntry.isDirectory()) {
        File f=new File(Utils.buildPath(outDirectory,zipEntry.getName()));
        f.mkdir();
        zin.closeEntry();
        continue;
      }
      File f=new File(Utils.buildPath(outDirectory,zipEntry.getName()));
      f.getParentFile().mkdirs();
      FileOutputStream fos=new FileOutputStream(f);
      int count;
      dest=new BufferedOutputStream(fos,Consts.BUFFER_8K);
      while ((count=zin.read(data,0,Consts.BUFFER_8K)) != -1) {
        dest.write(data,0,count);
      }
      dest.flush();
      dest.close();
    }
    zin.close();
    return true;
  }
 catch (  FileNotFoundException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
  return false;
}
 

Example 97

From project syncany, under directory /syncany/src/org/syncany/connection/plugins/box/.

Source file: BoxTransferManager.java

  31 
vote

@Override public Map<String,RemoteFile> list() throws StorageException {
  connect();
  try {
    GetAccountTreeResponse accountTreeResponse=box.getAccountTree(BoxRequestFactory.createGetAccountTreeRequest(getConnection().getApiKey(),getConnection().getToken(),getConnection().getFolderId(),new String[]{}));
    if (!"listing_ok".equals(accountTreeResponse.getStatus())) {
      throw new StorageException("List query failed. Status: " + accountTreeResponse.getStatus());
    }
    String base64Xml=accountTreeResponse.getEncodedTree();
    InputStream decodedBase64=new ByteArrayInputStream(Base64.decodeBase64(base64Xml));
    ZipInputStream zip=new ZipInputStream(decodedBase64);
    if (zip.getNextEntry() == null) {
      throw new StorageException("Cannot read folder tree. Invalid ZIP data.");
    }
    DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder=dbFactory.newDocumentBuilder();
    Document doc=dBuilder.parse(zip);
    XPathFactory factory=XPathFactory.newInstance();
    XPath xpath=factory.newXPath();
    Object result=xpath.evaluate("files/file",doc.getDocumentElement(),XPathConstants.NODESET);
    NodeList nodes=(NodeList)result;
    Map<String,RemoteFile> list=new HashMap<String,RemoteFile>();
    for (int i=0; i < nodes.getLength(); i++) {
      Node node=nodes.item(i);
      String name=node.getAttributes().getNamedItem("file_name").getTextContent();
      Integer size=StringUtil.parseInt(node.getAttributes().getNamedItem("size").getTextContent(),-1);
      list.put(name,new RemoteFile(name,size,node));
    }
    return list;
  }
 catch (  Exception ex) {
    Logger.getLogger(BoxTransferManager.class.getName()).log(Level.SEVERE,null,ex);
    throw new StorageException("...");
  }
}
 

Example 98

From project teuria, under directory /Teuria/src/il/co/zak/gplv3/hamakor/teuria/.

Source file: QuestionsFetcher.java

  31 
vote

/** 
 * @param urlstring - from which the xml file containing the questions is to be retrieved
 */
private static String retrieveZippedXmlFile(String urlstring) throws MalformedURLException, IOException {
  URL url=new URL(urlstring);
  HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
  int responseCode=urlConnection.getResponseCode();
  if (200 != responseCode) {
    throw new RuntimeException("Bad URL: " + urlstring);
  }
  InputStream in=urlConnection.getInputStream();
  ZipInputStream zipin=new ZipInputStream(new BufferedInputStream(in,32768));
  ZipEntry ze=zipin.getNextEntry();
  if (null == ze) {
    throw new RuntimeException("No ZIP archive in URL: " + urlstring);
  }
  String xmlfname=ze.getName();
  if (!xmlfname.substring(xmlfname.length() - 4).contentEquals(".xml")) {
    throw new RuntimeException("No XML file in ZIP archive in URL: " + urlstring);
  }
  byte[] xmlbytes=new byte[(int)ze.getSize()];
  int read_offset=0;
  while (read_offset < xmlbytes.length) {
    int read_bytes=zipin.read(xmlbytes,read_offset,xmlbytes.length - read_offset);
    if (read_bytes == 0) {
      throw new RuntimeException("ZIP read error");
    }
    read_offset+=read_bytes;
  }
  String xmlstuff=new String(xmlbytes,"UTF-8");
  zipin.closeEntry();
  zipin.close();
  return xmlstuff;
}
 

Example 99

From project tika, under directory /tika-parsers/src/main/java/org/apache/tika/parser/epub/.

Source file: EpubParser.java

  31 
vote

public void parse(InputStream stream,ContentHandler handler,Metadata metadata,ParseContext context) throws IOException, SAXException, TikaException {
  XHTMLContentHandler xhtml=new XHTMLContentHandler(handler,metadata);
  xhtml.startDocument();
  ContentHandler childHandler=new EmbeddedContentHandler(new BodyContentHandler(xhtml));
  ZipInputStream zip=new ZipInputStream(stream);
  ZipEntry entry=zip.getNextEntry();
  while (entry != null) {
    if (entry.getName().equals("mimetype")) {
      String type=IOUtils.toString(zip,"UTF-8");
      metadata.set(Metadata.CONTENT_TYPE,type);
    }
 else     if (entry.getName().equals("metadata.xml")) {
      meta.parse(zip,new DefaultHandler(),metadata,context);
    }
 else     if (entry.getName().endsWith(".opf")) {
      meta.parse(zip,new DefaultHandler(),metadata,context);
    }
 else     if (entry.getName().endsWith(".html") || entry.getName().endsWith(".xhtml")) {
      content.parse(zip,childHandler,metadata,context);
    }
    entry=zip.getNextEntry();
  }
  xhtml.endDocument();
}
 

Example 100

From project TPT-Helper, under directory /TPT Helper/src/com/amphoras/tpthelper/.

Source file: AllInOne.java

  31 
vote

@Override protected String doInBackground(FileInputStream... fins){
  String response="";
  for (  FileInputStream fin : fins) {
    File file=new File(Environment.getExternalStorageDirectory(),"/image");
    deleteDirectory(file);
    try {
      ZipInputStream zin=new ZipInputStream(fin);
      ZipEntry ze=null;
      while ((ze=zin.getNextEntry()) != null) {
        if (ze.isDirectory()) {
          MakeDirectory(ze.getName());
        }
 else {
          FileOutputStream fos=new FileOutputStream(unziplocation + ze.getName());
          byte[] buffer=new byte[1024];
          int length;
          while ((length=zin.read(buffer)) > 0) {
            fos.write(buffer,0,length);
          }
          zin.closeEntry();
          fos.close();
        }
      }
      zin.close();
      response="Unzip completed";
    }
 catch (    Exception e) {
      response="Unzip failed";
    }
  }
  return response;
}
 

Example 101

From project activiti-explorer, under directory /src/main/java/org/activiti/explorer/ui/management/deployment/.

Source file: DeploymentUploadReceiver.java

  30 
vote

protected void deployUploadedFile(){
  DeploymentBuilder deploymentBuilder=repositoryService.createDeployment().name(fileName);
  try {
    try {
      if (fileName.endsWith(".bpmn20.xml")) {
        validFile=true;
        deployment=deploymentBuilder.addInputStream(fileName,new ByteArrayInputStream(outputStream.toByteArray())).deploy();
      }
 else       if (fileName.endsWith(".bar") || fileName.endsWith(".zip")) {
        validFile=true;
        deployment=deploymentBuilder.addZipInputStream(new ZipInputStream(new ByteArrayInputStream(outputStream.toByteArray()))).deploy();
      }
 else {
        notificationManager.showErrorNotification(Messages.DEPLOYMENT_UPLOAD_INVALID_FILE,i18nManager.getMessage(Messages.DEPLOYMENT_UPLOAD_INVALID_FILE_EXPLANATION));
      }
    }
 catch (    ActivitiException e) {
      String errorMsg=e.getMessage().replace(System.getProperty("line.separator"),"<br/>");
      notificationManager.showErrorNotification(Messages.DEPLOYMENT_UPLOAD_FAILED,errorMsg);
    }
  }
  finally {
    if (outputStream != null) {
      try {
        outputStream.close();
      }
 catch (      IOException e) {
        notificationManager.showErrorNotification("Server-side error",e.getMessage());
      }
    }
  }
}
 

Example 102

From project activiti-webapp-rest-generic, under directory /activiti-webapp-rest/src/main/java/org/activiti/rest/api/repository/.

Source file: DeploymentPost.java

  30 
vote

/** 
 * Deletes the deployment.
 * @param req The webscripts request
 * @param status The webscripts status
 * @param cache The webscript cache
 * @param model The webscripts template model
 */
@Override protected void executeWebScript(ActivitiRequest req,Status status,Cache cache,Map<String,Object> model){
  try {
    FormData.FormField file=((WebScriptServletRequest)req.getWebScriptRequest()).getFileField("deployment");
    DeploymentBuilder deploymentBuilder=getRepositoryService().createDeployment();
    String fileName=file.getFilename();
    if (fileName.endsWith(".bpmn20.xml")) {
      deploymentBuilder.addInputStream(fileName,file.getInputStream());
    }
 else     if (fileName.endsWith(".bar") || fileName.endsWith(".zip")) {
      deploymentBuilder.addZipInputStream(new ZipInputStream(file.getInputStream()));
    }
 else {
      throw new WebScriptException(Status.STATUS_BAD_REQUEST,"File must be of type .bpmn20.xml, .bar or .zip");
    }
    deploymentBuilder.name(fileName);
    deploymentBuilder.deploy();
    String success=req.getBody().getString("success");
    if (success != null) {
      model.put("success",success);
    }
  }
 catch (  Exception e) {
    String failure=req.getString("failure",null);
    if (failure == null) {
      failure=req.getBody().getString("failure");
    }
    if (failure != null) {
      model.put("failure",failure);
      model.put("error",e.getMessage());
    }
 else     if (e instanceof WebScriptException) {
      throw (WebScriptException)e;
    }
 else {
      throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR,e.getMessage(),e);
    }
  }
}
 

Example 103

From project jboss-vfs, under directory /src/test/java/org/jboss/test/vfs/support/.

Source file: ClassPathIterator.java

  30 
vote

public ClassPathIterator(URL url) throws IOException {
  String protocol=url != null ? url.getProtocol() : null;
  if (protocol == null) {
  }
 else   if (protocol.equals(VFSUtils.VFS_PROTOCOL)) {
    URLConnection conn=url.openConnection();
    vf=(VirtualFile)conn.getContent();
    rootLength=vf.getPathName().length() + 1;
    vfIter=new VirtualFileIterator(vf);
  }
 else {
    InputStream is=url.openStream();
    zis=new ZipInputStream(is);
  }
}
 

Example 104

From project Sourcerer, under directory /infrastructure/tools/java/component-identifier/src/edu/uci/ics/sourcerer/tools/java/component/model/jar/.

Source file: JarCollection.java

  30 
vote

private void add(JarFile jar){
  Jar newJar=new Jar(jar);
  Map<String,Long> names=new HashMap<>();
  try (ZipInputStream zis=new ZipInputStream(new FileInputStream(jar.getFile().toFile()))){
    for (ZipEntry entry=zis.getNextEntry(); entry != null; entry=zis.getNextEntry()) {
      if (entry.getName().endsWith(".class")) {
        Long length=names.get(entry.getName());
        if (length == null) {
          names.put(entry.getName(),entry.getSize());
        }
      }
    }
  }
 catch (  IOException|IllegalArgumentException e) {
    logger.log(Level.SEVERE,"Error reading jar file: " + jar,e);
    return;
  }
  try (ZipInputStream zis=new ZipInputStream(new FileInputStream(jar.getFile().toFile()))){
    for (ZipEntry entry=zis.getNextEntry(); entry != null; entry=zis.getNextEntry()) {
      if (entry.getName().endsWith(".class")) {
        Long length=names.get(entry.getName());
        if (length != null && length.longValue() == entry.getSize()) {
          names.remove(entry.getName());
          String fqn=entry.getName();
          fqn=fqn.substring(0,fqn.lastIndexOf('.'));
          newJar.addFqn(rootFragment.getChild(fqn,'/').getVersion(Fingerprint.create(zis,entry.getSize())));
        }
      }
    }
    if (!newJar.getFqns().isEmpty()) {
      jars.put(jar.getProperties().HASH.getValue(),newJar);
    }
  }
 catch (  IOException|IllegalArgumentException e) {
    logger.log(Level.SEVERE,"Error reading jar file: " + jar,e);
    logger.severe("Would like to remove");
  }
}
 

Example 105

From project spring-activiti-sandbox, under directory /src/main/java/org/activiti/spring/.

Source file: SpringProcessEngineConfiguration.java

  30 
vote

protected void autoDeployResources(ProcessEngine processEngine){
  if (deploymentResources != null && deploymentResources.length > 0) {
    RepositoryService repositoryService=processEngine.getRepositoryService();
    DeploymentBuilder deploymentBuilder=repositoryService.createDeployment().enableDuplicateFiltering().name(deploymentName);
    for (    Resource resource : deploymentResources) {
      String resourceName=null;
      if (resource instanceof ContextResource) {
        resourceName=((ContextResource)resource).getPathWithinContext();
      }
 else       if (resource instanceof ByteArrayResource) {
        resourceName=resource.getDescription();
      }
 else {
        try {
          resourceName=resource.getFile().getAbsolutePath();
        }
 catch (        IOException e) {
          resourceName=resource.getFilename();
        }
      }
      try {
        if (resourceName.endsWith(".bar") || resourceName.endsWith(".zip") || resourceName.endsWith(".jar")) {
          deploymentBuilder.addZipInputStream(new ZipInputStream(resource.getInputStream()));
        }
 else {
          deploymentBuilder.addInputStream(resourceName,resource.getInputStream());
        }
      }
 catch (      IOException e) {
        throw new ActivitiException("couldn't auto deploy resource '" + resource + "': "+ e.getMessage(),e);
      }
    }
    deploymentBuilder.deploy();
  }
}
 

Example 106

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

Source file: Processor.java

  29 
vote

private void processEntry(final ZipInputStream zis,final ZipEntry ze,final ContentHandlerFactory handlerFactory){
  ContentHandler handler=handlerFactory.createContentHandler();
  try {
    boolean singleInputDocument=inRepresentation == SINGLE_XML;
    if (inRepresentation == BYTECODE) {
      ClassReader cr=new ClassReader(readEntry(zis,ze));
      cr.accept(new SAXClassAdapter(handler,singleInputDocument),0);
    }
 else {
      XMLReader reader=XMLReaderFactory.createXMLReader();
      reader.setContentHandler(handler);
      reader.parse(new InputSource(singleInputDocument ? (InputStream)new ProtectedInputStream(zis) : new ByteArrayInputStream(readEntry(zis,ze))));
    }
  }
 catch (  Exception ex) {
    update(ze.getName(),0);
    update(ex,0);
  }
}
 

Example 107

From project dawn-ui, under directory /org.dawb.workbench.ui/src/org/dawb/workbench/ui/editors/slicing/.

Source file: ZipUtils.java

  29 
vote

public static InputStream getStreamForFile(final File file) throws Exception {
  final String ext=FileUtils.getFileExtension(file);
  final Class<? extends InputStream> clazz=CLASSES.get(ext);
  final Constructor<? extends InputStream> c=clazz.getConstructor(InputStream.class);
  final InputStream in=c.newInstance(new FileInputStream(file));
  if (in instanceof ZipInputStream) {
    ((ZipInputStream)in).getNextEntry();
  }
  return in;
}
 

Example 108

From project enclojure, under directory /netbeans/plugins/org-enclojure-plugin/src/main/java/org/enclojure/ide/nb/clojure/project/.

Source file: ClojureTemplateWizardIterator.java

  29 
vote

public static void writeFile(ZipInputStream str,FileObject fo) throws IOException {
  OutputStream out=fo.getOutputStream();
  try {
    FileUtil.copy(str,out);
  }
  finally {
    out.flush();
    out.close();
  }
}
 

Example 109

From project imdb, under directory /src/main/java/org/neo4j/examples/imdb/parser/.

Source file: ImdbParser.java

  29 
vote

/** 
 * Get file reader that corresponds to file extension.
 * @param file the file name
 * @param pattern TODO
 * @param skipLines TODO
 * @return a file reader that uncompresses data if needed
 * @throws IOException
 * @throws FileNotFoundException
 */
private BufferedReader getFileReader(final String file,String pattern,int skipLines) throws IOException, FileNotFoundException {
  BufferedReader fileReader;
  if (file.endsWith(".gz")) {
    fileReader=new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(file))));
  }
 else   if (file.endsWith(".zip")) {
    fileReader=new BufferedReader(new InputStreamReader(new ZipInputStream(new FileInputStream(file))));
  }
 else {
    fileReader=new BufferedReader(new FileReader(file));
  }
  String line="";
  while (!pattern.equals(line)) {
    line=fileReader.readLine();
  }
  for (int i=0; i < skipLines; i++) {
    line=fileReader.readLine();
  }
  return fileReader;
}
 

Example 110

From project scisoft-core, under directory /uk.ac.diamond.scisoft.analysis/src/uk/ac/diamond/scisoft/analysis/io/.

Source file: CompressedLoader.java

  29 
vote

public void setFile(final String file) throws Exception {
  final Matcher m=ZIP_PATH.matcher((new File(file)).getName());
  if (m.matches()) {
    final String name=m.group(1);
    final String ext=m.group(2);
    final String zipType=m.group(3);
    final Class<? extends InputStream> clazz=LoaderFactory.getZipStream(zipType);
    final Constructor<? extends InputStream> c=clazz.getConstructor(InputStream.class);
    final InputStream in=c.newInstance(new FileInputStream(file));
    if (in instanceof ZipInputStream) {
      ((ZipInputStream)in).getNextEntry();
    }
    final File tmp=File.createTempFile(name,"." + ext);
    tmp.deleteOnExit();
    FileUtils.write(new BufferedInputStream(in),tmp);
    final Class<? extends AbstractFileLoader> lclass=LoaderFactory.getLoaderClass(ext);
    this.loader=LoaderFactory.getLoader(lclass,tmp.getAbsolutePath());
  }
}
 

Example 111

From project spring-data-neo4j, under directory /spring-data-neo4j-examples/imdb/src/main/java/org/neo4j/examples/imdb/parser/.

Source file: ImdbParser.java

  29 
vote

/** 
 * Get file reader that corresponds to file extension.
 * @param file      the file name
 * @param pattern   TODO
 * @param skipLines TODO
 * @return a file reader that uncompresses data if needed
 * @throws IOException
 * @throws FileNotFoundException
 */
private BufferedReader getFileReader(final String file,String pattern,int skipLines) throws IOException, FileNotFoundException {
  BufferedReader fileReader;
  if (file.endsWith(".gz")) {
    fileReader=new BufferedReader(new InputStreamReader(new GZIPInputStream(new ClassPathResource(file).getInputStream())));
  }
 else   if (file.endsWith(".zip")) {
    fileReader=new BufferedReader(new InputStreamReader(new ZipInputStream(new ClassPathResource(file).getInputStream())));
  }
 else {
    fileReader=new BufferedReader(new FileReader(file));
  }
  String line="";
  while (!pattern.equals(line)) {
    line=fileReader.readLine();
  }
  for (int i=0; i < skipLines; i++) {
    line=fileReader.readLine();
  }
  return fileReader;
}