Example usage for java.util.jar JarFile getEntry

List of usage examples for java.util.jar JarFile getEntry

Introduction

In this page you can find the example usage for java.util.jar JarFile getEntry.

Prototype

public ZipEntry getEntry(String name) 

Source Link

Document

Returns the ZipEntry for the given base entry name or null if not found.

Usage

From source file:org.springframework.boot.loader.tools.RepackagerTests.java

@Test
public void customLayoutFactoryWithoutLayout() throws Exception {
    this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
    File source = this.testJarFile.getFile();
    Repackager repackager = new Repackager(source, new TestLayoutFactory());
    repackager.repackage(NO_LIBRARIES);//from   w  w w  . j ava  2 s  . co m
    JarFile jarFile = new JarFile(source);
    assertThat(jarFile.getEntry("test")).isNotNull();
    jarFile.close();
}

From source file:org.springframework.boot.loader.tools.RepackagerTests.java

@Test
public void customLayoutFactoryWithLayout() throws Exception {
    this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
    File source = this.testJarFile.getFile();
    Repackager repackager = new Repackager(source, new TestLayoutFactory());
    repackager.setLayout(new Layouts.Jar());
    repackager.repackage(NO_LIBRARIES);/*from  w ww  .  ja va 2 s. c o m*/
    JarFile jarFile = new JarFile(source);
    assertThat(jarFile.getEntry("test")).isNull();
    jarFile.close();
}

From source file:com.palantir.gerrit.gerritci.servlets.JobsServlet.java

/**
 * Creates a new job on the specified Jenkins server with the specified name and configuration,
 * or updates the job with the specified name if it already exists on the server.
 *
 * @param jsc The Jenkins server to add the new job to.
 * @param name The name of the job to add.
 * @param type The JobType of the job to add.
 * @param params The configuration parameters for the new job.
 * @throws IOException/*from ww w.  j  ava2 s.c  o  m*/
 * @throws RuntimeException if the job wasn't created for other reasons.
 */
public void createOrUpdateJob(JenkinsServerConfiguration jsc, String name, JobType type,
        Map<String, Object> params) throws IOException {
    JenkinsServer server = JenkinsProvider.getJenkinsServer(jsc);
    VelocityContext velocityContext = new VelocityContext(params);
    StringWriter writer = new StringWriter();
    JarFile jarFile = new JarFile(sitePaths.plugins_dir.getAbsoluteFile() + File.separator + "gerrit-ci.jar");
    if (params.get("junitEnabled").toString().equals("false")) {
        params.put("junitPath", "");
    }
    IOUtils.copy(jarFile.getInputStream(jarFile.getEntry("templates" + type.getTemplate())), writer);
    String jobTemplate = writer.toString();
    writer = new StringWriter();
    IOUtils.copy(jarFile.getInputStream(jarFile.getEntry("scripts/prebuild-commands.sh")), writer);
    // We must escape special characters as this will be rendered into XML
    String prebuildScript = writer.toString().replace("&", "&amp;").replace(">", "&gt;").replace("<", "&lt;");
    params.put("cleanCommands", prebuildScript);
    StringWriter xmlWriter = new StringWriter();
    Velocity.evaluate(velocityContext, xmlWriter, "", jobTemplate);
    String jobXml = xmlWriter.toString();
    jarFile.close();
    if (JenkinsProvider.jobExists(jsc, name)) {
        try {
            server.updateJob(name, jobXml, false);
        } catch (IOException e) {
            throw new RuntimeException(String.format("Failed to update Jenkins job: %s", name), e);
        }
    } else {
        try {
            server.createJob(name, jobXml, false);
        } catch (IOException e) {
            throw new RuntimeException(String.format("Failed to create Jenkins job: %s", name), e);
        }
    }
}

From source file:org.ut.biolab.medsavant.client.plugin.AppController.java

