Java Code Examples for java.util.zip.ZipEntry#setSize()

The following examples show how to use java.util.zip.ZipEntry#setSize() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GridClientZipOptimizedMarshaller.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Zips bytes.
 *
 * @param input Input bytes.
 * @return Zipped byte array.
 * @throws IOException If failed.
 */
public static byte[] zipBytes(byte[] input) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream(DFLT_BUFFER_SIZE);

    try (ZipOutputStream zos = new ZipOutputStream(baos)) {
        ZipEntry entry = new ZipEntry("");

        try {
            entry.setSize(input.length);

            zos.putNextEntry(entry);
            zos.write(input);
        }
        finally {
            zos.closeEntry();
        }
    }

    return baos.toByteArray();
}
 
Example 2
Source File: ZipGenerator.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
public void addMimeTypeFile(String statedPath, String actualPath) throws IOException  {
  //  byte data[] = new byte[BUFFER];
    CRC32 crc = new CRC32();
    
  //  FileInputStream fi = new FileInputStream(actualPath);
  //  BufferedInputStream origin = new BufferedInputStream(fi, BUFFER);
    out.setLevel(0);
    ZipEntry entry = new ZipEntry(statedPath);
    entry.setExtra(null);
    names.add(statedPath);
    String contents = "application/epub+zip";
    crc.update(contents.getBytes());
    entry.setCompressedSize(contents.length());
    entry.setSize(contents.length());
    entry.setCrc(crc.getValue());
    entry.setMethod(ZipEntry.STORED);
    out.putNextEntry(entry);
 //   int count;
//    while ((count = origin.read(data, 0, BUFFER)) != -1) {
//      out.write(data, 0, count);
//    }
  //  origin.close();
    out.write(contents.getBytes(),0,contents.length());
    out.setLevel(Deflater.BEST_COMPRESSION);
  }
 
Example 3
Source File: DecompileAndAttachAction.java    From decompile-and-attach with MIT License 6 votes vote down vote up
private static void addFileEntry(ZipOutputStream jarOS, String relativePath, Set<String> writtenPaths,
        CharSequence decompiled) throws IOException {
    if (!writtenPaths.add(relativePath))
        return;

    ByteArrayInputStream fileIS = new ByteArrayInputStream(decompiled.toString().getBytes(Charsets.toCharset("UTF-8")));
    long size = decompiled.length();
    ZipEntry e = new ZipEntry(relativePath);
    if (size == 0) {
        e.setMethod(ZipEntry.STORED);
        e.setSize(0);
        e.setCrc(0);
    }
    jarOS.putNextEntry(e);
    try {
        FileUtil.copy(fileIS, jarOS);
    } finally {
        fileIS.close();
    }
    jarOS.closeEntry();
}
 
Example 4
Source File: AutoSTOREDZipOutputStream.java    From dexdiff with Apache License 2.0 6 votes vote down vote up
@Override
public void closeEntry() throws IOException {
    ZipEntry delayedEntry = this.delayedEntry;
    if (delayedEntry != null) {
        AccessBufByteArrayOutputStream delayedOutputStream = this.delayedOutputStream;
        byte[] buf = delayedOutputStream.getBuf();
        int size = delayedOutputStream.size();
        delayedEntry.setSize(size);
        delayedEntry.setCompressedSize(size);
        crc.reset();
        crc.update(buf, 0, size);
        delayedEntry.setCrc(crc.getValue());
        super.putNextEntry(delayedEntry);
        super.write(buf, 0, size);
        this.delayedEntry = null;
        delayedOutputStream.reset();
    }
    super.closeEntry();
}
 
Example 5
Source File: FileUtil.java    From nextreports-server with Apache License 2.0 6 votes vote down vote up
/** Zip files
 *
 * @param fileNames list of file names to zip
 * @param fileContents list of file contents
 * @return zip byte content
 * @throws java.io.IOException IOException
 */
