Example usage for java.util.zip ZipEntry ZipEntry

List of usage examples for java.util.zip ZipEntry ZipEntry

Introduction

In this page you can find the example usage for java.util.zip ZipEntry ZipEntry.

Prototype

public ZipEntry(ZipEntry e) 

Source Link

Document

Creates a new zip entry with fields taken from the specified zip entry.

Usage

From source file:com.asual.summer.onejar.OneJarServer.java

private static String getCurrentWarFile() throws IOException {
    JarFile jarFile = new JarFile(System.getProperty("java.class.path"));
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        String name = entries.nextElement().getName();
        if (name.endsWith(".war")) {
            File war = new File(new File(System.getProperty("java.io.tmpdir")),
                    "summer-onejar-" + System.currentTimeMillis() + ".war");
            InputStream input = jarFile.getInputStream(new ZipEntry(name));
            FileOutputStream output = new FileOutputStream(war);
            IOUtils.copy(input, output);
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(output);
            war.deleteOnExit();/*  w  w w .j ava 2s  .c o m*/
            return war.getAbsolutePath();
        }
    }
    return null;
}

From source file:herddb.upgrade.ZIPUtils.java

public static void createZipWithOneEntry(String entryfilename, InputStream filedata, OutputStream out,
        Charset fileNamesCharset) throws IOException {
    try (ZipOutputStream zipper = new ZipOutputStream(out, fileNamesCharset);) {
        int posslash = entryfilename.indexOf('/');
        if (posslash >= 0) { // gestione caso semplice di directory singola es. META-INF/magnews-app.xml per i test di MN
            String dire = entryfilename.substring(0, posslash);
            ZipEntry entry = new ZipEntry(dire);
            zipper.putNextEntry(entry);// w w w  . j a  v  a 2 s  .  c  o  m
            zipper.closeEntry();
        }
        ZipEntry entry = new ZipEntry(entryfilename);
        zipper.putNextEntry(entry);
        IOUtils.copyLarge(filedata, zipper);
        zipper.closeEntry();
    }
}

From source file:net.bpelunit.util.ZipUtil.java

public static void zipDirectory(File directory, File zipFile) throws IOException {
    @SuppressWarnings("unchecked")
    Collection<File> files = FileUtils.listFiles(directory, null, true);

    FileOutputStream fzos = null;
    ZipOutputStream zos = null;//  w  w  w  . jav a2  s. com
    try {
        fzos = new FileOutputStream(zipFile);
        zos = new ZipOutputStream(fzos);

        for (File f : files) {
            String fileNameInZIP = directory.toURI().relativize(f.toURI()).getPath();
            ZipEntry zipEntry = new ZipEntry(fileNameInZIP);
            zos.putNextEntry(zipEntry);
            FileInputStream fileInputStream = new FileInputStream(f);
            try {
                IOUtils.copy(fileInputStream, zos);
            } finally {
                IOUtils.closeQuietly(fileInputStream);
            }
        }
    } finally {
        IOUtils.closeQuietly(zos);
        IOUtils.closeQuietly(fzos);
    }
}

From source file:ezbake.frack.submitter.util.JarUtil.java

public static File addFilesToJar(File sourceJar, List<File> newFiles) throws IOException {
    JarOutputStream target = null;
    JarInputStream source;/* w w  w  . j ava 2  s  . co  m*/
    File outputJar = new File(sourceJar.getParentFile(), getRepackagedJarName(sourceJar.getAbsolutePath()));
    log.debug("Output file created at {}", outputJar.getAbsolutePath());
    outputJar.createNewFile();
    try {
        source = new JarInputStream(new FileInputStream(sourceJar));
        target = new JarOutputStream(new FileOutputStream(outputJar));
        ZipEntry entry = source.getNextEntry();
        while (entry != null) {
            String name = entry.getName();
            // Add ZIP entry to output stream.
            target.putNextEntry(new ZipEntry(name));
            // Transfer bytes from the ZIP file to the output file
            int len;
            byte[] buffer = new byte[BUFFER_SIZE];
            while ((len = source.read(buffer)) > 0) {
                target.write(buffer, 0, len);
            }
            entry = source.getNextEntry();
        }
        source.close();
        for (File fileToAdd : newFiles) {
            add(fileToAdd, fileToAdd.getParentFile().getAbsolutePath(), target);
        }
    } finally {
        if (target != null) {
            log.debug("Closing output stream");
            target.close();
        }
    }
    return outputJar;
}

