Example usage for java.util.jar JarOutputStream flush

List of usage examples for java.util.jar JarOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the compressed output stream.

Usage

From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java

private void compileJavaModule(File jarOutputFolder, File classesOutputFolder, String moduleName,
        String moduleVersion, File sourceFolder, File[] extraClassPath, String... sourceFileNames)
        throws IOException {
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    assertNotNull("Missing Java compiler, this test is probably being run with a JRE instead of a JDK!",
            javaCompiler);//from w  w w .j a  v  a2 s  .c  om
    StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, null, null);
    Set<String> sourceDirectories = new HashSet<String>();
    File[] javaSourceFiles = new File[sourceFileNames.length];
    for (int i = 0; i < javaSourceFiles.length; i++) {
        javaSourceFiles[i] = new File(sourceFolder, sourceFileNames[i]);
        String sfn = sourceFileNames[i].replace(File.separatorChar, '/');
        int p = sfn.lastIndexOf('/');
        String sourceDir = sfn.substring(0, p);
        sourceDirectories.add(sourceDir);
    }
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(javaSourceFiles);
    StringBuilder cp = new StringBuilder();
    for (int i = 0; i < extraClassPath.length; i++) {
        if (i > 0)
            cp.append(File.pathSeparator);
        cp.append(extraClassPath[i]);
    }
    CompilationTask task = javaCompiler.getTask(null, null, null, Arrays.asList("-d",
            classesOutputFolder.getPath(), "-cp", cp.toString(), "-sourcepath", sourceFolder.getPath()), null,
            compilationUnits);
    assertEquals(Boolean.TRUE, task.call());

    File jarFolder = new File(jarOutputFolder,
            moduleName.replace('.', File.separatorChar) + File.separatorChar + moduleVersion);
    jarFolder.mkdirs();
    File jarFile = new File(jarFolder, moduleName + "-" + moduleVersion + ".jar");
    // now jar it up
    JarOutputStream outputStream = new JarOutputStream(new FileOutputStream(jarFile));
    for (String sourceFileName : sourceFileNames) {
        String classFileName = sourceFileName.substring(0, sourceFileName.length() - 5) + ".class";
        ZipEntry entry = new ZipEntry(classFileName);
        outputStream.putNextEntry(entry);

        File classFile = new File(classesOutputFolder, classFileName);
        FileInputStream inputStream = new FileInputStream(classFile);
        Util.copy(inputStream, outputStream);
        inputStream.close();
        outputStream.flush();
    }
    outputStream.close();
    for (String sourceDir : sourceDirectories) {
        File module = null;
        String sourceName = "module.properties";
        File properties = new File(sourceFolder, sourceDir + File.separator + sourceName);
        if (properties.exists()) {
            module = properties;
        } else {
            sourceName = "module.xml";
            properties = new File(sourceFolder, sourceDir + File.separator + sourceName);
            if (properties.exists()) {
                module = properties;
            }
        }
        if (module != null) {
            File moduleFile = new File(sourceFolder, sourceDir + File.separator + sourceName);
            FileInputStream inputStream = new FileInputStream(moduleFile);
            FileOutputStream moduleOutputStream = new FileOutputStream(new File(jarFolder, sourceName));
            Util.copy(inputStream, moduleOutputStream);
            inputStream.close();
            moduleOutputStream.flush();
            moduleOutputStream.close();
        }
    }
}

From source file:com.sonicle.webtop.mail.Service.java

private void outputJarMailFolder(String foldername, Message msgs[], JarOutputStream jos) throws Exception {
    int digits = (msgs.length > 0 ? (int) Math.log10(msgs.length) + 1 : 1);
    for (int i = 0; i < msgs.length; ++i) {
        Message msg = msgs[i];//from   ww w .ja v a 2s . c o  m
        String subject = msg.getSubject();
        if (subject != null)
            subject = subject.replace('/', '_').replace('\\', '_').replace(':', '-');
        else
            subject = "";
        java.util.Date date = msg.getReceivedDate();
        if (date == null)
            date = new java.util.Date();

        String fname = LangUtils.zerofill(i + 1, digits) + " - " + subject + ".eml";
        String fullname = null;
        if (foldername != null && !foldername.isEmpty())
            fullname = foldername + "/" + fname;
        else
            fullname = fname;
        JarEntry je = new JarEntry(fullname);
        je.setTime(date.getTime());
        jos.putNextEntry(je);
        msg.writeTo(jos);
        jos.closeEntry();
    }
    jos.flush();
}

