Example usage for java.util.zip ZipInputStream close

List of usage examples for java.util.zip ZipInputStream close

Introduction

In this page you can find the example usage for java.util.zip ZipInputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:com.mobicage.rogerthat.plugins.messaging.BrandingMgr.java

private BrandingResult extractBranding(final BrandedItem item, final File encryptedBrandingFile,
        final File tmpDecryptedBrandingFile, final File tmpBrandingDir) throws BrandingFailureException {
    try {//  w w w. jav  a2s  .c  om
        L.i("Extracting " + tmpDecryptedBrandingFile + " (" + item.brandingKey + ")");
        File brandingFile = new File(tmpBrandingDir, "branding.html");
        File watermarkFile = null;
        Integer backgroundColor = null;
        Integer menuItemColor = null;
        ColorScheme scheme = ColorScheme.light;
        boolean showHeader = true;
        String contentType = null;
        boolean wakelockEnabled = false;
        ByteArrayOutputStream brandingBos = new ByteArrayOutputStream();
        try {
            MessageDigest digester = MessageDigest.getInstance("SHA256");
            DigestInputStream dis = new DigestInputStream(
                    new BufferedInputStream(new FileInputStream(tmpDecryptedBrandingFile)), digester);
            try {
                ZipInputStream zis = new ZipInputStream(dis);
                try {
                    byte data[] = new byte[BUFFER_SIZE];
                    ZipEntry entry;
                    while ((entry = zis.getNextEntry()) != null) {
                        L.d("Extracting: " + entry);
                        int count = 0;
                        if (entry.getName().equals("branding.html")) {
                            while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
                                brandingBos.write(data, 0, count);
                            }
                        } else {
                            if (entry.isDirectory()) {
                                L.d("Skipping branding dir " + entry.getName());
                                continue;
                            }
                            File destination = new File(tmpBrandingDir, entry.getName());
                            destination.getParentFile().mkdirs();
                            if ("__watermark__".equals(entry.getName())) {
                                watermarkFile = destination;
                            }
                            final OutputStream fos = new BufferedOutputStream(new FileOutputStream(destination),
                                    BUFFER_SIZE);
                            try {
                                while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
                                    fos.write(data, 0, count);
                                }
                            } finally {
                                fos.close();
                            }
                        }
                    }
                    while (dis.read(data) >= 0)
                        ;
                } finally {
                    zis.close();
                }
            } finally {
                dis.close();
            }
            String hexDigest = com.mobicage.rogerthat.util.TextUtils.toHex(digester.digest());
            if (!hexDigest.equals(item.brandingKey)) {
                encryptedBrandingFile.delete();
                SystemUtils.deleteDir(tmpBrandingDir);
                throw new BrandingFailureException("Branding cache was invalid!");
            }
            brandingBos.flush();
            byte[] brandingBytes = brandingBos.toByteArray();
            if (brandingBytes.length == 0) {
                encryptedBrandingFile.delete();
                SystemUtils.deleteDir(tmpBrandingDir);
                throw new BrandingFailureException("Invalid branding package!");
            }
            String brandingHtml = new String(brandingBytes, "UTF8");

            switch (item.type) {
            case BrandedItem.TYPE_MESSAGE:
                MessageTO message = (MessageTO) item.object;
                brandingHtml = brandingHtml.replace(NUNTIUZ_MESSAGE,
                        TextUtils.htmlEncode(message.message).replace("\r", "").replace("\n", "<br>"));

                brandingHtml = brandingHtml.replace(NUNTIUZ_TIMESTAMP,
                        TimeUtils.getDayTimeStr(mContext, message.timestamp * 1000));

                FriendsPlugin friendsPlugin = mMainService.getPlugin(FriendsPlugin.class);
                brandingHtml = brandingHtml.replace(NUNTIUZ_IDENTITY_NAME,
                        TextUtils.htmlEncode(friendsPlugin.getName(message.sender)));
                break;
            case BrandedItem.TYPE_FRIEND:
                FriendTO friend = (FriendTO) item.object;
                // In this case Friend is fully populated
                brandingHtml = brandingHtml.replace(NUNTIUZ_MESSAGE,
                        TextUtils.htmlEncode(friend.description).replace("\r", "").replace("\n", "<br>"));

                brandingHtml = brandingHtml.replace(NUNTIUZ_IDENTITY_NAME, TextUtils.htmlEncode(friend.name));

                break;
            case BrandedItem.TYPE_GENERIC:
                if (item.object instanceof FriendTO) {
                    brandingHtml = brandingHtml.replace(NUNTIUZ_IDENTITY_NAME,
                            TextUtils.htmlEncode(((FriendTO) item.object).name));
                }
                break;
            }

            Matcher matcher = RegexPatterns.BRANDING_BACKGROUND_COLOR.matcher(brandingHtml);
            if (matcher.find()) {
                String bg = matcher.group(1);
                if (bg.length() == 4) {
                    StringBuilder sb = new StringBuilder();
                    sb.append("#");
                    sb.append(bg.charAt(1));
                    sb.append(bg.charAt(1));
                    sb.append(bg.charAt(2));
                    sb.append(bg.charAt(2));
                    sb.append(bg.charAt(3));
                    sb.append(bg.charAt(3));
                    bg = sb.toString();
                }
                backgroundColor = Color.parseColor(bg);
            }

            matcher = RegexPatterns.BRANDING_MENU_ITEM_COLOR.matcher(brandingHtml);
            if (matcher.find()) {
                String bg = matcher.group(1);
                if (bg.length() == 4) {
                    StringBuilder sb = new StringBuilder();
                    sb.append("#");
                    sb.append(bg.charAt(1));
                    sb.append(bg.charAt(1));
                    sb.append(bg.charAt(2));
                    sb.append(bg.charAt(2));
                    sb.append(bg.charAt(3));
                    sb.append(bg.charAt(3));
                    bg = sb.toString();
                }
                menuItemColor = Color.parseColor(bg);
            }

            matcher = RegexPatterns.BRANDING_COLOR_SCHEME.matcher(brandingHtml);
            if (matcher.find()) {
                String schemeStr = matcher.group(1);
                scheme = "dark".equalsIgnoreCase(schemeStr) ? ColorScheme.dark : ColorScheme.light;
            }

            matcher = RegexPatterns.BRANDING_SHOW_HEADER.matcher(brandingHtml);
            if (matcher.find()) {
                String showHeaderStr = matcher.group(1);
                showHeader = "true".equalsIgnoreCase(showHeaderStr);
            }

            matcher = RegexPatterns.BRANDING_CONTENT_TYPE.matcher(brandingHtml);
            if (matcher.find()) {
                String contentTypeStr = matcher.group(1);
                L.i("Branding content-type: " + contentTypeStr);
                if (AttachmentViewerActivity.CONTENT_TYPE_PDF.equalsIgnoreCase(contentTypeStr)) {
                    File tmpBrandingFile = new File(tmpBrandingDir, "embed.pdf");
                    if (tmpBrandingFile.exists()) {
                        contentType = AttachmentViewerActivity.CONTENT_TYPE_PDF;
                    }
                }
            }

            Dimension dimension1 = null;
            Dimension dimension2 = null;
            matcher = RegexPatterns.BRANDING_DIMENSIONS.matcher(brandingHtml);
            if (matcher.find()) {
                String dimensionsStr = matcher.group(1);
                L.i("Branding dimensions: " + dimensionsStr);
                String[] dimensions = dimensionsStr.split(",");
                try {
                    dimension1 = new Dimension(Integer.parseInt(dimensions[0]),
                            Integer.parseInt(dimensions[1]));
                    dimension2 = new Dimension(Integer.parseInt(dimensions[2]),
                            Integer.parseInt(dimensions[3]));
                } catch (Exception e) {
                    L.bug("Invalid branding dimension: " + matcher.group(), e);
                }
            }

            matcher = RegexPatterns.BRANDING_WAKELOCK_ENABLED.matcher(brandingHtml);
            if (matcher.find()) {
                String wakelockEnabledStr = matcher.group(1);
                wakelockEnabled = "true".equalsIgnoreCase(wakelockEnabledStr);
            }

            final List<String> externalUrlPatterns = new ArrayList<String>();
            matcher = RegexPatterns.BRANDING_EXTERNAL_URLS.matcher(brandingHtml);
            while (matcher.find()) {
                externalUrlPatterns.add(matcher.group(1));
            }

            FileOutputStream fos = new FileOutputStream(brandingFile);

            try {
                fos.write(brandingHtml.getBytes("UTF8"));
            } finally {
                fos.close();
            }
            if (contentType != null
                    && AttachmentViewerActivity.CONTENT_TYPE_PDF.equalsIgnoreCase(contentType)) {
                brandingFile = new File(tmpBrandingDir, "embed.pdf");
            }
            return new BrandingResult(tmpBrandingDir, brandingFile, watermarkFile, backgroundColor,
                    menuItemColor, scheme, showHeader, dimension1, dimension2, contentType, wakelockEnabled,
                    externalUrlPatterns);
        } finally {
            brandingBos.close();
        }
    } catch (IOException e) {
        L.e(e);
        throw new BrandingFailureException("Error copying cached branded file to private space", e);
    } catch (NoSuchAlgorithmException e) {
        L.e(e);
        throw new BrandingFailureException("Cannot validate ", e);
    }
}

