Example usage for java.util.zip ZipFile ZipFile

List of usage examples for java.util.zip ZipFile ZipFile

Introduction

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

Prototype

public ZipFile(File file) throws ZipException, IOException 

Source Link

Document

Opens a ZIP file for reading given the specified File object.

Usage

From source file:com.facebook.buck.jvm.java.DefaultJavaLibraryIntegrationTest.java

@Test
public void testBuildJavaLibraryExportsDirectoryEntries() throws IOException {
    setUpProjectWorkspaceForScenario("export_directory_entries");

    // Run `buck build`.
    BuildTarget target = BuildTargetFactory.newInstance("//:empty_directory_entries");
    ProcessResult buildResult = workspace.runBuckBuild(target.getFullyQualifiedName());
    buildResult.assertSuccess();/*from ww  w . jav  a  2  s .  com*/

    Path outputFile = workspace.getPath(BuildTargetPaths.getGenPath(filesystem, target,
            "lib__%s__output/" + target.getShortName() + ".jar"));
    assertTrue(Files.exists(outputFile));

    ImmutableSet.Builder<String> jarContents = ImmutableSet.builder();
    try (ZipFile zipFile = new ZipFile(outputFile.toFile())) {
        for (ZipEntry zipEntry : Collections.list(zipFile.entries())) {
            jarContents.add(zipEntry.getName());
        }
    }

    // TODO(mread): Change the output to the intended output.
    assertEquals(jarContents.build(),
            ImmutableSet.of("META-INF/", "META-INF/MANIFEST.MF", "swag.txt", "yolo.txt"));

    workspace.verify();
}

From source file:com.headswilllol.basiclauncher.Launcher.java

