Example usage for java.util.jar JarFile getEntry

List of usage examples for java.util.jar JarFile getEntry

Introduction

In this page you can find the example usage for java.util.jar JarFile getEntry.

Prototype

public ZipEntry getEntry(String name) 

Source Link

Document

Returns the ZipEntry for the given base entry name or null if not found.

Usage

From source file:org.openmrs.module.SqlDiffFileParser.java

/**
 * Get the diff map. Return a sorted map<version, sql statements>
 *
 * @return SortedMap<String, String>
 * @throws ModuleException/*w  w  w . j  a  va2s  .  c  om*/
 */
public static SortedMap<String, String> getSqlDiffs(Module module) throws ModuleException {
    if (module == null) {
        throw new ModuleException("Module cannot be null");
    }

    SortedMap<String, String> map = new TreeMap<String, String>(new VersionComparator());

    InputStream diffStream = null;

    // get the diff stream
    JarFile jarfile = null;
    try {
        try {
            jarfile = new JarFile(module.getFile());
        } catch (IOException e) {
            throw new ModuleException("Unable to get jar file", module.getName(), e);
        }

        diffStream = ModuleUtil.getResourceFromApi(jarfile, module.getModuleId(), module.getVersion(),
                SQLDIFF_CHANGELOG_FILENAME);
        if (diffStream == null) {
            // Try the old way. Loading from the root of the omod
            ZipEntry diffEntry = jarfile.getEntry(SQLDIFF_CHANGELOG_FILENAME);
            if (diffEntry == null) {
                log.debug("No sqldiff.xml found for module: " + module.getName());
                return map;
            } else {
                try {
                    diffStream = jarfile.getInputStream(diffEntry);
                } catch (IOException e) {
                    throw new ModuleException("Unable to get sql diff file stream", module.getName(), e);
                }
            }
        }

        try {
            // turn the diff stream into an xml document
            Document diffDoc = null;
            try {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                db.setEntityResolver(new EntityResolver() {

                    @Override
                    public InputSource resolveEntity(String publicId, String systemId)
                            throws SAXException, IOException {
                        // When asked to resolve external entities (such as a DTD) we return an InputSource
                        // with no data at the end, causing the parser to ignore the DTD.
                        return new InputSource(new StringReader(""));
                    }
                });
                diffDoc = db.parse(diffStream);
            } catch (Exception e) {
                throw new ModuleException("Error parsing diff sqldiff.xml file", module.getName(), e);
            }

            Element rootNode = diffDoc.getDocumentElement();

            String diffVersion = rootNode.getAttribute("version");

            if (!validConfigVersions().contains(diffVersion)) {
                throw new ModuleException("Invalid config version: " + diffVersion, module.getModuleId());
            }

            NodeList diffNodes = getDiffNodes(rootNode, diffVersion);

            if (diffNodes != null && diffNodes.getLength() > 0) {
                int i = 0;
                while (i < diffNodes.getLength()) {
                    Element el = (Element) diffNodes.item(i++);
                    String version = getElement(el, diffVersion, "version");
                    String sql = getElement(el, diffVersion, "sql");
                    map.put(version, sql);
                }
            }
        } catch (ModuleException e) {
            if (diffStream != null) {
                try {
                    diffStream.close();
                } catch (IOException io) {
                    log.error("Error while closing config stream for module: " + module.getModuleId(), io);
                }
            }

            // rethrow the moduleException
            throw e;
        }

    } finally {
        try {
            if (jarfile != null) {
                jarfile.close();
            }
        } catch (IOException e) {
            log.warn("Unable to close jarfile: " + jarfile.getName());
        }
    }
    return map;
}

From source file:org.infoglue.deliver.portal.deploy.Deploy.java

/**
 * Prepare a portlet according to Pluto (switch web.xml)
 * //from  w ww .  j  av  a  2 s  .co  m
 * @param file .war to prepare
 * @param tmp the resulting updated .war
 * @param appName name of application (context name)
 * @return the portlet application definition (portlet.xml)
 * @throws IOException
 */
