Example usage for java.util.zip ZipInputStream closeEntry

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

Introduction

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

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for reading the next entry.

Usage

From source file:org.wso2.carbon.appmgt.hostobjects.ThemeManagerHostObject.java

/**
 * Deploy the uploaded custom theme to the correct custom theme directory. Files with unsupported extensions will be
 * omitted./* w ww . j  a va2  s.  co  m*/
 *
 * @param themeFile      Theme File in zip format
 * @param tenant         Tenant Domain
 * @param themeType      Theme Type (Default ,<assetType> e.g webapp)
 * @param whitelistedExt Whitelisted file extensions
 * @throws AppManagementException
 */
private static void deployCustomTheme(FileHostObject themeFile, String tenant, String themeType,
        Set<String> whitelistedExt) throws AppManagementException {

    if (log.isDebugEnabled()) {
        String msg = String.format("Deploy custom theme of type :%1s for tenant :%2s", themeType, tenant);
        log.debug(msg);
    }

    ZipInputStream zis = null;
    byte[] buffer = new byte[1024];

    //check store theme directory exists

    Path themeDir = getStoreThemePath();
    if (!Files.exists(themeDir)) {
        String msg = "Could not found directory :" + themeDir.toString();
        handleException(msg);
    }

    Path themePath = getCustomThemePath(tenant, themeType);
    InputStream zipInputStream = null;
    try {
        zipInputStream = themeFile.getInputStream();
    } catch (ScriptException e) {
        handleException("Error occurred while deploying custom theme file", e);
    }

    try {
        if (log.isDebugEnabled()) {
            String msg = String.format("Create custom theme dir :%s", themePath);
            log.debug(msg);
        }
        //create output directory if it is not exists
        if (!Files.exists(themePath)) {
            createDirectory(themePath);
        }

        if (log.isDebugEnabled()) {
            String msg = "Get zip file content and deploy";
            log.debug(msg);
        }
        //get the zip file content
        zis = new ZipInputStream(zipInputStream);
        //get the zipped file list entry
        ZipEntry ze = zis.getNextEntry();
        String ext = null;

        while (ze != null) {
            String fileName = ze.getName();
            Path newFilePath = themePath.resolve(fileName);
            if (ze.isDirectory()) {
                if (!Files.exists(newFilePath)) {
                    createDirectory(newFilePath);
                }
            } else {
                ext = FilenameUtils.getExtension(ze.getName());
                if (whitelistedExt.contains(ext)) {
                    //create all non exists folders
                    //else you will hit FileNotFoundException for compressed folder
                    Path parentDir = newFilePath.getParent();
                    if (!Files.exists(parentDir)) {
                        createDirectory(parentDir);
                    }
                    FileOutputStream fos = new FileOutputStream(newFilePath.toFile());

                    int len;
                    while ((len = zis.read(buffer)) > 0) {
                        fos.write(buffer, 0, len);
                    }

                    fos.close();
                } else {
                    String msg = String.format(
                            "Unsupported file is uploaded with custom theme by tenant %1s. File : %2s ", tenant,
                            ze.getName());
                    log.warn(msg);
                }

            }
            ze = zis.getNextEntry();
        }
        zis.closeEntry();
        zis.close();
    } catch (IOException e) {
        handleException("Failed to deploy custom theme", e);
    } finally {
        IOUtils.closeQuietly(zis);
        IOUtils.closeQuietly(zipInputStream);
    }
}

From source file:org.saiku.service.importer.impl.LegacyImporterImpl.java