From source file:org.jboss.tools.tycho.sitegenerator.GenerateRepositoryFacadeMojo.java

/**
 * Add p2 stats to the repository's artifacts.xml (and .jar and .xml.xz) 
 * See http://wiki.eclipse.org/Equinox_p2_download_stats
 *
 * @param p2repository//from  ww  w . j a  v a2  s  .c o m
 * @throws FileNotFoundException
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws TransformerFactoryConfigurationError
 * @throws TransformerConfigurationException
 * @throws TransformerException
 * @throws MojoFailureException
 */
private void addP2Stats(File p2repository) throws FileNotFoundException, IOException, SAXException,
        ParserConfigurationException, TransformerFactoryConfigurationError, TransformerConfigurationException,
        TransformerException, MojoFailureException {
    File artifactsJar = new File(p2repository, "artifacts.jar");
    ZipInputStream contentStream = new ZipInputStream(new FileInputStream(artifactsJar));
    ZipEntry entry = null;
    Document contentDoc = null;
    boolean done = false;
    while (!done && (entry = contentStream.getNextEntry()) != null) {
        if (entry.getName().equals("artifacts.xml")) {
            contentDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(contentStream);
            Element repoElement = (Element) contentDoc.getElementsByTagName("repository").item(0);
            // Add p2.StatsURI property
            Element repoProperties = (Element) contentDoc.getElementsByTagName("properties").item(0);
            int newRepoPropertiesSize = Integer.parseInt(repoProperties.getAttribute("size")) + 1;
            repoProperties.setAttribute("size", Integer.toString(newRepoPropertiesSize));
            Element p2statsElement = contentDoc.createElement("property");
            p2statsElement.setAttribute("name", "p2.statsURI");
            p2statsElement.setAttribute("value", this.p2StatsUrl);
            repoProperties.appendChild(p2statsElement);
            // process features
            NodeList artifacts = ((Element) repoElement.getElementsByTagName("artifacts").item(0))
                    .getElementsByTagName("artifact");
            for (int i = 0; i < artifacts.getLength(); i++) {
                Element currentArtifact = (Element) artifacts.item(i);
                if (currentArtifact.getAttribute("classifier").equals("org.eclipse.update.feature")) {
                    String iu = currentArtifact.getAttribute("id");
                    Element artifactProperties = (Element) currentArtifact.getElementsByTagName("properties")
                            .item(0);
                    int newArtifactPropertiesSize = Integer.parseInt(artifactProperties.getAttribute("size"))
                            + 1;
                    artifactProperties.setAttribute("size", Integer.toString(newArtifactPropertiesSize));
                    Element statsElement = contentDoc.createElement("property");
                    statsElement.setAttribute("name", "download.stats");
                    statsElement.setAttribute("value", iu);
                    artifactProperties.appendChild(statsElement);
                }
            }
            done = true;
        }
    }
    // .close and .closeEntry raise exception:
    // https://issues.apache.org/bugzilla/show_bug.cgi?id=3862
    ZipOutputStream outContentStream = new ZipOutputStream(new FileOutputStream(artifactsJar));
    ZipEntry contentXmlEntry = new ZipEntry("artifacts.xml");
    outContentStream.putNextEntry(contentXmlEntry);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    DOMSource source = new DOMSource(contentDoc);
    StreamResult result = new StreamResult(outContentStream);
    transformer.transform(source, result);
    contentStream.close();
    outContentStream.closeEntry();
    outContentStream.close();
    alterXzFile(new File(p2repository, "artifacts.xml"), new File(p2repository, "artifacts.xml.xz"),
            transformer, source);

}

