Example usage for java.util.zip ZipInputStream read

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

Introduction

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

Prototype

public int read(byte[] b, int off, int len) throws IOException 

Source Link

Document

Reads from the current ZIP entry into an array of bytes.

Usage

From source file:org.candlepin.sync.ExporterTest.java

/**
 * return true if export has a given entry named name.
 * @param export zip file to inspect// www .j ava  2 s . c o  m
 * @param name entry
 * @return
 */
private boolean verifyHasEntry(File export, String name) {
    ZipInputStream zis = null;
    boolean found = false;

    try {
        zis = new ZipInputStream(new FileInputStream(export));
        ZipEntry entry = null;

        while ((entry = zis.getNextEntry()) != null) {
            byte[] buf = new byte[1024];

            if (entry.getName().equals("consumer_export.zip")) {
                OutputStream os = new FileOutputStream("/tmp/consumer_export.zip");

                int n;
                while ((n = zis.read(buf, 0, 1024)) > -1) {
                    os.write(buf, 0, n);
                }
                os.flush();
                os.close();
                File exportdata = new File("/tmp/consumer_export.zip");
                // open up the zip and look for the metadata
                verifyHasEntry(exportdata, name);
            } else if (entry.getName().equals(name)) {
                found = true;
            }

            zis.closeEntry();
        }

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

    return found;
}

From source file:com.aurel.track.exchange.track.importer.TrackImportAction.java

/**
 * Render the import page/*from  ww  w.j av a2  s .co m*/
 */
@Override

/**
 * Save the zip file and import the data 
 * @return
 */
public String execute() {
    LOGGER.info("Import started");
    InputStream inputStream;
    try {
        inputStream = new FileInputStream(uploadFile);
    } catch (FileNotFoundException e) {
        LOGGER.error("Getting the input stream for the zip failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        JSONUtility.encodeJSON(servletResponse,
                JSONUtility.encodeJSONFailure(getText("admin.actions.importTp.err.failed")));
        return null;
    }

    /**
     * delete the old temporary attachment directory if exists from previous imports 
     */
    String tempAttachmentDirectory = AttachBL.getAttachDirBase() + File.separator + AttachBL.tmpAttachments;
    AttachBL.deleteDirectory(new File(tempAttachmentDirectory));

    /**
     * extract the zip to a temporary directory
     */
    ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream));
    final int BUFFER = 2048;
    File unzipTempDirectory = new File(tempAttachmentDirectory);
    if (!unzipTempDirectory.exists()) {
        unzipTempDirectory.mkdirs();
    }
    BufferedOutputStream dest = null;
    ZipEntry zipEntry;
    try {
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            File destFile = new File(unzipTempDirectory, zipEntry.getName());
            // grab file's parent directory structure         
            int count;
            byte data[] = new byte[BUFFER];
            // write the files to the disk
            FileOutputStream fos = new FileOutputStream(destFile);
            dest = new BufferedOutputStream(fos, BUFFER);
            while ((count = zipInputStream.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, count);
            }
            dest.flush();
            dest.close();
        }
        zipInputStream.close();
    } catch (Exception e) {
        LOGGER.error("Extracting the zip to the temporary directory failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        JSONUtility.encodeJSON(servletResponse,
                JSONUtility.encodeJSONFailure(getText("admin.actions.importTp.err.failed")), false);
        return null;
    }

    /**
     * get the data file (the only file from the zip which is not an attachment)  
     */
    File importDataFile = new File(tempAttachmentDirectory, ExchangeFieldNames.EXCHANGE_ZIP_ENTRY);
    if (!importDataFile.exists()) {
        LOGGER.error("The file " + ExchangeFieldNames.EXCHANGE_ZIP_ENTRY + " not found in the zip");
        JSONUtility.encodeJSON(servletResponse,
                JSONUtility.encodeJSONFailure(getText("admin.actions.importTp.err.failed")), false);
        return null;
    }

    /**
     * field parser
     */
    LOGGER.debug("Parsing the fields");
    List<ISerializableLabelBean> customFieldsBeans = new ImporterFieldParser().parse(importDataFile);
    Map<Integer, Integer> fieldsMatcherMap = null;
    try {
        fieldsMatcherMap = TrackImportBL.getFieldMatchMap(customFieldsBeans);
    } catch (ImportExceptionList importExceptionList) {
        LOGGER.error("Getting the field match map failed ");
        JSONUtility.encodeJSON(servletResponse,
                ImportJSON.importErrorMessageListJSON(
                        ErrorHandlerJSONAdapter.handleErrorList(importExceptionList.getErrorDataList(), locale),
                        null, true));
        return null;
    }

    /**
     * dropdown parser
     */
    LOGGER.debug("Parsing the external dropdowns");
    SortedMap<String, List<ISerializableLabelBean>> externalDropdowns = new ImporterDropdownParser()
            .parse(importDataFile, fieldsMatcherMap);

    /**
     * data parser
     */
    LOGGER.debug("Parsing the items");
    List<ExchangeWorkItem> externalReportBeansList = new ImporterDataParser().parse(importDataFile,
            fieldsMatcherMap);
    try {
        LOGGER.debug("Importing the items");
        ImportCounts importCounts = TrackImportBL.importWorkItems(externalReportBeansList, externalDropdowns,
                fieldsMatcherMap, personID, locale);
        LOGGER.debug("Imported " + importCounts.getNoOfCreatedIssues() + " new issues " + " modified "
                + importCounts.getNoOfUpdatedIssues());
        JSONUtility.encodeJSON(servletResponse,
                ImportJSON.importMessageJSON(true,
                        getText("admin.actions.importTp.lbl.result",
                                new String[] { Integer.valueOf(importCounts.getNoOfCreatedIssues()).toString(),
                                        Integer.valueOf(importCounts.getNoOfUpdatedIssues()).toString() }),
                        true, locale),
                false);
    } catch (ImportExceptionList importExceptionList) {
        JSONUtility.encodeJSON(servletResponse,
                ImportJSON.importErrorMessageListJSON(
                        ErrorHandlerJSONAdapter.handleErrorList(importExceptionList.getErrorDataList(), locale),
                        null, true),
                false);
        return null;
    } catch (ImportException importException) {
        JSONUtility.encodeJSON(servletResponse,
                ImportJSON.importMessageJSON(false, getText(importException.getMessage()), true, locale),
                false);
        return null;
    } catch (Exception e) {
        JSONUtility.encodeJSON(servletResponse,
                ImportJSON.importMessageJSON(false, getText("admin.actions.importTp.err.failed"), true, locale),
                false);
        return null;
    }
    LOGGER.info("Import done");
    return null;
}

