Example usage for java.util.zip ZipFile getEntry

List of usage examples for java.util.zip ZipFile getEntry

Introduction

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

Prototype

public ZipEntry getEntry(String name) 

Source Link

Document

Returns the zip file entry for the specified name, or null if not found.

Usage

From source file:com.sshtools.j2ssh.util.DynamicClassLoader.java

private InputStream loadResourceFromZipfile(File file, String name) {
    try {/*from   w w w.  j ava  2 s .com*/
        ZipFile zipfile = new ZipFile(file);
        ZipEntry entry = zipfile.getEntry(name);

        if (entry != null) {
            return zipfile.getInputStream(entry);
        } else {
            return null;
        }
    } catch (IOException e) {
        return null;
    }
}

From source file:org.wisdom.framework.vertx.ChunkedResponseTest.java

@Test
public void testZippedFileDownload() throws InterruptedException, IOException {

    // Prepare the configuration
    ApplicationConfiguration configuration = mock(ApplicationConfiguration.class);
    when(configuration.getIntegerWithDefault(eq("vertx.http.port"), anyInt())).thenReturn(0);
    when(configuration.getIntegerWithDefault(eq("vertx.https.port"), anyInt())).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.acceptBacklog", -1)).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.receiveBufferSize", -1)).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.sendBufferSize", -1)).thenReturn(-1);
    when(configuration.getStringArray("wisdom.websocket.subprotocols")).thenReturn(new String[0]);
    when(configuration.getStringArray("vertx.websocket-subprotocols")).thenReturn(new String[0]);

    // Prepare the router with a controller
    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result index() throws IOException {
            ZipFile zip = new ZipFile("src/test/resources/owl.png.zip");
            ZipEntry entry = zip.getEntry("owl.png");
            InputStream stream = zip.getInputStream(entry);
            return ok(stream);
        }/*  www. j  av  a  2 s.  co m*/
    };

    Router router = mock(Router.class);
    final Route route = new RouteBuilder().route(HttpMethod.GET).on("/").to(controller, "index");
    doAnswer(invocationOnMock -> route).when(router).getRouteFor(anyString(), anyString(), any(Request.class));

    // Configure the server.
    server = new WisdomVertxServer();
    server.configuration = configuration;
    server.accessor = new ServiceAccessor(null, configuration, router, getMockContentEngine(), executor, null,
            Collections.<ExceptionMapper>emptyList());
    server.vertx = vertx;

    server.start();

    VertxHttpServerTest.waitForStart(server);

    // Now start bunch of clients
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(NUMBER_OF_CLIENTS);

    int port = server.httpPort();

    for (int i = 0; i < NUMBER_OF_CLIENTS; ++i) {// create and start threads
        clients.submit(new DownloadClient(startSignal, doneSignal, port, i));
    }

    startSignal.countDown(); // let all threads proceed
    assertThat(doneSignal.await(60, TimeUnit.SECONDS)).isTrue();

    assertThat(failure).isEmpty();
    assertThat(success).hasSize(NUMBER_OF_CLIENTS);
}

From source file:org.polago.deployconf.DeployConfRunner.java

/**
 * Gets a DeploymentConfig instance from a Zip file.
 *
 * @param source the ZipFile to use/*from   w w w.  ja va 2  s .  c  o  m*/
 * @return a DeploymentConfig representation of the ReadableByteChannel
 * @throws Exception indicating error
 */
private DeploymentConfig getDeploymentConfigFromZip(String source) throws Exception {

    ZipFile zipFile = new ZipFile(source);
    ZipEntry entry = zipFile.getEntry(deploymentTemplatePath);
    if (entry == null) {
        zipFile.close();
        throw new IllegalArgumentException(
                "No deployment template file found in file '" + source + "': " + deploymentTemplatePath);
    }
    InputStream is = zipFile.getInputStream(entry);

    DeploymentReader reader = new DeploymentReader(is, groupManager);
    DeploymentConfig result = reader.parse();
    is.close();
    zipFile.close();

    return result;
}