From source file:org.apache.axis2.deployment.repository.util.ArchiveReader.java

/**
 * Creates service objects from wsdl file inside a service archive file.
 *
 * @param file <code>ArchiveFileData</code>
 * @throws DeploymentException <code>DeploymentException</code>
 *//*from w w w. j a va  2 s.co  m*/
public HashMap<String, AxisService> processWSDLs(DeploymentFileData file) throws DeploymentException {
    File serviceFile = file.getFile();
    // to store service come from wsdl files
    HashMap<String, AxisService> servicesMap = new HashMap<String, AxisService>();
    boolean isDirectory = serviceFile.isDirectory();
    if (isDirectory) {
        try {
            File metaInfFolder = new File(serviceFile, META_INF);

            if (!metaInfFolder.exists()) {
                metaInfFolder = new File(serviceFile, META_INF.toLowerCase());
                if (!metaInfFolder.exists()) {
                    throw new DeploymentException(
                            Messages.getMessage(DeploymentErrorMsgs.META_INF_MISSING, serviceFile.getName()));
                }
            }

            processFilesInFolder(metaInfFolder, servicesMap);

        } catch (FileNotFoundException e) {
            throw new DeploymentException(e);
        } catch (IOException e) {
            throw new DeploymentException(e);
        } catch (XMLStreamException e) {
            throw new DeploymentException(e);
        }
    } else {
        ZipInputStream zin;
        FileInputStream fin;
        try {
            fin = new FileInputStream(serviceFile);
            zin = new ZipInputStream(fin);

            //TODO Check whether this WSDL is empty

            ZipEntry entry;
            byte[] buf = new byte[1024];
            int read;
            ByteArrayOutputStream out;
            while ((entry = zin.getNextEntry()) != null) {
                String entryName = entry.getName().toLowerCase();
                if (entryName.startsWith(META_INF.toLowerCase()) && entryName.endsWith(SUFFIX_WSDL)) {
                    out = new ByteArrayOutputStream();

                    // we do not want to generate the services for the
                    // imported wsdl of one file.
                    if ((entryName.indexOf("/") != entryName.lastIndexOf("/"))
                            || (entryName.indexOf("wsdl_") != -1)) {
                        //only care abt the toplevel wsdl
                        continue;
                    }

                    while ((read = zin.read(buf)) > 0) {
                        out.write(buf, 0, read);
                    }

                    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());

                    // now the question is which version of WSDL file this archive contains.
                    // lets check the namespace of the root element and decide. But since we are
                    // using axiom (dude, you are becoming handy here :)), we will not build the
                    // whole thing.
                    OMNamespace documentElementNS = ((OMElement) XMLUtils.toOM(in)).getNamespace();
                    if (documentElementNS != null) {
                        WSDLToAxisServiceBuilder wsdlToAxisServiceBuilder;
                        if (WSDL2Constants.WSDL_NAMESPACE.equals(documentElementNS.getNamespaceURI())) {
                            // we have a WSDL 2.0 document here.
                            wsdlToAxisServiceBuilder = new WSDL20ToAllAxisServicesBuilder(
                                    new ByteArrayInputStream(out.toByteArray()));
                            wsdlToAxisServiceBuilder.setBaseUri(entryName);
                        } else if (Constants.NS_URI_WSDL11.equals(documentElementNS.getNamespaceURI())) {
                            wsdlToAxisServiceBuilder = new WSDL11ToAllAxisServicesBuilder(
                                    new ByteArrayInputStream(out.toByteArray()));
                            ((WSDL11ToAxisServiceBuilder) wsdlToAxisServiceBuilder)
                                    .setDocumentBaseUri(entryName);
                        } else {
                            throw new DeploymentException(Messages.getMessage("invalidWSDLFound"));
                        }
                        List<AxisService> services = processWSDLFile(wsdlToAxisServiceBuilder, serviceFile,
                                true, new ByteArrayInputStream(out.toByteArray()), entry.getName());
                        if (services != null) {
                            for (AxisService axisService : services) {
                                if (axisService != null) {
                                    servicesMap.put(axisService.getName(), axisService);
                                }
                            }
                        }
                    }
                }
            }
            try {
                zin.close();
            } catch (IOException e) {
                log.info(e);
            }
            try {
                fin.close();
            } catch (IOException e) {
                log.info(e);
            }
        } catch (FileNotFoundException e) {
            throw new DeploymentException(e);
        } catch (IOException e) {
            throw new DeploymentException(e);
        } catch (XMLStreamException e) {
            throw new DeploymentException(e);
        }
    }
    return servicesMap;
}

From source file:de.intranda.goobi.plugins.CSICMixedImport.java