From source file:sloca.json.update.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w w  w. j  a  va  2  s .c  o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/JSON");
    PrintWriter out = response.getWriter();
    //creates a new gson object
    //by instantiating a new factory object, set pretty printing, then calling the create method
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    //creats a new json object for printing the desired json output
    ArrayList<String> errList = new ArrayList<String>();
    JsonArray errMsg = new JsonArray();

    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Set factory constraints
    // factory.setSizeThreshold(yourMaxMemorySize);
    // factory.setRepository(yourTempDirectory);
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // upload.setSizeMax(yourMaxRequestSize);
    ServletContext servletContext = this.getServletConfig().getServletContext();
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    // Parse the request
    List<FileItem> uploadItems = null;
    try {
        uploadItems = upload.parseRequest(request);
    } catch (FileUploadException ex) {
        errList.add("invalid file");
    }
    String value = "";
    for (FileItem uploadItem : uploadItems) {
        if (uploadItem.isFormField()) {
            String fieldName = uploadItem.getFieldName();
            value = uploadItem.getString();
        }
    }
    JsonObject jsonOutput = new JsonObject();
    //validate token
    if (value == null) {

        errList.add("missing token");
    } else if (value.isEmpty()) {

        errList.add("blank token");
    } else {
        try {
            JWTUtility.verify(value, SharedSecretManager.getSharedSecretKeyAdmin());
        } catch (JWTException e) {
            errList.add("invalid token");
        }
    }
    Iterator<FileItem> iter = uploadItems.iterator();
    while (iter.hasNext()) {
        FileItem item = iter.next();

        if (!item.isFormField()) {
            InputStream is = item.getInputStream();

            ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
            ZipEntry ze;

            while ((ze = zis.getNextEntry()) != null) {
                String filePath = repository + File.separator + ze.getName();
                if (ze.getName().equals("demographics.csv") | ze.getName().equals("location.csv")) {
                    int count;
                    byte data[] = new byte[BUFFER];
                    FileOutputStream fos = new FileOutputStream(filePath);
                    BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER);
                    while ((count = zis.read(data, 0, BUFFER)) != -1) {
                        bos.write(data, 0, count);
                    }
                    bos.flush();
                    bos.close();
                }
            }
            zis.close();
        }
    }

    File[] files = new File(repository.toString()).listFiles();

    boolean isLocLookUpInserted = false;
    boolean isDemoInserted = false;
    boolean isLocInserted = false;

    boolean isValidFile = false;
    //check if zip files contain the any of the 3 data files
    for (File file : files) {

        String fileName = file.getName();
        if (fileName.contains("demographics.csv")) {
            isValidFile = true;
        } else if (fileName.contains("location.csv")) {
            isValidFile = true;
        }
    }
    //if uploaded folder does not contain the files, it will go back to bootstrap.jsp
    if (!isValidFile) {
        errList.add("invlaid file");
    }

    if (errList.isEmpty()) {

        BootStrapManager bm = new BootStrapManager();
        for (File file : files) {
            String fileName = file.getName();
            String filePath = repository + File.separator + fileName;
            //out.println("</br>" + filePath);
            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
                br.readLine();
                String line = null;
                if (!isDemoInserted && fileName.contains("demographics.csv")) {
                    bm.updateDemo(filePath);
                    isDemoInserted = true;

                }

                if (!isLocInserted && fileName.contains("location.csv")) {
                    bm.updateLoc(filePath);
                    isLocInserted = true;
                }

                br.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (br != null) {
                    br.close();
                }
            }

            file.delete();
        }
        //error List
        ArrayList<BootstrapError> locErrorList = BootStrapManager.locErrorList;
        //ArrayList<BootstrapError> locLookUpErrorList = BootStrapManager.locLookUpErrorList;
        ArrayList<BootstrapError> demoErrorList = BootStrapManager.demoErrorList;
        Collections.sort(locErrorList);
        //Collections.sort(locLookUpErrorList);
        Collections.sort(demoErrorList);

        if (locErrorList.isEmpty() && demoErrorList.isEmpty()) {
            jsonOutput.addProperty("status", "success");

            //add the array to output
            jsonOutput.add("num-record-loaded", getNumLoaded());

        } else {

            jsonOutput.addProperty("status", "error");

            jsonOutput.add("num-record-loaded", getNumLoaded());

            //create a json array of error
            JsonArray error = new JsonArray();
            //check demogrpahics file
            if (!demoErrorList.isEmpty()) {
                for (BootstrapError bse : demoErrorList) {
                    JsonObject demoError = new JsonObject();
                    demoError.addProperty("file", "demographics.csv");
                    demoError.addProperty("line", bse.getLineNum());
                    //get Errors
                    ArrayList<String> bseErr = bse.getErrMsg();
                    JsonArray errMsg2 = new JsonArray();
                    for (String e : bseErr) {
                        errMsg2.add(new JsonPrimitive(e));
                    }
                    demoError.add("message", errMsg2);
                    error.add(demoError);
                }
            }

            //check location file
            if (!locErrorList.isEmpty()) {
                for (BootstrapError bse : locErrorList) {
                    JsonObject demoError = new JsonObject();
                    demoError.addProperty("file", "location.csv");
                    demoError.addProperty("line", bse.getLineNum());
                    //get Errors
                    ArrayList<String> bseErr = bse.getErrMsg();
                    JsonArray errMsg2 = new JsonArray();
                    for (String e : bseErr) {
                        errMsg2.add(new JsonPrimitive(e));
                    }
                    demoError.add("message", errMsg2);
                    error.add(demoError);
                }

            }
            //check location lookup file
            //                if (!locLookUpErrorList.isEmpty()) {
            //                    for (BootstrapError bse : locLookUpErrorList) {
            //                        JsonObject demoError = new JsonObject();
            //                        demoError.addProperty("file", "location-lookup.csv");
            //                        demoError.addProperty("line", bse.getLineNum());
            //                        //get Errors
            //                        ArrayList<String> bseErr = bse.getErrMsg();
            //                        JsonArray errMsg2 = new JsonArray();
            //                        for (String e : bseErr) {
            //                            errMsg2.add(new JsonPrimitive(e));
            //                        }
            //                        demoError.add("message", errMsg2);
            //                        error.add(demoError);
            //                    }
            //                }
            jsonOutput.add("error", error);

        }
        //display output
        out.println(gson.toJson(jsonOutput));

    } else {
        jsonOutput.addProperty("status", "error");
        //sorting the errlist into alphabetical order
        HashSet hs = new HashSet();
        hs.addAll(errList);
        errList.clear();
        errList.addAll(hs);

        Collections.sort(errList);
        //loop through the errors to add into the json error array
        for (String err : errList) {
            errMsg.add(new JsonPrimitive(err));
        }

        jsonOutput.add("messages", errMsg);

        out.println(gson.toJson(jsonOutput));

    }
    out.close();
}