public static PortletApplicationDefinition prepareArchive(File file, File tmp, String appName)
        throws IOException {
    PortletApplicationDefinitionImpl portletApp = null;
    try {
        Mapping pdmXml = new Mapping();
        try {
            URL url = Deploy.class.getResource("/" + PORTLET_MAPPING);
            pdmXml.loadMapping(url);
        } catch (Exception e) {
            throw new IOException("Failed to load mapping file " + PORTLET_MAPPING);
        }

        // Open the jar file.
        JarFile jar = new JarFile(file);

        // Extract and parse portlet.xml
        ZipEntry portletEntry = jar.getEntry(PORTLET_XML);
        if (portletEntry == null) {
            throw new IOException("Unable to find portlet.xml");
        }

        InputStream pisDebug = jar.getInputStream(portletEntry);
        StringBuffer sb = new StringBuffer();
        int i;
        while ((i = pisDebug.read()) > -1) {
            sb.append((char) i);
        }
        pisDebug.close();

        InputSource xmlSource = new InputSource(new ByteArrayInputStream(sb.toString().getBytes("UTF-8")));
        DOMParser parser = new DOMParser();
        parser.parse(xmlSource);
        Document portletDocument = parser.getDocument();

        //InputStream pis = jar.getInputStream(portletEntry);
        //Document portletDocument = XmlParser.parsePortletXml(pis);
        //pis.close();
        InputStream pis = jar.getInputStream(portletEntry);

        ZipEntry webEntry = jar.getEntry(WEB_XML);
        InputStream wis = null;
        if (webEntry != null) {
            wis = jar.getInputStream(webEntry);
            /*  webDocument = XmlParser.parseWebXml(wis);
            wis.close();
            */
        }

        Unmarshaller unmarshaller = new Unmarshaller(pdmXml);
        unmarshaller.setWhitespacePreserve(true);
        unmarshaller.setIgnoreExtraElements(true);
        unmarshaller.setIgnoreExtraAttributes(true);

        portletApp = (PortletApplicationDefinitionImpl) unmarshaller.unmarshal(portletDocument);

        // refill structure with necessary information
        Vector structure = new Vector();
        structure.add(appName);
        structure.add(null);
        structure.add(null);
        portletApp.preBuild(structure);

        /*
        // now generate web part
        WebApplicationDefinitionImpl webApp = null;
        if (webDocument != null) {
        Unmarshaller unmarshallerWeb = new Unmarshaller(sdmXml);
                
        // modified by YCLI: START :: to ignore extra elements and
        // attributes
        unmarshallerWeb.setWhitespacePreserve(true);
        unmarshallerWeb.setIgnoreExtraElements(true);
        unmarshallerWeb.setIgnoreExtraAttributes(true);
        // modified by YCLI: END
                
        webApp = (WebApplicationDefinitionImpl) unmarshallerWeb.unmarshal(webDocument);
        } else {
        webApp = new WebApplicationDefinitionImpl();
        DisplayNameImpl dispName = new DisplayNameImpl();
        dispName.setDisplayName(appName);
        dispName.setLocale(Locale.ENGLISH);
        DisplayNameSetImpl dispSet = new DisplayNameSetImpl();
        dispSet.add(dispName);
        webApp.setDisplayNames(dispSet);
        DescriptionImpl desc = new DescriptionImpl();
        desc.setDescription("Automated generated Application Wrapper");
        desc.setLocale(Locale.ENGLISH);
        DescriptionSetImpl descSet = new DescriptionSetImpl();
        descSet.add(desc);
        webApp.setDescriptions(descSet);
        }
                
        org.apache.pluto.om.ControllerFactory controllerFactory = new org.apache.pluto.portalImpl.om.ControllerFactoryImpl();
                
        ServletDefinitionListCtrl servletDefinitionSetCtrl = (ServletDefinitionListCtrl) controllerFactory
            .get(webApp.getServletDefinitionList());
        Collection servletMappings = webApp.getServletMappings();
                
        Iterator portlets = portletApp.getPortletDefinitionList().iterator();
        while (portlets.hasNext()) {
                
        PortletDefinition portlet = (PortletDefinition) portlets.next();
                
        // check if already exists
        ServletDefinition servlet = webApp.getServletDefinitionList()
                .get(portlet.getName());
        if (servlet != null) {
            ServletDefinitionCtrl _servletCtrl = (ServletDefinitionCtrl) controllerFactory
                    .get(servlet);
            _servletCtrl.setServletClass("org.apache.pluto.core.PortletServlet");
        } else {
            servlet = servletDefinitionSetCtrl.add(portlet.getName(),
                    "org.apache.pluto.core.PortletServlet");
        }
                
        ServletDefinitionCtrl servletCtrl = (ServletDefinitionCtrl) controllerFactory
                .get(servlet);
                
        DisplayNameImpl dispName = new DisplayNameImpl();
        dispName.setDisplayName(portlet.getName() + " Wrapper");
        dispName.setLocale(Locale.ENGLISH);
        DisplayNameSetImpl dispSet = new DisplayNameSetImpl();
        dispSet.add(dispName);
        servletCtrl.setDisplayNames(dispSet);
        DescriptionImpl desc = new DescriptionImpl();
        desc.setDescription("Automated generated Portlet Wrapper");
        desc.setLocale(Locale.ENGLISH);
        DescriptionSetImpl descSet = new DescriptionSetImpl();
        descSet.add(desc);
        servletCtrl.setDescriptions(descSet);
        ParameterSet parameters = servlet.getInitParameterSet();
                
        ParameterSetCtrl parameterSetCtrl = (ParameterSetCtrl) controllerFactory
                .get(parameters);
                
        Parameter parameter1 = parameters.get("portlet-class");
        if (parameter1 == null) {
            parameterSetCtrl.add("portlet-class", portlet.getClassName());
        } else {
            ParameterCtrl parameterCtrl = (ParameterCtrl) controllerFactory.get(parameter1);
            parameterCtrl.setValue(portlet.getClassName());
                
        }
        Parameter parameter2 = parameters.get("portlet-guid");
        if (parameter2 == null) {
            parameterSetCtrl.add("portlet-guid", portlet.getId().toString());
        } else {
            ParameterCtrl parameterCtrl = (ParameterCtrl) controllerFactory.get(parameter2);
            parameterCtrl.setValue(portlet.getId().toString());
                
        }
                
        boolean found = false;
        Iterator mappings = servletMappings.iterator();
        while (mappings.hasNext()) {
            ServletMappingImpl servletMapping = (ServletMappingImpl) mappings.next();
            if (servletMapping.getServletName().equals(portlet.getName())) {
                found = true;
                servletMapping.setUrlPattern("/" + portlet.getName().replace(' ', '_')
                        + "/*");
            }
        }
        if (!found) {
            ServletMappingImpl servletMapping = new ServletMappingImpl();
            servletMapping.setServletName(portlet.getName());
            servletMapping.setUrlPattern("/" + portlet.getName().replace(' ', '_') + "/*");
            servletMappings.add(servletMapping);
        }
                
        SecurityRoleRefSet servletSecurityRoleRefs = ((ServletDefinitionImpl) servlet)
                .getInitSecurityRoleRefSet();
                
        SecurityRoleRefSetCtrl servletSecurityRoleRefSetCtrl = (SecurityRoleRefSetCtrl) controllerFactory
                .get(servletSecurityRoleRefs);
                
        SecurityRoleSet webAppSecurityRoles = webApp.getSecurityRoles();
                
        SecurityRoleRefSet portletSecurityRoleRefs = portlet.getInitSecurityRoleRefSet();
                
        Iterator p = portletSecurityRoleRefs.iterator();
        while (p.hasNext()) {
            SecurityRoleRef portletSecurityRoleRef = (SecurityRoleRef) p.next();
                
            if (portletSecurityRoleRef.getRoleLink() == null
                    && webAppSecurityRoles.get(portletSecurityRoleRef.getRoleName()) == null) {
                logger.info("Note: The web application has no security role defined which matches the role name \""
                                + portletSecurityRoleRef.getRoleName()
                                + "\" of the security-role-ref element defined for the wrapper-servlet with the name '"
                                + portlet.getName() + "'.");
                break;
            }
            SecurityRoleRef servletSecurityRoleRef = servletSecurityRoleRefs
                    .get(portletSecurityRoleRef.getRoleName());
            if (null != servletSecurityRoleRef) {
                logger.info("Note: Replaced already existing element of type <security-role-ref> with value \""
                                + portletSecurityRoleRef.getRoleName()
                                + "\" for subelement of type <role-name> for the wrapper-servlet with the name '"
                                + portlet.getName() + "'.");
                servletSecurityRoleRefSetCtrl.remove(servletSecurityRoleRef);
            }
            servletSecurityRoleRefSetCtrl.add(portletSecurityRoleRef);
        }
                
        }
        */

        /*
         * TODO is this necessary? TagDefinitionImpl portletTagLib = new
         * TagDefinitionImpl(); Collection taglibs =
         * webApp.getCastorTagDefinitions(); taglibs.add(portletTagLib);
         */

        // Duplicate jar-file with replaced web.xml
        FileOutputStream fos = new FileOutputStream(tmp);
        JarOutputStream tempJar = new JarOutputStream(fos);
        byte[] buffer = new byte[1024];
        int bytesRead;
        for (Enumeration entries = jar.entries(); entries.hasMoreElements();) {
            JarEntry entry = (JarEntry) entries.nextElement();
            JarEntry newEntry = new JarEntry(entry.getName());
            tempJar.putNextEntry(newEntry);

            if (entry.getName().equals(WEB_XML)) {
                // Swap web.xml
                /*
                log.debug("Swapping web.xml");
                OutputFormat of = new OutputFormat();
                of.setIndenting(true);
                of.setIndent(4); // 2-space indention
                of.setLineWidth(16384);
                of.setDoctype(Constants.WEB_PORTLET_PUBLIC_ID, Constants.WEB_PORTLET_DTD);
                        
                XMLSerializer serializer = new XMLSerializer(tempJar, of);
                Marshaller marshaller = new Marshaller(serializer.asDocumentHandler());
                marshaller.setMapping(sdmXml);
                marshaller.marshal(webApp);
                */

                PortletAppDescriptorService portletAppDescriptorService = new StreamPortletAppDescriptorServiceImpl(
                        appName, pis, null);
                File tmpf = File.createTempFile("infoglue-web-xml", null);
                WebAppDescriptorService webAppDescriptorService = new StreamWebAppDescriptorServiceImpl(appName,
                        wis, new FileOutputStream(tmpf));

                org.apache.pluto.driver.deploy.Deploy d = new org.apache.pluto.driver.deploy.Deploy(
                        webAppDescriptorService, portletAppDescriptorService);
                d.updateDescriptors();
                FileInputStream fis = new FileInputStream(tmpf);
                while ((bytesRead = fis.read(buffer)) != -1) {
                    tempJar.write(buffer, 0, bytesRead);
                }
                tmpf.delete();
            } else {
                InputStream entryStream = jar.getInputStream(entry);
                if (entryStream != null) {
                    while ((bytesRead = entryStream.read(buffer)) != -1) {
                        tempJar.write(buffer, 0, bytesRead);
                    }
                }
            }
        }
        tempJar.flush();
        tempJar.close();
        fos.flush();
        fos.close();
        /*
         * String strTo = dirDelim + "WEB-INF" + dirDelim + "tld" + dirDelim +
         * "portlet.tld"; String strFrom = "webapps" + dirDelim + strTo;
         * 
         * copy(strFrom, webAppsDir + webModule + strTo);
         */
    } catch (Exception e) {
        log.error("Failed to prepare archive", e);
        throw new IOException(e.getMessage());
    }

    return portletApp;
}

