Example usage for java.util.zip ZipFile getEntry

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

Introduction

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

Prototype

public ZipEntry getEntry(String name) 

Source Link

Document

Returns the zip file entry for the specified name, or null if not found.

Usage

From source file:net.fabricmc.installer.installer.ServerInstaller.java

public static void install(File mcDir, String version, IInstallerProgress progress, File fabricJar)
        throws IOException {
    progress.updateProgress(Translator.getString("gui.installing") + ": " + version, 0);
    String[] split = version.split("-");
    String mcVer = split[0];//from   w  w w  .  java2 s . c  o  m
    String fabricVer = split[1];

    File mcJar = new File(mcDir, "minecraft_server." + mcVer + ".jar");

    if (!mcJar.exists()) {
        progress.updateProgress(Translator.getString("install.server.downloadVersionList"), 10);
        JsonObject versionList = Utils
                .loadRemoteJSON(new URL("https://launchermeta.mojang.com/mc/game/version_manifest.json"));
        String url = null;

        for (JsonElement element : versionList.getAsJsonArray("versions")) {
            JsonObject object = element.getAsJsonObject();
            if (object.get("id").getAsString().equals(mcVer)) {
                url = object.get("url").getAsString();
                break;
            }
        }

        if (url == null) {
            throw new RuntimeException(Translator.getString("install.server.error.noVersion"));
        }

        progress.updateProgress(Translator.getString("install.server.downloadServerInfo"), 12);
        JsonObject serverInfo = Utils.loadRemoteJSON(new URL(url));
        url = serverInfo.getAsJsonObject("downloads").getAsJsonObject("server").get("url").getAsString();

        progress.updateProgress(Translator.getString("install.server.downloadServer"), 15);
        FileUtils.copyURLToFile(new URL(url), mcJar);
    }

    File libs = new File(mcDir, "libs");

    ZipFile fabricZip = new ZipFile(fabricJar);
    InstallerMetadata metadata;
    try (InputStream inputStream = fabricZip
            .getInputStream(fabricZip.getEntry(Reference.INSTALLER_METADATA_FILENAME))) {
        metadata = new InstallerMetadata(inputStream);
    }

    List<InstallerMetadata.LibraryEntry> fabricDeps = metadata.getLibraries("server", "common");
    for (int i = 0; i < fabricDeps.size(); i++) {
        InstallerMetadata.LibraryEntry dep = fabricDeps.get(i);
        File depFile = new File(libs, dep.getFilename());
        if (depFile.exists()) {
            depFile.delete();
        }
        progress.updateProgress("Downloading " + dep.getFilename(), 20 + (i * 70 / fabricDeps.size()));
        FileUtils.copyURLToFile(new URL(dep.getFullURL()), depFile);
    }

    progress.updateProgress(Translator.getString("install.success"), 100);
}

From source file:com.icesoft.icefaces.tutorial.component.autocomplete.AutoCompleteDictionary.java

private static void init() {
    // Raw list of xml cities.
    List cityList = null;/*from w  w w  . ja v a 2  s . com*/

    // load the city dictionary from the compressed xml file.

    // get the path of the compressed file
    HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
    String basePath = session.getServletContext().getRealPath("/WEB-INF/resources");
    basePath += "/city.xml.zip";

    // extract the file
    ZipEntry zipEntry;
    ZipFile zipFile;
    try {
        zipFile = new ZipFile(basePath);
        zipEntry = zipFile.getEntry("city.xml");
    } catch (Exception e) {
        log.error("Error retrieving records", e);
        return;
    }

    // get the xml stream and decode it.
    if (zipFile.size() > 0 && zipEntry != null) {
        try {
            BufferedInputStream dictionaryStream = new BufferedInputStream(zipFile.getInputStream(zipEntry));
            XMLDecoder xDecoder = new XMLDecoder(dictionaryStream);
            // get the city list.
            cityList = (List) xDecoder.readObject();
            dictionaryStream.close();
            zipFile.close();
            xDecoder.close();
        } catch (ArrayIndexOutOfBoundsException e) {
            log.error("Error getting city list, not city objects", e);
            return;
        } catch (IOException e) {
            log.error("Error getting city list", e);
            return;
        }
    }

    // Finally load the object from the xml file.
    if (cityList != null) {
        dictionary = new ArrayList(cityList.size());
        City tmpCity;
        for (int i = 0, max = cityList.size(); i < max; i++) {
            tmpCity = (City) cityList.get(i);
            if (tmpCity != null && tmpCity.getCity() != null) {
                dictionary.add(new SelectItem(tmpCity, tmpCity.getCity()));
            }
        }
        cityList.clear();
        // finally sort the list
        Collections.sort(dictionary, LABEL_COMPARATOR);
    }

}

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