public AppDescriptor getDescriptorFromFile(File f) throws PluginVersionException {
    XMLStreamReader reader;/*from   ww w  .j  a v a  2s  . c  o m*/

    try {
        JarFile jar = new JarFile(f);
        ZipEntry entry = jar.getEntry("plugin.xml");
        if (entry != null) {
            InputStream entryStream = jar.getInputStream(entry);
            reader = XMLInputFactory.newInstance().createXMLStreamReader(entryStream);
            String className = null;
            String id = null;
            String version = null;
            String sdkVersion = null;
            String name = null;
            String category = AppDescriptor.Category.UTILITY.toString();
            String currentElement = null;
            String currentText = "";
            do {
                switch (reader.next()) {
                case XMLStreamConstants.START_ELEMENT:
                    switch (readElement(reader)) {
                    case PLUGIN:
                        className = readAttribute(reader, AppDescriptor.PluginXMLAttribute.CLASS);

                        //category can be specified as an attribute or <property>.
                        category = readAttribute(reader, AppDescriptor.PluginXMLAttribute.CATEGORY);
                        break;

                    case ATTRIBUTE:
                        if ("sdk-version".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.ID))) {
                            sdkVersion = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                        }
                        break;

                    case PARAMETER:
                        if ("name".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.ID))) {
                            name = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                        }
                        break;

                    case PROPERTY:
                        if ("name".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.NAME))) {
                            name = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                            if (name == null) {
                                currentElement = "name";
                            }
                        }

                        if ("version".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.NAME))) {
                            version = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                            if (version == null) {
                                currentElement = "version";
                            }
                        }

                        if ("sdk-version"
                                .equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.NAME))) {
                            sdkVersion = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                            if (sdkVersion == null) {
                                currentElement = "sdk-version";
                            }
                        }

                        if ("category".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.NAME))) {
                            category = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                            if (category == null) {
                                currentElement = "category";
                            }
                        }

                        break;
                    }
                    break;

                case XMLStreamConstants.CHARACTERS:
                    if (reader.isWhiteSpace()) {
                        break;
                    } else if (currentElement != null) {
                        currentText += reader.getText().trim().replace("\t", "");
                    }
                    break;

                case XMLStreamConstants.END_ELEMENT:
                    if (readElement(reader) == AppDescriptor.PluginXMLElement.PROPERTY) {
                        if (currentElement != null && currentText.length() > 0) {
                            if (currentElement.equals("name")) {
                                name = currentText;
                            } else if (currentElement.equals("sdk-version")) {
                                sdkVersion = currentText;
                            } else if (currentElement.equals("category")) {
                                category = currentText;
                            } else if (currentElement.equals("version")) {
                                version = currentText;
                            }
                        }
                        currentText = "";
                        currentElement = null;
                    }
                    break;

                case XMLStreamConstants.END_DOCUMENT:
                    reader.close();
                    reader = null;
                    break;
                }
            } while (reader != null);

            System.out.println(className + " " + name + " " + version);

            if (className != null && name != null && version != null) {
                return new AppDescriptor(className, version, name, sdkVersion, category, f);
            }
        }
    } catch (Exception x) {
        LOG.error("Error parsing plugin.xml from " + f.getAbsolutePath() + ": " + x);
    }
    throw new PluginVersionException(f.getName() + " did not contain a valid plugin");
}

From source file:org.kantega.revoc.source.MavenSourceArtifactSourceSource.java