/**
 * Unzip a zip archive and write results into Array of Strings
 * //from   www . j a v a 2  s  . c om
 * @param source
 * @return
 */
private HashMap<String, byte[]> unzipFile(File source) {
    ArrayList<String> filenames = new ArrayList<String>();
    HashMap<String, byte[]> contentMap = new HashMap<String, byte[]>();

    FileInputStream fis = null;
    BufferedInputStream bis = null;
    ZipInputStream in = null;
    try {
        fis = new FileInputStream(source);
        bis = new BufferedInputStream(fis);
        in = new ZipInputStream(bis);
        ZipEntry entry;
        while ((entry = in.getNextEntry()) != null) {
            filenames.add(entry.getName());
            logger.debug("Unzipping file " + entry.getName() + " from archive " + source.getName());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            BufferedOutputStream out = new BufferedOutputStream(baos);
            int size;
            byte[] buffer = new byte[2048];
            while ((size = in.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, size);
            }

            if (entry != null)
                in.closeEntry();
            if (out != null) {
                out.close();
            }
            if (baos != null) {
                baos.close();
            }
            contentMap.put(entry.getName(), baos.toByteArray());

        }
    } catch (IOException e) {
        logger.error(e.toString(), e);
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            if (bis != null) {
                bis.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            logger.error(e.toString(), e);
        }
    }
    return contentMap;
}

From source file:nl.nn.adapterframework.pipes.UnzipPipe.java

public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException {
    InputStream in;/*  w w w .ja v  a 2 s  .c o m*/
    if (input instanceof InputStream) {
        in = (InputStream) input;
    } else {
        String filename = (String) input;
        try {
            in = new FileInputStream(filename);
        } catch (FileNotFoundException e) {
            throw new PipeRunException(this, "could not find file [" + filename + "]", e);
        }
    }
    String entryResults = "";
    int count = 0;
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(in));
    try {
        ZipEntry ze;
        while ((ze = zis.getNextEntry()) != null) {
            if (ze.isDirectory()) {
                if (isCreateSubdirectories()) {
                    File tmpFile = new File(dir, ze.getName());
                    if (!tmpFile.exists()) {
                        if (tmpFile.mkdirs()) {
                            log.debug(getLogPrefix(session) + "created directory [" + tmpFile.getPath() + "]");
                        } else {
                            log.warn(getLogPrefix(session) + "directory [" + tmpFile.getPath()
                                    + "] could not be created");
                        }
                    } else {
                        log.debug(getLogPrefix(session) + "directory entry [" + tmpFile.getPath()
                                + "] already exists");
                    }
                } else {
                    log.warn(getLogPrefix(session) + "skipping directory entry [" + ze.getName() + "]");
                }
            } else {
                String filename = ze.getName();
                String basename = null;
                String extension = null;
                int dotPos = filename.indexOf('.');
                if (dotPos >= 0) {
                    extension = filename.substring(dotPos);
                    basename = filename.substring(0, dotPos);
                    log.debug(getLogPrefix(session) + "parsed filename [" + basename + "] extension ["
                            + extension + "]");
                } else {
                    basename = filename;
                }
                File tmpFile;
                if (isKeepOriginalFileName()) {
                    tmpFile = new File(dir, filename);
                    if (tmpFile.exists()) {
                        throw new PipeRunException(this,
                                "file [" + tmpFile.getAbsolutePath() + "] already exists");
                    }
                } else {
                    tmpFile = File.createTempFile(basename, extension, dir);
                }
                if (isDeleteOnExit()) {
                    tmpFile.deleteOnExit();
                }
                if (isCreateSubdirectories()) {
                    //extra check
                    File tmpDir = tmpFile.getParentFile();
                    if (!tmpDir.exists()) {
                        if (tmpDir.mkdirs()) {
                            log.debug(getLogPrefix(session) + "created directory [" + tmpDir.getPath() + "]");
                        } else {
                            log.warn(getLogPrefix(session) + "directory [" + tmpDir.getPath()
                                    + "] could not be created");
                        }
                    }
                }
                FileOutputStream fos = new FileOutputStream(tmpFile);
                log.debug(getLogPrefix(session) + "writing ZipEntry [" + ze.getName() + "] to file ["
                        + tmpFile.getPath() + "]");
                count++;
                Misc.streamToStream(zis, fos, false);
                fos.close();
                if (isCollectResults()) {
                    entryResults += "<result item=\"" + count + "\"><zipEntry>"
                            + XmlUtils.encodeCdataString(ze.getName()) + "</zipEntry><fileName>"
                            + XmlUtils.encodeCdataString(tmpFile.getPath()) + "</fileName></result>";
                }
            }
        }
    } catch (IOException e) {
        throw new PipeRunException(this, "cannot unzip", e);
    } finally {
        try {
            zis.close();
        } catch (IOException e1) {
            log.warn(getLogPrefix(session) + "exception closing zip", e1);
        }
    }
    String result = "<results count=\"" + count + "\">" + entryResults + "</results>";
    return new PipeRunResult(getForward(), result);
}

From source file:org.openmeetings.servlet.outputhandler.BackupImportController.java