public static byte[] zip(List<String> fileNames, List<byte[]> fileContents) throws IOException {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // Create the ZIP file
    ZipOutputStream out = new ZipOutputStream(baos);

    for (int i=0, size=fileNames.size(); i<size; i++) {
        String name = fileNames.get(i);
        byte[] content = fileContents.get(i);

        // Add ZIP entry to output stream.
        ZipEntry entry = new ZipEntry(name);
        entry.setSize(content.length);            
        out.putNextEntry(entry);
        out.write(content);
        // Complete the entry
        out.closeEntry();
    }
    out.close();
    return baos.toByteArray();
}
 
Example 6
Source File: DexFileArchive.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a {@code .dex} file with the given details.
 */
public DexFileArchive addFile(ZipEntry entry, Dex dex) throws IOException {
  checkState(inUse.compareAndSet(null, entry), "Already in use");
  entry.setSize(dex.getLength());
  out.putNextEntry(entry);
  dex.writeTo(out);
  out.closeEntry();
  checkState(inUse.compareAndSet(entry, null), "Swooped in: ", inUse.get());
  return this;
}
 
Example 7
Source File: UpdateableZipTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void appendEntry(ZipOutputStream zos, String name, byte[] content) throws Exception{
  ZipEntry e = new ZipEntry(name);
  e.setMethod(ZipEntry.STORED);
  e.setSize(content.length);
  CRC32 crc = new CRC32();
  crc.update(content);
  e.setCrc(crc.getValue());
  zos.putNextEntry(e);
  zos.write(content, 0, content.length);
  zos.closeEntry();
}
 
Example 8
Source File: AbstractGetDataToSignASiCS.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected DSSDocument createPackageZip(List<DSSDocument> documents, Date signingDate) {
	try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos)) {

		for (int i = 0; i < documents.size(); i++) {
			DSSDocument document = documents.get(i);
			final String documentName = document.getName();
			final String name = documentName != null ? documentName : ZIP_ENTRY_DETACHED_FILE + i;
			final ZipEntry entryDocument = new ZipEntry(name);
			entryDocument.setTime(signingDate.getTime());
			entryDocument.setMethod(ZipEntry.STORED);
			byte[] byteArray = DSSUtils.toByteArray(document);
			entryDocument.setSize(byteArray.length);
			entryDocument.setCompressedSize(byteArray.length);
			final CRC32 crc = new CRC32();
			crc.update(byteArray);
			entryDocument.setCrc(crc.getValue());
			zos.putNextEntry(entryDocument);
			Utils.write(byteArray, zos);
		}

		zos.finish();

		return new InMemoryDocument(baos.toByteArray(), ASiCUtils.PACKAGE_ZIP);
	} catch (IOException e) {
		throw new DSSException("Unable to create package.zip file", e);
	}
}
 
Example 9
Source File: GradlePackageTask.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
private void copyBootJar(JarOutputStream zOs, File bootJar)
  throws IOException
{
  try (FileInputStream fIn = new FileInputStream(bootJar)) {
    zOs.setLevel(9);

    try (ZipInputStream zIn = new ZipInputStream(fIn)) {
      ZipEntry entry;
      
      String pkg = BaratineBoot.class.getPackage().getName().replace('.', '/') + "/";
      
      while ((entry = zIn.getNextEntry()) != null) {
        String name = entry.getName();
        if (! name.startsWith(pkg)) {
          continue;
        }
        
        ZipEntry entryOut = new ZipEntry(name);
        entryOut.setSize(entry.getSize());
        
        zOs.putNextEntry(entryOut);
        
        if (name.startsWith(pkg)) {
          IoUtil.copy(zIn, zOs);
        }
      }
    }
  }
}
 
Example 10
Source File: JarSigner.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void writeEntry(ZipFile zf, ZipOutputStream os, ZipEntry ze)
        throws IOException {
    ZipEntry ze2 = new ZipEntry(ze.getName());
    ze2.setMethod(ze.getMethod());
    ze2.setTime(ze.getTime());
    ze2.setComment(ze.getComment());
    ze2.setExtra(ze.getExtra());
    if (ze.getMethod() == ZipEntry.STORED) {
        ze2.setSize(ze.getSize());
        ze2.setCrc(ze.getCrc());
    }
    os.putNextEntry(ze2);
    writeBytes(zf, ze, os);
}
 