public void actionPerformed(ActionEvent e) { // button was pressed
    if (e.getActionCommand().equals("play")) { // play button was pressed
        // clear dem buttons
        this.remove(play);
        this.remove(force);
        this.remove(noUpdate);
        this.remove(quit);
        File dir = new File(appData(), FOLDER_NAME + File.separator + "resources");
        if (!downloadDir.isEmpty()) // -d flag was used
            dir = new File(downloadDir, FOLDER_NAME + File.separator + "resources");
        dir.mkdir();//from w  w  w  .  j  a  va  2  s.c o  m
        try {
            progress = "Downloading JSON file list...";
            paintImmediately(0, 0, width, height);
            Downloader jsonDl = new Downloader(new URL(JSON_LOCATION),
                    dir.getPath() + File.separator + "resources.json", "JSON file list", true);
            Thread jsonT = new Thread(jsonDl); // download in a separate thread so the GUI will continue to update
            jsonT.start();
            while (jsonT.isAlive()) {
            } // no need for a progress bar; it's tiny
            JSONArray files = (JSONArray) ((JSONObject) new JSONParser().parse(new InputStreamReader(
                    new File(dir.getPath(), "resources.json").toURI().toURL().openStream()))).get("resources");
            List<String> paths = new ArrayList<String>();
            for (Object obj : files) { // iterate the entries in the JSON file
                JSONObject jFile = (JSONObject) obj;
                String launch = ((String) jFile.get("launch")); // if true, resource will be used as main binary
                if (launch != null && launch.equals("true"))
                    main = new File(dir, ((String) jFile.get("localPath")).replace("/", File.separator));
                paths.add(((String) jFile.get("localPath")).replace("/", File.separator));
                File file = new File(dir, ((String) jFile.get("localPath")).replace("/", File.separator));
                boolean reacquire = false;
                if (!file.exists() || // files doesn't exist
                        (allowReacquire && // allow files to be reacquired
                                (update || // update forced
                                // mismatch between local and remote file
                                        !jFile.get("md5").equals(md5(file.getPath()))))) {
                    reacquire = true;
                    if (update)
                        System.out.println(
                                "Update forced, so file " + jFile.get("localPath") + " must be updated");
                    else if (!file.exists())
                        System.out.println("Cannot find local copy of file " + jFile.get("localPath"));
                    else
                        System.out.println("MD5 checksum for file " + jFile.get("localPath")
                                + " does not match expected value");
                    System.out.println("Attempting to reacquire...");
                    file.delete();
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                    progress = "Downloading " + jFile.get("id"); // update the GUI
                    paintImmediately(0, 0, width, height);
                    Downloader dl = new Downloader(new URL((String) jFile.get("location")),
                            dir + File.separator
                                    + ((String) jFile.get("localPath")).replace("/", File.separator),
                            (String) jFile.get("id"), !jFile.containsKey("doNotSpoofUserAgent")
                                    || !Boolean.parseBoolean((String) jFile.get("doNotSpoofUserAgent")));
                    Thread th = new Thread(dl);
                    th.start();
                    eSize = getFileSize(new URL((String) jFile.get("location"))) / 8; // expected file size
                    speed = 0; // stores the current download speed
                    lastSize = 0; // stores the size of the downloaded file the last time the GUI was updated
                    while (th.isAlive()) { // wait but don't hang the main thread
                        aSize = file.length() / 8;
                        if (lastTime != -1) {
                            // wait so the GUI isn't constantly updating
                            if (System.currentTimeMillis() - lastTime >= SPEED_UPDATE_INTERVAL) {
                                speed = (aSize - lastSize) / ((System.currentTimeMillis() - lastTime) / 1000)
                                        * 8; // calculate new speed
                                lastTime = System.currentTimeMillis();
                                lastSize = aSize; // update the downloaded file's size
                            }
                        } else {
                            speed = 0; // reset the download speed
                            lastTime = System.currentTimeMillis(); // and the last time
                        }
                        paintImmediately(0, 0, width, height);
                    }
                    eSize = -1;
                    aSize = -1;
                }
                if (jFile.containsKey("extract")) { // file should be unzipped
                    HashMap<String, JSONObject> elements = new HashMap<String, JSONObject>();
                    for (Object ex : (JSONArray) jFile.get("extract")) {
                        elements.put((String) ((JSONObject) ex).get("path"), (JSONObject) ex);
                        paths.add(((String) ((JSONObject) ex).get("localPath")).replace("/", File.separator));
                        File f = new File(dir,
                                ((String) ((JSONObject) ex).get("localPath")).replace("/", File.separator));
                        if (!f.exists() || // file doesn't exist
                        // file isn't directory and has checksum
                                (!f.isDirectory() && ((JSONObject) ex).get("md5") != null &&
                                // mismatch between local and remote file
                                        !md5(f.getPath()).equals((((JSONObject) ex).get("md5")))))

                            reacquire = true;
                        if (((JSONObject) ex).get("id").equals("natives")) // specific to LWJGL launching
                            natives = new File(dir,
                                    ((String) ((JSONObject) ex).get("localPath")).replace("/", File.separator));
                    }
                    if (reacquire) {
                        try {
                            ZipFile zip = new ZipFile(new File(dir,
                                    ((String) jFile.get("localPath")).replace("/", File.separator)));
                            @SuppressWarnings("rawtypes")
                            Enumeration en = zip.entries();
                            List<String> dirs = new ArrayList<String>();
                            while (en.hasMoreElements()) { // iterate entries in ZIP file
                                ZipEntry entry = (ZipEntry) en.nextElement();
                                boolean extract = false; // whether the entry should be extracted
                                String parentDir = "";
                                if (elements.containsKey(entry.getName())) // entry is in list of files to extract
                                    extract = true;
                                else
                                    for (String d : dirs)
                                        if (entry.getName().contains(d)) {
                                            extract = true;
                                            parentDir = d;
                                        }
                                if (extract) {
                                    progress = "Extracting " + (elements.containsKey(entry.getName())
                                            ? elements.get(entry.getName()).get("id")
                                            : entry.getName()
                                                    .substring(entry.getName().indexOf(parentDir),
                                                            entry.getName().length())
                                                    .replace("/", File.separator)); // update the GUI
                                    paintImmediately(0, 0, width, height);
                                    if (entry.isDirectory()) {
                                        if (parentDir.equals(""))
                                            dirs.add((String) elements.get(entry.getName()).get("localPath"));
                                    } else {
                                        File path = new File(dir, (parentDir.equals(""))
                                                ? ((String) elements.get(entry.getName()).get("localPath"))
                                                        .replace("/", File.separator)
                                                : entry.getName()
                                                        .substring(entry.getName().indexOf(parentDir),
                                                                entry.getName().length())
                                                        .replace("/", File.separator)); // path to extract to
                                        if (path.exists())
                                            path.delete();
                                        unzip(zip, entry, path); // *zziiiip*
                                    }
                                }
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            createExceptionLog(ex);
                            progress = "Failed to extract files from " + jFile.get("id");
                            fail = "Errors occurred; see log file for details";
                            launcher.paintImmediately(0, 0, width, height);
                        }
                    }
                }
            }

            checkFile(dir, dir, paths);
        } catch (Exception ex) { // can't open resource list
            ex.printStackTrace();
            createExceptionLog(ex);
            progress = "Failed to read JSON file list";
            fail = "Errors occurred; see log file for details";
            launcher.paintImmediately(0, 0, width, height);
        }

        launch();
    } else if (e.getActionCommand().equals("force")) {
        force.setActionCommand("noForce");
        force.setText("Will Force!");
        update = true;
        // reset do not reacquire button
        noUpdate.setActionCommand("noReacquire");
        noUpdate.setText("Do Not Reacquire");
        allowReacquire = true;
    } else if (e.getActionCommand().equals("noForce")) {
        force.setActionCommand("force");
        force.setText("Force Update");
        update = false;
    } else if (e.getActionCommand().equals("noReacquire")) {
        noUpdate.setActionCommand("yesReacquire");
        noUpdate.setText("Will Not Reacquire!");
        allowReacquire = false;
        // reset force update button
        force.setActionCommand("force");
        force.setText("Force Update");
        update = false;
    } else if (e.getActionCommand().equals("yesReacquire")) {
        noUpdate.setActionCommand("noReacquire");
        noUpdate.setText("Do Not Reacquire");
        allowReacquire = true;
    } else if (e.getActionCommand().equals("quit")) {
        pullThePlug();
    } else if (e.getActionCommand().equals("kill"))
        gameProcess.destroyForcibly();
}

From source file:org.liberty.android.fantastischmemopro.downloader.DownloaderAnyMemo.java

private void downloadDatabase(final DownloadItem di) throws Exception {
    String filename = di.getExtras("filename");
    if (filename == null) {
        throw new Exception("Could not get filename");
    }/*from   w  w w  . j  ava2s  . c om*/

    String sdpath = Environment.getExternalStorageDirectory().getAbsolutePath()
            + getString(R.string.default_dir);
    File outFile = new File(sdpath + filename);
    mHandler.post(new Runnable() {
        public void run() {
            mProgressDialog = new ProgressDialog(DownloaderAnyMemo.this);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setMessage(getString(R.string.loading_downloading));
            mProgressDialog.show();

        }
    });
    try {
        OutputStream out;
        if (outFile.exists()) {
            throw new IOException("Database already exist!");
        }
        try {
            outFile.createNewFile();
            out = new FileOutputStream(outFile);

            URL myURL = new URL(di.getAddress());
            Log.v(TAG, "URL IS: " + myURL);
            URLConnection ucon = myURL.openConnection();
            final int fileSize = ucon.getContentLength();
            mHandler.post(new Runnable() {
                public void run() {
                    mProgressDialog.setMax(fileSize);
                }
            });

            byte[] buf = new byte[8192];

            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is, 8192);
            Runnable increaseProgress = new Runnable() {
                public void run() {
                    mProgressDialog.setProgress(mDownloadProgress);
                }
            };
            int len = 0;
            int lenSum = 0;
            while ((len = bis.read(buf)) != -1) {
                out.write(buf, 0, len);
                lenSum += len;
                if (lenSum > fileSize / 50) {
                    /* This is tricky.
                     * The UI thread can not be updated too often.
                     * So we update it only 50 times
                     */
                    mDownloadProgress += lenSum;
                    lenSum = 0;
                    mHandler.post(increaseProgress);
                }
            }
            out.close();
            is.close();
            /* Uncompress the zip file that contains images */
            if (filename.endsWith(".zip")) {
                mHandler.post(new Runnable() {
                    public void run() {
                        mProgressDialog.setProgress(fileSize);
                        mProgressDialog.setMessage(getString(R.string.downloader_extract_zip));
                    }
                });

                BufferedOutputStream dest = null;
                BufferedInputStream ins = null;
                ZipEntry entry;
                ZipFile zipfile = new ZipFile(outFile);
                Enumeration<?> e = zipfile.entries();
                while (e.hasMoreElements()) {
                    entry = (ZipEntry) e.nextElement();
                    Log.v(TAG, "Extracting: " + entry);
                    if (entry.isDirectory()) {
                        new File(sdpath + "/" + entry.getName()).mkdir();
                    } else {
                        ins = new BufferedInputStream(zipfile.getInputStream(entry), 8192);
                        int count;
                        byte data[] = new byte[8192];
                        FileOutputStream fos = new FileOutputStream(sdpath + "/" + entry.getName());
                        dest = new BufferedOutputStream(fos, 8192);
                        while ((count = ins.read(data, 0, 8192)) != -1) {
                            dest.write(data, 0, count);
                        }
                        dest.flush();
                        dest.close();
                        ins.close();
                    }
                }
                /* Delete the zip file if it is successfully decompressed */
                outFile.delete();
            }
            /* We do not check ttf file as db */
            if (!filename.toLowerCase().endsWith(".ttf")) {
                /* Check if the db is correct */
                filename = filename.replace(".zip", ".db");
                DatabaseHelper dh = new DatabaseHelper(DownloaderAnyMemo.this, sdpath, filename);
                dh.close();
            }
        } catch (Exception e) {
            if (outFile.exists()) {
                outFile.delete();
            }
            throw new Exception(e);
        }

    } catch (Exception e) {
        Log.e(TAG, "Error downloading", e);
        throw new Exception(e);
    } finally {
        mHandler.post(new Runnable() {
            public void run() {
                mProgressDialog.dismiss();
            }
        });
    }

}

