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:org.apache.taverna.scufl2.ucfpackage.TestUCFPackage.java

@Test
public void fileEntryFromString() throws Exception {
    UCFPackage container = new UCFPackage();
    container.setPackageMediaType(UCFPackage.MIME_WORKFLOW_BUNDLE);

    container.addResource("Hello there ", "helloworld.txt", "text/plain");

    container.save(tmpFile);// w  ww. ja v a 2s.c  om
    ZipFile zipFile = new ZipFile(tmpFile);
    ZipEntry manifestEntry = zipFile.getEntry("META-INF/manifest.xml");
    InputStream manifestStream = zipFile.getInputStream(manifestEntry);
    //System.out.println(IOUtils.toString(manifestStream, "UTF-8"));
    /*
    <?xml version="1.0" encoding="UTF-8"?>
    <manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0">
    <manifest:file-entry manifest:media-type="text/plain" manifest:full-path="helloworld.txt" manifest:size="18"/>
    </manifest:manifest>
     */
    Document doc = parseXml(manifestStream);
    assertEquals(MANIFEST_NS, doc.getRootElement().getNamespace());
    assertEquals("manifest", doc.getRootElement().getNamespacePrefix());
    assertEquals("manifest:manifest", doc.getRootElement().getQualifiedName());
    assertXpathEquals("text/plain", doc.getRootElement(),
            "/manifest:manifest/manifest:file-entry/@manifest:media-type");
    assertXpathEquals("helloworld.txt", doc.getRootElement(),
            "/manifest:manifest/manifest:file-entry/@manifest:full-path");
    /*
     * Different platforms encode UTF8 in different ways
     *       assertXpathEquals("18", doc.getRootElement(), "/manifest:manifest/manifest:file-entry/@manifest:size");
     */

    InputStream io = zipFile.getInputStream(zipFile.getEntry("helloworld.txt"));
    assertEquals("Hello there ", IOUtils.toString(io, "UTF-8"));
}

From source file:org.apache.taverna.scufl2.ucfpackage.TestUCFPackage.java

@Test
public void setRootfileSaved() throws Exception {
    UCFPackage container = new UCFPackage();
    container.setPackageMediaType(UCFPackage.MIME_WORKFLOW_BUNDLE);
    container.addResource("Hello there", "helloworld.txt", "text/plain");
    container.addResource("Soup for everyone", "soup.txt", "text/plain");
    container.setRootFile("helloworld.txt");
    container.save(tmpFile);/*from ww w  .  j a va 2 s . c  o  m*/

    ZipFile zipFile = new ZipFile(tmpFile);
    ZipEntry manifestEntry = zipFile.getEntry("META-INF/container.xml");
    InputStream manifestStream = zipFile.getInputStream(manifestEntry);

    //System.out.println(IOUtils.toString(manifestStream, "UTF-8"));
    /*
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" xmlns:ns2="http://www.w3.org/2000/09/xmldsig#" xmlns:ns3="http://www.w3.org/2001/04/xmlenc#">
    <rootFiles>
      <rootFile full-path="helloworld.txt" media-type="text/plain"/>
    </rootFiles>
    </container>
     */
    Document doc = parseXml(manifestStream);
    assertEquals(CONTAINER_NS, doc.getRootElement().getNamespace());

    // Should work, but might still fail on Windows due to
    // TAVERNA-920. We'll avoid testing this to not break the build.
    // assertEquals("", doc.getRootElement().getNamespacePrefix());
    // assertEquals("container", doc.getRootElement().getQualifiedName());
    assertEquals("container", doc.getRootElement().getName());

    assertXpathEquals("helloworld.txt", doc.getRootElement(), "/c:container/c:rootFiles/c:rootFile/@full-path");
    assertXpathEquals("text/plain", doc.getRootElement(), "/c:container/c:rootFiles/c:rootFile/@media-type");

}

From source file:org.sead.repositories.reference.RefRepository.java