From source file:com.liferay.ide.server.util.ServerUtil.java

public static Properties getAllCategories(IPath portalDir) {
    Properties retval = null;/*  w ww  . j  a  v  a  2 s  .c om*/

    File implJar = portalDir.append("WEB-INF/lib/portal-impl.jar").toFile(); //$NON-NLS-1$

    if (implJar.exists()) {
        try {
            JarFile jar = new JarFile(implJar);
            Properties categories = new Properties();
            Properties props = new Properties();
            props.load(jar.getInputStream(jar.getEntry("content/Language.properties"))); //$NON-NLS-1$
            Enumeration<?> names = props.propertyNames();

            while (names.hasMoreElements()) {
                String name = names.nextElement().toString();

                if (name.startsWith("category.")) //$NON-NLS-1$
                {
                    categories.put(name, props.getProperty(name));
                }
            }

            retval = categories;
            jar.close();
        } catch (IOException e) {
            LiferayServerCore.logError(e);
        }
    }

    return retval;
}

From source file:com.photon.phresco.service.util.ServerUtil.java

public static InputStream getArtifactPomStream(File artifactFile) throws PhrescoException {
    String pomFile = null;/*from   w  w  w . ja va  2 s.  c  o m*/
    if (getFileExtension(artifactFile.getName()).equals(ServerConstants.JAR_FILE)) {
        try {
            JarFile jarfile = new JarFile(artifactFile);
            for (Enumeration<JarEntry> em = jarfile.entries(); em.hasMoreElements();) {
                JarEntry jarEntry = em.nextElement();
                if (jarEntry.getName().endsWith("pom.xml")) {
                    pomFile = jarEntry.getName();
                }
            }
            if (pomFile != null) {
                ZipEntry entry = jarfile.getEntry(pomFile);
                return jarfile.getInputStream(entry);
            }
        } catch (Exception e) {
            throw new PhrescoException(e);
        }
    }
    return null;
}