From source file:au.com.gaiaresources.bdrs.controller.theme.ThemeControllerTest.java

@Test
public void testEditCustomSubmit() throws Exception {
    ManagedFile mf = new ManagedFile();
    mf.setContentType("application/zip");
    mf.setFilename("testTheme.zip");
    mf.setCredit("");
    mf.setLicense("");
    mf.setDescription("");
    managedFileDAO.save(mf);//from  w w w .j  a va2  s  . co  m
    fileService.createFile(mf.getClass(), mf.getId(), mf.getFilename(), createTestTheme(DEFAULT_CONFIG_VALUES));

    Portal portal = getRequestContext().getPortal();

    Map<String, ThemeElement> themeElementMap = new HashMap<String, ThemeElement>();
    List<ThemeElement> themeElements = new ArrayList<ThemeElement>(DEFAULT_CONFIG_VALUES.size());
    for (Map.Entry<String, String> entry : DEFAULT_CONFIG_VALUES.entrySet()) {
        ThemeElement te = new ThemeElement();
        te.setKey(entry.getKey());
        te.setDefaultValue(entry.getValue());
        te.setCustomValue(entry.getValue());
        te.setType(ThemeElementType.TEXT);
        te = themeDAO.save(te);
        themeElements.add(te);
        themeElementMap.put(te.getKey(), te);
    }

    Theme theme = new Theme();
    theme.setActive(true);
    theme.setName("Test Theme");
    theme.setThemeFileUUID(mf.getUuid());
    theme.setCssFiles(new String[] { TEST_CSS_FILE_PATH });
    theme.setJsFiles(new String[] { TEST_JS_FILE_PATH });
    theme.setPortal(portal);
    theme.setThemeElements(themeElements);
    theme = themeDAO.save(theme);

    ZipUtils.decompressToDir(new ZipFile(fileService.getFile(mf, mf.getFilename()).getFile()),
            fileService.getTargetDirectory(theme, Theme.THEME_DIR_RAW, true));

    login("root", "password", new String[] { Role.ROOT });

    request.setMethod("POST");
    request.setRequestURI("/bdrs/root/theme/edit.htm");
    request.setParameter("portalPk", portal.getId().toString());
    request.setParameter("themePk", theme.getId().toString());
    request.setParameter("name", theme.getName());
    request.setParameter("themeFileUUID", theme.getThemeFileUUID());
    request.setParameter("active", String.valueOf(theme.isActive()));
    for (Map.Entry<String, String> customEntry : CUSTOM_CONFIG_VALUES.entrySet()) {
        ThemeElement te = themeElementMap.get(customEntry.getKey());
        request.setParameter(String.format(ThemeController.THEME_ELEMENT_CUSTOM_VALUE_TEMPLATE, te.getId()),
                customEntry.getValue());
    }

    ModelAndView mv = handle(request, response);
    ModelAndViewAssert.assertModelAttributeValue(mv, "portalId", portal.getId());
    Assert.assertTrue(mv.getView() instanceof RedirectView);
    RedirectView redirect = (RedirectView) mv.getView();
    Assert.assertEquals("/bdrs/root/theme/edit.htm", redirect.getUrl());

    Theme actualTheme = themeDAO.getTheme((Integer) mv.getModel().get("themeId"));
    Assert.assertEquals(theme.getName(), actualTheme.getName());
    Assert.assertEquals(theme.getThemeFileUUID(), actualTheme.getThemeFileUUID());
    Assert.assertEquals(theme.isActive(), actualTheme.isActive());

    Assert.assertEquals(DEFAULT_CONFIG_VALUES.size(), actualTheme.getThemeElements().size());
    for (ThemeElement elem : actualTheme.getThemeElements()) {
        String expectedDefaultValue = DEFAULT_CONFIG_VALUES.get(elem.getKey());
        Assert.assertEquals(expectedDefaultValue, elem.getDefaultValue());

        String expectedCustomValue = CUSTOM_CONFIG_VALUES.get(elem.getKey());
        Assert.assertEquals(expectedCustomValue, elem.getCustomValue());
    }

    // Check that the save theme files have been decompressed and processed correctly.
    // Check the raw file directory.
    File rawDir = fileService.getTargetDirectory(actualTheme, Theme.THEME_DIR_RAW, false);
    Assert.assertEquals(TEST_CSS_RAW_CONTENT, FileUtils.fileRead(new File(rawDir, TEST_CSS_FILE_PATH)));
    Assert.assertEquals(TEST_TEMPLATE_RAW_CONTENT,
            FileUtils.fileRead(new File(rawDir, TEST_TEMPLATE_FILE_PATH)));
    Assert.assertEquals(TEST_JS_RAW_CONTENT, FileUtils.fileRead(new File(rawDir, TEST_JS_FILE_PATH)));
    BufferedImage rawImg = ImageIO.read(new File(rawDir, TEST_IMAGE_FILE_PATH));
    Assert.assertEquals(IMAGE_WIDTH, rawImg.getWidth());
    Assert.assertEquals(IMAGE_HEIGHT, rawImg.getHeight());

    // Check the processed file directory
    File processedDir = fileService.getTargetDirectory(actualTheme, Theme.THEME_DIR_PROCESSED, false);
    Assert.assertEquals(String.format(TEST_CSS_CUSTOM_CONTENT_TMPL, actualTheme.getId()).trim(),
            FileUtils.fileRead(new File(processedDir, TEST_CSS_FILE_PATH)).trim());
    Assert.assertEquals(String.format(TEST_TEMPLATE_CUSTOM_CONTENT, actualTheme.getId()).trim(),
            FileUtils.fileRead(new File(processedDir, TEST_TEMPLATE_FILE_PATH)).trim());
    Assert.assertEquals(TEST_JS_CUSTOM_CONTENT,
            FileUtils.fileRead(new File(processedDir, TEST_JS_FILE_PATH)).trim());
    BufferedImage processedImg = ImageIO.read(new File(processedDir, TEST_IMAGE_FILE_PATH));
    Assert.assertEquals(IMAGE_WIDTH, processedImg.getWidth());
    Assert.assertEquals(IMAGE_HEIGHT, processedImg.getHeight());
}