From source file:com.sonicle.webtop.mail.Service.java

public void processGetAttachments(HttpServletRequest request, HttpServletResponse response) {
    MailAccount account = getAccount(request);
    String pfoldername = request.getParameter("folder");
    String puidmessage = request.getParameter("idmessage");
    String pids[] = request.getParameterValues("ids");
    String providername = request.getParameter("provider");
    String providerid = request.getParameter("providerid");

    try {//from  ww w . ja  v  a 2s . c  o m
        account.checkStoreConnected();
        FolderCache mcache = null;
        Message m = null;
        if (providername == null) {
            mcache = account.getFolderCache(pfoldername);
            long newmsguid = Long.parseLong(puidmessage);
            m = mcache.getMessage(newmsguid);
        } else {
            mcache = fcProvided;
            m = mcache.getProvidedMessage(providername, providerid);
        }
        HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
        String name = m.getSubject();
        if (name == null) {
            name = "attachments";
        }
        try {
            name = MailUtils.decodeQString(name);
        } catch (Exception exc) {
        }
        name += ".zip";
        //prepare hashmap to hold already used pnames
        HashMap<String, String> pnames = new HashMap<String, String>();
        ServletUtils.setFileStreamHeaders(response, "application/x-zip-compressed", DispositionType.INLINE,
                name);
        JarOutputStream jos = new java.util.jar.JarOutputStream(response.getOutputStream());
        byte[] b = new byte[64 * 1024];
        for (String pid : pids) {
            Part part = mailData.getAttachmentPart(Integer.parseInt(pid));
            String pname = part.getFileName();
            if (pname == null) {
                pname = "unknown";
            }
            /*
            try {
               pname = MailUtils.decodeQString(pname, "iso-8859-1");
            } catch (Exception exc) {
            }
            */
            //keep name and extension
            String bpname = pname;
            String extpname = null;
            int ix = pname.lastIndexOf(".");
            if (ix > 0) {
                bpname = pname.substring(0, ix);
                extpname = pname.substring(ix + 1);
            }
            //check for existing pname and find an unused name
            int xid = 0;
            String rpname = pname;
            while (pnames.containsKey(rpname)) {
                rpname = bpname + " (" + (++xid) + ")";
                if (extpname != null)
                    rpname += "." + extpname;
            }

            JarEntry je = new JarEntry(rpname);
            jos.putNextEntry(je);
            if (providername == null) {
                Folder folder = mailData.getFolder();
                if (!folder.isOpen()) {
                    folder.open(Folder.READ_ONLY);
                }
            }
            InputStream is = part.getInputStream();
            int len = 0;
            while ((len = is.read(b)) != -1) {
                jos.write(b, 0, len);
            }
            is.close();

            //remember used pname
            pnames.put(rpname, rpname);
        }
        jos.closeEntry();
        jos.flush();
        jos.close();

    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
    }
}

From source file:net.technicpack.launchercore.util.ZipUtils.java

public static void copyMinecraftJar(File minecraft, File output) throws IOException {
    String[] security = { "MOJANG_C.DSA", "MOJANG_C.SF", "CODESIGN.RSA", "CODESIGN.SF" };
    JarFile jarFile = new JarFile(minecraft);
    try {//from  www . j a  va 2  s .com
        String fileName = jarFile.getName();
        String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator));

        JarOutputStream jos = new JarOutputStream(new FileOutputStream(output));
        Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (containsAny(entry.getName(), security)) {
                continue;
            }
            InputStream is = jarFile.getInputStream(entry);

            //jos.putNextEntry(entry);
            //create a new entry to avoid ZipException: invalid entry compressed size
            jos.putNextEntry(new JarEntry(entry.getName()));
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = is.read(buffer)) != -1) {
                jos.write(buffer, 0, bytesRead);
            }
            is.close();
            jos.flush();
            jos.closeEntry();
        }
        jos.close();
    } finally {
        jarFile.close();
    }

}