public void performImport(InputStream is, String current_dir) throws Exception {
    File working_dir = new File(current_dir, OpenmeetingsVariables.UPLOAD_DIR + File.separatorChar + "import");
    if (!working_dir.exists()) {
        working_dir.mkdir();//from   www. j  a  va 2 s.  com
    }

    File f = new File(working_dir, "import_" + CalendarPatterns.getTimeForStreamId(new Date()));

    int recursiveNumber = 0;
    do {
        if (f.exists()) {
            f = new File(f.getAbsolutePath() + (recursiveNumber++));
        }
    } while (f.exists());
    f.mkdir();

    log.debug("##### WRITE FILE TO: " + f);

    ZipInputStream zipinputstream = new ZipInputStream(is);
    byte[] buf = new byte[1024];

    ZipEntry zipentry = zipinputstream.getNextEntry();

    while (zipentry != null) {
        // for each entry to be extracted
        int n;
        FileOutputStream fileoutputstream;
        File fentryName = new File(f, zipentry.getName());

        if (zipentry.isDirectory()) {
            if (!fentryName.mkdir()) {
                break;
            }
            zipentry = zipinputstream.getNextEntry();
            continue;
        }

        File fparent = new File(fentryName.getParent());

        if (!fparent.exists()) {

            File fparentparent = new File(fparent.getParent());

            if (!fparentparent.exists()) {

                File fparentparentparent = new File(fparentparent.getParent());

                if (!fparentparentparent.exists()) {

                    fparentparentparent.mkdir();
                    fparentparent.mkdir();
                    fparent.mkdir();

                } else {

                    fparentparent.mkdir();
                    fparent.mkdir();

                }

            } else {

                fparent.mkdir();

            }

        }

        fileoutputstream = new FileOutputStream(fentryName);

        while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
            fileoutputstream.write(buf, 0, n);
        }

        fileoutputstream.close();
        zipinputstream.closeEntry();
        zipentry = zipinputstream.getNextEntry();

    } // while

    zipinputstream.close();

    /*
     * ##################### Import Organizations
     */
    File orgFile = new File(f, "organizations.xml");
    if (!orgFile.exists()) {
        throw new Exception("organizations.xml missing");
    }
    this.importOrganizsations(orgFile);

    log.info("Organizations import complete, starting user import");

    /*
     * ##################### Import Users
     */
    File userFile = new File(f, "users.xml");
    if (!userFile.exists()) {
        throw new Exception("users.xml missing");
    }
    this.importUsers(userFile);

    log.info("Users import complete, starting room import");

    /*
     * ##################### Import Rooms
     */
    File roomFile = new File(f, "rooms.xml");
    if (!roomFile.exists()) {
        throw new Exception("rooms.xml missing");
    }
    this.importRooms(roomFile);

    log.info("Room import complete, starting room organizations import");

    /*
     * ##################### Import Room Organisations
     */
    File orgRoomListFile = new File(f, "rooms_organisation.xml");
    if (!orgRoomListFile.exists()) {
        throw new Exception("rooms_organisation.xml missing");
    }
    this.importOrgRooms(orgRoomListFile);

    log.info("Room organizations import complete, starting appointement import");

    /*
     * ##################### Import Appointements
     */
    File appointementListFile = new File(f, "appointements.xml");
    if (!appointementListFile.exists()) {
        throw new Exception("appointements.xml missing");
    }
    this.importAppointements(appointementListFile);

    log.info("Appointement import complete, starting meeting members import");

    /*
     * ##################### Import MeetingMembers
     * 
     * Reminder Invitations will be NOT send!
     */
    File meetingmembersListFile = new File(f, "meetingmembers.xml");
    if (!meetingmembersListFile.exists()) {
        throw new Exception("meetingmembersListFile missing");
    }
    this.importMeetingmembers(meetingmembersListFile);

    log.info("Meeting members import complete, starting ldap config import");

    /*
     * ##################### Import LDAP Configs
     */
    File ldapConfigListFile = new File(f, "ldapconfigs.xml");
    if (!ldapConfigListFile.exists()) {
        log.debug("meetingmembersListFile missing");
        // throw new Exception
        // ("meetingmembersListFile missing");
    } else {
        this.importLdapConfig(ldapConfigListFile);
    }

    log.info("Ldap config import complete, starting recordings import");

    /*
     * ##################### Import Recordings
     */
    File flvRecordingsListFile = new File(f, "flvRecordings.xml");
    if (!flvRecordingsListFile.exists()) {
        log.debug("flvRecordingsListFile missing");
        // throw new Exception
        // ("meetingmembersListFile missing");
    } else {
        this.importFlvRecordings(flvRecordingsListFile);
    }

    log.info("FLVrecording import complete, starting private message folder import");

    /*
     * ##################### Import Private Message Folders
     */
    File privateMessageFoldersFile = new File(f, "privateMessageFolder.xml");
    if (!privateMessageFoldersFile.exists()) {
        log.debug("privateMessageFoldersFile missing");
        // throw new Exception
        // ("meetingmembersListFile missing");
    } else {
        this.importPrivateMessageFolders(privateMessageFoldersFile);
    }

    log.info("Private message folder import complete, starting private message import");

    /*
     * ##################### Import Private Messages
     */
    File privateMessagesFile = new File(f, "privateMessages.xml");
    if (!privateMessagesFile.exists()) {
        log.debug("privateMessagesFile missing");
        // throw new Exception
        // ("meetingmembersListFile missing");
    } else {
        this.importPrivateMessages(privateMessagesFile);
    }

    log.info("Private message import complete, starting usercontact import");

    /*
     * ##################### Import User Contacts
     */
    File userContactsFile = new File(f, "userContacts.xml");
    if (!userContactsFile.exists()) {
        log.debug("userContactsFile missing");
        // throw new Exception
        // ("meetingmembersListFile missing");
    } else {
        this.importUserContacts(userContactsFile);
    }

    log.info("Usercontact import complete, starting file explorer item import");

    /*
     * ##################### Import File-Explorer Items
     */
    File fileExplorerListFile = new File(f, "fileExplorerItems.xml");
    if (!fileExplorerListFile.exists()) {
        log.debug("fileExplorerListFile missing");
        // throw new Exception
        // ("meetingmembersListFile missing");
    } else {
        this.importFileExplorerItems(fileExplorerListFile);
    }

    log.info("File explorer item import complete, starting file poll import");

    /*
     * ##################### Import Room Polls
     */
    File roomPollListFile = new File(f, "roompolls.xml");
    if (!roomPollListFile.exists()) {
        log.debug("roomPollListFile missing");
    } else {
        this.importRoomPolls(roomPollListFile);
    }
    log.info("Poll import complete, starting configs import");

    /*
     * ##################### Import Configs
     */
    File configsFile = new File(f, "configs.xml");
    if (!configsFile.exists()) {
        log.debug("configsFile missing");
    } else {
        importConfigs(configsFile);
    }
    log.info("Configs import complete, starting asteriskSipUsersFile import");

    /*
     * ##################### Import AsteriskSipUsers
     */
    File asteriskSipUsersFile = new File(f, "asterisksipusers.xml");
    if (!asteriskSipUsersFile.exists()) {
        log.debug("asteriskSipUsersFile missing");
    } else {
        importAsteriskSipUsers(asteriskSipUsersFile);
    }
    log.info("AsteriskSipUsers import complete, starting extensions import");

    /*
     * ##################### Import Extensions
     */
    File extensionsFile = new File(f, "extensions.xml");
    if (!extensionsFile.exists()) {
        log.debug("extensionsFile missing");
    } else {
        importExtensions(extensionsFile);
    }
    log.info("Extensions import complete, starting members import");

    /*
     * ##################### Import Extensions
     */
    File membersFile = new File(f, "members.xml");
    if (!membersFile.exists()) {
        log.debug("membersFile missing");
    } else {
        importMembers(membersFile);
    }
    log.info("Members import complete, starting copy of files and folders");

    /*
     * ##################### Import real files and folders
     */
    importFolders(current_dir, f);

    log.info("File explorer item import complete, clearing temp files");

    deleteDirectory(f);
}