From source file:com.globalsight.everest.tda.TdaHelper.java

public void leverageTDA(TDATM tda, File needLeverageXliffFile, String storePath, String fileName,
        String sourceLocal, String targetLocal) {
    int timeoutConnection = 15000;

    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

    DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
    String loginUrl = new String();

    if (tda.getHostName().indexOf("http://") < 0) {
        loginUrl = "http://" + tda.getHostName();
    } else {/*w ww .  j  av  a 2s  .co  m*/
        loginUrl = tda.getHostName();
    }

    if (tda.getHostName().lastIndexOf("/") < (tda.getHostName().length() - 1)) {
        loginUrl = loginUrl + "/";
    }

    try {
        // Judge if the TDA server has the source and target language
        HttpGet lanGet = new HttpGet(loginUrl + "lang/" + sourceLocal.toLowerCase() + ".json?auth_username="
                + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey);
        HttpResponse lanRes = httpclient.execute(lanGet);
        StatusLine stl = lanRes.getStatusLine();

        if (stl.getStatusCode() != 200) {
            loggerTDAInfo(stl, sourceLocal.toString());

            return;
        }
        lanGet.abort();
        HttpGet lanGet2 = new HttpGet(loginUrl + "lang/" + targetLocal.toLowerCase() + ".json?auth_username="
                + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey);
        HttpResponse lanRes2 = httpclient.execute(lanGet2);
        stl = lanRes2.getStatusLine();

        if (stl.getStatusCode() != 200) {
            loggerTDAInfo(stl, targetLocal.toString());

            return;
        }
        lanGet2.abort();

        HttpPost httpPost = new HttpPost(loginUrl + "leverage.json?action=create");
        FileBody fileBody = new FileBody(needLeverageXliffFile);
        StringBody nameBody = new StringBody(tda.getUserName());
        StringBody passwordBody = new StringBody(tda.getPassword());
        StringBody appKeyBody = new StringBody(appKey);
        StringBody srcBody = new StringBody(sourceLocal.toLowerCase());
        StringBody trBody = new StringBody(targetLocal.toLowerCase());
        StringBody confirmBody = new StringBody("true");
        MultipartEntity reqEntity = new MultipartEntity();

        reqEntity.addPart("file", fileBody);
        reqEntity.addPart("auth_username", nameBody);
        reqEntity.addPart("auth_password", passwordBody);
        reqEntity.addPart("auth_app_key", appKeyBody);
        reqEntity.addPart("source_lang", srcBody);
        reqEntity.addPart("target_lang", trBody);
        reqEntity.addPart("confirm", confirmBody);

        httpPost.setEntity(reqEntity);

        HttpResponse response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        StatusLine sl = response.getStatusLine();

        if (sl.getStatusCode() != 201) {
            loggerTDAInfo(stl, null);

            return;
        }

        JSONObject jso = new JSONObject(EntityUtils.toString(entity));
        JSONArray lev = jso.getJSONArray("leverage");

        httpPost.abort();

        if (lev.length() > 0) {
            JSONObject obj = lev.getJSONObject(0);
            String states = obj.getString("state");

            // waiting the "not ready" state becoming "ready" state
            Thread.sleep(3 * 1000);
            int i = 0;
            if (!states.equals("ready")) {
                boolean flag = true;

                while (flag) {
                    if (i > 40) {
                        s_logger.info("Get TDA job status overtime. TDA job id:" + obj.getInt("id"));
                        s_logger.info("TDA leveraging waited time:" + (40 * 3) + " seconds!");
                        return;
                    }

                    i++;
                    HttpGet httpget = new HttpGet(loginUrl + "leverage/" + obj.getInt("id")
                            + ".json?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword()
                            + "&auth_app_key=" + appKey);

                    response = httpclient.execute(httpget);
                    StatusLine status = response.getStatusLine();

                    if (status.getStatusCode() != 200) {
                        s_logger.info(
                                "Get TDA job status error, please confirm the TDA url is correct or not! TDA job id:"
                                        + obj.getInt("id"));
                        return;
                    }

                    entity = response.getEntity();
                    JSONObject getObj = new JSONObject(EntityUtils.toString(entity));

                    if (getObj.getJSONObject("leverage").getString("state").equals("ready")) {
                        s_logger.info("TDA leveraging waited time:" + (i * 3) + " seconds!");
                        flag = false;
                    } else {
                        Thread.sleep(3 * 1000);
                    }

                    httpget.abort();
                }
            }

            HttpPost httpPost2 = new HttpPost(loginUrl + "leverage/" + obj.getInt("id")
                    + ".json?action=approve&auth_username=" + tda.getUserName() + "&auth_password="
                    + tda.getPassword() + "&auth_app_key=" + appKey);

            response = httpclient.execute(httpPost2);
            entity = response.getEntity();
            httpPost2.abort();

            HttpGet httpGet = new HttpGet(loginUrl + "leverage/" + obj.getString("id")
                    + "/result.xlf.zip?auth_username=" + tda.getUserName() + "&auth_password="
                    + tda.getPassword() + "&auth_app_key=" + appKey);
            HttpResponse response2 = httpclient.execute(httpGet);
            entity = response2.getEntity();

            ZipInputStream fs = new ZipInputStream(entity.getContent());

            int BUFFER = 2048;

            byte data[] = new byte[BUFFER];
            int count;

            while (fs.getNextEntry() != null) {
                FileOutputStream fos = new FileOutputStream(storePath + File.separator + fileName);
                BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);

                while ((count = fs.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, count);
                }

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

            httpGet.abort();

            s_logger.info("Leverage TDA TM success, TDA id:" + obj.getString("id"));
        }
    } catch (Exception e) {
        s_logger.error("TDA leverage process error:" + e.getMessage());
    }
}