From source file:com.live.aac_jenius.globalgroupmute.utilities.Updater.java

/**
 * Part of Zip-File-Extractor, modified by Gravity for use with Updater.
 *
 * @param file the location of the file to extract.
 *///from   w  w w  . jav  a  2s .  c o m
private void unzip(String file) {
    final File fSourceZip = new File(file);
    try {
        final String zipPath = file.substring(0, file.length() - 4);
        ZipFile zipFile = new ZipFile(fSourceZip);
        Enumeration<? extends ZipEntry> e = zipFile.entries();
        while (e.hasMoreElements()) {
            ZipEntry entry = e.nextElement();
            File destinationFilePath = new File(zipPath, entry.getName());
            this.fileIOOrError(destinationFilePath.getParentFile(),
                    destinationFilePath.getParentFile().mkdirs(), true);
            if (!entry.isDirectory()) {
                final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                int b;
                final byte[] buffer = new byte[Updater.BYTE_SIZE];
                final FileOutputStream fos = new FileOutputStream(destinationFilePath);
                final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE);
                while ((b = bis.read(buffer, 0, Updater.BYTE_SIZE)) != -1) {
                    bos.write(buffer, 0, b);
                }
                bos.flush();
                bos.close();
                bis.close();
                final String name = destinationFilePath.getName();
                if (name.endsWith(".jar") && this.pluginExists(name)) {
                    File output = new File(updateFolder, name);
                    this.fileIOOrError(output, destinationFilePath.renameTo(output), true);
                }
            }
        }
        zipFile.close();

        // Move any plugin data folders that were included to the right place, Bukkit won't do this for us.
        moveNewZipFiles(zipPath);

    } catch (final IOException ex) {
        this.sender.sendMessage(
                this.prefix + "The auto-updater tried to unzip a new update file, but was unsuccessful.");
        this.result = Updater.UpdateResult.FAIL_DOWNLOAD;
        this.plugin.getLogger().log(Level.SEVERE, null, ex);
    } finally {
        this.fileIOOrError(fSourceZip, fSourceZip.delete(), false);
    }
}