Example 11
Source File: ZipUtils.java    From Stark with Apache License 2.0 5 votes vote down vote up
public static void writeEntry(ZipFile zf, ZipOutputStream os, ZipEntry ze)
        throws IOException {
    ZipEntry ze2 = new ZipEntry(ze.getName());
    ze2.setMethod(ze.getMethod());
    ze2.setTime(ze.getTime());
    ze2.setComment(ze.getComment());
    ze2.setExtra(ze.getExtra());
    if (ze.getMethod() == ZipEntry.STORED) {
        ze2.setSize(ze.getSize());
        ze2.setCrc(ze.getCrc());
    }
    os.putNextEntry(ze2);
    writeBytes(zf, ze, os);
}
 
Example 12
Source File: ZipArchivePackagingElement.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void addFile(@Nonnull ZipOutputStream zipOutputStream, @Nonnull InputStream stream, @Nonnull String relativePath, long fileLength, long lastModified) throws IOException {
  ZipEntry e = new ZipEntry(relativePath);
  e.setTime(lastModified);
  e.setSize(fileLength);

  zipOutputStream.putNextEntry(e);
  FileUtil.copy(stream, zipOutputStream);
  zipOutputStream.closeEntry();
}
 
Example 13
Source File: AnalysisExporter.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Export the output table in CSV
 *
 * @param connection
 *            the connection to the output table
 * @param version
 *            the version to export
 * @param fieldSeparator
 *            the separator of fields
 * @param lineSeparator
 *            the separator between lines
 * @return
 * @throws Exception
 */
public byte[] exportCSV(Connection connection, Integer version, String fieldSeparator, String lineSeparator, String fileName) throws Exception {

	byte[] toReturn = null;

	logger.debug("IN");
	ResultSet resultSet = executeExportDataQuery(connection, version);

	logger.debug("Initializing the output stream");
	ByteArrayOutputStream fos = new ByteArrayOutputStream();
	Writer out = new OutputStreamWriter(fos);

	try {
		logger.debug("Starts to navigate the result set");
		int ncols = resultSet.getMetaData().getColumnCount();
		for (int j = 1; j < (ncols + 1); j++) {
			out.append(resultSet.getMetaData().getColumnName(j));
			if (j < ncols) {
				out.append(fieldSeparator);
			} else {
				out.append(lineSeparator);
			}
		}

		while (resultSet.next()) {

			for (int k = 1; k < (ncols + 1); k++) {

				out.append(resultSet.getString(k));

				if (k < ncols) {
					out.append(fieldSeparator);
				} else {
					out.append(lineSeparator);
				}
			}

		}
		out.flush();
		toReturn = fos.toByteArray();
		
		logger.debug("Finished to navigate the result set");
		logger.debug("Start Creating zip");
		
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ZipOutputStream zos = new ZipOutputStream(baos);
		ZipEntry entry = new ZipEntry(fileName);
		entry.setSize(toReturn.length);
		zos.putNextEntry(entry);
		zos.write(toReturn);
		zos.closeEntry();
		zos.close();
		
		toReturn = baos.toByteArray();
		
		logger.debug("zip created");

		
		logger.debug("OUT");
	} catch (Exception e) {
		out.close();
	}

	return toReturn;
}
 