@Path("/researchobjects/{id}/data/{relpath}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@GET/*from w  w w . ja  v  a2 s  . co m*/
public Response getDatafile(@PathParam(value = "id") String id, @PathParam(value = "relpath") String datapath) {
    String path = getDataPathTo(id);

    String bagNameRoot = getBagNameRoot(id);
    File result = new File(path, bagNameRoot + ".zip");
    StreamingOutput stream = null;

    try {
        final ZipFile zf = new ZipFile(result);
        ZipEntry archiveEntry1 = zf.getEntry(bagNameRoot + "/data/" + datapath);
        if (archiveEntry1 != null) {
            final InputStream inputStream = new BufferedInputStream(zf.getInputStream(archiveEntry1));

            stream = new StreamingOutput() {
                public void write(OutputStream os) throws IOException, WebApplicationException {
                    IOUtils.copy(inputStream, os);
                    IOUtils.closeQuietly(os);
                    IOUtils.closeQuietly(inputStream);
                    IOUtils.closeQuietly(zf);
                }
            };
        }
    } catch (IOException e) {
        log.error(e.getLocalizedMessage());
        e.printStackTrace();
    }
    if (stream == null) {
        return Response.serverError().build();
    }

    return Response.ok(stream).build();
}

From source file:org.zeroturnaround.zip.ZipsTest.java

public void testTransformationPreservesTimestamps() throws IOException {
    final String name = "foo";
    final byte[] contents = "bar".getBytes();

    File source = File.createTempFile("temp", ".zip");
    File destination = File.createTempFile("temp", ".zip");
    try {/* ww  w .jav  a2s  .  c o m*/
        // Create the ZIP file
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(source));
        try {
            for (int i = 0; i < 2; i++) {
                // we need many entries, some are transformed, some just copied.
                ZipEntry e = new ZipEntry(name + (i == 0 ? "" : "" + i));
                // 5 seconds ago.
                e.setTime(System.currentTimeMillis() - 5000);
                zos.putNextEntry(e);
                zos.write(contents);
                zos.closeEntry();
            }
        } finally {
            IOUtils.closeQuietly(zos);
        }
        // Transform the ZIP file
        ZipEntryTransformer transformer = new ByteArrayZipEntryTransformer() {
            protected byte[] transform(ZipEntry zipEntry, byte[] input) throws IOException {
                String s = new String(input);
                assertEquals(new String(contents), s);
                return s.toUpperCase().getBytes();
            }

            protected boolean preserveTimestamps() {
                // transformed entries preserve timestamps thanks to this.
                return true;
            }
        };
        Zips.get(source).destination(destination).preserveTimestamps().addTransformer(name, transformer)
                .process();

        final ZipFile zf = new ZipFile(source);
        try {
            Zips.get(destination).iterate(new ZipEntryCallback() {
                public void process(InputStream in, ZipEntry zipEntry) throws IOException {
                    String name = zipEntry.getName();
                    assertEquals("Timestapms differ at entry " + name, zf.getEntry(name).getTime(),
                            zipEntry.getTime());
                }
            });
        } finally {
            ZipUtil.closeQuietly(zf);
        }
        // Test the ZipUtil
        byte[] actual = ZipUtil.unpackEntry(destination, name);
        assertNotNull(actual);
        assertEquals(new String(contents).toUpperCase(), new String(actual));
    } finally {
        FileUtils.deleteQuietly(source);
        FileUtils.deleteQuietly(destination);
    }

}

From source file:org.sead.repositories.reference.RefRepository.java

@Path("/researchobjects/{id}/meta/{relpath}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@GET/*from   w w  w.j  ava  2s.  c om*/
public Response getMetadatafile(@PathParam(value = "id") String id,
        @PathParam(value = "relpath") String metadatapath) {
    String path = getDataPathTo(id);

    String bagNameRoot = getBagNameRoot(id);
    File result = new File(path, bagNameRoot + ".zip");

    // Don't let this call be used to get data from the data dir
    if (metadatapath.startsWith("data") || metadatapath.startsWith("/data")) {
        return Response.status(Status.BAD_REQUEST).build();
    }
    StreamingOutput stream = null;
    try {
        final ZipFile zf = new ZipFile(result);
        ZipEntry archiveEntry1 = zf.getEntry(bagNameRoot + "/" + metadatapath);
        if (archiveEntry1 != null) {
            final InputStream inputStream = new BufferedInputStream(zf.getInputStream(archiveEntry1));
            stream = new StreamingOutput() {
                public void write(OutputStream os) throws IOException, WebApplicationException {
                    IOUtils.copy(inputStream, os);
                    IOUtils.closeQuietly(inputStream);
                    IOUtils.closeQuietly(os);
                    IOUtils.closeQuietly(zf);
                }
            };
        }
    } catch (IOException e) {
        log.error(e.getLocalizedMessage());
        e.printStackTrace();
    }
    if (stream == null) {
        return Response.serverError().build();
    }

    return Response.ok(stream).build();

}

From source file:com.pari.mw.api.execute.reports.template.ReportTemplateRunner.java

private InputStream getInputStream(ZipFile zipFile, String entryFileName) throws Exception {
    ZipEntry topLevelFolder = null;
    ZipEntry specificEntry = null;
    InputStream ipStream = null;/*from w  w w  .  j  a  va 2  s .c  o  m*/

    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        topLevelFolder = entries.nextElement();
        if (topLevelFolder.isDirectory()) {
            break;
        }
    }

    if (topLevelFolder != null) {
        String lookupFile = topLevelFolder + entryFileName;
        specificEntry = zipFile.getEntry(lookupFile);
    }

    if (specificEntry != null) {
        ipStream = zipFile.getInputStream(specificEntry);
    }

    return ipStream;
}

