java.util.zip.ZipOutputStream Java Examples

The following examples show how to use java.util.zip.ZipOutputStream. 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: ZipStreamDemo.java    From javacore with Creative Commons Attribution Share Alike 4.0 International 7 votes vote down vote up
/**
 * 压缩一个文件
 */
public static void output1(String filepath, String zipfilepath) throws Exception {
    // 1.使用 File 类绑定一个文件
    // 定义要压缩的文件
    File file = new File(filepath);
    // 定义压缩文件名称
    File zipFile = new File(zipfilepath);

    // 2.把 File 对象绑定到流对象上
    InputStream input = new FileInputStream(file);
    ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));

    // 3.进行读或写操作
    zipOut.putNextEntry(new ZipEntry(file.getName()));
    zipOut.setComment("This is a zip file.");
    int temp = 0;
    while ((temp = input.read()) != -1) { // 读取内容
        zipOut.write(temp); // 压缩输出
    }

    // 4.关闭流
    input.close();
    zipOut.close();
}
 
Example #2
Source File: CompressionUtilities.java    From geopaparazzi with GNU General Public License v3.0 6 votes vote down vote up
static private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip, String... excludeNames)
        throws IOException {
    if (isInArray(srcFolder, excludeNames)) {
        // jump folder if excluded
        return;
    }
    File folder = new File(srcFolder);
    String listOfFiles[] = folder.list();
    for (int i = 0; i < listOfFiles.length; i++) {
        if (isInArray(listOfFiles[i], excludeNames)) {
            // jump if excluded
            continue;
        }

        String folderPath = null;
        if (path.length() < 1) {
            folderPath = folder.getName();
        } else {
            folderPath = path + File.separator + folder.getName();
        }
        String srcFile = srcFolder + File.separator + listOfFiles[i];
        addToZip(folderPath, srcFile, zip, excludeNames);
    }
}
 
Example #3
Source File: SupportBundleManager.java    From datacollector with Apache License 2.0 6 votes vote down vote up
/**
 * Return InputStream from which a new generated resource bundle can be retrieved.
 */
public SupportBundle generateNewBundle(List<String> generatorNames, BundleType bundleType) throws IOException {
  List<BundleContentGeneratorDefinition> defs = getRequestedDefinitions(generatorNames);

  PipedInputStream inputStream = new PipedInputStream();
  PipedOutputStream outputStream = new PipedOutputStream();
  inputStream.connect(outputStream);
  ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);

  executor.submit(() -> generateNewBundleInternal(defs, bundleType, zipOutputStream));

  String bundleName = generateBundleName(bundleType);
  String bundleKey = generateBundleDate(bundleType) + "/" + bundleName;

  return new SupportBundle(
    bundleKey,
    bundleName,
    inputStream
  );
}
 
Example #4
Source File: ZipDatasets.java    From java-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Loop over each input dataset name (or pattern) given and
 * add entries for it to the Zip file.
 * If an exception occurs processing one entry, try to clean it
 * up and continue with the next entry. 
 * The {@link ZipDatasetSource} class does all of the real work.
 * <p/>
 * @param zipOutStream
 */
private void processInputFiles(ZipOutputStream zipOutStream) {
	for (int i=0; i<indsnames.length; i++) {
		String inputName = indsnames[i];
		ZipDatasetSource source = new ZipDatasetSource(inputName);
		try {
			source.addTo(zipOutStream, targetEncoding);
		} catch( Throwable t) {
			errors++;
			try { 
				zipOutStream.closeEntry(); 
			} catch (IOException ignore) {}
			System.out.println(">>> Error occuring processing input dataset: " + inputName);
			System.err.println(">>> Error occuring processing input dataset: " + inputName);
			t.printStackTrace();
		}
	}
}
 
Example #5
Source File: ZipDatasetSource.java    From java-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Add an single {@link ZipEntry} for a single dataset or member.
 * 
 * @param zipOutStream the target ZipOutputStream
 * @param targetEncoding the target text encoding
 * @param ddname the DD allocated to the dataset or member
 * @param memberName the member name; used to create the entry name
 * @throws IOException
 */