From source file:io.fabric8.tooling.archetype.generator.ArchetypeHelper.java

/**
 * Main method which extracts given Maven Archetype in destination directory
 *
 * @return//from www.ja  va  2s.  c  o m
 */
public int execute() throws IOException {
    outputDir.mkdirs();

    if (packageName == null || packageName.length() == 0) {
        packageName = groupId + "." + artifactId;
    }

    String packageDir = packageName.replace('.', '/');

    info("Creating archetype using Maven groupId: " + groupId + ", artifactId: " + artifactId + ", version: "
            + version + " in directory: " + outputDir);

    Map<String, String> replaceProperties = new HashMap<String, String>();

    ZipInputStream zip = null;
    try {
        zip = new ZipInputStream(archetypeIn);
        boolean ok = true;
        while (ok) {
            ZipEntry entry = zip.getNextEntry();
            if (entry == null) {
                ok = false;
            } else {
                if (!entry.isDirectory()) {
                    String fullName = entry.getName();
                    if (fullName != null && fullName.startsWith(zipEntryPrefix)) {
                        String name = replaceFileProperties(fullName.substring(zipEntryPrefix.length()),
                                replaceProperties);
                        debug("Processing resource: " + name);

                        int idx = name.lastIndexOf('/');
                        Matcher matcher = sourcePathRegexPattern.matcher(name);
                        String dirName;
                        if (packageName.length() > 0 && idx > 0 && matcher.matches()) {
                            String prefix = matcher.group(1);
                            dirName = prefix + packageDir + "/" + name.substring(prefix.length());
                        } else if (packageName.length() > 0 && name.startsWith(webInfResources)) {
                            dirName = "src/main/webapp/WEB-INF/" + packageDir + "/resources"
                                    + name.substring(webInfResources.length());
                        } else {
                            dirName = name;
                        }

                        // lets replace properties...
                        File file = new File(outputDir, dirName);
                        file.getParentFile().mkdirs();
                        FileOutputStream out = null;
                        try {
                            out = new FileOutputStream(file);
                            boolean isBinary = false;
                            for (String suffix : binarySuffixes) {
                                if (name.endsWith(suffix)) {
                                    isBinary = true;
                                    break;
                                }
                            }
                            if (isBinary) {
                                // binary file?  don't transform.
                                copy(zip, out);
                            } else {
                                // text file...
                                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                                copy(zip, bos);
                                String text = new String(bos.toByteArray(), "UTF-8");
                                out.write(transformContents(text, replaceProperties).getBytes());
                            }
                        } finally {
                            if (out != null) {
                                out.close();
                            }
                        }
                    } else if (fullName != null && fullName.equals("META-INF/maven/archetype-metadata.xml")) {
                        // we assume that this resource will be first in Archetype's ZIP
                        // this way we can find out what are the required properties before we will actually use them
                        parseReplaceProperties(zip, replaceProperties);
                        replaceProperties.putAll(overrideProperties);
                    }
                }
                zip.closeEntry();
            }
        }
    } catch (Exception e) {
        throw new IOException(e.getMessage(), e);
    } finally {
        if (zip != null) {
            zip.close();
        }
    }

    info("Using replace properties: " + replaceProperties);

    // now lets replace all the properties in the pom.xml
    if (!replaceProperties.isEmpty()) {
        File pom = new File(outputDir, "pom.xml");
        FileReader reader = new FileReader(pom);
        String text = IOUtils.toString(reader);
        IOUtils.closeQuietly(reader);
        for (Map.Entry<String, String> e : replaceProperties.entrySet()) {
            text = replaceVariable(text, e.getKey(), e.getValue());
        }
        FileWriter writer = new FileWriter(pom);
        IOUtils.write(text, writer);
        IOUtils.closeQuietly(writer);
    }

    // now lets create the default directories
    if (createDefaultDirectories) {
        File srcDir = new File(outputDir, "src");
        File mainDir = new File(srcDir, "main");
        File testDir = new File(srcDir, "test");

        String srcDirName = "java";
        // Who needs Scala in 2014?
        //            if (new File(mainDir, "scala").exists() || new File(textDir, "scala").exists()) {
        //                srcDirName = "scala";
        //            }

        for (File dir : new File[] { mainDir, testDir }) {
            for (String name : new String[] { srcDirName + "/" + packageDir, "resources" }) {
                new File(dir, name).mkdirs();
            }
        }
    }

    return 0;
}