Example 14
Source File: NativeUnpack.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
private void writeEntry(JarOutputStream j, String name,
                        long mtime, long lsize, boolean deflateHint,
                        ByteBuffer data0, ByteBuffer data1) throws IOException {
    int size = (int)lsize;
    if (size != lsize)
        throw new IOException("file too large: "+lsize);

    CRC32 crc32 = _crc32;

    if (_verbose > 1)
        Utils.log.fine("Writing entry: "+name+" size="+size
                         +(deflateHint?" deflated":""));

    if (_buf.length < size) {
        int newSize = size;
        while (newSize < _buf.length) {
            newSize <<= 1;
            if (newSize <= 0) {
                newSize = size;
                break;
            }
        }
        _buf = new byte[newSize];
    }
    assert(_buf.length >= size);

    int fillp = 0;
    if (data0 != null) {
        int size0 = data0.capacity();
        data0.get(_buf, fillp, size0);
        fillp += size0;
    }
    if (data1 != null) {
        int size1 = data1.capacity();
        data1.get(_buf, fillp, size1);
        fillp += size1;
    }
    while (fillp < size) {
        // Fill in rest of data from the stream itself.
        int nr = in.read(_buf, fillp, size - fillp);
        if (nr <= 0)  throw new IOException("EOF at end of archive");
        fillp += nr;
    }

    ZipEntry z = new ZipEntry(name);
    z.setTime(mtime * 1000);

    if (size == 0) {
        z.setMethod(ZipOutputStream.STORED);
        z.setSize(0);
        z.setCrc(0);
        z.setCompressedSize(0);
    } else if (!deflateHint) {
        z.setMethod(ZipOutputStream.STORED);
        z.setSize(size);
        z.setCompressedSize(size);
        crc32.reset();
        crc32.update(_buf, 0, size);
        z.setCrc(crc32.getValue());
    } else {
        z.setMethod(Deflater.DEFLATED);
        z.setSize(size);
    }

    j.putNextEntry(z);

    if (size > 0)
        j.write(_buf, 0, size);

    j.closeEntry();
    if (_verbose > 0) Utils.log.info("Writing " + Utils.zeString(z));
}
 
Example 15
Source File: NativeUnpack.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
private void writeEntry(JarOutputStream j, String name,
                        long mtime, long lsize, boolean deflateHint,
                        ByteBuffer data0, ByteBuffer data1) throws IOException {
    int size = (int)lsize;
    if (size != lsize)
        throw new IOException("file too large: "+lsize);

    CRC32 crc32 = _crc32;

    if (_verbose > 1)
        Utils.log.fine("Writing entry: "+name+" size="+size
                         +(deflateHint?" deflated":""));

    if (_buf.length < size) {
        int newSize = size;
        while (newSize < _buf.length) {
            newSize <<= 1;
            if (newSize <= 0) {
                newSize = size;
                break;
            }
        }
        _buf = new byte[newSize];
    }
    assert(_buf.length >= size);

    int fillp = 0;
    if (data0 != null) {
        int size0 = data0.capacity();
        data0.get(_buf, fillp, size0);
        fillp += size0;
    }
    if (data1 != null) {
        int size1 = data1.capacity();
        data1.get(_buf, fillp, size1);
        fillp += size1;
    }
    while (fillp < size) {
        // Fill in rest of data from the stream itself.
        int nr = in.read(_buf, fillp, size - fillp);
        if (nr <= 0)  throw new IOException("EOF at end of archive");
        fillp += nr;
    }

    ZipEntry z = new ZipEntry(name);
    z.setTime(mtime * 1000);

    if (size == 0) {
        z.setMethod(ZipOutputStream.STORED);
        z.setSize(0);
        z.setCrc(0);
        z.setCompressedSize(0);
    } else if (!deflateHint) {
        z.setMethod(ZipOutputStream.STORED);
        z.setSize(size);
        z.setCompressedSize(size);
        crc32.reset();
        crc32.update(_buf, 0, size);
        z.setCrc(crc32.getValue());
    } else {
        z.setMethod(Deflater.DEFLATED);
        z.setSize(size);
    }

    j.putNextEntry(z);

    if (size > 0)
        j.write(_buf, 0, size);

    j.closeEntry();
    if (_verbose > 0) Utils.log.info("Writing " + Utils.zeString(z));
}
 