private void addDatasetOrMember(ZipOutputStream zipOutStream, String targetEncoding, 
									String ddname, String memberName) throws IOException {

	Reader reader = null;
	try {	
		reader = openInputFile(ddname, memberName);
		// Construct the name of the Zip entry that we will add
		String entryName = memberName == null 
							? name
							: name + "/" + memberName;
		// Start a new ZipEntry in the Zip file,
		// copy the dataset/member data into the Zip entry,
		// and close the entry
		ZipEntry entry = new ZipEntry(entryName);
		zipOutStream.putNextEntry(entry);
		copyData(reader, zipOutStream, targetEncoding);
		zipOutStream.closeEntry();

		System.out.println("  added: " + entryName 
							+ "  (" + entry.getSize() + " -> " + entry.getCompressedSize() + ")");
	} finally {
		closeInputFile(reader);
		freeDD(ddname);
	}
}
 
Example #6
Source File: Androlib.java    From ratel with Apache License 2.0 6 votes vote down vote up
public void buildUnknownFiles(File appDir, File outFile, MetaInfo meta)
        throws AndrolibException {
    if (meta.unknownFiles != null) {
        LOGGER.info("Copying unknown files/dir...");

        Map<String, String> files = meta.unknownFiles;
        File tempFile = new File(outFile.getParent(), outFile.getName() + ".apktool_temp");
        boolean renamed = outFile.renameTo(tempFile);
        if (!renamed) {
            throw new AndrolibException("Unable to rename temporary file");
        }

        try (
                ZipFile inputFile = new ZipFile(tempFile);
                ZipOutputStream actualOutput = new ZipOutputStream(new FileOutputStream(outFile))
        ) {
            copyExistingFiles(inputFile, actualOutput);
            copyUnknownFiles(appDir, actualOutput, files);
        } catch (IOException | BrutException ex) {
            throw new AndrolibException(ex);
        }

        // Remove our temporary file.
        tempFile.delete();
    }
}
 
Example #7
Source File: ExtensionUtilsTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Create a generic zip that is a valid extension archive. 
 * 
 * @param zipName name of the zip to create
 * @return a zip file
 * @throws IOException if there's an error creating the zip
 */
private File createExtensionZip(String zipName) throws IOException {

	File f = new File(gLayout.getExtensionArchiveDir().getFile(false), zipName + ".zip");
	try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f))) {
		out.putNextEntry(new ZipEntry(zipName + "/"));
		out.putNextEntry(new ZipEntry(zipName + "/extension.properties"));

		StringBuilder sb = new StringBuilder();
		sb.append("name:" + zipName);
		byte[] data = sb.toString().getBytes();
		out.write(data, 0, data.length);
		out.closeEntry();
	}

	return f;
}
 
Example #8
Source File: MaintenancePlugin.java    From AndroidAPS with GNU Affero General Public License v3.0 6 votes vote down vote up
public void zip(File zipFile, List<File> files) throws IOException {
    final int BUFFER_SIZE = 2048;

    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));

    for (File file : files) {
        byte[] data = new byte[BUFFER_SIZE];

        try(FileInputStream fileInputStream = new FileInputStream( file )) {

            try(BufferedInputStream origin = new BufferedInputStream(fileInputStream, BUFFER_SIZE)) {
                ZipEntry entry = new ZipEntry(file.getName());

                out.putNextEntry(entry);
                int count;
                while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) {
                    out.write(data, 0, count);
                }

            }
        }
    }

    out.close();
}
 
Example #9
Source File: ZipContentUtil.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Iterates the collection.getMembers() and streams content resources recursively to the ZipOutputStream
 * 
 * @param rootId
 * @param collection
 * @param out
 * @throws Exception
 */
private void storeContentCollection(String rootId, ContentCollection collection, ZipOutputStream out) throws Exception {
	List<String> members = collection.getMembers();
	if (members.isEmpty()) storeEmptyFolder(rootId,collection,out);
	else {
		for (String memberId: members) {
			if (memberId.endsWith(Entity.SEPARATOR)) {
				ContentCollection memberCollection = ContentHostingService.getCollection(memberId);
				storeContentCollection(rootId,memberCollection,out);
			} 
			else {
				ContentResource resource = ContentHostingService.getResource(memberId);
				storeContentResource(rootId, resource, out);
			}
		}
	}
}
 
