Example usage for java.util.jar JarFile JarFile

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

Introduction

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

Prototype

public JarFile(File file) throws IOException 

Source Link

Document

Creates a new JarFile to read from the specified File object.

Usage

From source file:org.ebayopensource.turmeric.eclipse.core.Activator.java

/**
 * Old type library jar(NOT in workspace) has the dir structure \types\<xsd>
 * and the new one has meta-src\types\<typeLibName>\<xsd>
 * //from   w  w w.  j  a  v  a  2 s.  co m
 * @return
 * @throws IOException
 * @throws URISyntaxException
 */
public static boolean isNewTypLibrary(URL jarURL, String projectName) throws IOException {
    File file = new File(jarURL.getPath());
    JarFile jarFile;
    jarFile = new JarFile(file);
    return jarFile.getEntry(TYPES_LOCATION_IN_JAR + WorkspaceUtil.PATH_SEPERATOR + projectName) != null;

}

From source file:javadepchecker.Main.java

private static boolean checkPkg(File env) {
    boolean needed = true;
    HashSet<String> pkgs = new HashSet<String>();
    Collection<String> deps = null;

    BufferedReader in = null;/*from  ww w  . ja  v  a 2s . co m*/
    try {
        Pattern dep_re = Pattern.compile("^DEPEND=\"([^\"]*)\"$");
        Pattern cp_re = Pattern.compile("^CLASSPATH=\"([^\"]*)\"$");

        String line;
        in = new BufferedReader(new FileReader(env));
        while ((line = in.readLine()) != null) {
            Matcher m = dep_re.matcher(line);
            if (m.matches()) {
                String atoms = m.group(1);
                for (String atom : atoms.split(":")) {
                    String pkg = atom;
                    if (atom.contains("@")) {
                        pkg = atom.split("@")[1];
                    }
                    pkgs.add(pkg);
                }
                continue;
            }
            m = cp_re.matcher(line);
            if (m.matches()) {
                Main classParser = new Main();
                for (String jar : m.group(1).split(":")) {
                    if (jar.endsWith(".jar")) {
                        classParser.processJar(new JarFile(image + jar));
                    }
                }
                deps = classParser.getDeps();
            }
        }

        for (String pkg : pkgs) {
            if (!depNeeded(pkg, deps)) {
                System.out.println(pkg);
                needed = false;
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            in.close();
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return needed;
}

From source file:javadepchecker.Main.java

private static boolean checkPkg(File env) {
    boolean needed = true;
    HashSet<String> pkgs = new HashSet<String>();
    Collection<String> deps = null;

    BufferedReader in = null;//from  w  ww  . j  av a2 s  .  c  o m
    try {
        Pattern dep_re = Pattern.compile("^DEPEND=\"([^\"]*)\"$");
        Pattern cp_re = Pattern.compile("^CLASSPATH=\"([^\"]*)\"$");

        String line;
        in = new BufferedReader(new FileReader(env));
        while ((line = in.readLine()) != null) {
            Matcher m = dep_re.matcher(line);
            if (m.matches()) {
                String atoms = m.group(1);
                for (String atom : atoms.split(":")) {
                    String pkg = atom;
                    if (atom.contains("@")) {
                        pkg = atom.split("@")[1];
                    }
                    pkgs.add(pkg);
                }
                continue;
            }
            m = cp_re.matcher(line);
            if (m.matches()) {
                Main classParser = new Main();
                for (String jar : m.group(1).split(":")) {
                    classParser.processJar(new JarFile(image + jar));
                }
                deps = classParser.getDeps();
            }
        }

        for (String pkg : pkgs) {
            if (!depNeeded(pkg, deps)) {
                System.out.println(pkg);
                needed = false;
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            in.close();
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return needed;
}

From source file:com.mgmtp.perfload.core.console.meta.LtMetaInfoHandler.java

/**
 * Dumps the specified meta information to specified writer.
 * /*from   ww  w .  ja  va2s.  co m*/
 * @param metaInfo
 *            the meta information object
 * @param writer
 *            the writer
 */
public void dumpMetaInfo(final LtMetaInfo metaInfo, final Writer writer) {
    PrintWriter pr = new PrintWriter(writer);

    URL url = getClass().getProtectionDomain().getCodeSource().getLocation();
    if (url.getPath().endsWith(".jar")) {
        try {
            JarFile jarFile = new JarFile(toFile(url));
            Manifest mf = jarFile.getManifest();
            Attributes attr = mf.getMainAttributes();
            pr.printf("perfload.implementation.version=%s", attr.getValue("Implementation-Version"));
            pr.println();
            pr.printf("perfload.implementation.date=%s", attr.getValue("Implementation-Date"));
            pr.println();
            pr.printf("perfload.implementation.revision=%s", attr.getValue("Implementation-Revision"));
            pr.println();
        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
        }
    }

    pr.printf("test.file=%s", metaInfo.getTestplanFileName());
    pr.println();

    pr.printf("test.start=%s", DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(metaInfo.getStartTimestamp()));
    pr.println();
    pr.printf("test.finish=%s", DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(metaInfo.getFinishTimestamp()));
    pr.println();

    List<Daemon> daemonList = metaInfo.getDaemons();
    Collections.sort(daemonList);

    for (Daemon daemon : daemonList) {
        pr.printf("daemon.%d=%s:%d", daemon.getId(), daemon.getHost(), daemon.getPort());
        pr.println();
    }

    List<String> lpTargets = metaInfo.getLpTargets();
    if (!lpTargets.isEmpty()) {
        Collections.sort(lpTargets);
        pr.printf("targets=%s", on(',').join(lpTargets));
        pr.println();
    }

    List<String> lpOperations = metaInfo.getLpOperations();
    if (!lpOperations.isEmpty()) {
        Collections.sort(lpOperations);
        pr.printf("operations=%s", on(',').join(lpOperations));
        pr.println();
    }

    List<Executions> executionsList = metaInfo.getExecutionsList();
    Collections.sort(executionsList);
    for (Executions executions : executionsList) {
        pr.printf("executions.%s.%s=%d", executions.operation, executions.target, executions.executions);
        pr.println();
    }
}

From source file:com.impetus.kundera.classreading.ClasspathReader.java

/**
 * Scan class resource in the provided urls with the additional Class-Path
 * of each jar checking/*from w ww. ja  v a2 s. c om*/
 * 
 * @param classRelativePath
 *            relative path to a class resource
 * @param urls
 *            urls to be checked
 * @return list of class path included in the base package
 */
private URL[] findResourcesInUrls(String classRelativePath, URL[] urls) {
    List<URL> list = new ArrayList<URL>();
    for (URL url : urls) {
        if (AllowedProtocol.isValidProtocol(url.getProtocol().toUpperCase())
                && url.getPath().endsWith(".jar")) {
            try {
                JarFile jarFile = new JarFile(URLDecoder.decode(url.getFile(), Constants.CHARSET_UTF8));

                // Checking the dependencies of this jar file
                Manifest manifest = jarFile.getManifest();
                if (manifest != null) {
                    String classPath = manifest.getMainAttributes().getValue("Class-Path");
                    // Scan all entries in the classpath if they are
                    // specified in the jar
                    if (!StringUtils.isEmpty(classPath)) {
                        List<URL> subList = new ArrayList<URL>();
                        for (String cpEntry : classPath.split(" ")) {
                            try {
                                subList.add(new URL(cpEntry));
                            } catch (MalformedURLException e) {
                                URL subResources = ClasspathReader.class.getClassLoader().getResource(cpEntry);
                                if (subResources != null) {
                                    subList.add(subResources);
                                }
                                // logger.warn("Incorrect URL in the classpath of a jar file ["
                                // + url.toString()
                                // + "]: " + cpEntry);
                            }
                        }
                        list.addAll(Arrays.asList(findResourcesInUrls(classRelativePath,
                                subList.toArray(new URL[subList.size()]))));
                    }
                }
                JarEntry present = jarFile.getJarEntry(classRelativePath + ".class");
                if (present != null) {
                    list.add(url);
                }
            } catch (IOException e) {
                logger.warn("Error during loading from context , Caused by:" + e.getMessage());
            }

        } else if (url.getPath().endsWith("/")) {
            File file = new File(url.getPath() + classRelativePath + ".class");
            if (file.exists()) {
                try {
                    list.add(file.toURL());
                } catch (MalformedURLException e) {
                    throw new ResourceReadingException(e);
                }
            }
        }

    }
    return list.toArray(new URL[list.size()]);
}

From source file:com.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfigurator.java

@Override
public void configure(ProjectServiceConfiguration configuration) {

    // Get a reference to our template WAR, and make sure it exists.
    File jenkinsTemplateWar = new File(warTemplateFile);

    if (!jenkinsTemplateWar.exists() || !jenkinsTemplateWar.isFile()) {
        String message = "The given Jenkins template WAR [" + jenkinsTemplateWar
                + "] either did not exist or was not a file!";
        LOG.error(message);// www. j av a 2  s  . co m
        throw new IllegalStateException(message);
    }

    String pathProperty = perOrg ? configuration.getOrganizationIdentifier()
            : configuration.getProjectIdentifier();

    String deployedUrl = configuration.getProperties().get(ProjectServiceConfiguration.PROFILE_BASE_URL)
            + jenkinsPath + pathProperty + "/jenkins/";
    deployedUrl.replace("//", "/");
    URL deployedJenkinsUrl;
    try {
        deployedJenkinsUrl = new URL(deployedUrl);
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
    String webappName = deployedJenkinsUrl.getPath();
    if (webappName.startsWith("/")) {
        webappName = webappName.substring(1);
    }
    if (webappName.endsWith("/")) {
        webappName = webappName.substring(0, webappName.length() - 1);
    }
    webappName = webappName.replace("/", "#");
    webappName = webappName + ".war";

    // Calculate our final filename.

    String deployLocation = targetWebappsDir + webappName;

    File jenkinsDeployFile = new File(deployLocation);

    if (jenkinsDeployFile.exists()) {
        String message = "When trying to deploy new WARfile [" + jenkinsDeployFile.getAbsolutePath()
                + "] a file or directory with that name already existed! Continuing with provisioning.";
        LOG.info(message);
        return;
    }

    try {
        // Get a reference to our template war
        JarFile jenkinsTemplateWarJar = new JarFile(jenkinsTemplateWar);

        // Extract our web.xml from this war
        JarEntry webXmlEntry = jenkinsTemplateWarJar.getJarEntry(webXmlFilename);
        String webXmlContents = IOUtils.toString(jenkinsTemplateWarJar.getInputStream(webXmlEntry));

        // Update the web.xml to contain the correct JENKINS_HOME value
        String updatedXml = applyDirectoryToWebXml(webXmlContents, configuration);

        File tempDirFile = new File(tempDir);
        if (!tempDirFile.exists()) {
            tempDirFile.mkdirs();
        }

        // Put the web.xml back into the war
        File updatedJenkinsWar = File.createTempFile("jenkins", ".war", tempDirFile);

        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(updatedJenkinsWar),
                jenkinsTemplateWarJar.getManifest());

        // Loop through our existing zipfile and add in all of the entries to it except for our web.xml
        JarEntry curEntry = null;
        Enumeration<JarEntry> entries = jenkinsTemplateWarJar.entries();
        while (entries.hasMoreElements()) {
            curEntry = entries.nextElement();

            // If this is the manifest, skip it.
            if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                continue;
            }

            if (curEntry.getName().equals(webXmlEntry.getName())) {
                JarEntry newEntry = new JarEntry(curEntry.getName());
                jarOutStream.putNextEntry(newEntry);

                // Substitute our edited entry content.
                IOUtils.write(updatedXml, jarOutStream);
            } else {
                jarOutStream.putNextEntry(curEntry);
                IOUtils.copy(jenkinsTemplateWarJar.getInputStream(curEntry), jarOutStream);
            }
        }

        // Clean up our resources.
        jarOutStream.close();

        // Move the war into its deployment location so that it can be picked up and deployed by the app server.
        FileUtils.moveFile(updatedJenkinsWar, jenkinsDeployFile);
    } catch (IOException ioe) {
        // Log this exception and rethrow wrapped in a RuntimeException
        LOG.error(ioe.getMessage());
        throw new RuntimeException(ioe);
    }
}

From source file:ezbake.deployer.utilities.VersionHelper.java

private static String getVersionFromPomProperties(File artifact) throws IOException {
    List<JarEntry> pomPropertiesFiles = new ArrayList<>();
    String versionNumber = null;/*from w w  w .j  a va  2s  .  c o m*/
    try (JarFile jar = new JarFile(artifact)) {
        JarEntry entry;
        Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            entry = entries.nextElement();
            if (!entry.isDirectory() && entry.getName().endsWith("pom.properties")) {
                pomPropertiesFiles.add(entry);
            }
        }

        if (pomPropertiesFiles.size() == 1) {
            Properties pomProperties = new Properties();
            pomProperties.load(jar.getInputStream(pomPropertiesFiles.get(0)));
            versionNumber = pomProperties.getProperty("version", null);
        } else {
            logger.debug("Found {} pom.properties files. Cannot use that for version",
                    pomPropertiesFiles.size());
        }
    }
    return versionNumber;
}

From source file:edu.sampleu.admin.EdocLiteXmlIngesterBase.java

protected String[] getResourceListing(Class clazz, String pathStartsWith) throws Exception {
    String classPath = clazz.getName().replace(".", "/") + ".class";
    URL dirUrl = clazz.getClassLoader().getResource(classPath);

    if (!"jar".equals(dirUrl.getProtocol())) {
        throw new UnsupportedOperationException("Cannot list files for URL " + dirUrl);
    }//  ww  w .j av  a 2 s . com

    String jarPath = dirUrl.getPath().substring(5, dirUrl.getPath().indexOf("!")); //strip out only the JAR file
    JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
    Enumeration<JarEntry> entries = jar.entries();
    Set<String> result = new HashSet<String>();

    while (entries.hasMoreElements()) {
        String entry = entries.nextElement().getName();
        if (entry.startsWith(pathStartsWith) && !entry.endsWith("/")) { //filter according to the pathStartsWith skipping directories
            result.add(entry);
        }
    }

    return result.toArray(new String[result.size()]);
}

From source file:org.ebayopensource.turmeric.tools.codegen.util.ClassPathUtil.java

private static List<File> getJarClassPathRefs(File file) {
    List<File> refs = new ArrayList<File>();

    JarFile jar = null;/*from  ww  w .j a v  a2s  .  c  om*/
    try {
        jar = new JarFile(file);
        Manifest manifest = jar.getManifest();
        if (manifest == null) {
            // No manifest, no classpath.
            return refs;
        }

        Attributes attrs = manifest.getMainAttributes();
        if (attrs == null) {
            /*
             * No main attributes. (not sure how that's possible, but we can skip this jar)
             */
            return refs;
        }
        String classPath = attrs.getValue(Attributes.Name.CLASS_PATH);
        if (CodeGenUtil.isEmptyString(classPath)) {
            return refs;
        }

        String parentDir = FilenameUtils.getFullPath(file.getAbsolutePath());
        File possible;
        for (String path : StringUtils.splitStr(classPath, ' ')) {
            possible = new File(path);

            if (!possible.isAbsolute()) {
                // relative path?
                possible = new File(FilenameUtils.normalize(parentDir + path));
            }

            if (!refs.contains(possible)) {
                refs.add(possible);
            }
        }
    } catch (IOException e) {
        LOG.log(Level.WARNING, "Unable to load/read/parse Jar File: " + file.getAbsolutePath(), e);
    } finally {
        CodeGenUtil.closeQuietly(jar);
    }

    return refs;
}

From source file:generate.MapGenerateAction.java

@Override
public String execute() {

    String file_path = "/home/chanakya/NetBeansProjects/Concepto/UploadedFiles";
    try {/*from  w w  w . j a  va  2s  . c om*/
        File fileToCreate = new File(file_path, concept_map.getUploadedFileFileName());
        FileUtils.copyFile(concept_map.getUploadedFile(), fileToCreate);
    } catch (Throwable t) {
        System.out.println("E1: " + t.getMessage());
        return ERROR;
    }
    try {
        List<String> temp_text = FileUtils.readLines(concept_map.getUploadedFile());
        StringBuilder text = new StringBuilder();
        for (String s : temp_text) {
            text.append(s);
        }
        concept_map.setInput_text(text.toString());
    } catch (IOException e) {
        //e.printStackTrace();
        System.out.println("E2: " + e.getMessage());
        return ERROR;
    }
    String temp_filename = concept_map.getUploadedFileFileName().split("\\.(?=[^\\.]+$)")[0];
    temp_filename = temp_filename.trim();

    try {
        String temp = "java -jar /home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCore.jar "
                + file_path + " " + temp_filename;
        System.out.println(temp);
        File jarfile = new File("/home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCore.jar");
        JarFile jar = new JarFile(jarfile);
        Manifest manifest = jar.getManifest();
        Attributes attrs = manifest.getMainAttributes();
        String mainClassName = attrs.getValue(Attributes.Name.MAIN_CLASS);
        System.out.println(mainClassName);
        URL url = new URL("file", null, jarfile.getAbsolutePath());
        ClassLoader cl = new URLClassLoader(new URL[] { url });
        Class mainClass = cl.loadClass(mainClassName);
        Method mainMethod = mainClass.getMethod("main", new Class[] { String[].class });
        String[] args = new String[2];
        args[0] = file_path;
        args[1] = temp_filename;
        System.out.println(args[0]);
        System.out.println(args[1]);
        try {
            mainMethod.invoke(mainClass, new Object[] { args });
        } catch (InvocationTargetException e) {
            System.out.println("This is the exception: " + e.getTargetException().toString());
        }
    } catch (IllegalArgumentException | IllegalAccessException | NoSuchMethodException | ClassNotFoundException
            | IOException e) {
        System.out.println("E3: " + e.getMessage());
        return ERROR;
    }

    try {
        String temp2 = "java -jar /home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCoreII.jar "
                + file_path + " " + temp_filename;
        System.out.println(temp2);
        File jarfile = new File("/home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCoreII.jar");
        JarFile jar = new JarFile(jarfile);
        Manifest manifest = jar.getManifest();
        Attributes attrs = manifest.getMainAttributes();
        String mainClassName = attrs.getValue(Attributes.Name.MAIN_CLASS);
        System.out.println(mainClassName);
        URL url = new URL("file", null, jarfile.getAbsolutePath());
        ClassLoader cl = new URLClassLoader(new URL[] { url });
        Class mainClass = cl.loadClass(mainClassName);
        Method mainMethod = mainClass.getMethod("main", new Class[] { String[].class });
        String[] args = new String[2];
        args[0] = file_path;
        args[1] = temp_filename;
        mainMethod.invoke(mainClass, new Object[] { args });
    } catch (InvocationTargetException | IllegalArgumentException | IllegalAccessException
            | NoSuchMethodException | ClassNotFoundException | IOException e) {
        System.out.println("E4: " + e.getMessage());
        return ERROR;
    }

    String cmd = "python /home/chanakya/NetBeansProjects/Concepto/src/java/generate/add_to_graph.py \"/home/chanakya/NetBeansProjects/Concepto/UploadedFiles/"
            + temp_filename + "_OllieOutput.txt\"";
    String[] finalCommand;
    finalCommand = new String[3];
    finalCommand[0] = "/bin/sh";
    finalCommand[1] = "-c";
    finalCommand[2] = cmd;
    System.out.println("CMD: " + cmd);
    try {
        //ProcessBuilder builder = new ProcessBuilder(finalCommand);
        //builder.redirectErrorStream(true);
        //Process process = builder.start();
        Process process = Runtime.getRuntime().exec(finalCommand);
        int exitVal = process.waitFor();
        System.out.println("Process exitValue2: " + exitVal);
    } catch (Throwable t) {
        System.out.println("E5: " + t.getMessage());
        return ERROR;
    }

    cmd = "python /home/chanakya/NetBeansProjects/Concepto/src/java/generate/json_correct.py";
    finalCommand = new String[3];
    finalCommand[0] = "/bin/sh";
    finalCommand[1] = "-c";
    finalCommand[2] = cmd;

    try {
        //Process process = Runtime.getRuntime().exec(finalCommand);

        ProcessBuilder builder = new ProcessBuilder(finalCommand);
        // builder.redirectErrorStream(true);
        Process process = builder.start();
        int exitVal = process.waitFor();
        System.out.println("Process exitValue3: " + exitVal);
    } catch (Throwable t) {
        System.out.println("E6: " + t.getMessage());
        return ERROR;
    }

    try {
        List<String> temp_text_1 = FileUtils
                .readLines(FileUtils.getFile("/home/chanakya/NetBeansProjects/Concepto/web", "new_graph.json"));
        StringBuilder text_1 = new StringBuilder();
        for (String s : temp_text_1) {
            text_1.append(s);
        }
        concept_map.setOutput_text(text_1.toString());
    } catch (IOException e) {
        System.out.println("E7: " + e.getMessage());
        return ERROR;
    }
    Random rand = new Random();
    int unique_id = rand.nextInt(99999999);
    System.out.println("Going In DB");
    try {
        MongoClient mongo = new MongoClient();
        DB db = mongo.getDB("Major");
        DBCollection collection = db.getCollection("ConceptMap");
        BasicDBObject document = new BasicDBObject();
        document.append("InputText", concept_map.getInput_text());
        document.append("OutputText", concept_map.getOutput_text());
        document.append("ChapterName", concept_map.getChapter_name());
        document.append("ChapterNumber", concept_map.getChapter_number());
        document.append("SectionName", concept_map.getSection_name());
        document.append("SectionNumber", concept_map.getSection_number());
        document.append("UniqueID", Integer.toString(unique_id));
        collection.insert(document);
        //collection.save(document);
    } catch (MongoException e) {
        System.out.println("E8: " + e.getMessage());
        return ERROR;
    } catch (UnknownHostException ex) {
        Logger.getLogger(MapGenerateAction.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("E9");
        return ERROR;
    }
    System.out.println("Out DB");
    return SUCCESS;
}