From source file:org.ejbca.ui.web.admin.certprof.CertProfilesBean.java

public void importProfilesFromZip(byte[] filebuffer) throws CertificateProfileExistsException,
        AuthorizationDeniedException, NumberFormatException, IOException {

    if (filebuffer.length == 0) {
        throw new IllegalArgumentException("No input file");
    }/* w  w w  . j av a2 s . c o m*/

    String importedFiles = "";
    String ignoredFiles = "";
    int nrOfFiles = 0;

    ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(filebuffer));
    ZipEntry ze = zis.getNextEntry();
    if (ze == null) {
        String msg = uploadFile.getName() + " is not a zip file.";
        log.info(msg);
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, null));
        return;
    }

    do {
        nrOfFiles++;
        String filename = ze.getName();
        if (log.isDebugEnabled()) {
            log.debug("Importing file: " + filename);
        }

        if (ignoreFile(filename)) {
            ignoredFiles += filename + ", ";
            continue;
        }

        try {
            filename = URLDecoder.decode(filename, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException("UTF-8 was not a known character encoding", e);
        }
        int index1 = filename.indexOf("_");
        int index2 = filename.lastIndexOf("-");
        int index3 = filename.lastIndexOf(".xml");
        String profilename = filename.substring(index1 + 1, index2);
        int profileid = 0;
        try {
            profileid = Integer.parseInt(filename.substring(index2 + 1, index3));
        } catch (NumberFormatException e) {
            if (log.isDebugEnabled()) {
                log.debug("NumberFormatException parsing certificate profile id: " + e.getMessage());
            }
            ignoredFiles += filename + ", ";
            continue;
        }
        if (log.isDebugEnabled()) {
            log.debug("Extracted profile name '" + profilename + "' and profile ID '" + profileid + "'");
        }

        if (ignoreProfile(filename, profilename, profileid)) {
            ignoredFiles += filename + ", ";
            continue;
        }

        if (getEjbcaWebBean().getEjb().getCertificateProfileSession()
                .getCertificateProfile(profileid) != null) {
            log.warn("Certificate profile id '" + profileid
                    + "' already exist in database. Adding with a new profile id instead.");
            profileid = -1; // means we should create a new id when adding the cert profile
        }

        byte[] filebytes = new byte[102400];
        int i = 0;
        while ((zis.available() == 1) && (i < filebytes.length)) {
            filebytes[i++] = (byte) zis.read();
        }

        final CertificateProfile certificateProfile = getCertProfileFromByteArray(profilename, filebytes);
        if (certificateProfile == null) {
            String msg = "Faulty XML file '" + filename + "'. Failed to read Certificate Profile.";
            log.info(msg + " Ignoring file.");
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, null));
            continue;
        }

        certificateProfile.setAvailableCAs(getEjbcaWebBean().getInformationMemory().getAuthorizedCAIds());
        getEjbcaWebBean().getEjb().getCertificateProfileSession().addCertificateProfile(getAdmin(), profilename,
                certificateProfile);
        getEjbcaWebBean().getInformationMemory().certificateProfilesEdited();
        importedFiles += filename + ", ";
        log.info("Added Certificate profile: " + profilename);
    } while ((ze = zis.getNextEntry()) != null);
    zis.closeEntry();
    zis.close();

    String msg = uploadFile.getName() + " contained " + nrOfFiles + " files. ";
    log.info(msg);
    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, msg, null));

    if (StringUtils.isNotEmpty(importedFiles)) {
        importedFiles = importedFiles.substring(0, importedFiles.length() - 2);
    }
    msg = "Imported Certificate Profiles from files: " + importedFiles;
    if (log.isDebugEnabled()) {
        log.debug(msg);
    }
    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, msg, null));

    if (StringUtils.isNotEmpty(ignoredFiles)) {
        ignoredFiles = ignoredFiles.substring(0, ignoredFiles.length() - 2);
    }
    msg = "Ignored files: " + ignoredFiles;
    if (log.isDebugEnabled()) {
        log.debug(msg);
    }
    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, msg, null));
}

From source file:org.ejbca.ui.web.admin.rainterface.RAInterfaceBean.java

