Example usage for java.util.jar JarEntry JarEntry

List of usage examples for java.util.jar JarEntry JarEntry

Introduction

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

Prototype

public JarEntry(JarEntry je) 

Source Link

Document

Creates a new JarEntry with fields taken from the specified JarEntry object.

Usage

From source file:org.dspace.installer_edm.InstallerEDMConfEDMExport.java

/**
 * Aadimos el contenido del documento jdom como archivo web.xml al flujo de escritura del war
 *
 * @param jarOutputStream flujo de escritura del war
 * @throws TransformerException/*  w w  w  .  j a  v a  2 s  .c om*/
 * @throws IOException
 */
private void addNewWebXml(JarOutputStream jarOutputStream) throws TransformerException, IOException {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    //transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    DocumentType docType = eDMExportDocument.getDoctype();
    if (docType != null) {
        if (docType.getPublicId() != null)
            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, docType.getPublicId());
        transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, docType.getSystemId());
    }
    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);
    DOMSource source = new DOMSource(eDMExportDocument);
    transformer.transform(source, result);
    String xmlString = sw.toString();
    jarOutputStream.putNextEntry(new JarEntry("WEB-INF/web.xml"));
    jarOutputStream.write(xmlString.getBytes());
    jarOutputStream.closeEntry();
}

From source file:org.echocat.nodoodle.transport.HandlerPacker.java

protected void writeType(Class<?> type, JarOutputStream jar, Set<String> namesOfWrittenFiles)
        throws IOException {
    if (jar == null) {
        throw new NullPointerException();
    }//from w w  w .  j  a  v  a  2 s. co  m
    if (namesOfWrittenFiles == null) {
        throw new NullPointerException();
    }
    if (type != null) {
        final String fileName = type.getName().replace('.', '/') + ".class";
        // noinspection UnnecessaryLocalVariable
        final String sourceFileName = fileName;
        final String targetFileName = TransportConstants.CLASSES_PREFIX + fileName;
        if (namesOfWrittenFiles.contains(targetFileName)) {
            throw new IllegalStateException("The target file '" + targetFileName
                    + "' was already written to jar file. Is '" + type
                    + "' the handler and in the list of dependencyTypes or is dependencyTypes simply not unique?");
        }
        final InputStream inputStream = type.getClassLoader().getResourceAsStream(sourceFileName);
        try {
            final JarEntry e = new JarEntry(targetFileName);
            jar.putNextEntry(e);
            IOUtils.copy(inputStream, jar);
            jar.closeEntry();
        } finally {
            inputStream.close();
        }
        namesOfWrittenFiles.add(targetFileName);
    }
}

From source file:org.echocat.nodoodle.transport.HandlerPacker.java

protected void writeJarResource(JarResource jarResource, JarOutputStream jar, String fileName)
        throws IOException {
    if (jar == null) {
        throw new NullPointerException();
    }//from   www  . ja  v  a 2s  .  com
    if (fileName == null) {
        throw new NullPointerException();
    }
    if (jarResource != null) {
        final InputStream inputStream = jarResource.getResourceAsJar();
        try {
            final JarEntry e = new JarEntry(fileName);
            jar.putNextEntry(e);
            IOUtils.copy(inputStream, jar);
            jar.closeEntry();
        } finally {
            inputStream.close();
        }
    }
}

From source file:org.echocat.nodoodle.transport.HandlerPacker.java

protected void writeData(Handler<?> handler, JarOutputStream jar, String dataFileName) throws IOException {
    if (handler == null) {
        throw new NullPointerException();
    }/*w w  w.j  a v  a  2s .  c  o m*/
    if (jar == null) {
        throw new NullPointerException();
    }
    final JarEntry entry = new JarEntry(dataFileName);
    jar.putNextEntry(entry);
    final ObjectOutputStream oos = new ObjectOutputStream(jar);
    oos.writeObject(handler);
    oos.flush();
    jar.closeEntry();
}

From source file:org.gradle.jvm.tasks.api.ApiJar.java