From source file:uk.co.beerdragon.mvn.natives.UnpackDependenciesMojo.java

private void unpack(final Artifact artifact, final Map<String, Set<Artifact>> names, final File targetDir)
        throws MojoFailureException {
    getLog().info("Unpacking " + ArtifactUtils.key(artifact));
    final IOExceptionHandler errorLog = new MojoLoggingErrorCallback(this);
    check(artifact, (new IOCallback<InputStream, Boolean>(open(artifact)) {

        @Override/*from  w  w w  .ja  v a  2 s  . c  om*/
        protected Boolean apply(final InputStream input) throws IOException {
            final byte[] buffer = new byte[4096];
            final ZipInputStream zip = new ZipInputStream(new BufferedInputStream(input));
            ZipEntry entry;
            while ((entry = zip.getNextEntry()) != null) {
                final String dest = createUniqueName(artifact, entry.getName(), names.get(entry.getName()));
                getLog().debug("Writing " + entry.getName() + " as " + dest);
                File targetFile = targetDir;
                for (final String component : dest.split("/")) {
                    targetFile.mkdir();
                    targetFile = new File(targetFile, component);
                }
                if ((new IOCallback<OutputStream, Boolean>(getOutputStreams().open(targetFile)) {

                    @Override
                    protected Boolean apply(final OutputStream output) throws IOException {
                        int bytes;
                        while ((bytes = zip.read(buffer, 0, buffer.length)) > 0) {
                            output.write(buffer, 0, bytes);
                        }
                        output.close();
                        return Boolean.TRUE;
                    }

                }).call(errorLog) != Boolean.TRUE) {
                    return Boolean.FALSE;
                }
            }
            return Boolean.TRUE;
        }

    }).call(errorLog));
}