From source file:de.uni_koeln.spinfo.maalr.services.admin.shared.DataLoader.java

public void createFromSQLDump(File file, int maxEntries)
        throws IOException, NoDatabaseAvailableException, InvalidEntryException, IndexException {

    if (!file.exists()) {
        logger.info("No data to import - file " + file + " does not exist.");
        return;/*from   w  w  w.ja  v a 2s  .c o m*/
    }

    BufferedReader br;
    ZipFile zipFile = null;
    if (file.getName().endsWith(".zip")) {
        logger.info("Trying to read data from zip file=" + file.getName());
        zipFile = new ZipFile(file);
        String entryName = file.getName().replaceAll(".zip", "");
        //         ZipEntry entry = zipFile.getEntry(entryName+".tsv");
        ZipEntry entry = zipFile.getEntry(entryName);
        if (entry == null) {
            logger.info("No file named " + entryName + " found in zip file - skipping import");
            zipFile.close();
            return;
        }
        br = new BufferedReader(new InputStreamReader(zipFile.getInputStream(entry), "UTF-8"));
    } else {
        logger.info("Trying to read data from file " + file);
        br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
    }

    String line = br.readLine();
    String[] keys = line.split("\t", -1);
    Database db = Database.getInstance();
    List<DBObject> entries = new ArrayList<DBObject>();
    int counter = 0;
    String userId = loginManager.getCurrentUserId();
    while ((line = br.readLine()) != null) {
        String[] values = line.split("\t", -1);
        if (values.length != keys.length) {
            logger.warn("Ignoring entry: Attribute mismatch (" + values.length + " entries found, "
                    + keys.length + " entries expected) in line " + line);
            continue;
        }
        LemmaVersion version = new LemmaVersion();
        for (int i = 0; i < keys.length; i++) {
            String value = values[i].trim();
            String key = keys[i].trim();
            if (value.length() == 0)
                continue;
            if (key.length() == 0)
                continue;
            version.setValue(key, value);
        }
        LexEntry entry = new LexEntry(version);
        entry.setCurrent(version);
        entry.getCurrent().setStatus(Status.NEW_ENTRY);
        entry.getCurrent().setVerification(Verification.ACCEPTED);
        long timestamp = System.currentTimeMillis();
        String embeddedTimeStamp = version.getEntryValue(LemmaVersion.TIMESTAMP);
        if (embeddedTimeStamp != null) {
            timestamp = Long.parseLong(embeddedTimeStamp);
            version.removeEntryValue(LemmaVersion.TIMESTAMP);
        }
        entry.getCurrent().setUserId(userId);
        entry.getCurrent().setTimestamp(timestamp);
        entry.getCurrent().setCreatorRole(Role.ADMIN_5);
        entries.add(Converter.convertLexEntry(entry));
        if (entries.size() == 10000) {
            db.insertBatch(entries);
            entries.clear();
        }
        counter++;
        if (counter == maxEntries) {
            logger.warn("Skipping db creation, as max entries is " + maxEntries);
            break;
        }
    }
    db.insertBatch(entries);
    entries.clear();
    //loginManager.login("admin", "admin");
    Iterator<LexEntry> iterator = db.getEntries();
    index.dropIndex();
    index.addToIndex(iterator);
    logger.info("Index has been created, swapping to RAM...");
    index.reloadIndex();
    logger.info("RAM-Index updated.");
    br.close();
    if (zipFile != null) {
        zipFile.close();
    }
    //loginManager.logout();
    logger.info("Dataloader initialized.");
}

From source file:org.bdval.ConsensusBDVModel.java

/**
 * @param options specific options to use when loading the properties
 * @throws IOException if there is a problem accessing the properties
 *///from w ww. j a v  a  2  s. c  om