Example 16
Source File: NativeUnpack.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
private void writeEntry(JarOutputStream j, String name,
                        long mtime, long lsize, boolean deflateHint,
                        ByteBuffer data0, ByteBuffer data1) throws IOException {
    int size = (int)lsize;
    if (size != lsize)
        throw new IOException("file too large: "+lsize);

    CRC32 crc32 = _crc32;

    if (_verbose > 1)
        Utils.log.fine("Writing entry: "+name+" size="+size
                         +(deflateHint?" deflated":""));

    if (_buf.length < size) {
        int newSize = size;
        while (newSize < _buf.length) {
            newSize <<= 1;
            if (newSize <= 0) {
                newSize = size;
                break;
            }
        }
        _buf = new byte[newSize];
    }
    assert(_buf.length >= size);

    int fillp = 0;
    if (data0 != null) {
        int size0 = data0.capacity();
        data0.get(_buf, fillp, size0);
        fillp += size0;
    }
    if (data1 != null) {
        int size1 = data1.capacity();
        data1.get(_buf, fillp, size1);
        fillp += size1;
    }
    while (fillp < size) {
        // Fill in rest of data from the stream itself.
        int nr = in.read(_buf, fillp, size - fillp);
        if (nr <= 0)  throw new IOException("EOF at end of archive");
        fillp += nr;
    }

    ZipEntry z = new ZipEntry(name);
    z.setTime(mtime * 1000);

    if (size == 0) {
        z.setMethod(ZipOutputStream.STORED);
        z.setSize(0);
        z.setCrc(0);
        z.setCompressedSize(0);
    } else if (!deflateHint) {
        z.setMethod(ZipOutputStream.STORED);
        z.setSize(size);
        z.setCompressedSize(size);
        crc32.reset();
        crc32.update(_buf, 0, size);
        z.setCrc(crc32.getValue());
    } else {
        z.setMethod(Deflater.DEFLATED);
        z.setSize(size);
    }

    j.putNextEntry(z);

    if (size > 0)
        j.write(_buf, 0, size);

    j.closeEntry();
    if (_verbose > 0) Utils.log.info("Writing " + Utils.zeString(z));
}
 
Example 17
Source File: NativeUnpack.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
private void writeEntry(JarOutputStream j, String name,
                        long mtime, long lsize, boolean deflateHint,
                        ByteBuffer data0, ByteBuffer data1) throws IOException {
    int size = (int)lsize;
    if (size != lsize)
        throw new IOException("file too large: "+lsize);

    CRC32 crc32 = _crc32;

    if (_verbose > 1)
        Utils.log.fine("Writing entry: "+name+" size="+size
                         +(deflateHint?" deflated":""));

    if (_buf.length < size) {
        int newSize = size;
        while (newSize < _buf.length) {
            newSize <<= 1;
            if (newSize <= 0) {
                newSize = size;
                break;
            }
        }
        _buf = new byte[newSize];
    }
    assert(_buf.length >= size);

    int fillp = 0;
    if (data0 != null) {
        int size0 = data0.capacity();
        data0.get(_buf, fillp, size0);
        fillp += size0;
    }
    if (data1 != null) {
        int size1 = data1.capacity();
        data1.get(_buf, fillp, size1);
        fillp += size1;
    }
    while (fillp < size) {
        // Fill in rest of data from the stream itself.
        int nr = in.read(_buf, fillp, size - fillp);
        if (nr <= 0)  throw new IOException("EOF at end of archive");
        fillp += nr;
    }

    ZipEntry z = new ZipEntry(name);
    z.setTime(mtime * 1000);

    if (size == 0) {
        z.setMethod(ZipOutputStream.STORED);
        z.setSize(0);
        z.setCrc(0);
        z.setCompressedSize(0);
    } else if (!deflateHint) {
        z.setMethod(ZipOutputStream.STORED);
        z.setSize(size);
        z.setCompressedSize(size);
        crc32.reset();
        crc32.update(_buf, 0, size);
        z.setCrc(crc32.getValue());
    } else {
        z.setMethod(Deflater.DEFLATED);
        z.setSize(size);
    }

    j.putNextEntry(z);

    if (size > 0)
        j.write(_buf, 0, size);

    j.closeEntry();
    if (_verbose > 0) Utils.log.info("Writing " + Utils.zeString(z));
}
 