From source file:com.smartbear.jenkins.plugins.testcomplete.TcLogParser.java

public TcLogInfo parse(BuildListener listener) {
    try {/*from www.  ja v  a2  s.c o  m*/
        ZipFile logArchive = new ZipFile(log);

        Node descriptionTopLevelNode = NodeUtils.getRootDocumentNodeFromArchive(logArchive,
                DESCRIPTION_ENTRY_NAME);
        if (descriptionTopLevelNode == null) {
            throw new ParsingException("Unable to obtain description top-level node.");
        }

        long startTime = Utils
                .safeConvertDate(NodeUtils.getTextProperty(descriptionTopLevelNode, START_TIME_PROPERTY_NAME));
        long stopTime = Utils
                .safeConvertDate(NodeUtils.getTextProperty(descriptionTopLevelNode, STOP_TIME_PROPERTY_NAME));

        int testCount = 0;
        try {
            testCount = Integer
                    .parseInt(NodeUtils.getTextProperty(descriptionTopLevelNode, TEST_COUNT_PROPERTY_NAME));
        } catch (NumberFormatException e) {
            // Do nothing
        }

        int warningCount = 0;
        try {
            warningCount = Integer
                    .parseInt(NodeUtils.getTextProperty(descriptionTopLevelNode, WARNING_COUNT_PROPERTY_NAME));
        } catch (NumberFormatException e) {
            // Do nothing
        }

        int errorCount = 0;
        try {
            errorCount = Integer
                    .parseInt(NodeUtils.getTextProperty(descriptionTopLevelNode, ERROR_COUNT_PROPERTY_NAME));
        } catch (NumberFormatException e) {
            // Do nothing
        }

        TcLogInfo logInfo = new TcLogInfo(startTime, stopTime, testCount, errorCount, warningCount);

        String xml = null;

        if (generateJUnitReports) {
            XMLStreamWriter xmlStreamWriter = null;
            try {
                StringWriter stringWriter = new StringWriter();
                xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(stringWriter);
                convertToXML(logArchive, logInfo, xmlStreamWriter);
                xmlStreamWriter.flush();
                xmlStreamWriter.close();
                xmlStreamWriter = null;
                xml = stringWriter.toString();
            } catch (Exception e) {
                TcLog.error(listener, Messages.TcTestBuilder_ExceptionOccurred(), e.toString());
            } finally {
                if (xmlStreamWriter != null) {
                    xmlStreamWriter.close();
                }
            }
        }

        logInfo.setXML(xml);

        return logInfo;
    } catch (Exception e) {
        TcLog.error(listener, Messages.TcTestBuilder_ExceptionOccurred(), e.toString());
        return null;
    }
}