From source file:org.apache.openjpa.eclipse.PluginLibrary.java

void copyJar(JarInputStream jar, JarOutputStream out) throws IOException {
    if (jar == null || out == null)
        return;//from w  w  w.j  av  a  2  s . c  o m

    try {
        JarEntry entry = null;
        while ((entry = jar.getNextJarEntry()) != null) {
            out.putNextEntry(entry);
            int b = -1;
            while ((b = jar.read()) != -1) {
                out.write(b);
            }
        }
        out.closeEntry();
    } finally {
        out.finish();
        out.flush();
        out.close();
        jar.close();
    }
}

From source file:org.apache.pluto.util.assemble.ear.EarAssembler.java

public void assembleInternal(AssemblerConfig config) throws UtilityException, IOException {

    File source = config.getSource();
    File dest = config.getDestination();

    JarInputStream earIn = new JarInputStream(new FileInputStream(source));
    JarOutputStream earOut = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(dest), BUFLEN));

    try {/*from  w w  w  . j av  a2s  . c o m*/

        JarEntry entry;

        // Iterate over entries in the EAR archive
        while ((entry = earIn.getNextJarEntry()) != null) {

            // If a war file is encountered, assemble it into a
            // ByteArrayOutputStream and write the assembled bytes
            // back to the EAR archive.
            if (entry.getName().toLowerCase().endsWith(".war")) {

                if (LOG.isDebugEnabled()) {
                    LOG.debug("Assembling war file " + entry.getName());
                }

                // keep a handle to the AssemblySink so we can write out
                // JarEntry metadata and the bytes later.
                AssemblySink warBytesOut = getAssemblySink(config, entry);
                JarOutputStream warOut = new JarOutputStream(warBytesOut);

                JarStreamingAssembly.assembleStream(new JarInputStream(earIn), warOut,
                        config.getDispatchServletClass());

                JarEntry warEntry = new JarEntry(entry);

                // Write out the assembled JarEntry metadata
                warEntry.setSize(warBytesOut.getByteCount());
                warEntry.setCrc(warBytesOut.getCrc());
                warEntry.setCompressedSize(-1);
                earOut.putNextEntry(warEntry);

                // Write out the assembled WAR file to the EAR
                warBytesOut.writeTo(earOut);

                earOut.flush();
                earOut.closeEntry();
                earIn.closeEntry();

            } else {

                earOut.putNextEntry(entry);
                IOUtils.copy(earIn, earOut);

                earOut.flush();
                earOut.closeEntry();
                earIn.closeEntry();

            }
        }

    } finally {

        earOut.close();
        earIn.close();

    }
}

From source file:org.apache.pluto.util.assemble.io.JarStreamingAssembly.java

/**
 * Reads the source JarInputStream, copying entries to the destination JarOutputStream. 
 * The web.xml and portlet.xml are cached, and after the entire archive is copied 
 * (minus the web.xml) a re-written web.xml is generated and written to the 
 * destination JAR./*from  www. j a  v  a 2 s .co  m*/
 * 
 * @param source the WAR source input stream
 * @param dest the WAR destination output stream
 * @param dispatchServletClass the name of the dispatch class
 * @throws IOException
 */