Example #10
Source File: BundleMaker.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private boolean addUrlItemRecursively(ZipOutputStream zout, String root, String item, Predicate<? super String> filter) throws IOException {
    InputStream itemFound = null;
    try {
        itemFound = resources.getResourceFromUrl(item);
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        return false;
    }
    try {
        // can't reliably tell if item a file or a folder (listing files), esp w classpath where folder is treated as a list of files, 
        // so if we can't tell try it as a list of files; not guaranteed, and empty dir and a file of size 0 will appear identical, but better than was
        // (mainly used for tests)
        if (isKnownNotToBeADirectoryListing(item) || !addUrlDirToZipRecursively(zout, root, item, itemFound, filter)) {
            addUrlFileToZip(zout, root, item, filter);
        }
        return true;
    } finally {
        Streams.closeQuietly(itemFound);
    }
}
 
Example #11
Source File: ZipOutputStreamTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeAbleToAddASingleNonZeroLengthFile() throws IOException {
  File reference = File.createTempFile("reference", ".zip");

  try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(output, mode);
      ZipOutputStream ref = new ZipOutputStream(new FileOutputStream(reference))) {
    byte[] bytes = "cheese".getBytes();
    ZipEntry entry = new ZipEntry("example.txt");
    entry.setTime(System.currentTimeMillis());
    out.putNextEntry(entry);
    ref.putNextEntry(entry);
    out.write(bytes);
    ref.write(bytes);
  }

  byte[] seen = Files.readAllBytes(output);
  byte[] expected = Files.readAllBytes(reference.toPath());

  assertArrayEquals(expected, seen);
}
 
Example #12
Source File: OpenApi2JaxRs.java    From apicurio-studio with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a JaxRs project and streams the generated ZIP to the given
 * output stream.
 * @param output
 * @throws IOException
 */
public final void generate(OutputStream output) throws IOException {
    StringBuilder log = new StringBuilder();

    try (ZipOutputStream zos = new ZipOutputStream(output)) {
        try {
            CodegenInfo info = getInfoFromApiDoc();
            generateAll(info, log, zos);
        } catch (Exception e) {
            // If we get an error, put an PROJECT_GENERATION_ERROR file into the ZIP.
            zos.putNextEntry(new ZipEntry("PROJECT_GENERATION_FAILED.txt"));
            zos.write("An unexpected server error was encountered while generating the project.  See\r\n".getBytes());
            zos.write("the details of the error below.\r\n\r\n".getBytes());
            zos.write("Generation Log:\r\n\r\n".getBytes());
            zos.write(log.toString().getBytes(utf8));
            zos.write("\r\n\r\nServer Stack Trace:\r\n".getBytes());
            
            PrintWriter writer = new PrintWriter(zos);
            e.printStackTrace(writer);
            writer.flush();
            zos.closeEntry();
        }
    }
}
 
Example #13
Source File: TerminologyLoaderTestIT.java    From careconnect-reference-implementation with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadLoinc() throws Exception {
    ourLog.info("TEST = testLoadLoinc()");
    ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
    ZipOutputStream zos1 = new ZipOutputStream(bos1);
    addEntry(zos1, "/loinc/", "loinc.csv");
    zos1.close();
    ourLog.info("ZIP file has {} bytes", bos1.toByteArray().length);

    ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
    ZipOutputStream zos2 = new ZipOutputStream(bos2);
    addEntry(zos2, "/loinc/", "LOINC_2.54_MULTI-AXIAL_HIERARCHY.CSV");
    zos2.close();
    ourLog.info("ZIP file has {} bytes", bos2.toByteArray().length);

    RequestDetails details = mock(RequestDetails.class);
    when(codeSvc.findBySystem("http://loinc.org")).thenReturn(new CodeSystemEntity());
    mySvc.loadLoinc(list(bos1.toByteArray(), bos2.toByteArray()), details);

    verify(codeSvc).storeNewCodeSystemVersion( myCsvCaptor.capture(), any(RequestDetails.class));

    CodeSystemEntity ver = myCsvCaptor.getValue();
    ConceptEntity code = ver.getConcepts().iterator().next();
    assertEquals("10013-1", code.getCode());

}
 