From source file:com.taobao.android.builder.tasks.incremental.ApDependencies.java

public ApDependencies(Project project, TBuildType tBuildType) {
    this.dependencies = project.getDependencies();
    File apBaseFile;/* ww  w  . ja v  a  2  s. c  o m*/
    apBaseFile = getBaseApFile(project, tBuildType);

    try (ZipFile zip = new ZipFile(apBaseFile)) {
        ZipEntry entry = zip.getEntry(DEPENDENCIES_FILENAME);
        try (InputStream in = zip.getInputStream(entry)) {
            apDependencyJson = JSON.parseObject(IOUtils.toString(in, StandardCharsets.UTF_8),
                    DependencyJson.class);
        }
    } catch (IOException e) {
        throw new RuntimeException("Unable to read dependencies.txt from " + apBaseFile.getAbsolutePath(), e);
    }

    for (String mainDex : apDependencyJson.getMainDex()) {
        addDependency(mainDex, mMainDependenciesMap);
    }
    for (Map.Entry<String, ArrayList<String>> entry : apDependencyJson.getAwbs().entrySet()) {
        String awb = entry.getKey();
        Map<ModuleIdentifier, String> awbDependencies = getAwbDependencies(awb);
        addDependency(awb, awbDependencies);
        ArrayList<String> dependenciesString = entry.getValue();
        for (String dependencyString : dependenciesString) {
            addDependency(dependencyString, awbDependencies);
        }
    }
}

From source file:net.rptools.lib.FileUtil.java

public static void unzipFile(File sourceFile, File destDir) throws IOException {
    if (!sourceFile.exists())
        throw new IOException("source file does not exist: " + sourceFile);

    ZipFile zipFile = null;// www  . j  a  v a 2s. co m
    InputStream is = null;
    OutputStream os = null;
    try {
        zipFile = new ZipFile(sourceFile);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory())
                continue;

            File file = new File(destDir, entry.getName());
            String path = file.getAbsolutePath();
            file.getParentFile().mkdirs();

            //System.out.println("Writing file: " + path);
            is = zipFile.getInputStream(entry);
            os = new BufferedOutputStream(new FileOutputStream(path));
            copyWithClose(is, os);
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
        }
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
        try {
            if (zipFile != null)
                zipFile.close();
        } catch (Exception e) {
        }
    }
}

From source file:com.htmlhifive.tools.wizard.download.DownloadModule.java

/**
 * 1???.//from  www .  j a  v  a 2s  .c  o m
 * 
 * @param monitor 
 * @param totalWork 
 * @param file 
 * @param uri URI
 * @throws CoreException 
 */