Example 18
Source File: ZipReaderTest.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Test public void testZipEntryFields() throws IOException {
  CRC32 crc = new CRC32();
  Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true);
  long date = 791784306000L; // 2/3/1995 04:05:06
  byte[] extra = new ExtraData((short) 0xaa, new byte[] { (byte) 0xbb, (byte) 0xcd }).getBytes();
  byte[] tmp = new byte[128];
  try (ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(test))) {

    ZipEntry foo = new ZipEntry("foo");
    foo.setComment("foo comment.");
    foo.setMethod(ZipEntry.DEFLATED);
    foo.setTime(date);
    foo.setExtra(extra);
    zout.putNextEntry(foo);
    zout.write("foo".getBytes(UTF_8));
    zout.closeEntry();

    ZipEntry bar = new ZipEntry("bar");
    bar.setComment("bar comment.");
    bar.setMethod(ZipEntry.STORED);
    bar.setSize("bar".length());
    bar.setCompressedSize("bar".length());
    crc.reset();
    crc.update("bar".getBytes(UTF_8));
    bar.setCrc(crc.getValue());
    zout.putNextEntry(bar);
    zout.write("bar".getBytes(UTF_8));
    zout.closeEntry();
  }

  try (ZipReader reader = new ZipReader(test, UTF_8)) {
    ZipFileEntry fooEntry = reader.getEntry("foo");
    assertThat(fooEntry.getName()).isEqualTo("foo");
    assertThat(fooEntry.getComment()).isEqualTo("foo comment.");
    assertThat(fooEntry.getMethod()).isEqualTo(Compression.DEFLATED);
    assertThat(fooEntry.getVersion()).isEqualTo(Compression.DEFLATED.getMinVersion());
    assertThat(fooEntry.getTime()).isEqualTo(date);
    assertThat(fooEntry.getSize()).isEqualTo("foo".length());
    deflater.reset();
    deflater.setInput("foo".getBytes(UTF_8));
    deflater.finish();
    assertThat(fooEntry.getCompressedSize()).isEqualTo(deflater.deflate(tmp));
    crc.reset();
    crc.update("foo".getBytes(UTF_8));
    assertThat(fooEntry.getCrc()).isEqualTo(crc.getValue());
    assertThat(fooEntry.getExtra().getBytes()).isEqualTo(extra);

    ZipFileEntry barEntry = reader.getEntry("bar");
    assertThat(barEntry.getName()).isEqualTo("bar");
    assertThat(barEntry.getComment()).isEqualTo("bar comment.");
    assertThat(barEntry.getMethod()).isEqualTo(Compression.STORED);
    assertThat(barEntry.getVersion()).isEqualTo(Compression.STORED.getMinVersion());
    assertDateAboutNow(new Date(barEntry.getTime()));
    assertThat(barEntry.getSize()).isEqualTo("bar".length());
    assertThat(barEntry.getCompressedSize()).isEqualTo("bar".length());
    crc.reset();
    crc.update("bar".getBytes(UTF_8));
    assertThat(barEntry.getCrc()).isEqualTo(crc.getValue());
    assertThat(barEntry.getExtra().getBytes()).isEqualTo(new byte[] {});
  }
}
 