From source file:sbml.test.UploadUnzipTest.java

private TreeSet<UserTestCase> unzipUserArchive(ServletFileUpload reqHandler)
        throws ServletException, IOException {
    // parseRequest() returns a list of items, but our particular
    // httpRequest will only have one: the zip file uploaded by the user.
    // If we don't get that, something went wrong.

    List items;//from  ww  w.ja  v  a  2s. c  o m
    try {
        items = reqHandler.parseRequest(httpRequest);
    } catch (FileUploadException e) {
        propagateError(BAD_UPLOAD, e);
        return null;
    }

    // Some sanity checking.  The case of > 1 shouldn't happen because
    // we're in control of this part (via uploadresults.jsp), but let's
    // check it in case someone edits things in the future and
    // inadvertently breaks this part.

    if (items.isEmpty()) {
        propagateError(BAD_UPLOAD, "No file uploaded.");
        return null;
    } else if (items.size() > 1) {
        propagateError(BAD_UPLOAD, "More than one file uploaded.");
        return null;
    }

    // Unzip the file and write out the individual file contents to
    // disk.  This will create a bunch of files that are expected to be
    // the user's CSV results files.  We create objects representing
    // each of these user results and put them in a list.  We ignore
    // any files that don't have the expected name pattern.

    FileItem zipFile = (FileItem) items.get(0);
    TreeSet<UserTestCase> cases = new TreeSet<UserTestCase>();
    ArrayList<String> badFileNames = new ArrayList<String>();
    try {
        ZipInputStream zis = new ZipInputStream(zipFile.getInputStream());
        ZipEntry entry;
        UserTestCase theCase;

        while ((entry = zis.getNextEntry()) != null) {
            String fileName = entry.getName();
            String caseNumStr = caseNameFromFileName(fileName);
            if (caseNumStr == null) {
                badFileNames.add(fileName);
                continue;
            }

            File path = UserTestCase.pathToDataFile(uploadDir, caseNumStr);
            FileOutputStream fs = new FileOutputStream(path);
            BufferedOutputStream bos = new BufferedOutputStream(fs, 2048);

            int count;
            byte data[] = new byte[2048];

            while ((count = zis.read(data, 0, 2048)) != -1)
                bos.write(data, 0, count);

            bos.flush();
            bos.close();

            theCase = new UserTestCase(refCasesDir, uploadDir, caseNumStr);
            cases.add(theCase);
        }
        zis.close();
    } catch (Exception e) {
        propagateError(SERVER_ERROR, e);
        return null;
    }

    if (cases.size() >= 1) {
        OnlineSTS.logInfo(httpRequest, "Got " + cases.size() + " case" + (cases.size() > 1 ? "s" : ""));
        return cases;
    } else {
        if (badFileNames.size() >= 1)
            propagateError(BAD_FILE_NAMES, badFileNames.get(0));
        else
            propagateError(EMPTY_ARCHIVE, zipFile.getName());

        return null;
    }
}