private ZipFile download(final IProgressMonitor monitor, final int totalWork, ResultStatus logger, IFile file,
        final String urlStr) throws CoreException {

    // PI0111=INFO,[{0}]...
    monitor.subTask(Messages.PI0111.format(urlStr));

    lastDownloadStatus = false;

    int ret = 0;
    while (ret == 0) {
        try {
            if (file != null) {
                // ??.

                IConnectMethod method = ConnectMethodFactory.getMethod(urlStr, true);
                method.setConnectionTimeout(PluginConstant.URL_LIBRARY_CONNECTION_TIMEOUT);
                method.setProxy(getProxyService());
                method.getInputStream();

                boolean updateResult = updateFile(monitor, 0, logger, file, method);
                if (updateResult) {
                    lastDownloadStatus = true;
                }
                monitor.worked(totalWork);
            } else {
                // file?null?????ZipFile???.

                BufferedInputStream bufferIs = null;
                OutputStream os = null;

                try {
                    IConnectMethod method = ConnectMethodFactory.getMethod(urlStr, true);
                    method.setConnectionTimeout(PluginConstant.URL_LIBRARY_CONNECTION_TIMEOUT);
                    method.setProxy(getProxyService());
                    if (!method.connect()) {
                        // SE0101=ERROR,({0})??????URL={1}, File={2}
                        logger.log(Messages.SE0101, urlStr, file != null ? file.toString() : "");
                        return null;
                    }
                    final int contentLength = method.getContentLength();
                    //                  final int perWork;
                    //                  if (contentLength > 0) {
                    //                     perWork = Math.max(1, totalWork * DEFAULT_BUFFER_SIZE / 8 / contentLength);
                    //                  }else{
                    //                     perWork  = totalWork;
                    //                  }
                    InputStream is = method.getInputStream();

                    //                  if (H5IOUtils.isClassResources(urlStr)) {
                    //                     // url?null??????.
                    //                     is = DownloadModule.class.getResourceAsStream(urlStr);
                    //                  } else {
                    //                     // ?URL
                    //                     HttpMethod method = DownloadModule.this.connect(urlStr,
                    //                           PluginResource.URL_LIBRARY_CONNECTION_TIMEOUT);
                    //                     if (method == null) {
                    //                        return null;
                    //                     }
                    //
                    //                     // ??????.
                    //                     Header header = method.getResponseHeader("Content-Length");
                    //                     if (header != null) {
                    //                        contentLength = Integer.valueOf(header.getValue());
                    //                     }
                    //                     if (contentLength > 0) {
                    //                        perWork = Math.max(1, perWork * DEFAULT_BUFFER_SIZE / contentLength);
                    //                     }
                    //                     is = method.getResponseBodyAsStream();
                    //                  }
                    if (is == null) {
                        // SE0101=ERROR,({0})??????URL={1}, File={2}
                        logger.log(Messages.SE0101, urlStr, file != null ? file.toString() : "");
                        return null;
                    }

                    bufferIs = new BufferedInputStream(is) {
                        private int current = 0;
                        private final int perWork = Math.max(1, totalWork * buf.length / 8 / contentLength);

                        @Override
                        public synchronized int read() throws IOException {

                            int result = super.read();
                            current += result * 16;
                            monitor.subTask(Messages.PI0143.format(current, contentLength, urlStr));
                            //monitor.worked(result * 16);
                            monitor.worked(perWork);

                            return result;
                        }
                    };

                    // SE0093=INFO,{0}???
                    logger.log(Messages.SE0093, urlStr);

                    // ZIP.
                    File tempFile = File.createTempFile(H5WizardPlugin.getId(), "tmp");
                    // VM????.
                    tempFile.deleteOnExit();
                    // ??.
                    os = FileUtils.openOutputStream(tempFile);
                    IOUtils.copy(bufferIs, os);

                    //                  byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
                    //                  int n = 0;
                    //                  while (-1 != (n = is.read(buffer))) {
                    //                     os.write(buffer, 0, n);
                    //                     if (contentLength > 0) {
                    //                        monitor.worked(perWork);
                    //                     }
                    //                  }
                    if (contentLength == 0) {
                        monitor.worked(totalWork);
                    }

                    // SE0094=INFO,{0}????
                    logger.log(Messages.SE0094, urlStr);

                    lastDownloadStatus = true;
                    return new ZipFile(tempFile);
                } finally {
                    IOUtils.closeQuietly(bufferIs);
                    IOUtils.closeQuietly(os);
                }
            }
            ret = 1;
        } catch (IOException e) {
            // SE0101=ERROR,({0})??????URL={1}, File={2}
            logger.log(e, Messages.SE0101, urlStr, file != null ? file.toString() : "");

            // ?????.
            MessageDialog dialog = new MessageDialog(null, Messages.SE0115.format(),
                    Dialog.getImage(Dialog.DLG_IMG_MESSAGE_WARNING), Messages.SE0116.format(urlStr),
                    MessageDialog.QUESTION,
                    new String[] { UIMessages.Dialog_RETRY, UIMessages.Dialog_IGNORE, UIMessages.Dialog_STOP },
                    0);
            ret = dialog.open();
            if (ret == 2) {
                // 
                throw new OperationCanceledException(
                        Messages.SE0101.format(urlStr, file != null ? file.toString() : ""));
            }
        }
    }
    return null;
}