public static void assembleStream(JarInputStream source, JarOutputStream dest, String dispatchServletClass)
        throws IOException {

    try {
        //Need to buffer the web.xml and portlet.xml files for the rewritting
        JarEntry servletXmlEntry = null;
        byte[] servletXmlBuffer = null;
        byte[] portletXmlBuffer = null;

        JarEntry originalJarEntry;

        //Read the source archive entry by entry
        while ((originalJarEntry = source.getNextJarEntry()) != null) {

            final JarEntry newJarEntry = smartClone(originalJarEntry);
            originalJarEntry = null;

            //Capture the web.xml JarEntry and contents as a byte[], don't write it out now or
            //update the CRC or length of the destEntry.
            if (Assembler.SERVLET_XML.equals(newJarEntry.getName())) {
                servletXmlEntry = newJarEntry;
                servletXmlBuffer = IOUtils.toByteArray(source);
            }

            //Capture the portlet.xml contents as a byte[]
            else if (Assembler.PORTLET_XML.equals(newJarEntry.getName())) {
                portletXmlBuffer = IOUtils.toByteArray(source);
                dest.putNextEntry(newJarEntry);
                IOUtils.write(portletXmlBuffer, dest);
            }

            //Copy all other entries directly to the output archive
            else {
                dest.putNextEntry(newJarEntry);
                IOUtils.copy(source, dest);
            }

            dest.closeEntry();
            dest.flush();

        }

        // If no portlet.xml was found in the archive, skip the assembly step.
        if (portletXmlBuffer != null) {
            // container for assembled web.xml bytes
            final byte[] webXmlBytes;

            // Checks to make sure the web.xml was found in the archive
            if (servletXmlBuffer == null) {
                throw new FileNotFoundException(
                        "File '" + Assembler.SERVLET_XML + "' could not be found in the source input stream.");
            }

            //Create streams of the byte[] data for the updater method
            final InputStream webXmlIn = new ByteArrayInputStream(servletXmlBuffer);
            final InputStream portletXmlIn = new ByteArrayInputStream(portletXmlBuffer);
            final ByteArrayOutputStream webXmlOut = new ByteArrayOutputStream(servletXmlBuffer.length);

            //Update the web.xml
            WebXmlStreamingAssembly.assembleStream(webXmlIn, portletXmlIn, webXmlOut, dispatchServletClass);
            IOUtils.copy(webXmlIn, webXmlOut);
            webXmlBytes = webXmlOut.toByteArray();

            //If no compression is being used (STORED) we have to manually update the size and crc
            if (servletXmlEntry.getMethod() == ZipEntry.STORED) {
                servletXmlEntry.setSize(webXmlBytes.length);
                final CRC32 webXmlCrc = new CRC32();
                webXmlCrc.update(webXmlBytes);
                servletXmlEntry.setCrc(webXmlCrc.getValue());
            }

            //write out the assembled web.xml entry and contents
            dest.putNextEntry(servletXmlEntry);
            IOUtils.write(webXmlBytes, dest);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Jar stream " + source + " successfully assembled.");
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("No portlet XML file was found, assembly was not required.");
            }

            //copy the original, unmodified web.xml entry to the destination
            dest.putNextEntry(servletXmlEntry);
            IOUtils.write(servletXmlBuffer, dest);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Jar stream " + source + " successfully assembled.");
            }
        }

    } finally {

        dest.flush();
        dest.close();

    }
}

From source file:org.bonitasoft.engine.io.IOUtil.java

public static byte[] generateJar(final Map<String, byte[]> resources) throws IOException {
    if (resources == null || resources.isEmpty()) {
        final String message = "No resources available";
        throw new IOException(message);
    }//from w  ww.  j  a v a  2 s . c om

    ByteArrayOutputStream baos = null;
    JarOutputStream jarOutStream = null;
    try {
        baos = new ByteArrayOutputStream();
        jarOutStream = new JarOutputStream(new BufferedOutputStream(baos));
        for (final Map.Entry<String, byte[]> resource : resources.entrySet()) {
            jarOutStream.putNextEntry(new JarEntry(resource.getKey()));
            jarOutStream.write(resource.getValue());
        }
        jarOutStream.flush();
        baos.flush();
    } finally {
        if (jarOutStream != null) {
            jarOutStream.close();
        }
        if (baos != null) {
            baos.close();
        }
    }

    return baos.toByteArray();
}

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
 *//* ww  w .  j  a va2s.  com*/
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)
 * //ww  w.  j a v a  2 s .c o  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;
}