From source file:com.griddynamics.deming.ecommerce.api.endpoint.catalog.CatalogManagerEndpoint.java

@POST
@Path("import")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response importCatalog(@FormDataParam("file") InputStream uploadInputStream)
        throws ServiceException, IOException {
    removeCatalog();//  ww  w  .j av a2s . c o m

    try {
        ZipInputStream inputStream = new ZipInputStream(uploadInputStream);

        try {
            byte[] buf = new byte[1024];

            for (ZipEntry entry = inputStream.getNextEntry(); entry != null; entry = inputStream
                    .getNextEntry()) {
                try {
                    String entryName = entry.getName();
                    entryName = entryName.replace('/', File.separatorChar);
                    entryName = entryName.replace('\\', File.separatorChar);

                    LOGGER.debug("Entry name: {}", entryName);

                    if (entry.isDirectory()) {
                        LOGGER.debug("Entry ({}) is directory", entryName);
                    } else if (PRODUCT_CATALOG_FILE.equals(entryName)) {
                        ByteArrayOutputStream jsonBytes = new ByteArrayOutputStream(1024);

                        for (int n = inputStream.read(buf, 0, 1024); n > -1; n = inputStream.read(buf, 0,
                                1024)) {
                            jsonBytes.write(buf, 0, n);
                        }

                        byte[] bytes = jsonBytes.toByteArray();

                        ObjectMapper mapper = new ObjectMapper();

                        JaxbAnnotationModule jaxbAnnotationModule = new JaxbAnnotationModule();
                        mapper.registerModule(jaxbAnnotationModule);

                        ImportCategoryWrapper catalog = mapper.readValue(bytes, ImportCategoryWrapper.class);
                        escape(catalog);
                        saveCategoryTree(catalog);
                    } else {
                        MultipartFile file = new MultipartFileAdapter(inputStream, entryName);
                        dmgStaticAssetStorageService.createStaticAssetStorageFromFile(file);
                    }

                } finally {
                    inputStream.closeEntry();
                }
            }
        } finally {
            inputStream.close();
        }

    } catch (IOException e) {
        return Response.status(Response.Status.BAD_REQUEST).entity("Unable load catalog.\n").build();
    }

    Thread rebuildSearchIndex = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(10000);
                searchService.rebuildIndex();
            } catch (Exception e) {
                /* nothing */}
        }
    });
    rebuildSearchIndex.start();

    return Response.status(Response.Status.OK).entity("Catalog was imported successfully!\n").build();
}