Example #14
Source File: UnzipUtils.java    From imsdk-android with MIT License 6 votes vote down vote up
public static void zipFiles(Collection<File> resFileList, File zipFile, String comment, FeedBackServcie.Callback callback)
        throws IOException {
    final int BUFF_SIZE = 2048;
    ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(
            zipFile), BUFF_SIZE));
    int i = 0;
    for (File resFile : resFileList) {
        zipFile(resFile, zipout, "");
        if(callback != null){
            i++;
            callback.showFeedProgress(i,resFileList.size(), FeedBackServcie.FeedType.ZIP);
        }
    }
    zipout.setComment(comment);
    zipout.close();
}
 
Example #15
Source File: ZipUtils.java    From zuihou-admin-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * 通过流打包下载文件
 *
 * @param out
 * @param fileName
 * @param
 */
public static void zipFilesByInputStream(ZipOutputStream out, String fileName, InputStream is) throws Exception {
    byte[] buf = new byte[1024];
    try {
        out.putNextEntry(new ZipEntry(fileName));
        int len;
        while ((len = is.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        is.close();
    } catch (Exception e) {
        throw e;
    } finally {
        if (is != null) {
            is.close();
        }
    }
}
 
Example #16
Source File: Archive.java    From tomee with Apache License 2.0 6 votes vote down vote up
public File toJar(final String prefix, final String suffix) throws IOException {
    final File file = File.createTempFile(prefix, suffix);
    file.deleteOnExit();

    // Create the ZIP file
    final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(file)));

    for (final Map.Entry<String, byte[]> entry : entries().entrySet()) {
        out.putNextEntry(new ZipEntry(entry.getKey()));
        out.write(entry.getValue());
    }

    // Complete the ZIP file
    out.close();
    return file;
}
 
Example #17
Source File: ZIPUtils.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a zip archive from the provided list of files
 *
 * @param zipFile absolute path to the zip file which needs to be created
 * @param fileList list of files
 * @throws APIManagementException when error occurred while creating the zip file
 */
public static void zipFiles(String zipFile, Collection<File> fileList) throws APIManagementException {
    byte[] buffer = new byte[1024];
    try (FileOutputStream fos = new FileOutputStream(zipFile);
         ZipOutputStream zos = new ZipOutputStream(fos)) {
        for (File file : fileList) {
            String path = file.getAbsolutePath().substring(
                    file.getAbsolutePath().indexOf(APIConstants.API_WSDL_EXTRACTED_DIRECTORY)
                            + APIConstants.API_WSDL_EXTRACTED_DIRECTORY.length() + 1);
            ZipEntry ze = new ZipEntry(path);
            zos.putNextEntry(ze);
            try (FileInputStream in = new FileInputStream(file)) {
                int len;
                while ((len = in.read(buffer)) > 0) {
                    zos.write(buffer, 0, len);
                }
            }
        }
    } catch (IOException e) {
        throw new APIManagementException("Error occurred while creating the ZIP file: " + zipFile, e);
    }
}
 
Example #18
Source File: ClassFileInstaller.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static void writeJar(String jarFile, Manifest manifest, String classes[], int from, int to) throws Exception {
    if (DEBUG) {
        System.out.println("ClassFileInstaller: Writing to " + getJarPath(jarFile));
    }

    (new File(jarFile)).delete();
    FileOutputStream fos = new FileOutputStream(jarFile);
    ZipOutputStream zos = new ZipOutputStream(fos);

    // The manifest must be the first or second entry. See comments in JarInputStream
    // constructor and JDK-5046178.
    if (manifest != null) {
        writeToDisk(zos, "META-INF/MANIFEST.MF", manifest.getInputStream());
    }

    for (int i=from; i<to; i++) {
        writeClassToDisk(zos, classes[i]);
    }

    zos.close();
    fos.close();
}
 
Example #19
Source File: ZipUtilities.java    From submarine with Apache License 2.0 6 votes vote down vote up
private static void addFileToZip(ZipOutputStream zos, File base, File file)
    throws IOException {
  byte[] buffer = new byte[1024];
  try (FileInputStream fis = new FileInputStream(file)) {
    String name = base.toURI().relativize(file.toURI()).getPath();
    LOG.info("Adding file {} to zip", name);
    zos.putNextEntry(new ZipEntry(name));
    int length;
    while ((length = fis.read(buffer)) > 0) {
      zos.write(buffer, 0, length);
    }
    zos.flush();
  } finally {
    zos.closeEntry();
  }
}
 