public static boolean extractFile(File zip, File output, String fileName) throws IOException {
    if (!zip.exists() || fileName == null) {
        return false;
    }/* www.j av a  2 s  . c  om*/

    ZipFile zipFile = new ZipFile(zip);
    try {
        ZipEntry entry = zipFile.getEntry(fileName);
        if (entry == null) {
            Utils.getLogger().log(Level.WARNING, "File " + fileName + " not found in " + zip.getAbsolutePath());
            return false;
        }
        File outputFile = new File(output, entry.getName());

        if (outputFile.getParentFile() != null) {
            outputFile.getParentFile().mkdirs();
        }

        unzipEntry(zipFile, zipFile.getEntry(fileName), outputFile);
        return true;
    } catch (IOException e) {
        Utils.getLogger().log(Level.WARNING,
                "Error extracting file " + fileName + " from " + zip.getAbsolutePath());
        return false;
    } finally {
        zipFile.close();
    }
}

From source file:io.inkstand.scribble.rules.ZipAssert.java

/**
 * Verifies if a folder with the specified path exists
 * @param zf/*from  w w  w  .  j a va 2 s  . com*/
 *  the zip file to search for the entry
 * @param entryPath
 *  the path to the folder entry. Note that it is required that the path ends with '/' otherwise it can't
 *  be recognized as a directory, even though the entry may be found with the trailing slash
 */
public static void assertZipFolderExists(final ZipFile zf, final String entryPath) {
    final String folderPath;
    if (entryPath.endsWith("/")) {
        folderPath = entryPath;
    } else {
        folderPath = entryPath + '/';
    }
    final ZipEntry entry = zf.getEntry(folderPath);
    assertNotNull("Entry " + folderPath + " does not exist", entry);
    assertTrue("Entry " + folderPath + " is no folder", entry.isDirectory());
}

From source file:org.apache.oozie.tools.OozieDBImportCLI.java

private static <E> int importFromJSONtoDB(EntityManager entityManager, ZipFile zipFile, String filename,
        Class<E> clazz) throws JPAExecutorException, IOException {
    int wfjSize = 0;
    Gson gson = new Gson();
    ZipEntry entry = zipFile.getEntry(filename);
    if (entry != null) {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(zipFile.getInputStream(entry), "UTF-8"));
        String line;//from w  w w.  j  a  v a 2 s . co m
        while ((line = reader.readLine()) != null) {
            E workflow = gson.fromJson(line, clazz);
            entityManager.persist(workflow);
            wfjSize++;
        }
        reader.close();
    }
    return wfjSize;
}

From source file:com.skwas.cordova.appinfo.AppInfo.java

public static long getBuildDate(Context context) {

    ZipFile zf = null;
    try {//from   w w w . ja  v a 2 s  .  com
        ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);
        zf = new ZipFile(ai.sourceDir);
        ZipEntry ze = zf.getEntry("classes.dex");
        long time = ze.getTime();
        return time;

    } catch (Exception e) {
    }

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

    return 0l;
}

From source file:org.silverpeas.file.ZipUtil.java

/**
 * ---------------------------------------------------------------------
 * @param fromZipFile/*from ww  w.  ja  v a 2s  .  c o  m*/
 * @param fileName
 * @param toDir
 * @throws Exception
 * @see
 */
public static void extractFile(String fromZipFile, String fileName, String toDir) throws Exception {
    ZipFile zipFile = new ZipFile(fromZipFile);
    File dir = new File(toDir);
    if (!dir.exists()) {
        dir.mkdirs();
    } else if (dir.isFile()) {
        throw new Exception("destination cannot be a file");
    }
    if (zipFile.getEntry(fileName) == null) {
        throw new Exception("file \"" + fileName + "\" not found into \"" + fromZipFile + "\".");
    }
    extractFile(zipFile, zipFile.getEntry(fileName), dir);
}

From source file:org.digidoc4j.utils.Helper.java