From source file:org.jdesktop.wonderland.artupload.UploadServlet.java

/**
 * Write files to the specified directory
 * @param items the list of items containing the files to write
 * @throws IOException if there is an error writing the files
 * @throws ServletException if there is an error writing the files
 *//*from w ww  . ja v a 2  s  .c om*/
private void writeFiles(List<FileItem> items) throws IOException, ServletException {
    // get the value of the "name" field
    FileItem nameItem = findItem(items, "name");
    String name = nameItem.getString();

    // write the model file
    FileItem modelItem = findItem(items, "model");
    File modelsDir = new File(Util.getArtDir(getServletContext()), "models");
    File modelFile = new File(modelsDir, name + ".j3s.gz");

    try {
        modelItem.write(modelFile);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }

    // unzip the textures
    FileItem texturesItem = findItem(items, "textures");
    ZipInputStream zin = new ZipInputStream(texturesItem.getInputStream());

    ZipEntry entry;
    File curDir = new File(Util.getArtDir(getServletContext()), "textures");
    while ((entry = zin.getNextEntry()) != null) {
        if (entry.isDirectory()) {
            File dir = new File(curDir, entry.getName());
            dir.mkdirs();
        } else {
            // write the unzipped texture data
            File texture = new File(curDir, entry.getName());
            FileOutputStream out = new FileOutputStream(texture);

            byte[] buffer;
            if (entry.getSize() > -1) {
                buffer = new byte[(int) entry.getSize()];
            } else {
                buffer = new byte[64 * 1024];
            }

            int read = 0;
            while ((read = zin.read(buffer, 0, buffer.length)) > -1) {
                out.write(buffer, 0, read);
            }
            out.close();
        }
    }
}

From source file:com.mcleodmoores.mvn.natives.UnpackDependenciesMojo.java