From source file:Main.java

/**
 * Zips a subfolder/*from  w w w .  j  a va 2  s . co m*/
 */
protected static void zipSubFolder(ZipOutputStream zipOut, File srcFolder, int basePathLength)
        throws IOException {
    final int BUFFER = 2048;

    File[] fileList = srcFolder.listFiles();
    BufferedInputStream bis = null;

    for (File file : fileList) {

        if (file.isDirectory()) {
            zipSubFolder(zipOut, file, basePathLength);

        } else {
            byte data[] = new byte[BUFFER];
            String unmodifiedFilePath = file.getPath();
            String relativePath = unmodifiedFilePath.substring(basePathLength);
            Log.d("ZIP SUBFOLDER", "Relative Path : " + relativePath);

            FileInputStream fis = new FileInputStream(unmodifiedFilePath);
            bis = new BufferedInputStream(fis, BUFFER);

            ZipEntry zipEntry = new ZipEntry(relativePath);
            zipOut.putNextEntry(zipEntry);

            int count;
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                zipOut.write(data, 0, count);
            }

            bis.close();
        }
    }
}

From source file:Main.java

static private void addToZip(String path, String srcFile, ZipOutputStream zip) throws IOException {
    File folder = new File(srcFile);
    if (folder.isDirectory()) {
        addFolderToZip(path, srcFile, zip, true);
    } else {/*from  www .j a va 2  s  .  com*/
        byte[] buf = new byte[1024];
        int len;
        FileInputStream in = null;
        try {
            in = new FileInputStream(srcFile);
            zip.putNextEntry(new ZipEntry(path + File.separator + folder.getName()));
            while ((len = in.read(buf)) > 0) {
                zip.write(buf, 0, len);
            }
        } finally {
            if (in != null)
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
}

From source file:com.github.ansell.shp.SHPDump.java

public static void main(String... args) throws Exception {
    final OptionParser parser = new OptionParser();

    final OptionSpec<Void> help = parser.accepts("help").forHelp();
    final OptionSpec<File> input = parser.accepts("input").withRequiredArg().ofType(File.class).required()
            .describedAs("The input SHP file");
    final OptionSpec<File> output = parser.accepts("output").withRequiredArg().ofType(File.class).required()
            .describedAs("The output directory to use for debugging files");
    final OptionSpec<String> outputPrefix = parser.accepts("prefix").withRequiredArg().ofType(String.class)
            .defaultsTo("shp-debug").describedAs("The output prefix to use for debugging files");
    final OptionSpec<File> outputMappingTemplate = parser.accepts("output-mapping").withRequiredArg()
            .ofType(File.class).describedAs("The output mapping template file if it needs to be generated.");
    final OptionSpec<Integer> resolution = parser.accepts("resolution").withRequiredArg().ofType(Integer.class)
            .defaultsTo(2048).describedAs("The output image file resolution");
    final OptionSpec<String> format = parser.accepts("format").withRequiredArg().ofType(String.class)
            .defaultsTo("png").describedAs("The output image format");
    final OptionSpec<String> removeIfEmpty = parser.accepts("remove-if-empty").withRequiredArg()
            .ofType(String.class).describedAs(
                    "The name of an attribute to remove if its value is empty before outputting the resulting shapefile. Use multiple times to specify multiple fields to check");

    OptionSet options = null;/*from   w  ww . j  av  a2 s  .  c o m*/

    try {
        options = parser.parse(args);
    } catch (final OptionException e) {
        System.out.println(e.getMessage());
        parser.printHelpOn(System.out);
        throw e;
    }

    if (options.has(help)) {
        parser.printHelpOn(System.out);
        return;
    }

    final Path inputPath = input.value(options).toPath();
    if (!Files.exists(inputPath)) {
        throw new FileNotFoundException("Could not find input SHP file: " + inputPath.toString());
    }

    final Path outputPath = output.value(options).toPath();
    if (!Files.exists(outputPath)) {
        throw new FileNotFoundException("Output directory does not exist: " + outputPath.toString());
    }

    final Path outputMappingPath = options.has(outputMappingTemplate)
            ? outputMappingTemplate.value(options).toPath()
            : null;
    if (options.has(outputMappingTemplate) && Files.exists(outputMappingPath)) {
        throw new FileNotFoundException(
                "Output mapping template file already exists: " + outputMappingPath.toString());
    }

    final Set<String> filterFields = ConcurrentHashMap.newKeySet();
    if (options.has(removeIfEmpty)) {
        for (String nextFilterField : removeIfEmpty.values(options)) {
            System.out.println("Will filter field if empty value found: " + nextFilterField);
            filterFields.add(nextFilterField);
        }
    }

    if (!filterFields.isEmpty()) {
        System.out.println("Full set of filter fields: " + filterFields);
    }

    final String prefix = outputPrefix.value(options);

    FileDataStore store = FileDataStoreFinder.getDataStore(inputPath.toFile());

    if (store == null) {
        throw new RuntimeException("Could not read the given input as an ESRI Shapefile: "
                + inputPath.toAbsolutePath().toString());
    }

    for (String typeName : new LinkedHashSet<>(Arrays.asList(store.getTypeNames()))) {
        System.out.println("");
        System.out.println("Type: " + typeName);
        SimpleFeatureSource featureSource = store.getFeatureSource(typeName);
        SimpleFeatureType schema = featureSource.getSchema();

        Name outputSchemaName = new NameImpl(schema.getName().getNamespaceURI(),
                schema.getName().getLocalPart().replace(" ", "").replace("%20", ""));
        System.out.println("Replacing name on schema: " + schema.getName() + " with " + outputSchemaName);
        SimpleFeatureType outputSchema = SHPUtils.changeSchemaName(schema, outputSchemaName);

        List<String> attributeList = new ArrayList<>();
        for (AttributeDescriptor attribute : schema.getAttributeDescriptors()) {
            System.out.println("Attribute: " + attribute.getName().toString());
            attributeList.add(attribute.getName().toString());
        }
        CsvSchema csvSchema = CSVUtil.buildSchema(attributeList);

        SimpleFeatureCollection collection = featureSource.getFeatures();
        int featureCount = 0;
        Path nextCSVFile = outputPath.resolve(prefix + ".csv");
        Path nextSummaryCSVFile = outputPath
                .resolve(prefix + "-" + outputSchema.getTypeName() + "-Summary.csv");
        List<SimpleFeature> outputFeatureList = new CopyOnWriteArrayList<>();

        try (SimpleFeatureIterator iterator = collection.features();
                Writer bufferedWriter = Files.newBufferedWriter(nextCSVFile, StandardCharsets.UTF_8,
                        StandardOpenOption.CREATE_NEW);
                SequenceWriter csv = CSVUtil.newCSVWriter(bufferedWriter, csvSchema);) {
            List<String> nextLine = new ArrayList<>();
            while (iterator.hasNext()) {
                SimpleFeature feature = iterator.next();
                featureCount++;
                if (featureCount <= 2) {
                    System.out.println("");
                    System.out.println(feature.getIdentifier());
                } else if (featureCount % 100 == 0) {
                    System.out.print(".");
                }
                boolean filterThisFeature = false;
                for (AttributeDescriptor attribute : schema.getAttributeDescriptors()) {
                    String featureString = Optional.ofNullable(feature.getAttribute(attribute.getName()))
                            .orElse("").toString();
                    nextLine.add(featureString);
                    if (filterFields.contains(attribute.getName().toString())
                            && featureString.trim().isEmpty()) {
                        filterThisFeature = true;
                    }
                    if (featureString.length() > 100) {
                        featureString = featureString.substring(0, 100) + "...";
                    }
                    if (featureCount <= 2) {
                        System.out.print(attribute.getName() + "=");
                        System.out.println(featureString);
                    }
                }
                if (!filterThisFeature) {
                    outputFeatureList.add(SHPUtils.changeSchemaName(feature, outputSchema));
                    csv.write(nextLine);
                }
                nextLine.clear();
            }
        }
        try (Reader csvReader = Files.newBufferedReader(nextCSVFile, StandardCharsets.UTF_8);
                Writer summaryOutput = Files.newBufferedWriter(nextSummaryCSVFile, StandardCharsets.UTF_8,
                        StandardOpenOption.CREATE_NEW);
                final Writer mappingWriter = options.has(outputMappingTemplate)
                        ? Files.newBufferedWriter(outputMappingPath)
                        : NullWriter.NULL_WRITER) {
            CSVSummariser.runSummarise(csvReader, summaryOutput, mappingWriter,
                    CSVSummariser.DEFAULT_SAMPLE_COUNT, false);
        }
        if (featureCount > 100) {
            System.out.println("");
        }
        System.out.println("");
        System.out.println("Feature count: " + featureCount);

        SimpleFeatureCollection outputCollection = new ListFeatureCollection(outputSchema, outputFeatureList);
        Path outputShapefilePath = outputPath.resolve(prefix + "-" + outputSchema.getTypeName() + "-dump");
        if (!Files.exists(outputShapefilePath)) {
            Files.createDirectory(outputShapefilePath);
        }
        SHPUtils.writeShapefile(outputCollection, outputShapefilePath);

        // Create ZIP file from the contents to keep the subfiles together
        Path outputShapefileZipPath = outputPath
                .resolve(prefix + "-" + outputSchema.getTypeName() + "-dump.zip");
        try (final OutputStream out = Files.newOutputStream(outputShapefileZipPath,
                StandardOpenOption.CREATE_NEW);
                final ZipOutputStream zip = new ZipOutputStream(out, StandardCharsets.UTF_8);) {
            Files.list(outputShapefilePath).forEachOrdered(Unchecked.consumer(e -> {
                zip.putNextEntry(new ZipEntry(e.getFileName().toString()));
                Files.copy(e, zip);
                zip.closeEntry();
            }));
        }

        try (final OutputStream outputStream = Files.newOutputStream(
                outputPath.resolve(prefix + "." + format.value(options)), StandardOpenOption.CREATE_NEW);) {
            MapContent map = new MapContent();
            map.setTitle(prefix + "-" + outputSchema.getTypeName());
            Style style = SLD.createSimpleStyle(featureSource.getSchema());
            Layer layer = new FeatureLayer(new CollectionFeatureSource(outputCollection), style);
            map.addLayer(layer);
            SHPUtils.renderImage(map, outputStream, resolution.value(options), format.value(options));
        }
    }
}

From source file:Main.java

private static void zipDir(String dir, ZipOutputStream out) throws IOException {
    File directory = new File(dir);

    URI base = directory.toURI();

    ArrayList<File> filesToZip = new ArrayList<File>();

    GetFiles(directory, filesToZip);/*from www  .ja va 2s . com*/

    for (int i = 0; i < filesToZip.size(); ++i) {
        FileInputStream in = new FileInputStream(filesToZip.get(i));

        String name = base.relativize(filesToZip.get(i).toURI()).getPath();

        out.putNextEntry(new ZipEntry(name));

        byte[] buf = new byte[4096];
        int bytes = 0;

        while ((bytes = in.read(buf)) != -1) {
            out.write(buf, 0, bytes);
        }

        out.closeEntry();

        in.close();
    }

    out.finish();
    out.flush();
}

From source file:com.ikanow.aleph2.analytics.spark.utils.SparkPyTechnologyUtils.java

/** Create a zip containing the Aleph2 driver
 * @param bucket// www . ja va 2s.  c  om
 * @param job
 * @throws IOException
 */
public static String writeAleph2DriverZip(final String signature) throws IOException {
    final String tmp_dir = System.getProperty("java.io.tmpdir");
    final String filename = tmp_dir + "/aleph2_driver_py_" + signature + ".zip";

    final InputStream io_stream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("aleph2_driver.py");
    final FileOutputStream fout = new FileOutputStream(filename);
    final ZipOutputStream zout = new ZipOutputStream(fout);
    final ZipEntry ze = new ZipEntry("aleph2_driver.py");
    zout.putNextEntry(ze);
    zout.write(IOUtils.toString(io_stream).getBytes());
    zout.closeEntry();
    zout.close();

    return filename;
}

From source file:Main.java

private static boolean addEntryInputStream(ZipOutputStream zos, String entryName, InputStream inputStream) {
    final ZipEntry zipEntry = new ZipEntry(entryName);
    try {//from   w  ww . j  ava 2  s  .com
        zos.putNextEntry(zipEntry);
    } catch (final ZipException e) {

        // Ignore duplicate entry - no overwriting
        return false;
    } catch (final IOException e) {
        throw new RuntimeException("Error while adding zip entry " + zipEntry, e);
    }
    final int buffer = 2048;
    final BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream, buffer);
    int count;
    try {
        final byte data[] = new byte[buffer];
        while ((count = bufferedInputStream.read(data, 0, buffer)) != -1) {
            zos.write(data, 0, count);
        }
        bufferedInputStream.close();
        inputStream.close();
        zos.closeEntry();
        return true;
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}