public void importLegacyReports(@NotNull IRepositoryManager repositoryManager, byte[] file) {

    ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(file));
    //get the zipped file list entry
    ZipEntry ze = null;//from   www.j  a  v  a 2 s  . c  o m
    try {
        ze = zis.getNextEntry();
    } catch (IOException e) {
        e.printStackTrace();
    }
    String strUnzipped = "";
    while (ze != null) {

        /* String fileName = ze.getName();
         File newFile = new File(fileName);
                
         System.out.println("file unzip : "+ newFile.getAbsoluteFile());
                
         byte[] bytes= new byte[2048];
         try {
        zis.read(bytes, 0, 2048);
         } catch (IOException e) {
        e.printStackTrace();
         }
         try {
        strUnzipped= new String( bytes, "UTF-8" );
         } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
         }*/
        String fileName = ze.getName();
        int size;
        byte[] buffer = new byte[2048];

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
                bos.write(buffer, 0, size);
            }
            bos.flush();
            bos.close();
            strUnzipped = new String(bos.toByteArray(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            repositoryManager.saveInternalFile(strUnzipped, "/etc/legacyreports/" + fileName, "nt:saikufiles");
        } catch (RepositoryException e) {
            e.printStackTrace();
        }

        try {
            ze = zis.getNextEntry();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    try {
        zis.closeEntry();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        zis.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.wso2.carbon.wsdl2code.ui.fileupload.WSDL2CodeFileUploadExecutor.java

public boolean execute(HttpServletRequest request, HttpServletResponse response)
        throws CarbonException, IOException {
    PrintWriter out = response.getWriter();
    try {/*from ww  w  . j  a  v  a 2  s  .com*/
        List<FileItemData> fileItemDataList = getAllFileItems();
        String filePaths = "";

        //todo why several fileItemData objects for wsdl2code
        for (FileItemData fileItemData : fileItemDataList) {

            FileItem fileItem = fileItemData.getFileItem();
            String fileName = getFileName(fileItem.getName());
            checkServiceFileExtensionValidity(fileName, ALLOWED_FILE_EXTENSIONS);

            //for plain text WSDL files
            if (fileName.endsWith(".wsdl") || fileName.endsWith(".xml")) {

                String uuid = String.valueOf(System.currentTimeMillis() + Math.random());
                String serviceUploadDir = configurationContext.getProperty(ServerConstants.WORK_DIR)
                        + File.separator + "extra" + File.separator + uuid + File.separator;
                File dir = new File(serviceUploadDir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File uploadedFile = new File(dir, uuid + ".xml");
                FileOutputStream fileOutStream = new FileOutputStream(uploadedFile);
                fileItemData.getDataHandler().writeTo(fileOutStream);
                fileOutStream.flush();
                fileOutStream.close();
                response.setContentType("text/plain; charset=utf-8");

                String outPath = File.separator + "extra" + File.separator
                        + uploadedFile.getAbsolutePath().split(File.separator + "tmp" + File.separator + "work"
                                + File.separator + "extra" + File.separator)[1];

                filePaths = filePaths + outPath + ",";

                filePaths = filePaths.substring(0, filePaths.length() - 1);
                out.write(filePaths);
                out.flush();
            } else if (fileName.endsWith(".zip")) {
                ZipInputStream zipInputStream = null;
                try {
                    zipInputStream = new ZipInputStream(fileItemData.getFileItem().getInputStream());
                    String serviceUploadDir = configurationContext.getProperty(ServerConstants.WORK_DIR)
                            + File.separator + "extra" + File.separator;

                    String uuidDir = String.valueOf(System.currentTimeMillis() + Math.random());

                    String zipPath = serviceUploadDir + uuidDir;
                    new File(zipPath).mkdir();

                    ZipEntry ze;
                    while ((ze = zipInputStream.getNextEntry()) != null) {
                        File destinationFilePath = new File(zipPath, ze.getName());
                        //create directories if required.
                        destinationFilePath.getParentFile().mkdirs();

                        if (!ze.isDirectory()) {
                            String uuid;
                            if (ze.getName().endsWith(".wsdl")) {
                                uuid = String.valueOf(System.currentTimeMillis() + Math.random());
                                destinationFilePath = new File(
                                        destinationFilePath.getParent() + File.separator + uuid + ".xml");
                                response.setContentType("text/plain; charset=utf-8");
                                String outPath = File.separator + "extra" + File.separator
                                        + destinationFilePath.getAbsolutePath()
                                                .split(File.separator + "tmp" + File.separator + "work"
                                                        + File.separator + "extra" + File.separator)[1];

                                filePaths = filePaths + outPath + ",";
                            }

                            copyInputStream(zipInputStream,
                                    new BufferedOutputStream(new FileOutputStream(destinationFilePath)));
                            zipInputStream.closeEntry();

                        }
                    }
                } catch (IOException e) {
                    throw new Exception(e);
                } finally {
                    if (zipInputStream != null) {
                        zipInputStream.close();
                    }
                }

                if (filePaths.length() != 0) {
                    filePaths = filePaths.substring(0, filePaths.length() - 1);
                    out.write(filePaths);
                } else {
                    throw new Exception("No WSDL found in the provided archive " + fileName);
                }
                out.flush();
            }
            log.info("File Successfully Uploaded " + fileName);
        }
    } catch (Exception e) {
        log.error("File upload FAILED", e);
        out.write("<script type=\"text/javascript\">"
                + "top.wso2.wsf.Util.alertWarning('File upload FAILED. File may be non-existent or invalid.');"
                + "</script>");
    } finally {
        out.close();
    }
    return true;
}

From source file:de.xirp.plugin.PluginManager.java

/**
 * Extracts files from the plugins jar./*from   w  w w  .ja  v  a  2  s.c o  m*/
 * 
 * @param info
 *            the information about the plugin
 * @param destination
 *            destination for extraction
 * @param comparer
 *            comparer which returns <code>0</code> if an
 *            element from the jar should be extracted
 * @param replace
 *            string of the elements path which should be deleted
 * @param deleteOnExit
 *            <code>true</code> if the extracted files should be
 *            deleted on exit of the application.
 * @return <code>false</code> if an error occurred while
 *         extraction
 */
private static boolean extractFromJar(PluginInfo info, String destination, Comparable<String> comparer,
        String replace, boolean deleteOnExit) {
    if (logClass.isTraceEnabled()) {
        logClass.trace(Constants.LINE_SEPARATOR + "Extracting for Plugin: " + info.getDefaultName() //$NON-NLS-1$
                + " to path " + destination + Constants.LINE_SEPARATOR); //$NON-NLS-1$
    }
    ZipInputStream zip = null;
    FileInputStream in = null;
    try {
        in = new FileInputStream(info.getAbsoluteJarPath());
        zip = new ZipInputStream(in);

        ZipEntry entry = null;
        while ((entry = zip.getNextEntry()) != null) {
            // relative name with slashes to separate dirnames.
            String elementName = entry.getName();
            // Check if it's an entry within Plugin Dir.
            // Only need to extract these

            if (comparer.compareTo(elementName) == 0) {
                // Remove Help Dir Name, because we don't like
                // to extract this parent dir
                elementName = elementName.replaceFirst(replace + JAR_SEPARATOR, "").trim(); //$NON-NLS-1$ 

                if (!elementName.equalsIgnoreCase("")) { //$NON-NLS-1$
                    // if parent dir for File does not exist,
                    // create
                    // it
                    File elementFile = new File(destination, elementName);
                    if (!elementFile.exists()) {
                        elementFile.getParentFile().mkdirs();
                        if (deleteOnExit) {
                            DeleteManager.deleteOnShutdown(elementFile);
                        }
                    }

                    // Only extract files, directorys are created
                    // above with mkdirs
                    if (!entry.isDirectory()) {
                        FileOutputStream fos = new FileOutputStream(elementFile);
                        byte[] buf = new byte[1024];
                        int len;
                        while ((len = zip.read(buf)) > 0) {
                            fos.write(buf, 0, len);
                        }
                        fos.close();
                        elementFile.setLastModified(entry.getTime());
                    }
                    logClass.trace("Extracted: " + elementName + Constants.LINE_SEPARATOR); //$NON-NLS-1$
                }
            }
            zip.closeEntry();
        }

    } catch (IOException e) {
        logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
        return false;
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (IOException e) {
                logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
            }
        }
    }

    return true;
}

From source file:it.doqui.index.ecmengine.business.personalization.importer.ArchiveImporterJob.java

/**
 * Estrae il contenuto di un archivio in formato ZIP.
 *
 * @param archiveInputStream L'input stream da cui leggere il contenuto dell'archivio.
 * @param path Il path della directory in cui estrarre il contenuto dell'archivio.
 *
 * @throws Exception/*ww w .j a  v  a 2 s  .  c  om*/
 */
// TODO: verificare come mai se il file non e' ZIP non va in errore
private void extractZip(InputStream archiveInputStream, String path) throws Exception {
    logger.debug("[ArchiveImporterJob::extractZip] BEGIN");
    ZipInputStream inputStream = null;
    FileOutputStream fileOutputStream = null;
    try {
        inputStream = new ZipInputStream(archiveInputStream);
        String entryName = null;
        byte[] buffer = new byte[1024];
        int n = 0;
        for (ZipEntry entry = inputStream.getNextEntry(); entry != null; entry = inputStream.getNextEntry()) {
            entryName = entry.getName();
            File entryFile = new File(path + File.separator + entryName);
            if (entry.isDirectory()) {
                if (!entryFile.mkdirs()) {
                    throw new EcmEngineException("cannot create directory: " + entryFile.getAbsolutePath());
                }
            } else {
                File parentDir = entryFile.getParentFile();
                if (!parentDir.exists()) {
                    if (!parentDir.mkdirs()) {
                        throw new EcmEngineException("cannot create directory: " + parentDir.getAbsolutePath());
                    }
                }
                fileOutputStream = new FileOutputStream(entryFile);
                while ((n = inputStream.read(buffer, 0, buffer.length)) > -1) {
                    fileOutputStream.write(buffer, 0, n);
                }
                fileOutputStream.close();
            }
            inputStream.closeEntry();
        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (Exception e) {
            }
            try {
                fileOutputStream.close();
            } catch (Exception e) {
            }
        }
        logger.debug("[ArchiveImporterJob::extractZip] END");
    }
}

From source file:org.eclipse.skalli.core.rest.admin.ProjectBackupResource.java

@Put
public Representation restore(Representation entity) {
    if (!Permits.isAllowed(getAction(), getPath())) {
        return createUnauthorizedRepresentation();
    }//from  w w  w. j  a v a  2 s. c o  m

    StorageService storageService = getStorageService();
    if (storageService == null) {
        return createServiceUnavailableRepresentation(ERROR_ID_NO_STORAGE_SERVICE, "Storage Service");
    }

    String action = getQuery().getValues(ACTION_PARAM);
    Set<String> included = getCategories(INCLUDE_PARAM);
    Set<String> excluded = getCategories(EXCLUDE_PARAM);

    Set<String> accepted = new HashSet<String>();
    Set<String> rejected = new HashSet<String>();
    for (String category : CATEGORIES) {
        if (included.size() > 0 && !included.contains(category)) {
            continue;
        }
        if (excluded.size() > 0 && excluded.contains(category)) {
            continue;
        }
        try {
            if (ACTION_OVERWRITE.equals(action) || storageService.keys(category).isEmpty()) {
                accepted.add(category);
            } else {
                rejected.add(category);
            }
        } catch (StorageException e) {
            LOG.error(MessageFormat.format("Failed to retrieve keys for category {0} ({1})", category,
                    ERROR_ID_FAILED_TO_RETRIEVE_KEYS), e);
            return createErrorRepresentation(Status.SERVER_ERROR_INTERNAL, ERROR_ID_FAILED_TO_RETRIEVE_KEYS,
                    "Failed to store the attached backup resource");
        }
    }
    if (rejected.size() > 0) {
        return createErrorRepresentation(Status.CLIENT_ERROR_PRECONDITION_FAILED,
                ERROR_ID_OVERWRITE_EXISTING_DATA,
                MessageFormat.format(
                        "Restore might overwrite existing project data in the folling categories:\n{0}\n"
                                + "Either exclude these categories from the restore with a \"exclude=<comma-separated-list>\" "
                                + "parameter or enforce the restore with \"action=overwrite\".",
                        CollectionUtils.toString(rejected, '\n')));
    }
    if (accepted.isEmpty()) {
        setStatus(Status.SUCCESS_NO_CONTENT);
        return null;
    }

    ZipInputStream zipStream = null;
    try {
        zipStream = new ZipInputStream(entity.getStream());
        ZipEntry entry = zipStream.getNextEntry();
        while (entry != null) {
            try {
                if (!entry.isDirectory()) {
                    String entryName = entry.getName().replace('\\', '/');
                    String[] parts = StringUtils.split(entryName, '/');
                    if (parts.length != 2) {
                        LOG.info(MessageFormat.format("Restore: {0} is not recognized as entity key",
                                entryName));
                        continue;
                    }
                    // ensure that the category of the entry, i.e. the directory name,
                    // is in the set of accepted categories
                    String category = parts[0];
                    String key = parts[1];
                    if (accepted.contains(category)) {
                        if (key.endsWith(".xml")) { //$NON-NLS-1$
                            key = key.substring(0, key.length() - 4);
                        }
                        try {
                            storageService.write(category, key, zipStream);
                        } catch (StorageException e) {
                            LOG.error(MessageFormat.format(
                                    "Failed to store entity with key {0} and category {1} ({2})", key, category,
                                    ERROR_ID_FAILED_TO_STORE), e);
                            return createErrorRepresentation(Status.SERVER_ERROR_INTERNAL,
                                    ERROR_ID_FAILED_TO_STORE, "Failed to store the attached backup");
                        }
                    } else {
                        LOG.info(MessageFormat.format("Restore: Excluded {0} (category ''{1}'' not accepted)",
                                key, category));
                    }
                }
            } finally {
                zipStream.closeEntry();
                entry = zipStream.getNextEntry();
            }
        }
    } catch (IOException e) {
        return createIOErrorRepresentation(ERROR_ID_IO_ERROR, e);
    } finally {
        IOUtils.closeQuietly(zipStream);
    }

    // ensure that the persistence service attached to the storage
    // refreshes all caches and reloads all entities
    PersistenceService persistenceService = Services.getService(PersistenceService.class);
    if (persistenceService != null) {
        persistenceService.refreshAll();
    }
    setStatus(Status.SUCCESS_NO_CONTENT);
    return null;
}

From source file:fr.vdl.android.holocolors.HoloColorsDialog.java

private void unzipFile(File zipFile) throws Exception {
    File outputFolder = new File(resPathTextField.getText());

    boolean overwriteAll = false;
    boolean overwriteNone = false;
    Object[] overwriteOptions = { "Overwrite this file", "Overwrite all", "Do not overwrite this file",
            "Do not overwrite any file" };

    ZipInputStream zis = null;
    byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
    try {// w w  w .  ja  v  a2s  . co m
        zis = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry ze = zis.getNextEntry();
        while (ze != null) {
            String fileName = ze.getName().replaceFirst("res/", "");
            File newFile = new File(outputFolder + File.separator + fileName);

            new File(newFile.getParent()).mkdirs();

            boolean overwrite = overwriteAll || (!newFile.exists());
            if (newFile.exists() && newFile.isFile() && !overwriteAll && !overwriteNone) {
                int option = JOptionPane.showOptionDialog(ahcPanel,
                        newFile.getName() + " already exists, overwrite ?", "File exists",
                        JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
                        new ImageIcon(getClass().getResource("/icons/H64.png")), overwriteOptions,
                        overwriteOptions[0]);

                switch (option) {
                case 0:
                    overwrite = true;
                    break;
                case 1:
                    overwrite = true;
                    overwriteAll = true;
                    break;
                case 2:
                    overwrite = false;
                    break;
                case 3:
                    overwrite = false;
                    overwriteNone = true;
                    break;
                default:
                    overwrite = false;
                }
            }

            if (overwrite && !fileName.endsWith(File.separator)) {
                FileOutputStream fos = new FileOutputStream(newFile);
                int len;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
                fos.close();
            }
            ze = zis.getNextEntry();
        }

        zis.closeEntry();
        zis.close();
    } finally {
        if (zis != null) {
            try {
                zis.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:org.eclipse.kura.web.server.servlet.FileServlet.java

private void doPostCommand(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    UploadRequest upload = new UploadRequest(this.m_diskFileItemFactory);

    try {//from w  w  w .java2 s .com
        upload.parse(req);
    } catch (FileUploadException e) {
        s_logger.error("Error parsing the file upload request");
        throw new ServletException("Error parsing the file upload request", e);
    }

    // BEGIN XSRF - Servlet dependent code
    Map<String, String> formFields = upload.getFormFields();

    try {
        GwtXSRFToken token = new GwtXSRFToken(formFields.get("xsrfToken"));
        KuraRemoteServiceServlet.checkXSRFToken(req, token);
    } catch (Exception e) {
        throw new ServletException("Security error: please retry this operation correctly.", e);
    }
    // END XSRF security check

    List<FileItem> fileItems = null;
    InputStream is = null;
    File localFolder = new File(System.getProperty("java.io.tmpdir"));
    OutputStream os = null;

    try {
        fileItems = upload.getFileItems();

        if (fileItems.size() > 0) {
            FileItem item = fileItems.get(0);
            is = item.getInputStream();

            byte[] bytes = IOUtils.toByteArray(is);
            ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(bytes));

            int entries = 0;
            long total = 0;
            ZipEntry ze = zis.getNextEntry();
            while (ze != null) {
                byte[] buffer = new byte[BUFFER];

                String expectedFilePath = new StringBuilder(localFolder.getPath()).append(File.separator)
                        .append(ze.getName()).toString();
                String fileName = validateFileName(expectedFilePath, localFolder.getPath());
                File newFile = new File(fileName);
                if (newFile.isDirectory()) {
                    newFile.mkdirs();
                    ze = zis.getNextEntry();
                    continue;
                }
                if (newFile.getParent() != null) {
                    File parent = new File(newFile.getParent());
                    parent.mkdirs();
                }

                FileOutputStream fos = new FileOutputStream(newFile);
                int len;
                while (total + BUFFER <= tooBig && (len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                    total += len;
                }
                fos.flush();
                fos.close();

                entries++;
                if (entries > tooMany) {
                    throw new IllegalStateException("Too many files to unzip.");
                }
                if (total > tooBig) {
                    throw new IllegalStateException("File being unzipped is too big.");
                }

                ze = zis.getNextEntry();
            }

            zis.closeEntry();
            zis.close();
        }
    } catch (IOException e) {
        throw e;
    } catch (GwtKuraException e) {
        throw new ServletException("File is outside extraction target directory.");
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                s_logger.warn("Cannot close output stream", e);
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                s_logger.warn("Cannot close input stream", e);
            }
        }
        if (fileItems != null) {
            for (FileItem fileItem : fileItems) {
                fileItem.delete();
            }
        }
    }
}

From source file:org.openbravo.erpCommon.modules.ImportModule.java

/**
 * Returns all the modules and dependencies described within the obx file (as InputStream)
 * //from  www.ja  v a  2  s .  co  m
 * Used to check dependencies in local installation
 * 
 * @param dModulesToInstall
 * @param dDependencies
 * @param obx
 * @param merges
 *          (output param) It contains all the merges defines in the obx as
 *          (MergedModuleId,MergedBy)
 * @throws Exception
 */
private void getModulesFromObx(Vector<DynaBean> dModulesToInstall, Vector<DynaBean> dDependencies,
        Vector<DynaBean> dDBprefix, InputStream obx, Map<String, String> merges) throws Exception {
    final ZipInputStream obxInputStream = new ZipInputStream(obx);
    ZipEntry entry = null;
    boolean foundAll = false;
    boolean foundModule = false;
    boolean foundDependency = false;
    boolean foundPrefix = false;
    boolean foundMerge = false;
    while (((entry = obxInputStream.getNextEntry()) != null) && !foundAll) {

        if (entry.getName().endsWith(".obx")) {
            // If it is a new module, install it
            final ByteArrayInputStream ba = getCurrentEntryStream(obxInputStream);
            obxInputStream.closeEntry();
            getModulesFromObx(dModulesToInstall, dDependencies, dDBprefix, ba, merges);
        } else if (entry.getName().replace("\\", "/").endsWith("src-db/database/sourcedata/AD_MODULE.xml")) {
            final Vector<DynaBean> module = getEntryDynaBeans(getBytesCurrentEntryStream(obxInputStream));
            boolean isPackage = false;
            if (module != null && module.size() > 0) {
                isPackage = !((String) module.get(0).get("TYPE")).equals("M");
            }
            dModulesToInstall.addAll(module);
            obxInputStream.closeEntry();
            foundModule = true && !isPackage;
        } else if (entry.getName().replace("\\", "/")
                .endsWith("src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml")) {
            dDependencies.addAll(getEntryDynaBeans(getBytesCurrentEntryStream(obxInputStream)));
            obxInputStream.closeEntry();
            foundDependency = true;
        } else if (entry.getName().replace("\\", "/")
                .endsWith("src-db/database/sourcedata/AD_MODULE_DBPREFIX.xml")) {
            dDBprefix.addAll(getEntryDynaBeans(getBytesCurrentEntryStream(obxInputStream)));
            obxInputStream.closeEntry();
            foundPrefix = true;
        } else if (entry.getName().replace("\\", "/")
                .endsWith("/src-db/database/sourcedata/AD_MODULE_MERGE.xml")) {
            Vector<DynaBean> dynMerges = getEntryDynaBeans(getBytesCurrentEntryStream(obxInputStream));
            for (DynaBean merge : dynMerges) {
                merges.put((String) merge.get("MERGED_MODULE_UUID"), (String) merge.get("AD_MODULE_ID"));
            }
            obxInputStream.closeEntry();
            foundMerge = true;
        } else {
            obxInputStream.closeEntry();
        }
        foundAll = foundModule && foundDependency && foundPrefix && foundMerge;
    }
    obxInputStream.close();
}

From source file:org.wso2.carbon.governance.platform.extensions.handlers.RESTZipWSDLMediaTypeHandler.java

public void put(RequestContext requestContext) throws RegistryException {
    if (!CommonUtil.isUpdateLockAvailable()) {
        return;/*www.j  a  v  a2 s  . c o m*/
    }
    CommonUtil.acquireUpdateLock();
    try {
        Resource resource = requestContext.getResource();
        String path = requestContext.getResourcePath().getPath();
        try {
            if (resource != null) {
                Object resourceContent = resource.getContent();
                InputStream in = new ByteArrayInputStream((byte[]) resourceContent);
                Stack<File> fileList = new Stack<File>();
                List<String> uriList = new LinkedList<String>();
                List<UploadTask> tasks = new LinkedList<UploadTask>();

                int threadPoolSize = this.threadPoolSize;

                int wsdlPathDepth = Integer.MAX_VALUE;
                int xsdPathDepth = Integer.MAX_VALUE;
                File tempFile = File.createTempFile(tempFilePrefix, archiveExtension);
                File tempDir = new File(tempFile.getAbsolutePath().substring(0,
                        tempFile.getAbsolutePath().length() - archiveExtension.length()));
                try {
                    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile));
                    try {
                        byte[] contentChunk = new byte[1024];
                        int byteCount;
                        while ((byteCount = in.read(contentChunk)) != -1) {
                            out.write(contentChunk, 0, byteCount);
                        }
                        out.flush();
                    } finally {
                        out.close();
                    }
                    ZipEntry entry;

                    makeDir(tempDir);
                    ZipInputStream zs;
                    List<String> wsdlUriList = new LinkedList<String>();
                    List<String> xsdUriList = new LinkedList<String>();
                    zs = new ZipInputStream(new FileInputStream(tempFile));
                    try {
                        entry = zs.getNextEntry();
                        while (entry != null) {
                            String entryName = entry.getName();
                            FileOutputStream os;
                            File file = new File(tempFile.getAbsolutePath().substring(0,
                                    tempFile.getAbsolutePath().length() - archiveExtension.length())
                                    + File.separator + entryName);
                            if (entry.isDirectory()) {
                                if (!file.exists()) {
                                    makeDirs(file);
                                    fileList.push(file);
                                }
                                entry = zs.getNextEntry();
                                continue;
                            }
                            File parentFile = file.getParentFile();
                            if (!parentFile.exists()) {
                                makeDirs(parentFile);
                            }
                            os = new FileOutputStream(file);
                            try {
                                fileList.push(file);
                                byte[] contentChunk = new byte[1024];
                                int byteCount;
                                while ((byteCount = zs.read(contentChunk)) != -1) {
                                    os.write(contentChunk, 0, byteCount);
                                }
                            } finally {
                                os.close();
                            }
                            zs.closeEntry();
                            entry = zs.getNextEntry();
                            if (entryName != null && entryName.toLowerCase().endsWith(wsdlExtension)) {
                                String uri = tempFile.toURI().toString();
                                uri = uri.substring(0, uri.length() - archiveExtension.length()) + "/"
                                        + entryName;
                                if (uri.startsWith("file:")) {
                                    uri = uri.substring(5);
                                }
                                while (uri.startsWith("/")) {
                                    uri = uri.substring(1);
                                }
                                uri = "file:///" + uri;
                                if (uri.endsWith("/")) {
                                    uri = uri.substring(0, uri.length() - 1);
                                }
                                int uriPathDepth = uri.split("/").length;
                                if (uriPathDepth < wsdlPathDepth) {
                                    wsdlPathDepth = uriPathDepth;
                                    wsdlUriList = new LinkedList<String>();
                                }
                                if (wsdlPathDepth == uriPathDepth) {
                                    wsdlUriList.add(uri);
                                }
                            } else if (entryName != null && entryName.toLowerCase().endsWith(xsdExtension)) {
                                String uri = tempFile.toURI().toString();
                                uri = uri.substring(0, uri.length() - archiveExtension.length()) + "/"
                                        + entryName;
                                if (uri.startsWith("file:")) {
                                    uri = uri.substring(5);
                                }
                                while (uri.startsWith("/")) {
                                    uri = uri.substring(1);
                                }
                                uri = "file:///" + uri;
                                if (uri.endsWith("/")) {
                                    uri = uri.substring(0, uri.length() - 1);
                                }
                                int uriPathDepth = uri.split("/").length;
                                if (uriPathDepth < xsdPathDepth) {
                                    xsdPathDepth = uriPathDepth;
                                    xsdUriList = new LinkedList<String>();
                                }
                                if (xsdPathDepth == uriPathDepth) {
                                    xsdUriList.add(uri);
                                }
                            } else if (entryName != null) {
                                String uri = tempFile.toURI().toString();
                                uri = uri.substring(0, uri.length() - archiveExtension.length()) + "/"
                                        + entryName;
                                if (uri.startsWith("file:")) {
                                    uri = uri.substring(5);
                                }
                                while (uri.startsWith("/")) {
                                    uri = uri.substring(1);
                                }
                                uri = "file:///" + uri;
                                if (uri.endsWith("/")) {
                                    uri = uri.substring(0, uri.length() - 1);
                                }
                                uriList.add(uri);
                            }
                        }
                    } finally {
                        zs.close();
                    }
                    Map<String, String> localPathMap = null;
                    if (CurrentSession.getLocalPathMap() != null) {
                        localPathMap = Collections.unmodifiableMap(CurrentSession.getLocalPathMap());
                    }
                    if (wsdlUriList.isEmpty() && xsdUriList.isEmpty()) {
                        throw new RegistryException("No WSDLs or Schemas found in the given WSDL archive");
                    }
                    if (wsdlPathDepth < Integer.MAX_VALUE) {
                        for (String uri : wsdlUriList) {
                            tasks.add(new UploadWSDLTask(requestContext, uri, CurrentSession.getTenantId(),
                                    CurrentSession.getUserRegistry(), CurrentSession.getUserRealm(),
                                    CurrentSession.getUser(), CurrentSession.getCallerTenantId(),
                                    localPathMap));
                        }
                    }
                    if (xsdPathDepth < Integer.MAX_VALUE) {
                        for (String uri : xsdUriList) {
                            tasks.add(new UploadXSDTask(requestContext, uri, CurrentSession.getTenantId(),
                                    CurrentSession.getUserRegistry(), CurrentSession.getUserRealm(),
                                    CurrentSession.getUser(), CurrentSession.getCallerTenantId(),
                                    localPathMap));
                        }
                    }

                    for (String uri : uriList) {
                        if (uri.endsWith(restExtension)) {
                            tasks.add(new UploadRESTModelTask(requestContext, uri, CurrentSession.getTenantId(),
                                    CurrentSession.getUserRegistry(), CurrentSession.getUserRealm(),
                                    CurrentSession.getUser(), CurrentSession.getCallerTenantId(),
                                    localPathMap));
                        }
                    }

                    // calculate thread pool size for efficient use of resources in concurrent
                    // update scenarios.
                    int toAdd = wsdlUriList.size() + xsdUriList.size();
                    if (toAdd < threadPoolSize) {
                        if (toAdd < (threadPoolSize / 8)) {
                            threadPoolSize = 0;
                        } else if (toAdd < (threadPoolSize / 2)) {
                            threadPoolSize = (threadPoolSize / 8);
                        } else {
                            threadPoolSize = (threadPoolSize / 4);
                        }
                    }
                } finally {
                    in.close();
                    resourceContent = null;
                    resource.setContent(null);
                }
                uploadFiles(tasks, tempFile, fileList, tempDir, threadPoolSize, path, uriList, requestContext);
            }
        } catch (IOException e) {
            throw new RegistryException("Error occurred while unpacking Governance Archive", e);
        }

        requestContext.setProcessingComplete(true);
    } finally {
        CommonUtil.releaseUpdateLock();
    }
}