private void loadProperties(final DAVOptions options) throws IOException {
    final boolean zipExists = new File(zipFilename).exists();
    if (LOG.isDebugEnabled()) {
        LOG.debug("model zip file exists: " + BooleanUtils.toStringYesNo(zipExists));
    }

    properties.clear();

    // check to see if a zip file exists - if it doesn't we assume it's an old binary format
    if (zipModel && zipExists) {
        LOG.info("Reading model from filename: " + zipFilename);

        final ZipFile zipFile = new ZipFile(zipFilename);
        try {
            final ZipEntry propertyEntry = zipFile.getEntry(FilenameUtils.getName(modelPropertiesFilename));
            // load properties
            properties.clear();
            properties.addAll(loadProperties(zipFile.getInputStream(propertyEntry), options));
        } finally {
            try {
                zipFile.close();
            } catch (IOException e) { // NOPMD
                // ignore since there is not much we can do anyway
            }
        }
    } else {
        final File propertyFile = new File(modelFilenamePrefix + "." + ModelFileExtension.props.toString());
        if (propertyFile.exists() && propertyFile.canRead()) {
            LOG.debug("Loading properties from " + propertyFile.getAbsolutePath());
            properties.addAll(loadProperties(FileUtils.openInputStream(propertyFile), options));
        }
    }
}

From source file:org.zgis.wps.swat.AnnotatedSwatRunnerAlgorithm.java

private URI extractToTemp(final ZipFile zipFile, final String filename) throws IOException {
    final File tempFile;
    final ZipEntry entry;

    tempFile = new File(ExecutionContextFactory.getContext().getTempDirectoryPath()
            + System.getProperty("file.separator") + filename);
    tempFile.getParentFile().mkdirs();//from w w w .  j av a 2  s  .  c om
    entry = zipFile.getEntry(filename);

    if (entry == null) {
        throw new FileNotFoundException("cannot find file: " + filename + " in archive: " + zipFile.getName());
    }

    try (OutputStream fileStream = new FileOutputStream(tempFile);
            InputStream zipStream = zipFile.getInputStream(entry)) {
        final byte[] buf;
        int i;

        buf = new byte[1024];
        i = 0;

        while ((i = zipStream.read(buf)) != -1) {
            fileStream.write(buf, 0, i);
        }
    }

    return (tempFile.toURI());
}

From source file:com.sshtools.j2ssh.util.DynamicClassLoader.java

private byte[] loadClassFromZipfile(File file, String name, ClassCacheEntry cache) throws IOException {
    // Translate class name to file name
    String classFileName = name.replace('.', '/') + ".class";

    ZipFile zipfile = new ZipFile(file);

    try {/*w  w w. j a v a  2  s. c o  m*/
        ZipEntry entry = zipfile.getEntry(classFileName);

        if (entry != null) {
            cache.origin = file;

            return loadBytesFromStream(zipfile.getInputStream(entry), (int) entry.getSize());
        } else {
            // Not found
            return null;
        }
    } finally {
        zipfile.close();
    }
}

From source file:de.dfki.km.perspecting.obie.corpus.LabeledTextCorpus.java

public Reader getGroundTruth(final URI uri) throws Exception {
    if (labelFileMediaType == MediaType.DIRECTORY) {
        return new StringReader(FileUtils.readFileToString(new File(uri)));
    } else if (labelFileMediaType == MediaType.ZIP) {
        ZipFile zipFile = new ZipFile(labelFolder);
        String[] entryName = uri.toURL().getFile().split("/");
        ZipEntry entry = zipFile.getEntry(URLDecoder.decode(entryName[entryName.length - 1], "utf-8"));

        if (entry != null) {
            log.info("found labels for: " + uri.toString());
        } else {/* w w w . j av a  2  s . c o  m*/
            throw new Exception("did not found labels for: " + uri.toString());
        }
        return new InputStreamReader(zipFile.getInputStream(entry));
    } else {
        throw new Exception("Unsupported media format for labels: " + labelFileMediaType + ". "
                + "Please use zip or plain directories instead.");
    }
}

From source file:org.dspace.content.packager.AbstractMETSIngester.java