@TaskAction
public void createApiJar() throws IOException {
    // Make sure all entries are always written in the same order
    final File[] sourceFiles = sortedSourceFiles();
    final ApiClassExtractor apiClassExtractor = new ApiClassExtractor(getExportedPackages());
    withResource(new JarOutputStream(new BufferedOutputStream(new FileOutputStream(getOutputFile()), 65536)),
            new ErroringAction<JarOutputStream>() {
                @Override//  w w  w. j a  v a2s  .  c  o  m
                protected void doExecute(final JarOutputStream jos) throws Exception {
                    writeManifest(jos);
                    writeClasses(jos);
                }

                private void writeManifest(JarOutputStream jos) throws IOException {
                    writeEntry(jos, "META-INF/MANIFEST.MF", "Manifest-Version: 1.0\n".getBytes());
                }

                private void writeClasses(JarOutputStream jos) throws Exception {
                    for (File sourceFile : sourceFiles) {
                        if (!isClassFile(sourceFile)) {
                            continue;
                        }
                        ClassReader classReader = new ClassReader(readFileToByteArray(sourceFile));
                        if (!apiClassExtractor.shouldExtractApiClassFrom(classReader)) {
                            continue;
                        }

                        byte[] apiClassBytes = apiClassExtractor.extractApiClassFrom(classReader);
                        String internalClassName = classReader.getClassName();
                        String entryPath = internalClassName + ".class";
                        writeEntry(jos, entryPath, apiClassBytes);
                    }
                }

                private void writeEntry(JarOutputStream jos, String name, byte[] bytes) throws IOException {
                    JarEntry je = new JarEntry(name);
                    // Setting time to 0 because we need API jars to be identical independently of
                    // the timestamps of class files
                    je.setTime(0);
                    je.setSize(bytes.length);
                    jos.putNextEntry(je);
                    jos.write(bytes);
                    jos.closeEntry();
                }
            });
}

From source file:org.hecl.jarhack.JarHack.java

/**
 * The <code>substHecl</code> method takes the filenames of two
 * .jar's - one as input, the second as output, in addition to the
 * name of the application.  Where it counts, the old name (Hecl,
 * usually) is overridden with the new name, and the new .jar file
 * is written to the specified outfile.  Via the iconname argument
 * it is also possible to specify a new icon file to use.
 *
 * @param infile a <code>FileInputStream</code> value
 * @param outfile a <code>String</code> value
 * @param newname a <code>String</code> value
 * @param iconname a <code>String</code> value
 * @exception IOException if an error occurs
 *//*from   w  w w. j  av  a  2  s . co m*/
public static void substHecl(InputStream infile, String outfile, String newname, String iconname,
        String scriptfile) throws IOException {

    JarInputStream jif = new JarInputStream(infile);
    Manifest mf = jif.getManifest();
    Attributes attrs = mf.getMainAttributes();

    Set keys = attrs.keySet();
    Iterator it = keys.iterator();
    while (it.hasNext()) {
        Object key = it.next();
        Object value = attrs.get(key);
        String keyname = key.toString();

        /* These are the three cases that interest us in
         * particular, where we need to make changes. */
        if (keyname.equals("MIDlet-Name")) {
            attrs.putValue(keyname, newname);
        } else if (keyname.equals("MIDlet-1")) {
            String valuestr = value.toString();
            /* FIXME - the stringsplit method is used for older
             * versions of GCJ.  Once newer versions are common,
             * it can go away.  Or not - it works just fine. */
            String properties[] = stringsplit(valuestr, ", ");
            attrs.putValue(keyname, newname + ", " + properties[1] + ", " + properties[2]);
        } else if (keyname.equals("MicroEdition-Configuration")) {
            cldcversion = value.toString();
        } else if (keyname.equals("MicroEdition-Profile")) {
            midpversion = value.toString();
        } else if (keyname.equals("MIDlet-Jar-URL")) {
            attrs.put(key, newname + ".jar");
        }
    }

    JarOutputStream jof = new JarOutputStream(new FileOutputStream(outfile), mf);

    byte[] buf = new byte[4096];

    /* Go through the various entries. */
    JarEntry entry;
    int read;
    while ((entry = jif.getNextJarEntry()) != null) {

        /* Don't copy the manifest file. */
        if ("META-INF/MANIFEST.MF".equals(entry.getName()))
            continue;

        /* Insert our own icon */
        if (iconname != null && "Hecl.png".equals(entry.getName())) {
            jof.putNextEntry(new JarEntry("Hecl.png"));
            FileInputStream inf = new FileInputStream(iconname);
            while ((read = inf.read(buf)) != -1) {
                jof.write(buf, 0, read);
            }
            inf.close();
        }
        /* Insert our own copy of the script file. */
        else if ("script.hcl".equals(entry.getName())) {
            jof.putNextEntry(new JarEntry("script.hcl"));
            FileInputStream inf = new FileInputStream(scriptfile);
            while ((read = inf.read(buf)) != -1) {
                jof.write(buf, 0, read);
            }
            inf.close();
        } else {
            /* Otherwise, just copy the entry. */
            jof.putNextEntry(entry);
            while ((read = jif.read(buf)) != -1) {
                jof.write(buf, 0, read);
            }
        }

        jof.closeEntry();
    }

    jof.flush();
    jof.close();
    jif.close();
}

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