Example #20
Source File: ZipUtility.java    From jmbe with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Compresses a list of files to a destination zip file
 *
 * @param listFiles A collection of files and directories
 * @param destZipFile The path of the destination zip file
 * @throws FileNotFoundException
 * @throws IOException
 */
public void zip(List<File> listFiles, String destZipFile) throws FileNotFoundException,
    IOException
{
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destZipFile));
    for(File file : listFiles)
    {
        if(file.isDirectory())
        {
            zipDirectory(file, file.getName(), zos);
        }
        else
        {
            zipFile(file, zos);
        }
    }
    zos.flush();
    zos.close();
}
 
Example #21
Source File: GenServiceImpl.java    From RuoYi with Apache License 2.0 5 votes vote down vote up
/**
 * 根据表信息生成代码
 * @param zip 生成后的压缩包
 * @param tableName 表名
 */
private void generatorCode(ZipOutputStream zip, String tableName) {
    // 查询表信息
    TableInfo table = genMapper.selectTableByName(tableName);
    // 查询列信息
    List<ColumnInfo> columns = genMapper.selectTableColumnsByName(tableName);
    // 表名转换成Java属性名
    String className = GenUtils.tableToJava(table.getTableName());
    table.setClassName(className);
    table.setClassname(StrUtil.lowerFirst(className));
    // 列信息
    table.setColumns(GenUtils.transColums(columns));
    // 设置主键
    table.setPrimaryKey(table.getColumnsLast());

    VelocityInitializer.initVelocity();

    String packageName = Global.getPackageName();
    String moduleName = GenUtils.getModuleName(packageName);

    VelocityContext context = GenUtils.getVelocityContext(table);

    // 获取模板列表
    List<String> templates = GenUtils.getTemplates();
    for (String template : templates) {
        // 渲染模板
        StringWriter sw = new StringWriter();
        Template tpl = Velocity.getTemplate(template, CharsetKit.UTF8);
        tpl.merge(context, sw);
        try {
            // 添加到zip
            zip.putNextEntry(new ZipEntry(Objects.requireNonNull(GenUtils.getFileName(template, table, moduleName))));
            IOUtils.write(sw.toString(), zip, CharsetKit.UTF8);
            IOUtils.closeQuietly(sw);
            zip.closeEntry();
        } catch (IOException e) {
            log.error("渲染模板失败,表名:" + table.getTableName(), e);
        }
    }
}
 
Example #22
Source File: ZipUtil.java    From android-tv-launcher with MIT License 5 votes vote down vote up
/**
 * 批量压缩文件(夹)
 *
 * @param resFileList 要压缩的文件(夹)列表
 * @param zipFile 生成的压缩文件
 * @param comment 压缩文件的注释
 * @throws IOException 当压缩过程出错时抛出
 */
public static void zipFiles(Collection<File> resFileList, File zipFile, String comment)
        throws IOException {
    ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(
            zipFile), BUFF_SIZE));
    for (File resFile : resFileList) {
        zipFile(resFile, zipout, "");
    }
    zipout.setComment(comment);
    zipout.close();
}
 
Example #23
Source File: Comment.java    From native-obfuscator with GNU General Public License v3.0 5 votes vote down vote up
private static void writeZipFile(String name, String comment)
    throws IOException
{
    try (FileOutputStream fos = new FileOutputStream(name);
         ZipOutputStream zos = new ZipOutputStream(fos))
    {
        zos.setComment(comment);
        ZipEntry ze = new ZipEntry(entryName);
        ze.setMethod(ZipEntry.DEFLATED);
        zos.putNextEntry(ze);
        new DataOutputStream(zos).writeUTF(entryContents);
        zos.closeEntry();
    }
}
 
Example #24
Source File: UnzipUtils.java    From imsdk-android with MIT License 5 votes vote down vote up
/**
 * 批量压缩文件(夹)
 *
 * @param resFileList 要压缩的文件(夹)列表
 * @param zipFile 生成的压缩文件
 * @throws IOException 当压缩过程出错时抛出
 */