From source file:org.kaaproject.kaa.server.control.service.sdk.JavaSdkGenerator.java

@Override
public FileData generateSdk(String buildVersion, List<BootstrapNodeInfo> bootstrapNodes,
        SdkProfileDto sdkProfile, String profileSchemaBody, String notificationSchemaBody,
        String configurationProtocolSchemaBody, String configurationSchemaBody, byte[] defaultConfigurationData,
        List<EventFamilyMetadata> eventFamilies, String logSchemaBody) throws Exception {

    final String sdkToken = sdkProfile.getToken();
    final Integer profileSchemaVersion = sdkProfile.getProfileSchemaVersion();
    final Integer notificationSchemaVersion = sdkProfile.getNotificationSchemaVersion();
    final Integer logSchemaVersion = sdkProfile.getLogSchemaVersion();

    final Schema configurationSchema = new Schema.Parser().parse(configurationSchemaBody);
    final Schema profileSchema = new Schema.Parser().parse(profileSchemaBody);
    final Schema notificationSchema = new Schema.Parser().parse(notificationSchemaBody);
    final Schema logSchema = new Schema.Parser().parse(logSchemaBody);

    List<String> flatEventClassCtlSchemas = new ArrayList<>();
    eventFamilies.forEach(ecf -> flatEventClassCtlSchemas.addAll(ecf.getRawCtlsSchemas()));
    List<Schema> eventClassCtlSchemas = new LinkedList<>();
    if (!flatEventClassCtlSchemas.isEmpty()) {
        for (String flatCtlSchema : flatEventClassCtlSchemas) {
            Schema eventClassCtlSchema = new Schema.Parser().parse(flatCtlSchema);
            eventClassCtlSchemas.add(eventClassCtlSchema);
        }/*from w w  w.  ja va  2s .co m*/
    }

    List<Schema> schemasToCheck = new LinkedList<>();
    schemasToCheck.add(configurationSchema);
    schemasToCheck.add(profileSchema);
    schemasToCheck.add(notificationSchema);
    schemasToCheck.add(logSchema);
    schemasToCheck.addAll(eventClassCtlSchemas);

    Map<String, Schema> uniqueSchemasMap = SchemaUtil.getUniqueSchemasMap(schemasToCheck);

    String sdkTemplateLocation;
    if (sdkPlatform == JAVA) {
        sdkTemplateLocation = Environment.getServerHomeDir() + "/" + JAVA_SDK_DIR + "/" + JAVA_SDK_PREFIX
                + buildVersion + ".jar";
        LOG.debug("Lookup Java SDK template: {}", sdkTemplateLocation);
    } else { // ANDROID
        sdkTemplateLocation = Environment.getServerHomeDir() + "/" + ANDROID_SDK_DIR + "/" + ANDROID_SDK_PREFIX
                + buildVersion + ".jar";
        LOG.debug("Lookup Android SDK template: {}", sdkTemplateLocation);
    }

    File sdkTemplateFile = new File(sdkTemplateLocation);
    ZipFile templateArhive = new ZipFile(sdkTemplateFile);

    Map<String, ZipEntryData> replacementData = new HashMap<String, ZipEntryData>();

    ZipEntry clientPropertiesEntry = templateArhive.getEntry(CLIENT_PROPERTIES);
    byte[] clientPropertiesData = generateClientProperties(templateArhive.getInputStream(clientPropertiesEntry),
            bootstrapNodes, sdkToken, configurationProtocolSchemaBody, defaultConfigurationData);

    replacementData.put(CLIENT_PROPERTIES,
            new ZipEntryData(new ZipEntry(CLIENT_PROPERTIES), clientPropertiesData));

    List<JavaDynamicBean> javaSources = new ArrayList<JavaDynamicBean>();

    String configurationClassName = configurationSchema.getName();
    String configurationClassPackage = configurationSchema.getNamespace();

    javaSources.addAll(generateSchemaSources(configurationSchema, uniqueSchemasMap));

    String configurationManagerImplTemplate = readResource(CONFIGURATION_MANAGER_IMPL_SOURCE_TEMPLATE);
    String configurationManagerImplSource = configurationManagerImplTemplate
            .replaceAll(CONFIGURATION_CLASS_PACKAGE_VAR, configurationClassPackage)
            .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName);

    JavaDynamicBean configurationManagerImplClassBean = new JavaDynamicBean(CONFIGURATION_MANAGER_IMPL,
            configurationManagerImplSource);
    javaSources.add(configurationManagerImplClassBean);

    String configurationManagerTemplate = readResource(CONFIGURATION_MANAGER_SOURCE_TEMPLATE);
    String configurationManagerSource = configurationManagerTemplate
            .replaceAll(CONFIGURATION_CLASS_PACKAGE_VAR, configurationClassPackage)
            .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName);

    JavaDynamicBean configurationManagerClassBean = new JavaDynamicBean(CONFIGURATION_MANAGER,
            configurationManagerSource);
    javaSources.add(configurationManagerClassBean);

    String configurationListenerTemplate = readResource(CONFIGURATION_LISTENER_SOURCE_TEMPLATE);
    String configurationListenerSource = configurationListenerTemplate
            .replaceAll(CONFIGURATION_CLASS_PACKAGE_VAR, configurationClassPackage)
            .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName);

    JavaDynamicBean configurationListenerClassBean = new JavaDynamicBean(CONFIGURATION_LISTENER,
            configurationListenerSource);
    javaSources.add(configurationListenerClassBean);

    String configurationDeserializerSourceTemplate = readResource(CONFIGURATION_DESERIALIZER_SOURCE_TEMPLATE);
    String configurationDeserializerSource = configurationDeserializerSourceTemplate
            .replaceAll(CONFIGURATION_CLASS_PACKAGE_VAR, configurationClassPackage)
            .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName);

    JavaDynamicBean configurationDeserializerClassBean = new JavaDynamicBean(CONFIGURATION_DESERIALIZER,
            configurationDeserializerSource);
    javaSources.add(configurationDeserializerClassBean);

    String profileClassName = profileSchema.getName();
    String profileClassPackage = profileSchema.getNamespace();

    if (profileSchemaVersion != DEFAULT_PROFILE_SCHEMA_VERSION) {
        javaSources.addAll(generateSchemaSources(profileSchema, uniqueSchemasMap));
    }

    String profileContainerTemplate = readResource(PROFILE_CONTAINER_SOURCE_TEMPLATE);
    String profileContainerSource = profileContainerTemplate
            .replaceAll(PROFILE_CLASS_PACKAGE_VAR, profileClassPackage)
            .replaceAll(PROFILE_CLASS_VAR, profileClassName);

    JavaDynamicBean profileContainerClassBean = new JavaDynamicBean(PROFILE_CONTAINER, profileContainerSource);

    javaSources.add(profileContainerClassBean);

    String defaultProfileContainerTemplate = readResource(DEFAULT_PROFILE_CONTAINER_SOURCE_TEMPLATE);
    String defaultProfileContainerSource = defaultProfileContainerTemplate
            .replaceAll(PROFILE_CLASS_PACKAGE_VAR, profileClassPackage)
            .replaceAll(PROFILE_CLASS_VAR, profileClassName);
    JavaDynamicBean defaultProfileContainerClassBean = new JavaDynamicBean(DEFAULT_PROFILE_CONTAINER,
            defaultProfileContainerSource);
    javaSources.add(defaultProfileContainerClassBean);

    String profileSerializerTemplate;
    if (profileSchemaVersion == DEFAULT_PROFILE_SCHEMA_VERSION) {
        profileSerializerTemplate = readResource(DEFAULT_PROFILE_SERIALIZER_SOURCE_TEMPLATE);
    } else {
        profileSerializerTemplate = readResource(PROFILE_SERIALIZER_SOURCE_TEMPLATE);
    }
    String profileSerializerSource = profileSerializerTemplate
            .replaceAll(PROFILE_CLASS_PACKAGE_VAR, profileClassPackage)
            .replaceAll(PROFILE_CLASS_VAR, profileClassName);

    JavaDynamicBean profileSerializerClassBean = new JavaDynamicBean(PROFILE_SERIALIZER,
            profileSerializerSource);

    javaSources.add(profileSerializerClassBean);

    String notificationClassName = notificationSchema.getName();
    String notificationClassPackage = notificationSchema.getNamespace();

    if (notificationSchemaVersion != DEFAULT_SCHEMA_VERSION) {
        javaSources.addAll(generateSchemaSources(notificationSchema, uniqueSchemasMap));
    }

    String notificationListenerTemplate = readResource(NOTIFICATION_LISTENER_SOURCE_TEMPLATE);
    String notificationListenerSource = notificationListenerTemplate
            .replaceAll(NOTIFICATION_CLASS_PACKAGE_VAR, notificationClassPackage)
            .replaceAll(NOTIFICATION_CLASS_VAR, notificationClassName);

    JavaDynamicBean notificationListenerClassBean = new JavaDynamicBean(NOTIFICATION_LISTENER,
            notificationListenerSource);
    javaSources.add(notificationListenerClassBean);

    String notificationDeserializerSourceTemplate = readResource(NOTIFICATION_DESERIALIZER_SOURCE_TEMPLATE);

    String notificationDeserializerSource = notificationDeserializerSourceTemplate
            .replaceAll(NOTIFICATION_CLASS_PACKAGE_VAR, notificationClassPackage)
            .replaceAll(NOTIFICATION_CLASS_VAR, notificationClassName);

    JavaDynamicBean notificationDeserializerClassBean = new JavaDynamicBean(NOTIFICATION_DESERIALIZER,
            notificationDeserializerSource);
    javaSources.add(notificationDeserializerClassBean);

    if (logSchemaVersion != DEFAULT_SCHEMA_VERSION) {
        javaSources.addAll(generateSchemaSources(logSchema, uniqueSchemasMap));
    }

    String logRecordTemplate = readResource(LOG_RECORD_SOURCE_TEMPLATE);
    String logRecordSource = logRecordTemplate
            .replaceAll(LOG_RECORD_CLASS_PACKAGE_VAR, logSchema.getNamespace())
            .replaceAll(LOG_RECORD_CLASS_VAR, logSchema.getName());

    String logCollectorInterfaceTemplate = readResource(LOG_COLLECTOR_INTERFACE_TEMPLATE);
    String logCollectorInterface = logCollectorInterfaceTemplate
            .replaceAll(LOG_RECORD_CLASS_PACKAGE_VAR, logSchema.getNamespace())
            .replaceAll(LOG_RECORD_CLASS_VAR, logSchema.getName());

    String logCollectorSourceTemplate = readResource(LOG_COLLECTOR_SOURCE_TEMPLATE);
    String logCollectorSource = logCollectorSourceTemplate
            .replaceAll(LOG_RECORD_CLASS_PACKAGE_VAR, logSchema.getNamespace())
            .replaceAll(LOG_RECORD_CLASS_VAR, logSchema.getName());

    JavaDynamicBean logRecordClassBean = new JavaDynamicBean(LOG_RECORD, logRecordSource);
    JavaDynamicBean logCollectorInterfaceClassBean = new JavaDynamicBean(LOG_COLLECTOR_INTERFACE,
            logCollectorInterface);
    JavaDynamicBean logCollectorSourceClassBean = new JavaDynamicBean(LOG_COLLECTOR_SOURCE, logCollectorSource);

    javaSources.add(logRecordClassBean);
    javaSources.add(logCollectorInterfaceClassBean);
    javaSources.add(logCollectorSourceClassBean);

    if (eventFamilies != null && !eventFamilies.isEmpty()) {
        for (Schema ctlSchema : eventClassCtlSchemas) {
            javaSources.addAll(generateSchemaSources(ctlSchema, uniqueSchemasMap));
        }
        javaSources.addAll(JavaEventClassesGenerator.generateEventClasses(eventFamilies));
    }

    String defaultVerifierToken = sdkProfile.getDefaultVerifierToken();
    String userVerifierConstantsTemplate = readResource(USER_VERIFIER_CONSTANTS_SOURCE_TEMPLATE);
    if (defaultVerifierToken == null) {
        defaultVerifierToken = "null";
    } else {
        defaultVerifierToken = "\"" + defaultVerifierToken + "\"";
    }
    String userVerifierConstantsSource = userVerifierConstantsTemplate
            .replaceAll(DEFAULT_USER_VERIFIER_TOKEN_VAR, defaultVerifierToken);

    JavaDynamicBean userVerifierConstantsClassBean = new JavaDynamicBean(USER_VERIFIER_CONSTANTS,
            userVerifierConstantsSource);
    javaSources.add(userVerifierConstantsClassBean);

    String kaaClientTemplate = readResource(KAA_CLIENT_SOURCE_TEMPLATE);

    String kaaClientSource = kaaClientTemplate
            .replaceAll(LOG_RECORD_CLASS_PACKAGE_VAR, logSchema.getNamespace())
            .replaceAll(LOG_RECORD_CLASS_VAR, logSchema.getName())
            .replaceAll(CONFIGURATION_CLASS_PACKAGE_VAR, configurationClassPackage)
            .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName);

    JavaDynamicBean kaaClientClassBean = new JavaDynamicBean(KAA_CLIENT, kaaClientSource);
    javaSources.add(kaaClientClassBean);

    String baseKaaClientTemplate = readResource(BASE_KAA_CLIENT_SOURCE_TEMPLATE);
    String baseKaaClientSource = baseKaaClientTemplate
            .replaceAll(LOG_RECORD_CLASS_PACKAGE_VAR, logSchema.getNamespace())
            .replaceAll(LOG_RECORD_CLASS_VAR, logSchema.getName())
            .replaceAll(CONFIGURATION_CLASS_PACKAGE_VAR, configurationClassPackage)
            .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName);

    JavaDynamicBean baseKaaClientClassBean = new JavaDynamicBean(BASE_KAA_CLIENT, baseKaaClientSource);
    javaSources.add(baseKaaClientClassBean);

    packageSources(javaSources, replacementData);

    ByteArrayOutputStream sdkOutput = new ByteArrayOutputStream();
    ZipOutputStream sdkFile = new ZipOutputStream(sdkOutput);

    Enumeration<? extends ZipEntry> entries = templateArhive.entries();

    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        if (replacementData.containsKey(entry.getName())) {
            ZipEntryData replacementEntry = replacementData.remove(entry.getName());
            sdkFile.putNextEntry(replacementEntry.getEntry());
            sdkFile.write(replacementEntry.getData());
        } else {
            sdkFile.putNextEntry(entry);
            if (!entry.isDirectory()) {
                IOUtils.copy(templateArhive.getInputStream(entry), sdkFile);
            }
        }
        sdkFile.closeEntry();
    }
    templateArhive.close();

    for (String entryName : replacementData.keySet()) {
        ZipEntryData replacementEntry = replacementData.get(entryName);
        sdkFile.putNextEntry(replacementEntry.getEntry());
        sdkFile.write(replacementEntry.getData());
        sdkFile.closeEntry();
    }

    sdkFile.close();

    String fileNamePrefix = (sdkPlatform == JAVA ? JAVA_SDK_PREFIX : ANDROID_SDK_PREFIX);
    String sdkFileName = fileNamePrefix + sdkProfile.getToken() + ".jar";

    byte[] sdkData = sdkOutput.toByteArray();

    FileData sdk = new FileData();
    sdk.setFileName(sdkFileName);
    sdk.setFileData(sdkData);
    return sdk;
}