/**
 * Prepare a portlet according to Pluto (switch web.xml)
 * //from   www .j a v  a 2 s  . c om
 * @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:org.jahia.modules.serversettings.portlets.BasePortletHelper.java

static void addToJar(String resource, String targetJarEntry, JarOutputStream jos) throws IOException {
    jos.putNextEntry(new JarEntry(targetJarEntry));
    InputStream is = BasePortletHelper.class.getClassLoader().getResourceAsStream(resource);
    try {/*w  w w. j a va2  s.com*/
        IOUtils.copy(is, jos);
        jos.closeEntry();
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:org.jahia.modules.serversettings.portlets.BasePortletHelper.java

static JarEntry cloneEntry(JarEntry originalJarEntry) {
    final JarEntry newJarEntry = new JarEntry(originalJarEntry.getName());
    newJarEntry.setComment(originalJarEntry.getComment());
    newJarEntry.setExtra(originalJarEntry.getExtra());
    newJarEntry.setMethod(originalJarEntry.getMethod());
    newJarEntry.setTime(originalJarEntry.getTime());

    // Must set size and CRC for STORED entries
    if (newJarEntry.getMethod() == ZipEntry.STORED) {
        newJarEntry.setSize(originalJarEntry.getSize());
        newJarEntry.setCrc(originalJarEntry.getCrc());
    }/*from  w ww.  j  a v a 2 s. c  om*/

    return newJarEntry;
}

From source file:org.mule.util.JarUtils.java

public static void createJarFileEntries(File jarFile, LinkedHashMap entries) throws Exception {
    JarOutputStream jarStream = null;
    FileOutputStream fileStream = null;

    if (jarFile != null) {
        logger.debug("Creating jar file " + jarFile.getAbsolutePath());

        try {/* w  w w .  j a  v  a 2 s  . com*/
            fileStream = new FileOutputStream(jarFile);
            jarStream = new JarOutputStream(fileStream);

            if (entries != null && !entries.isEmpty()) {
                Iterator iter = entries.keySet().iterator();
                while (iter.hasNext()) {
                    String jarFilePath = (String) iter.next();
                    Object content = entries.get(jarFilePath);

                    JarEntry entry = new JarEntry(jarFilePath);
                    jarStream.putNextEntry(entry);

                    logger.debug("Adding jar entry " + jarFilePath + " to " + jarFile.getAbsolutePath());

                    if (content instanceof String) {
                        writeJarEntry(jarStream, ((String) content).getBytes());
                    } else if (content instanceof byte[]) {
                        writeJarEntry(jarStream, (byte[]) content);
                    } else if (content instanceof File) {
                        writeJarEntry(jarStream, (File) content);
                    }
                }
            }

            jarStream.flush();
            fileStream.getFD().sync();
        } finally {
            if (jarStream != null) {
                try {
                    jarStream.close();
                } catch (Exception jarNotClosed) {
                    logger.debug(jarNotClosed);
                }
            }
            if (fileStream != null) {
                try {
                    fileStream.close();
                } catch (Exception fileNotClosed) {
                    logger.debug(fileNotClosed);
                }
            }
        }
    }
}