public String importProfilesFromZip(byte[] filebuffer) {
    if (log.isTraceEnabled()) {
        log.trace(">importProfiles(): " + importedProfileName + " - " + filebuffer.length + " bytes");
    }/*from  w ww.j a va2  s.c o m*/

    String retmsg = "";
    String faultXMLmsg = "";

    if (StringUtils.isEmpty(importedProfileName) || filebuffer.length == 0) {
        retmsg = "Error: No input file";
        log.error(retmsg);
        return retmsg;
    }

    int importedFiles = 0;
    int ignoredFiles = 0;
    int nrOfFiles = 0;
    try {
        ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(filebuffer));
        ZipEntry ze = zis.getNextEntry();
        if (ze == null) {
            retmsg = "Error: Expected a zip file. '" + importedProfileName + "' is not a  zip file.";
            log.error(retmsg);
            return retmsg;
        }

        do {
            nrOfFiles++;
            String filename = ze.getName();
            if (log.isDebugEnabled()) {
                log.debug("Importing file: " + filename);
            }

            if (ignoreFile(filename)) {
                ignoredFiles++;
                continue;
            }

            String profilename;
            filename = URLDecoder.decode(filename, "UTF-8");

            int index1 = filename.indexOf("_");
            int index2 = filename.lastIndexOf("-");
            int index3 = filename.lastIndexOf(".xml");
            profilename = filename.substring(index1 + 1, index2);
            int profileid = 0;
            try {
                profileid = Integer.parseInt(filename.substring(index2 + 1, index3));
            } catch (NumberFormatException e) {
                if (log.isDebugEnabled()) {
                    log.debug("NumberFormatException parsing certificate profile id: " + e.getMessage());
                }
                ignoredFiles++;
                continue;
            }
            if (log.isDebugEnabled()) {
                log.debug("Extracted profile name '" + profilename + "' and profile ID '" + profileid + "'");
            }

            if (ignoreProfile(filename, profilename, profileid)) {
                ignoredFiles++;
                continue;
            }

            if (endEntityProfileSession.getEndEntityProfile(profileid) != null) {
                int newprofileid = endEntityProfileSession.findFreeEndEntityProfileId();
                log.warn("Entity profileid '" + profileid + "' already exist in database. Using " + newprofileid
                        + " instead.");
                profileid = newprofileid;
            }

            byte[] filebytes = new byte[102400];
            int i = 0;
            while ((zis.available() == 1) && (i < filebytes.length)) {
                filebytes[i++] = (byte) zis.read();
            }

            EndEntityProfile eprofile = getEEProfileFromByteArray(profilename, filebytes);
            if (eprofile == null) {
                String msg = "Faulty XML file '" + filename + "'. Failed to read End Entity Profile.";
                log.info(msg + " Ignoring file.");
                ignoredFiles++;
                faultXMLmsg += filename + ", ";
                continue;
            }

            profiles.addEndEntityProfile(profilename, eprofile);
            importedFiles++;
            log.info("Added EndEntity profile: " + profilename);

        } while ((ze = zis.getNextEntry()) != null);
        zis.closeEntry();
        zis.close();
    } catch (UnsupportedEncodingException e) {
        retmsg = "Error: UTF-8 was not a known character encoding.";
        log.error(retmsg, e);
        return retmsg;
    } catch (IOException e) {
        log.error(e);
        retmsg = "Error: " + e.getLocalizedMessage();
        return retmsg;
    } catch (AuthorizationDeniedException e) {
        log.error(e);
        retmsg = "Error: " + e.getLocalizedMessage();
        return retmsg;
    } catch (EndEntityProfileExistsException e) {
        log.error(e);
        retmsg = "Error: " + e.getLocalizedMessage();
        return retmsg;
    }

    if (StringUtils.isNotEmpty(faultXMLmsg)) {
        faultXMLmsg = faultXMLmsg.substring(0, faultXMLmsg.length() - 2);
        retmsg = "Faulty XML files: " + faultXMLmsg + ". " + importedFiles + " profiles were imported.";
    } else {
        retmsg = importedProfileName + " contained " + nrOfFiles + " files. " + importedFiles
                + " EndEntity Profiles were imported and " + ignoredFiles + " files  were ignored.";
    }
    log.info(retmsg);

    return retmsg;
}

From source file:freenet.client.ArchiveManager.java

private void handleZIPArchive(ArchiveStoreContext ctx, FreenetURI key, InputStream data, String element,
        ArchiveExtractCallback callback, MutableBoolean gotElement, boolean throwAtExit, ClientContext context)
        throws ArchiveFailureException, ArchiveRestartException {
    if (logMINOR)
        Logger.minor(this, "Handling a ZIP Archive");
    ZipInputStream zis = null;
    try {/*w ww . j  a va 2s  .  c o m*/
        zis = new ZipInputStream(data);

        // MINOR: Assumes the first entry in the zip is a directory.
        ZipEntry entry;

        byte[] buf = new byte[32768];
        HashSet<String> names = new HashSet<String>();
        boolean gotMetadata = false;

        outerZIP: while (true) {
            entry = zis.getNextEntry();
            if (entry == null)
                break;
            if (entry.isDirectory())
                continue;
            String name = stripLeadingSlashes(entry.getName());
            if (names.contains(name)) {
                Logger.error(this, "Duplicate key " + name + " in archive " + key);
                continue;
            }
            long size = entry.getSize();
            if (name.equals(".metadata"))
                gotMetadata = true;
            if (size > maxArchivedFileSize && !name.equals(element)) {
                addErrorElement(ctx, key, name,
                        "File too big: " + maxArchivedFileSize
                                + " greater than current archived file size limit " + maxArchivedFileSize,
                        true);
            } else {
                // Read the element
                long realLen = 0;
                Bucket output = tempBucketFactory.makeBucket(size);
                OutputStream out = output.getOutputStream();
                try {

                    int readBytes;
                    while ((readBytes = zis.read(buf)) > 0) {
                        out.write(buf, 0, readBytes);
                        readBytes += realLen;
                        if (readBytes > maxArchivedFileSize) {
                            addErrorElement(ctx, key, name, "File too big: " + maxArchivedFileSize
                                    + " greater than current archived file size limit " + maxArchivedFileSize,
                                    true);
                            out.close();
                            out = null;
                            output.free();
                            continue outerZIP;
                        }
                    }

                } finally {
                    if (out != null)
                        out.close();
                }
                if (size <= maxArchivedFileSize) {
                    addStoreElement(ctx, key, name, output, gotElement, element, callback, context);
                    names.add(name);
                    trimStoredData();
                } else {
                    // We are here because they asked for this file.
                    callback.gotBucket(output, context);
                    gotElement.value = true;
                    addErrorElement(
                            ctx, key, name, "File too big: " + size
                                    + " greater than current archived file size limit " + maxArchivedFileSize,
                            true);
                }
            }
        }

        // If no metadata, generate some
        if (!gotMetadata) {
            generateMetadata(ctx, key, names, gotElement, element, callback, context);
            trimStoredData();
        }
        if (throwAtExit)
            throw new ArchiveRestartException("Archive changed on re-fetch");

        if ((!gotElement.value) && element != null)
            callback.notInArchive(context);

    } catch (IOException e) {
        throw new ArchiveFailureException("Error reading archive: " + e.getMessage(), e);
    } finally {
        if (zis != null) {
            try {
                zis.close();
            } catch (IOException e) {
                Logger.error(this, "Failed to close stream: " + e, e);
            }
        }
    }
}