From source file:org.mozilla.gecko.AboutHomeContent.java

private String readFromZipFile(Activity activity, String filename) {
    ZipFile zip = null;
    String str = null;//from w  w w  .  j  a  v a2  s.  co  m
    try {
        InputStream fileStream = null;
        File applicationPackage = new File(activity.getApplication().getPackageResourcePath());
        zip = new ZipFile(applicationPackage);
        if (zip == null)
            return null;
        ZipEntry fileEntry = zip.getEntry(filename);
        if (fileEntry == null)
            return null;
        fileStream = zip.getInputStream(fileEntry);
        str = readStringFromStream(fileStream);
    } catch (IOException ioe) {
        Log.e(LOGTAG, "error reading zip file: " + filename, ioe);
    } finally {
        try {
            if (zip != null)
                zip.close();
        } catch (IOException ioe) {
            // catch this here because we can continue even if the
            // close failed
            Log.e(LOGTAG, "error closing zip filestream", ioe);
        }
    }
    return str;
}

From source file:org.apache.taverna.scufl2.ucfpackage.TestUCFPackage.java

@Test
public void setRootfileExtendsContainerXml() throws Exception {
    UCFPackage container = new UCFPackage();
    container.setPackageMediaType(UCFPackage.MIME_WORKFLOW_BUNDLE);
    container.addResource("Hello there", "helloworld.txt", "text/plain");
    container.addResource("<html><body><h1>Yo</h1></body></html>", "helloworld.html", "text/html");

    String containerXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
            + "<container xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\" xmlns:ex='http://example.com/' xmlns:ns2=\"http://www.w3.org/2000/09/xmldsig#\" xmlns:ns3=\"http://www.w3.org/2001/04/xmlenc#\">\n"
            + "    <rootFiles>\n"
            + "        <rootFile ex:extraAnnotation='hello' media-type=\"text/html\" full-path=\"helloworld.html\"/>\n"
            + "    </rootFiles>\n" + "   <ex:example>more example</ex:example>\n" + "</container>\n";
    // Should overwrite setRootFile()
    container.addResource(containerXml, "META-INF/container.xml", "text/xml");
    assertEquals("helloworld.html", container.getRootFiles().get(0).getPath());

    container.setRootFile("helloworld.txt");
    assertEquals("helloworld.html", container.getRootFiles().get(0).getPath());
    assertEquals("helloworld.txt", container.getRootFiles().get(1).getPath());
    container.save(tmpFile);// w ww .  j  a  v  a2  s.co  m
    //
    //      String expectedContainerXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
    //            + "<container xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\" xmlns:ns2=\"http://www.w3.org/2000/09/xmldsig#\" xmlns:ns3=\"http://www.w3.org/2001/04/xmlenc#\">\n"
    //            + "    <rootFiles>\n"
    //            + "        <rootFile xmlns:ex=\"http://example.com/\" media-type=\"text/html\" full-path=\"helloworld.html\" ex:extraAnnotation=\"hello\"/>\n"
    //            + "        <rootFile media-type=\"text/plain\" full-path=\"helloworld.txt\"/>\n"
    //            + "    </rootFiles>\n"
    //            + "    <ex:example xmlns:ex=\"http://example.com/\">more example</ex:example>\n"
    //            +
    //            "</container>\n";

    ZipFile zipFile = new ZipFile(tmpFile);
    ZipEntry manifestEntry = zipFile.getEntry("META-INF/container.xml");
    InputStream manifestStream = zipFile.getInputStream(manifestEntry);

    //System.out.println(IOUtils.toString(manifestStream, "UTF-8"));
    /*
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" xmlns:ns2="http://www.w3.org/2000/09/xmldsig#" xmlns:ns3="http://www.w3.org/2001/04/xmlenc#">
    <rootFiles>
      <rootFile xmlns:ex="http://example.com/" full-path="helloworld.html" media-type="text/html" ex:extraAnnotation="hello"/>
      <rootFile full-path="helloworld.txt" media-type="text/plain"/>
    </rootFiles>
    <ex:example xmlns:ex="http://example.com/">more example</ex:example>
    </container>
     */
    Document doc = parseXml(manifestStream);
    assertEquals(CONTAINER_NS, doc.getRootElement().getNamespace());
    // Should work, but we'll avoid testing it (TAVERNA-920)
    //assertEquals("", doc.getRootElement().getNamespacePrefix());
    //assertEquals("container", doc.getRootElement().getQualifiedName());
    assertEquals("container", doc.getRootElement().getName());
    assertXpathEquals("helloworld.html", doc.getRootElement(),
            "/c:container/c:rootFiles/c:rootFile[1]/@full-path");
    assertXpathEquals("text/html", doc.getRootElement(), "/c:container/c:rootFiles/c:rootFile[1]/@media-type");
    assertXpathEquals("hello", doc.getRootElement(),
            "/c:container/c:rootFiles/c:rootFile[1]/@ex:extraAnnotation");

    assertXpathEquals("helloworld.txt", doc.getRootElement(),
            "/c:container/c:rootFiles/c:rootFile[2]/@full-path");
    assertXpathEquals("text/plain", doc.getRootElement(), "/c:container/c:rootFiles/c:rootFile[2]/@media-type");

    assertXpathEquals("more example", doc.getRootElement(), "/c:container/ex:example");

    // Check order
    Element first = (Element) xpathSelectElement(doc.getRootElement(), "/c:container/*[1]");
    //assertEquals("rootFiles", first.getQualifiedName());
    assertEquals("rootFiles", first.getName());
    Element second = (Element) xpathSelectElement(doc.getRootElement(), "/c:container/*[2]");
    assertEquals("ex:example", second.getQualifiedName());

}