public static void zipFiles(Collection<File> resFileList, File zipFile) throws IOException {
    final int BUFF_SIZE = 2048;
    ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(
            zipFile), BUFF_SIZE));
    for (File resFile : resFileList) {
        zipFile(resFile, zipout, "");
    }
    zipout.close();
}
 
Example #25
Source File: CreateAar.java    From intellij with Apache License 2.0 5 votes vote down vote up
public static void addFileToAar(File file, String dest, ZipOutputStream zos) throws IOException {
  try (FileInputStream fis = new FileInputStream(file)) {
    ZipEntry zipEntry = new ZipEntry(dest);
    zos.putNextEntry(zipEntry);
    ByteStreams.copy(fis, zos);
    zos.closeEntry();
  }
}
 
Example #26
Source File: AbstractASiCSignatureService.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void storeDocuments(List<DSSDocument> documents, ZipOutputStream zos) throws IOException {
	for (DSSDocument doc : documents) {
		final ZipEntry entrySignature = new ZipEntry(doc.getName());
		zos.putNextEntry(entrySignature);
		doc.writeTo(zos);
	}
}
 
Example #27
Source File: ZipUtils.java    From letv with Apache License 2.0 5 votes vote down vote up
public static void zipFiles(Collection<File> resFileList, File zipFile, String comment) throws IOException {
    ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile), 1048576));
    for (File resFile : resFileList) {
        zipFile(resFile, zipout, "");
    }
    zipout.setComment(comment);
    zipout.close();
}
 
Example #28
Source File: ZipUtils.java    From atlas with Apache License 2.0 5 votes vote down vote up
public static boolean removeZipEntry(File file, Pattern pattern, File targetFile)
    throws FileNotFoundException, IOException {
    byte[] buffer = new byte[1024];
    java.util.zip.ZipFile zipFile = new java.util.zip.ZipFile(file);
    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(targetFile)));
    BufferedOutputStream bo = new BufferedOutputStream(out);
    InputStream inputStream;
    Enumeration enumeration = zipFile.entries();
    while (enumeration.hasMoreElements()) {
        ZipEntry zipEntry = (ZipEntry)enumeration.nextElement();
        String name = zipEntry.getName();
        if (pattern.matcher(name).find()) {
            continue;
        }
        out.putNextEntry(zipEntry);
        inputStream = zipFile.getInputStream(zipEntry);
        write(inputStream, out, buffer);
        bo.flush();

    }

    closeQuitely(zipFile);
    closeQuitely(out);
    closeQuitely(bo);

    return true;
}
 
Example #29
Source File: CliFrontendSavepointTest.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Tests disposal with a JAR file.
 */
@Test
public void testDisposeWithJar() throws Exception {
	replaceStdOutAndStdErr();

	final CompletableFuture<String> disposeSavepointFuture = new CompletableFuture<>();

	final DisposeSavepointClusterClient clusterClient = new DisposeSavepointClusterClient(
		(String savepointPath) -> {
			disposeSavepointFuture.complete(savepointPath);
			return CompletableFuture.completedFuture(Acknowledge.get());
		}, getConfiguration());

	try {
		CliFrontend frontend = new MockedCliFrontend(clusterClient);

		// Fake JAR file
		File f = tmp.newFile();
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f));
		out.close();

		final String disposePath = "any-path";
		String[] parameters = { "-d", disposePath, "-j", f.getAbsolutePath() };

		frontend.savepoint(parameters);

		final String actualSavepointPath = disposeSavepointFuture.get();

		assertEquals(disposePath, actualSavepointPath);
	} finally {
		clusterClient.shutdown();
		restoreStdOutAndStdErr();
	}
}
 
Example #30
Source File: DbToolBase.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static ZipOutputStream getZipOutputStream(File zipFile) throws IOException {
  BufferedOutputStream out = new BufferedOutputStream(
      Files.newOutputStream(zipFile.toPath()), STREAM_BUFFER_SIZE);
  ZipOutputStream zipOutStream = new ZipOutputStream(out);
  zipOutStream.setLevel(Deflater.BEST_SPEED);
  return zipOutStream;
}