public String[] getSource(String className, ClassLoader classLoader) {

    URL resource = classLoader.getResource(className + ".class");

    String filePath = getFilePath(resource);

    if (filePath == null) {
        return null;
    }//  ww  w.  j  ava 2s  . com

    try {

        MavenSourceInfo info;

        synchronized (mavenInfoMap) {

            if (!mavenInfoMap.containsKey(filePath)) {
                mavenInfoMap.put(filePath, parseInfo(filePath, resource));
            }
            info = mavenInfoMap.get(filePath);
        }

        JarFile sourceFile;
        synchronized (sourceFileMap) {
            if (!sourceFileMap.containsKey(filePath)) {
                sourceFileMap.put(filePath, getSourceFile(filePath, info));
            }
            sourceFile = sourceFileMap.get(filePath);
        }

        if (sourceFile == null) {
            return null;
        }
        String sourcePath = className.replace('.', '/') + ".java";
        ZipEntry entry = sourceFile.getEntry(sourcePath);
        if (entry == null) {
            return null;
        }
        InputStream inputStream = sourceFile.getInputStream(entry);
        List<String> lines = IOUtils.readLines(inputStream);
        return lines.toArray(new String[lines.size()]);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

From source file:org.jtheque.modules.impl.ModuleLoader.java

/**
 * Read the config of the module.//from   w w  w  .ja v a  2  s. c o  m
 *
 * @param file The file of the module.
 *
 * @return The module resources.
 *
 * @throws IOException If an error occurs during Jar File reading.
 * @throws org.jtheque.modules.ModuleException
 *                     If the config cannot be read.
 */
private ModuleResources readConfig(File file) throws IOException, ModuleException {
    JarFile jarFile = null;
    try {
        jarFile = new JarFile(file);

        ZipEntry configEntry = jarFile.getEntry("module.xml");

        if (configEntry == null) {
            return new ModuleResources(CollectionUtils.<ImageResource>emptyList(),
                    CollectionUtils.<I18NResource>emptyList(), CollectionUtils.<Resource>emptyList());
        }

        ModuleResources resources = importConfig(jarFile.getInputStream(configEntry));

        //Install necessary resources before installing the bundle
        for (Resource resource : resources.getResources()) {
            if (resource != null) {
                resourceService.installResource(resource);
            }
        }

        return resources;
    } finally {
        if (jarFile != null) {
            jarFile.close();
        }
    }
}

From source file:eu.stratosphere.yarn.Client.java

private File generateDefaultConf(Path localJarPath) throws IOException, FileNotFoundException {
    JarFile jar = null;
    try {//from w  w w. jav a2s  . c  o m
        jar = new JarFile(localJarPath.toUri().getPath());
    } catch (FileNotFoundException fne) {
        LOG.fatal("Unable to access jar file. Specify jar file or configuration file.", fne);
        System.exit(1);
    }
    InputStream confStream = jar.getInputStream(jar.getEntry("stratosphere-conf.yaml"));

    if (confStream == null) {
        LOG.warn("Given jar file does not contain yaml conf.");
        confStream = this.getClass().getResourceAsStream("stratosphere-conf.yaml");
        if (confStream == null) {
            throw new RuntimeException("Unable to find stratosphere-conf in jar file");
        }
    }
    File outFile = new File("stratosphere-conf.yaml");
    if (outFile.exists()) {
        throw new RuntimeException("File unexpectedly exists");
    }
    FileOutputStream outputStream = new FileOutputStream(outFile);
    int read = 0;
    byte[] bytes = new byte[1024];
    while ((read = confStream.read(bytes)) != -1) {
        outputStream.write(bytes, 0, read);
    }
    confStream.close();
    outputStream.close();
    jar.close();
    return outFile;
}

From source file:de.nmichael.efa.Daten.java

public static Vector getEfaInfos(boolean efaInfos, boolean pluginInfos, boolean javaInfos, boolean hostInfos,
        boolean jarInfos) {
    Vector infos = new Vector();

    // efa-Infos/* w  ww  . ja va 2s  . co m*/
    if (efaInfos) {
        infos.add("efa.version=" + Daten.VERSIONID);
        if (EFALIVE_VERSION != null && EFALIVE_VERSION.length() > 0) {
            infos.add("efalive.version=" + Daten.EFALIVE_VERSION);
        }
        if (applID != APPL_EFABH || applMode == APPL_MODE_ADMIN) {
            if (Daten.efaMainDirectory != null) {
                infos.add("efa.dir.main=" + Daten.efaMainDirectory);
            }
            if (Daten.efaBaseConfig != null && Daten.efaBaseConfig.efaUserDirectory != null) {
                infos.add("efa.dir.user=" + Daten.efaBaseConfig.efaUserDirectory);
            }
            if (Daten.efaProgramDirectory != null) {
                infos.add("efa.dir.program=" + Daten.efaProgramDirectory);
            }
            if (Daten.efaPluginDirectory != null) {
                infos.add("efa.dir.plugin=" + Daten.efaPluginDirectory);
            }
            if (Daten.efaDocDirectory != null) {
                infos.add("efa.dir.doc=" + Daten.efaDocDirectory);
            }
            if (Daten.efaDataDirectory != null) {
                infos.add("efa.dir.data=" + Daten.efaDataDirectory);
            }
            if (Daten.efaCfgDirectory != null) {
                infos.add("efa.dir.cfg=" + Daten.efaCfgDirectory);
            }
            if (Daten.efaBakDirectory != null) {
                infos.add("efa.dir.bak=" + Daten.efaBakDirectory);
            }
            if (Daten.efaTmpDirectory != null) {
                infos.add("efa.dir.tmp=" + Daten.efaTmpDirectory);
            }
        }
    }

    // efa Plugin-Infos
    if (pluginInfos) {
        try {
            File dir = new File(Daten.efaPluginDirectory);
            if ((applID != APPL_EFABH || applMode == APPL_MODE_ADMIN) && Logger.isDebugLogging()) {
                File[] files = dir.listFiles();
                for (File file : files) {
                    if (file.isFile()) {
                        infos.add("efa.plugin.file=" + file.getName() + ":" + file.length());
                    }
                }
            }

            Plugins plugins = Plugins.getPluginInfoFromLocalFile();
            String[] names = plugins.getAllPluginNames();
            for (String name : names) {
                infos.add("efa.plugin." + name + "="
                        + (Plugins.isPluginInstalled(name) ? "installed" : "not installed"));
            }
        } catch (Exception e) {
            Logger.log(Logger.ERROR, Logger.MSG_CORE_INFOFAILED,
                    International.getString("Programminformationen konnten nicht ermittelt werden") + ": "
                            + e.toString());
            return null;
        }
    }

    // Java Infos
    if (javaInfos) {
        infos.add("java.version=" + System.getProperty("java.version"));
        infos.add("java.vendor=" + System.getProperty("java.vendor"));
        infos.add("java.home=" + System.getProperty("java.home"));
        infos.add("java.vm.version=" + System.getProperty("java.vm.version"));
        infos.add("java.vm.vendor=" + System.getProperty("java.vm.vendor"));
        infos.add("java.vm.name=" + System.getProperty("java.vm.name"));
        infos.add("os.name=" + System.getProperty("os.name"));
        infos.add("os.arch=" + System.getProperty("os.arch"));
        infos.add("os.version=" + System.getProperty("os.version"));
        if (applID != APPL_EFABH || applMode == APPL_MODE_ADMIN) {
            infos.add("user.home=" + System.getProperty("user.home"));
            infos.add("user.name=" + System.getProperty("user.name"));
            infos.add("user.dir=" + System.getProperty("user.dir"));
            infos.add("java.class.path=" + System.getProperty("java.class.path"));
        }
    }

    // Host Infos
    if (hostInfos) {
        if (applID != APPL_EFABH || applMode == APPL_MODE_ADMIN) {
            try {
                infos.add("host.name=" + InetAddress.getLocalHost().getCanonicalHostName());
                infos.add("host.ip=" + InetAddress.getLocalHost().getHostAddress());
                infos.add("host.interface=" + EfaUtil
                        .getInterfaceInfo(NetworkInterface.getByInetAddress(InetAddress.getLocalHost())));
            } catch (Exception eingore) {
            }
        }
    }

    // JAR methods
    if (jarInfos && Logger.isDebugLogging()) {
        try {
            String cp = System.getProperty("java.class.path");
            while (cp != null && cp.length() > 0) {
                int pos = cp.indexOf(";");
                if (pos < 0) {
                    pos = cp.indexOf(":");
                }
                String jarfile;
                if (pos >= 0) {
                    jarfile = cp.substring(0, pos);
                    cp = cp.substring(pos + 1);
                } else {
                    jarfile = cp;
                    cp = null;
                }
                if (jarfile != null && jarfile.length() > 0 && new File(jarfile).isFile()) {
                    try {
                        infos.add("java.jar.filename=" + jarfile);
                        JarFile jar = new JarFile(jarfile);
                        Enumeration _enum = jar.entries();
                        Object o;
                        while (_enum.hasMoreElements() && (o = _enum.nextElement()) != null) {
                            infos.add(
                                    "java.jar.content=" + o + ":" + (jar.getEntry(o.toString()) == null ? "null"
                                            : Long.toString(jar.getEntry(o.toString()).getSize())));
                        }
                        jar.close();
                    } catch (Exception e) {
                        Logger.log(Logger.ERROR, Logger.MSG_CORE_INFOFAILED, e.toString());
                        return null;
                    }
                }
            }
        } catch (Exception e) {
            Logger.log(Logger.ERROR, Logger.MSG_CORE_INFOFAILED,
                    International.getString("Programminformationen konnten nicht ermittelt werden") + ": "
                            + e.toString());
            return null;
        }
    }
    return infos;
}

From source file:org.apache.flink.yarn.Client.java

private File generateDefaultConf(Path localJarPath) throws IOException, FileNotFoundException {
    JarFile jar = null;
    try {//w  ww . j a v  a 2s. co  m
        jar = new JarFile(localJarPath.toUri().getPath());
    } catch (FileNotFoundException fne) {
        LOG.error("Unable to access jar file. Specify jar file or configuration file.", fne);
        System.exit(1);
    }
    InputStream confStream = jar.getInputStream(jar.getEntry("flink-conf.yaml"));

    if (confStream == null) {
        LOG.warn("Given jar file does not contain yaml conf.");
        confStream = this.getClass().getResourceAsStream("flink-conf.yaml");
        if (confStream == null) {
            throw new RuntimeException("Unable to find flink-conf in jar file");
        }
    }
    File outFile = new File("flink-conf.yaml");
    if (outFile.exists()) {
        throw new RuntimeException("File unexpectedly exists");
    }
    FileOutputStream outputStream = new FileOutputStream(outFile);
    int read = 0;
    byte[] bytes = new byte[1024];
    while ((read = confStream.read(bytes)) != -1) {
        outputStream.write(bytes, 0, read);
    }
    confStream.close();
    outputStream.close();
    jar.close();
    return outFile;
}

From source file:org.apache.archiva.rest.services.DefaultBrowseService.java

@Override
public ArtifactContent getArtifactContentText(String groupId, String artifactId, String version,
        String classifier, String type, String path, String repositoryId) throws ArchivaRestServiceException {
    List<String> selectedRepos = getSelectedRepos(repositoryId);
    try {//from w  w w.java  2s . c o m
        for (String repoId : selectedRepos) {

            ManagedRepositoryContent managedRepositoryContent = repositoryContentFactory
                    .getManagedRepositoryContent(repoId);
            ArchivaArtifact archivaArtifact = new ArchivaArtifact(groupId, artifactId, version, classifier,
                    StringUtils.isEmpty(type) ? "jar" : type, repoId);
            File file = managedRepositoryContent.toFile(archivaArtifact);
            if (!file.exists()) {
                log.debug("file: {} not exists for repository: {} try next repository", file, repoId);
                continue;
            }
            if (StringUtils.isNotBlank(path)) {
                // zip entry of the path -> path must a real file entry of the archive
                JarFile jarFile = new JarFile(file);
                ZipEntry zipEntry = jarFile.getEntry(path);
                try (InputStream inputStream = jarFile.getInputStream(zipEntry)) {
                    return new ArtifactContent(IOUtils.toString(inputStream), repoId);
                } finally {
                    closeQuietly(jarFile);
                }
            }
            return new ArtifactContent(FileUtils.readFileToString(file), repoId);
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new ArchivaRestServiceException(e.getMessage(),
                Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e);
    } catch (RepositoryNotFoundException e) {
        log.error(e.getMessage(), e);
        throw new ArchivaRestServiceException(e.getMessage(),
                Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e);
    } catch (RepositoryException e) {
        log.error(e.getMessage(), e);
        throw new ArchivaRestServiceException(e.getMessage(),
                Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e);
    }
    log.debug("artifact: {}:{}:{}:{}:{} not found", groupId, artifactId, version, classifier, type);
    // 404 ?
    return new ArtifactContent();
}