From source file:org.ebayopensource.turmeric.eclipse.typelibrary.ui.TypeLibraryUtil.java

/**
 * Old type library jar(NOT in workspace) has the dir structure \types\<xsd>
 * and the new one has meta-src\types\<typeLibName>\<xsd>.
 *
 * @param jarURL the jar url//from w  w  w.j a va  2s  . c  o m
 * @param projectName the project name
 * @return true, if is new typ library
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static boolean isNewTypLibrary(URL jarURL, String projectName) throws IOException {
    File file = new File(jarURL.getPath());
    JarFile jarFile;
    jarFile = new JarFile(file);
    return jarFile.getEntry(
            SOATypeLibraryConstants.TYPES_LOCATION_IN_JAR + WorkspaceUtil.PATH_SEPERATOR + projectName) != null;

}

From source file:org.jumpmind.util.JarBuilderUnitTest.java

@Test
public void testJarCreation() throws Exception {
    final String TEST_JAR_DIR = "target/test.jar.dir";
    File outputFile = new File("target/test.jar");
    outputFile.delete();//ww  w. j a  v  a2s .  c  o  m
    assertFalse(outputFile.exists());

    FileUtils.deleteDirectory(new File(TEST_JAR_DIR));

    mkdir(TEST_JAR_DIR + "/subdir");
    mkdir(TEST_JAR_DIR + "/META-INF");
    emptyFile(TEST_JAR_DIR + "/META-INF/MANIFEST.MF");
    emptyFile(TEST_JAR_DIR + "/subdir/file2.txt");
    emptyFile(TEST_JAR_DIR + "/file2.txt");
    emptyFile("target/file1.txt");
    emptyFile(TEST_JAR_DIR + "/file3.txt");

    JarBuilder jarFile = new JarBuilder(new File(TEST_JAR_DIR), outputFile,
            new File[] { new File(TEST_JAR_DIR), new File("target/file1.txt") }, "3.0.0");
    jarFile.build();

    assertTrue(outputFile.exists());

    JarFile finalJar = new JarFile(outputFile);
    assertNotNull(finalJar.getEntry("subdir/file2.txt"));
    assertNotNull(finalJar.getEntry("file2.txt"));
    assertNull(finalJar.getEntry("target/test.jar.dir"));
    assertNull(finalJar.getEntry("test.jar.dir"));
    assertNull(finalJar.getEntry("file1.txt"));
    assertNotNull(finalJar.getEntry("file3.txt"));
    finalJar.close();
}

From source file:rubah.runtime.classloader.VersionLoader.java

@Override
public byte[] getResource(String resourceName) throws IOException {
    if (this.versionJar == null) {
        return super.getResource(resourceName);
    }//from w w w .java2s .  co  m

    JarFile jarFile = this.versionJar;

    ZipEntry ze = jarFile.getEntry(resourceName);
    if (ze == null)
        throw new FileNotFoundException(resourceName);
    return IOUtils.toByteArray(jarFile.getInputStream(ze));
}

From source file:org.codehaus.mojo.license.osgi.AboutFileLicenseResolver.java

public List<License> resolve(String artifactId, File file) throws IOException {
    List<License> licenses = new ArrayList<License>();
    JarFile jarFile = new JarFile(file);
    try {/*w w  w  .  j  a v  a  2 s.  com*/
        ZipEntry entry = jarFile.getEntry(ABOUT_HTML);
        if (entry != null) {
            licenses.add(createJarEmbeddedLicense(artifactId, file, ABOUT_HTML));
            String content = readContent(jarFile, entry);
            licenses.addAll(findThrirdPartyLicenses(artifactId, file, content));
        }
        return licenses;
    } finally {
        jarFile.close();
    }
}