/**
 * Retrieve the inputStream for a File referenced from a specific path
 * within a METS package./*  www.java2 s  .co  m*/
 * <p>
 * If the packager is set to 'manifest-only' (i.e. pkgFile is just a
 * manifest), we assume the file is available for download via a URL.
 * <p>
 * Otherwise, the pkgFile is a Zip, so the file should be retrieved from
 * within that Zip package.
 * 
 * @param pkgFile
 *            the full package file (which may include content files if a
 *            zip)
 * @param params
 *            Parameters passed to METSIngester
 * @param path
 *            the File path (either path in Zip package or a URL)
 * @return the InputStream for the file
 * @throws MetadataValidationException if validation error
 * @throws IOException if IO error
 */
protected static InputStream getFileInputStream(File pkgFile, PackageParameters params, String path)
        throws MetadataValidationException, IOException {
    // If this is a manifest only package (i.e. not a zip file)
    if (params.getBooleanProperty("manifestOnly", false)) {
        // NOTE: since we are only dealing with a METS manifest,
        // we will assume all external files are available via URLs.
        try {
            // attempt to open a connection to given URL
            URL fileURL = new URL(path);
            URLConnection connection = fileURL.openConnection();

            // open stream to access file contents
            return connection.getInputStream();
        } catch (IOException io) {
            log.error("Unable to retrieve external file from URL '" + path
                    + "' for manifest-only METS package.  All externally referenced files must be retrievable via URLs.");
            // pass exception upwards
            throw io;
        }
    } else {
        // open the Zip package
        ZipFile zipPackage = new ZipFile(pkgFile);

        // Retrieve the manifest file entry by name
        ZipEntry manifestEntry = zipPackage.getEntry(path);

        // Get inputStream associated with this file
        if (manifestEntry != null)
            return zipPackage.getInputStream(manifestEntry);
        else {
            throw new MetadataValidationException(
                    "Manifest file references file '" + path + "' not included in the zip.");
        }
    }
}

From source file:org.roda.common.certification.ODFSignatureUtils.java

private static List<Reference> getReferenceList(ZipFile zipFile, DocumentBuilder documentBuilder,
        XMLSignatureFactory factory, NodeList listFileEntry, DigestMethod digestMethod) throws Exception {

    Transform transform = factory.newTransform(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS,
            (TransformParameterSpec) null);
    List<Transform> transformList = new ArrayList<Transform>();
    transformList.add(transform);/*from w w  w . j a  v  a 2  s  .c o  m*/

    MessageDigest messageDigest = MessageDigest.getInstance(RodaConstants.SHA1);
    List<Reference> referenceList = new ArrayList<Reference>();

    for (int i = 0; i < listFileEntry.getLength(); i++) {
        String fullPath = ((Element) listFileEntry.item(i)).getAttribute("manifest:full-path");
        Reference reference;

        if (!fullPath.endsWith("/") && !fullPath.equals(META_INF_DOCUMENTSIGNATURES_XML)) {
            if (fullPath.equals("content.xml") || fullPath.equals("meta.xml") || fullPath.equals("styles.xml")
                    || fullPath.equals("settings.xml")) {

                InputStream xmlFile = zipFile.getInputStream(zipFile.getEntry(fullPath));
                Element root = documentBuilder.parse(xmlFile).getDocumentElement();
                IOUtils.closeQuietly(xmlFile);

                Canonicalizer canonicalizer = Canonicalizer
                        .getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
                byte[] docCanonicalize = canonicalizer.canonicalizeSubtree(root);
                byte[] digestValue = messageDigest.digest(docCanonicalize);
                reference = factory.newReference(fullPath.replaceAll(" ", "%20"), digestMethod, transformList,
                        null, null, digestValue);

            } else {
                InputStream is = zipFile.getInputStream(zipFile.getEntry(fullPath));
                byte[] digestValue = messageDigest.digest(IOUtils.toByteArray(is));
                IOUtils.closeQuietly(is);
                reference = factory.newReference(fullPath.replaceAll(" ", "%20"), digestMethod, null, null,
                        null, digestValue);
            }

            referenceList.add(reference);
        }
    }

    return referenceList;
}