Example 19
Source File: WorkspaceEndpoint.java    From tool.accelerate.core with Apache License 2.0 4 votes vote down vote up
@GET
@Path("files")
@Produces("application/zip")
//Swagger annotations
@ApiOperation(value = "Retrieve a zip of the content from a directory in the workspace", httpMethod = "GET", notes = "Get zip containing files from the workspace.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully produced a zip of the required workspace files") })
public Response getFiles(@QueryParam("workspace") String workspaceId, @QueryParam("serviceId") String serviceId, @QueryParam("dir") String dir) throws IOException {
    log.info("GET request for /workspace/files");
    String techWorkspaceDir = StarterUtil.getWorkspaceDir(workspaceId) + "/";
    String filesDir = techWorkspaceDir + "/" + serviceId + "/" + dir;
    File directory = new File(filesDir);
    if(directory.exists() && directory.isDirectory()) {
        IOFileFilter filter;
        if("swagger".equals(serviceId)) {
            filter = FileFilterUtils.notFileFilter(new NameFileFilter(new String[]{"RestApplication.java", "AndroidManifest.xml"}));
        } else {
            filter = FileFilterUtils.trueFileFilter();
        }
        Iterator<File> itr = FileUtils.iterateFilesAndDirs(directory, filter, FileFilterUtils.trueFileFilter());
        StreamingOutput so = (OutputStream os) -> {
            ZipOutputStream zos = new ZipOutputStream(os);
            while(itr.hasNext()) {
                File file = itr.next();
                if(file.isFile()) {
                    byte[] byteArray = FileUtils.readFileToByteArray(file);
                    String path = file.getAbsolutePath().replace('\\', '/');
                    int index = path.indexOf(serviceId + "/" + dir);
                    String relativePath = path.substring(index);
                    ZipEntry entry = new ZipEntry(relativePath);
                    entry.setSize(byteArray.length);
                    entry.setCompressedSize(-1);
                    try {
                        zos.putNextEntry(entry);
                        zos.write(byteArray);
                    } catch (IOException e) {
                        throw new IOException(e);
                    }
                }
            }
            zos.close();
        };
        log.info("Copied files from " + filesDir + " to zip.");
        return Response.ok(so, "application/zip").header("Content-Disposition", "attachment; filename=\"swagger.zip\"").build();
    } else {
        log.severe("File directory doesn't exist : " + filesDir);
        return Response.status(Status.BAD_REQUEST).entity("File directory specified doesn't exist").build();
    }
}
 
Example 20
Source File: NativeUnpack.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
private void writeEntry(JarOutputStream j, String name,
                        long mtime, long lsize, boolean deflateHint,
                        ByteBuffer data0, ByteBuffer data1) throws IOException {
    int size = (int)lsize;
    if (size != lsize)
        throw new IOException("file too large: "+lsize);

    CRC32 crc32 = _crc32;

    if (_verbose > 1)
        Utils.log.fine("Writing entry: "+name+" size="+size
                         +(deflateHint?" deflated":""));

    if (_buf.length < size) {
        int newSize = size;
        while (newSize < _buf.length) {
            newSize <<= 1;
            if (newSize <= 0) {
                newSize = size;
                break;
            }
        }
        _buf = new byte[newSize];
    }
    assert(_buf.length >= size);

    int fillp = 0;
    if (data0 != null) {
        int size0 = data0.capacity();
        data0.get(_buf, fillp, size0);
        fillp += size0;
    }
    if (data1 != null) {
        int size1 = data1.capacity();
        data1.get(_buf, fillp, size1);
        fillp += size1;
    }
    while (fillp < size) {
        // Fill in rest of data from the stream itself.
        int nr = in.read(_buf, fillp, size - fillp);
        if (nr <= 0)  throw new IOException("EOF at end of archive");
        fillp += nr;
    }

    ZipEntry z = new ZipEntry(name);
    z.setTime(mtime * 1000);

    if (size == 0) {
        z.setMethod(ZipOutputStream.STORED);
        z.setSize(0);
        z.setCrc(0);
        z.setCompressedSize(0);
    } else if (!deflateHint) {
        z.setMethod(ZipOutputStream.STORED);
        z.setSize(size);
        z.setCompressedSize(size);
        crc32.reset();
        crc32.update(_buf, 0, size);
        z.setCrc(crc32.getValue());
    } else {
        z.setMethod(Deflater.DEFLATED);
        z.setSize(size);
    }

    j.putNextEntry(z);

    if (size > 0)
        j.write(_buf, 0, size);

    j.closeEntry();
    if (_verbose > 0) Utils.log.info("Writing " + Utils.zeString(z));
}