private void unpack(final Artifact artifact, final Map<String, Set<Artifact>> names, final File targetDir)
        throws MojoFailureException {
    getLog().info("Unpacking " + ArtifactUtils.key(artifact));
    final IOExceptionHandler errorLog = new MojoLoggingErrorCallback(this);
    check(artifact, (new IOCallback<InputStream, Boolean>(open(artifact)) {

        @Override/*from  w  w  w  . java  2 s.c o m*/
        protected Boolean apply(final InputStream input) throws IOException {
            final byte[] buffer = new byte[4096];
            final ZipInputStream zip = new ZipInputStream(new BufferedInputStream(input));
            ZipEntry entry;
            while ((entry = zip.getNextEntry()) != null) {
                final String dest = createUniqueName(artifact, entry.getName(), names.get(entry.getName()));
                getLog().debug("Writing " + entry.getName() + " as " + dest);
                File targetFile = targetDir;
                for (final String component : dest.split("/")) {
                    targetFile.mkdir();
                    targetFile = new File(targetFile, component);
                }
                targetFile.getParentFile().mkdirs();
                if ((new IOCallback<OutputStream, Boolean>(getOutputStreams().open(targetFile)) {

                    @Override
                    protected Boolean apply(final OutputStream output) throws IOException {
                        int bytes;
                        while ((bytes = zip.read(buffer, 0, buffer.length)) > 0) {
                            output.write(buffer, 0, bytes);
                        }
                        output.close();
                        return Boolean.TRUE;
                    }

                }).call(errorLog) != Boolean.TRUE) {
                    return Boolean.FALSE;
                }
            }
            return Boolean.TRUE;
        }

    }).call(errorLog));
}

From source file:Main.java

public static boolean unzip(InputStream inputStream, String dest, boolean replaceIfExists) {

    final int BUFFER_SIZE = 4096;

    BufferedOutputStream bufferedOutputStream = null;

    boolean succeed = true;

    try {/*from   w  w w  .j  av  a2 s.  com*/
        ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream));
        ZipEntry zipEntry;

        while ((zipEntry = zipInputStream.getNextEntry()) != null) {

            String zipEntryName = zipEntry.getName();

            //             if(!zipEntry.isDirectory()) {
            //                 File fil = new File(dest + zipEntryName);
            //                 fil.getParent()
            //             }

            // file exists ? delete ?
            File file2 = new File(dest + zipEntryName);

            if (file2.exists()) {
                if (replaceIfExists) {

                    try {
                        boolean b = deleteDir(file2);
                        if (!b) {
                            Log.e("Haggle", "Unzip failed to delete " + dest + zipEntryName);
                        } else {
                            Log.d("Haggle", "Unzip deleted " + dest + zipEntryName);
                        }
                    } catch (Exception e) {
                        Log.e("Haggle", "Unzip failed to delete " + dest + zipEntryName, e);
                    }
                }
            }

            // extract
            File file = new File(dest + zipEntryName);

            if (file.exists()) {

            } else {
                if (zipEntry.isDirectory()) {
                    file.mkdirs();
                    chmod(file, 0755);

                } else {

                    // create parent file folder if not exists yet
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                        chmod(file.getParentFile(), 0755);
                    }

                    byte buffer[] = new byte[BUFFER_SIZE];
                    bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file), BUFFER_SIZE);
                    int count;

                    while ((count = zipInputStream.read(buffer, 0, BUFFER_SIZE)) != -1) {
                        bufferedOutputStream.write(buffer, 0, count);
                    }

                    bufferedOutputStream.flush();
                    bufferedOutputStream.close();
                }
            }

            // enable standalone python
            if (file.getName().endsWith(".so") || file.getName().endsWith(".xml")
                    || file.getName().endsWith(".py") || file.getName().endsWith(".pyc")
                    || file.getName().endsWith(".pyo")) {
                chmod(file, 0755);
            }

            Log.d("Haggle", "Unzip extracted " + dest + zipEntryName);
        }

        zipInputStream.close();

    } catch (FileNotFoundException e) {
        Log.e("Haggle", "Unzip error, file not found", e);
        succeed = false;
    } catch (Exception e) {
        Log.e("Haggle", "Unzip error: ", e);
        succeed = false;
    }

    return succeed;
}