From source file:fr.paris.lutece.plugins.upload.web.UploadJspBean.java

/**
 * Process file upload/*from   www.  j  a v  a  2s.  co  m*/
 *
 * @param request Http request
 * @return Html form
 */
public String doCreateFile(HttpServletRequest request) {
    String strDirectoryIndex = null;

    try {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        FileItem item = multiRequest.getFile(PARAMETER_FILE_NAME);

        // The index and value of the directory combo in the form
        strDirectoryIndex = multiRequest.getParameter(PARAMETER_DIRECTORY);

        String strRelativeDirectory = getDirectory(strDirectoryIndex);

        // The absolute path of the target directory
        String strDestDirectory = AppPathService.getWebAppPath() + strRelativeDirectory;

        // List the files in the target directory
        File[] existingFiles = (new File(strDestDirectory)).listFiles();

        // Is the 'unzip' checkbox checked?
        boolean bUnzip = (multiRequest.getParameter(PARAMETER_UNZIP) != null);

        if (item != null && !item.getName().equals(StringUtils.EMPTY)) {
            if (!bUnzip) // copy the file
            {
                AppLogService.debug("copying the file");

                // Getting downloadFile's name
                String strNameFile = FileUploadService.getFileNameOnly(item);

                // Clean name
                String strClearName = UploadUtil.cleanFileName(strNameFile);

                // Checking duplicate
                if (duplicate(strClearName, existingFiles)) {
                    return AdminMessageService.getMessageUrl(request, MESSAGE_FILE_EXISTS,
                            AdminMessage.TYPE_STOP);
                }

                // Move the file to the target directory
                File destFile = new File(strDestDirectory, strClearName);

                FileOutputStream fos = new FileOutputStream(destFile);
                fos.flush();
                fos.write(item.get());
                fos.close();
            } else // unzip the file
            {
                AppLogService.debug("unzipping the file");

                ZipFile zipFile;

                try {
                    // Create a temporary file with result of getTime() as unique file name
                    File tempFile = File.createTempFile(Long.toString((new Date()).getTime()), ".zip");
                    // Delete temp file when program exits.
                    tempFile.deleteOnExit();

                    FileOutputStream fos = new FileOutputStream(tempFile);
                    fos.flush();
                    fos.write(item.get());
                    fos.close();
                    zipFile = new ZipFile(tempFile);
                } catch (ZipException ze) {
                    AppLogService.error("Error opening zip file", ze);

                    return AdminMessageService.getMessageUrl(request, MESSAGE_ZIP_ERROR,
                            AdminMessage.TYPE_STOP);
                }

                // Each zipped file is indentified by a zip entry :
                Enumeration zipEntries = zipFile.entries();

                while (zipEntries.hasMoreElements()) {
                    ZipEntry zipEntry = (ZipEntry) zipEntries.nextElement();

                    // Clean the name :
                    String strZippedName = zipEntry.getName();
                    String strClearName = UploadUtil.cleanFilePath(strZippedName);

                    if (strZippedName.equals(strClearName)) {
                        // The unzipped file :
                        File destFile = new File(strDestDirectory, strClearName);

                        // Create the parent directory structure if needed :
                        destFile.getParentFile().mkdirs();

                        if (!zipEntry.isDirectory()) // don't unzip directories
                        {
                            AppLogService.debug("unzipping " + strZippedName + " to " + destFile.getName());

                            // InputStream from zipped data
                            InputStream inZipStream = zipFile.getInputStream(zipEntry);

                            // OutputStream to the destination file
                            OutputStream outDestStream = new FileOutputStream(destFile);

                            // Helper method to copy data
                            copyStream(inZipStream, outDestStream);

                            inZipStream.close();
                            outDestStream.close();
                        } else {
                            AppLogService.debug("skipping directory " + strZippedName);
                        }
                    } else {
                        AppLogService.debug("skipping accented file " + strZippedName);
                    }
                }
            }
        } else {
            return AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FIELDS,
                    AdminMessage.TYPE_STOP);
        }
    } catch (IOException e) {
        AppLogService.error(e.getMessage(), e);
    }

    // Returns upload management page
    UrlItem url = new UrlItem(getHomeUrl(request));

    if (strDirectoryIndex != null) {
        url.addParameter(PARAMETER_DIRECTORY, strDirectoryIndex);
    }

    return url.getUrl();
}