From source file:demo.config.diff.support.ConfigurationMetadataRepositoryLoader.java

private Resource load(ConfigurationMetadataRepositoryJsonBuilder builder, String moduleId, String version,
        boolean mandatory) throws IOException {
    String coordinates = moduleId + ":" + version;
    try {//  w  w w.j av a2s. c om
        ArtifactResult artifactResult = dependencyResolver.resolveDependency(coordinates);
        File file = artifactResult.getArtifact().getFile();
        JarFile jarFile = new JarFile(file);
        ZipEntry entry = jarFile.getEntry("META-INF/spring-configuration-metadata.json");
        if (entry != null) {
            logger.info("Adding meta-data from '" + coordinates + "'");
            try (InputStream stream = jarFile.getInputStream(entry)) {
                builder.withJsonResource(stream);
            }
        } else {
            logger.info("No meta-data found for '" + coordinates + "'");
        }
    } catch (ArtifactResolutionException e) {
        if (mandatory) {
            throw new UnknownSpringBootVersion("Could not load '" + coordinates + "'", version);
        }
        logger.info("Ignoring '" + coordinates + " (not found)");
    }
    return null;
}

From source file:com.betfair.cougar.test.socket.app.JarRunner.java

private void init() throws IOException {
    JarFile jar = new JarFile(jarFile);
    ZipEntry entry = jar.getEntry("META-INF/maven/com.betfair.cougar/socket-tester/pom.properties");
    Properties props = new Properties();
    props.load(jar.getInputStream(entry));
    version = props.getProperty("version");
    jar.close();/*  w ww . j  a  va2 s.com*/
}