From source file:org.apache.taverna.scufl2.ucfpackage.TestUCFPackage.java

@Test
public void addResourceContainerXml() throws Exception {
    UCFPackage container = new UCFPackage();
    container.setPackageMediaType(UCFPackage.MIME_WORKFLOW_BUNDLE);
    container.addResource("Hello there", "helloworld.txt", "text/plain");
    container.addResource("Soup for everyone", "soup.txt", "text/plain");
    container.setRootFile("helloworld.txt");
    assertEquals("helloworld.txt", container.getRootFiles().get(0).getPath());

    String containerXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
            + "<container xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\" xmlns:ns2=\"http://www.w3.org/2000/09/xmldsig#\" xmlns:ns3=\"http://www.w3.org/2001/04/xmlenc#\">\n"
            + "    <ex:example xmlns:ex=\"http://example.com/\">first example</ex:example>\n"
            + "    <rootFiles>\n"
            + "        <rootFile xmlns:ex=\"http://example.com/\" media-type=\"text/plain\" full-path=\"soup.txt\" ex:extraAnnotation=\"hello\"/>\n"
            + "    </rootFiles>\n"
            + "    <ex:example xmlns:ex=\"http://example.com/\">second example</ex:example>\n"
            + "    <ex:example xmlns:ex=\"http://example.com/\">third example</ex:example>\n"
            + "</container>\n";
    // Should overwrite setRootFile()
    container.addResource(containerXml, "META-INF/container.xml", "text/xml");

    assertEquals("soup.txt", container.getRootFiles().get(0).getPath());

    container.save(tmpFile);// w ww.j  a  va 2  s .  c  om

    ZipFile zipFile = new ZipFile(tmpFile);
    ZipEntry manifestEntry = zipFile.getEntry("META-INF/container.xml");
    InputStream manifestStream = zipFile.getInputStream(manifestEntry);

    //System.out.println(IOUtils.toString(manifestStream, "UTF-8"));
    /*
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" xmlns:ns2="http://www.w3.org/2000/09/xmldsig#" xmlns:ns3="http://www.w3.org/2001/04/xmlenc#">
    <ex:example xmlns:ex="http://example.com/">first example</ex:example>
    <rootFiles>
      <rootFile xmlns:ex="http://example.com/" full-path="soup.txt" media-type="text/plain" ex:extraAnnotation="hello"/>
    </rootFiles>
    <ex:example xmlns:ex="http://example.com/">second example</ex:example>
    <ex:example xmlns:ex="http://example.com/">third example</ex:example>
    </container>
     */
    Document doc = parseXml(manifestStream);
    assertEquals(CONTAINER_NS, doc.getRootElement().getNamespace());

    // Should work, but we'll ignore testing these (TAVERNA-920)
    //assertEquals("", doc.getRootElement().getNamespacePrefix());
    //assertEquals("container", doc.getRootElement().getQualifiedName());
    assertEquals("container", doc.getRootElement().getName());

    assertXpathEquals("soup.txt", doc.getRootElement(), "/c:container/c:rootFiles/c:rootFile[1]/@full-path");
    assertXpathEquals("text/plain", doc.getRootElement(), "/c:container/c:rootFiles/c:rootFile[1]/@media-type");
    assertXpathEquals("hello", doc.getRootElement(),
            "/c:container/c:rootFiles/c:rootFile[1]/@ex:extraAnnotation");

    assertXpathEquals("first example", doc.getRootElement(), "/c:container/ex:example[1]");
    assertXpathEquals("second example", doc.getRootElement(), "/c:container/ex:example[2]");
    assertXpathEquals("third example", doc.getRootElement(), "/c:container/ex:example[3]");

    // Check order
    Element first = (Element) xpathSelectElement(doc.getRootElement(), "/c:container/*[1]");
    assertEquals("ex:example", first.getQualifiedName());
    Element second = (Element) xpathSelectElement(doc.getRootElement(), "/c:container/*[2]");

    // Should work, but we'll ignore testing these (TAVERNA-920)
    //assertEquals("rootFiles", second.getQualifiedName());
    assertEquals("rootFiles", second.getName());

    Element third = (Element) xpathSelectElement(doc.getRootElement(), "/c:container/*[3]");
    assertEquals("ex:example", third.getQualifiedName());
    Element fourth = (Element) xpathSelectElement(doc.getRootElement(), "/c:container/*[4]");
    assertEquals("ex:example", fourth.getQualifiedName());

}