/**
 * Get the signature from a file.//  w w w .  java 2s.co  m
 *
 * @param file  file containing the container
 * @param index index of the signature file
 * @return signature
 * @throws IOException when the signature is not found
 */
public static String extractSignature(String file, int index) throws IOException {
    ZipFile zipFile = new ZipFile(file);
    String signatureFileName = "META-INF/signatures" + index + ".xml";
    ZipEntry entry = zipFile.getEntry(signatureFileName);

    if (entry == null)
        throw new IOException(signatureFileName + " does not exists in archive: " + file);

    InputStream inputStream = zipFile.getInputStream(entry);
    String signatureContent = IOUtils.toString(inputStream, "UTF-8");

    zipFile.close();
    inputStream.close();

    return signatureContent;
}

From source file:com.netspective.commons.xdm.XdmComponentFactory.java

/**
 * Factory method for obtaining a particular component from a file that can be found in the classpath (including
 * JARs and ZIPs on the classpath)./*from   ww w . j  a v  a2 s . c o m*/
 */
public static XdmComponent get(Class componentClass, String fileName, int flags, boolean forceReload)
        throws DataModelException, InvocationTargetException, InstantiationException, IllegalAccessException,
        IOException, NoSuchMethodException, FileNotFoundException {
    FileFind.FileFindResults ffResults = FileFind.findInClasspath(fileName,
            FileFind.FINDINPATHFLAG_SEARCH_INSIDE_ARCHIVES_LAST);
    if (ffResults.isFileFound()) {
        if (ffResults.isFoundFileInJar()) {
            ZipFile zipFile = new ZipFile(ffResults.getFoundFile());
            ZipEntry zipEntry = zipFile.getEntry(ffResults.getSearchFileName());
            String systemId = ffResults.getFoundFile().getAbsolutePath() + "!" + ffResults.getSearchFileName();

            XdmComponent component = forceReload ? null : getCachedComponent(systemId, flags);
            if (component != null)
                return component;

            // if we we get to this point, we're parsing an XML file into a given component class
            XdmParseContext pc = null;
            List errors = null;
            List warnings = null;

            // create a new class instance and hang onto the error list for use later
            component = (XdmComponent) discoverClass.newInstance(componentClass, componentClass.getName());
            errors = component.getErrors();
            warnings = component.getWarnings();

            // if the class's attributes and model is not known, get it now
            XmlDataModelSchema.getSchema(componentClass);

            // parse the XML file
            long startTime = System.currentTimeMillis();
            pc = XdmParseContext.parse(component, ffResults.getFoundFile(), zipEntry);
            component.setLoadDuration(startTime, System.currentTimeMillis());

            // if we had some syntax errors, make sure the component records them for later use
            if (pc != null && pc.getErrors().size() != 0)
                errors.addAll(pc.getErrors());

            if (pc != null && pc.getWarnings().size() != 0)
                warnings.addAll(pc.getWarnings());

            component.loadedFromXml(flags);

            // if there are no errors, cache this component so if the file is needed again, it's available immediately
            if ((flags & XDMCOMPFLAG_CACHE_ALWAYS) != 0
                    || (((flags & XDMCOMPFLAG_CACHE_WHEN_NO_ERRORS) != 0) && errors.size() == 0))
                cacheComponent(systemId, component, flags);

            return component;
        } else
            return get(componentClass, ffResults.getFoundFile(), flags, forceReload);
    } else
        throw new FileNotFoundException("File '" + fileName + "' not found in classpath. Searched: "
                + TextUtils.getInstance().join(ffResults.getSearchPaths(), ", "));
}

From source file:nz.ac.otago.psyanlab.common.util.FileUtils.java

/**
 * Extract a single named file from an archive.
 * //w  w  w.  j av  a  2  s .c o  m
 * @param needle Archive relative path of file to extract.
 * @param paleFile Experiment archive file.
 * @throws IOException
 * @throws ZipException
 */
public static byte[] extractJust(String needle, File paleFile) throws ZipException, IOException {
    ZipFile archive = new ZipFile(paleFile);
    try {
        ZipEntry ze = archive.getEntry(needle);
        if (ze == null) {
            throw new RuntimeException("Could not find experiment json in " + paleFile.getName());
        }
        InputStream in = archive.getInputStream(ze);
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        try {
            copy(in, out);
            return out.toByteArray();
        } finally {
            in.close();
            out.close();
        }
    } finally {
        archive.close();
    }
}