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:com.dtolabs.rundeck.ExpandRunServer.java

/**
 * Load the manifest main attributes from the enclosing jar
 *
 * @return/*  ww  w  .j a  va  2s  .  c om*/
 */
private static Attributes getJarMainAttributes() {
    Attributes mainAttributes = null;
    try {
        final File file = thisJarFile();
        final JarFile jarFile = new JarFile(file);
        mainAttributes = jarFile.getManifest().getMainAttributes();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return mainAttributes;
}

From source file:org.ebayopensource.turmeric.eclipse.typelibrary.ui.TypeLibraryUtil.java

/**
 * Gets the project name from wtp base location.
 *
 * @param baseLocationStr the base location str
 * @return the project name from wtp base location
 * @throws ParserConfigurationException the parser configuration exception
 * @throws SAXException the sAX exception
 * @throws IOException Signals that an I/O exception has occurred.
 *//*  www  .  j a  v  a2s.c o m*/
public static String getProjectNameFromWTPBaseLocation(String baseLocationStr)
        throws ParserConfigurationException, SAXException, IOException {
    IPath path = new Path(baseLocationStr);
    // this is a jar location if base location starts with jar for eg:
    // "jar:file:/D:/Views/soapost22/v3jars/services/MarketPlaceServiceCommonTypeLibrary/3.0.0/java50/MarketPlaceServiceCommonTypeLibrary.jar!/types/BaseServiceResponse.xsd"
    if (baseLocationStr.toLowerCase().startsWith("jar:file:/")) {
        JarFile jarFile = new JarFile(getJarFile(baseLocationStr.substring(10, baseLocationStr.length())));
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (entry.getName().startsWith(SOATypeLibraryConstants.INFO_DEP_XML_PATH_IN_JAR)
                    && entry.getName().endsWith(SOATypeLibraryConstants.FILE_TYPE_INFO_XML)) {
                return getTypeLibName(entry, jarFile);
            }
        }
    } else {
        // New style has the type library name also. So removing an
        // additional segment at the end.
        if (isNewStyleBaseLocation(baseLocationStr)) {
            path = path.removeLastSegments(4);
        } else {
            // removing meta-src/types/abcd.xsd
            path = path.removeLastSegments(3);
        }
    }
    return path.lastSegment();
}

From source file:dalma.container.ClassLoaderImpl.java

/**
 * Get the manifest from the given jar, if it is indeed a jar and it has a
 * manifest/* w  w w  . j av  a  2  s  . c  om*/
 *
 * @param container the File from which a manifest is required.
 *
 * @return the jar's manifest or null is the container is not a jar or it
 *         has no manifest.
 *
 * @exception IOException if the manifest cannot be read.
 */
private Manifest getJarManifest(File container) throws IOException {
    if (container.isDirectory()) {
        return null;
    }
    JarFile jarFile = null;
    try {
        jarFile = new JarFile(container);
        return jarFile.getManifest();
    } finally {
        if (jarFile != null) {
            jarFile.close();
        }
    }
}

From source file:ar.edu.taco.TacoMain.java

/**
 * /*from w ww.  j  av  a 2 s.  c o  m*/
 */
private static String getManifestAttribute(Name name) {
    String manifestAttributeValue = "Undefined";
    try {

        String jarFileName = System.getProperty("java.class.path")
                .split(System.getProperty("path.separator"))[0];
        JarFile jar = new JarFile(jarFileName);
        Manifest manifest = jar.getManifest();

        Attributes mainAttributes = manifest.getMainAttributes();
        manifestAttributeValue = mainAttributes.getValue(name);
        jar.close();
    } catch (IOException e) {
    }

    return manifestAttributeValue;
}

From source file:org.ebayopensource.turmeric.eclipse.maven.core.utils.MavenCoreUtils.java

/**
 * Gets the input stream from jar.//from w  w  w.j  a v  a  2 s. co m
 *
 * @param mProject the m project
 * @param jarEntryPath the jar entry path
 * @return The input stream for the specified jar entry
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static InputStream getInputStreamFromJar(final MavenProject mProject, final String jarEntryPath)
        throws IOException {
    if (SOALogger.DEBUG)
        logger.entering(mProject, jarEntryPath);
    final File file = getJarFileForService(mProject);

    InputStream io = null;
    if (file.exists() && file.canRead()) {
        final JarFile jarFile = new JarFile(file);
        final JarEntry jarEntry = jarFile.getJarEntry(jarEntryPath);
        if (jarEntry != null) {
            io = jarFile.getInputStream(jarEntry);
        } else {
            logger.warning("Can not find the jar entry->" + jarEntryPath);
        }
    } else {
        logger.warning("Jar file is either not exist or not readable ->" + file);
    }
    if (SOALogger.DEBUG)
        logger.exiting(io);
    return io;
}

From source file:com.evolveum.midpoint.provisioning.ucf.impl.ConnectorFactoryIcfImpl.java

/**
 * Test if provided file is connector bundle
 * //from   w  ww .j  a  va 2  s .  co  m
 * @param file
 *            tested file
 * @return boolean
 */
private Boolean isThisJarFileBundle(File file) {
    // Startup tests
    if (null == file) {
        throw new IllegalArgumentException("No file is providied for bundle test.");
    }

    // Skip all processing if it is not a file
    if (!file.isFile()) {
        LOGGER.debug("This {} is not a file", file.getAbsolutePath());
        return false;
    }

    Properties prop = new Properties();
    JarFile jar = null;
    // Open jar file
    try {
        jar = new JarFile(file);
    } catch (IOException ex) {
        LOGGER.debug("Unable to read jar file: " + file.getAbsolutePath() + " [" + ex.getMessage() + "]");
        return false;
    }

    // read jar file
    InputStream is;
    try {
        JarEntry entry = new JarEntry("META-INF/MANIFEST.MF");
        is = jar.getInputStream(entry);
    } catch (IOException ex) {
        LOGGER.debug("Unable to fine MANIFEST.MF in jar file: " + file.getAbsolutePath() + " ["
                + ex.getMessage() + "]");
        return false;
    }

    // Parse jar file
    try {
        prop.load(is);
    } catch (IOException ex) {
        LOGGER.debug("Unable to parse jar file: " + file.getAbsolutePath() + " [" + ex.getMessage() + "]");
        return false;
    } catch (NullPointerException ex) {
        LOGGER.debug("Unable to parse jar file: " + file.getAbsolutePath() + " [" + ex.getMessage() + "]");
        return false;
    }

    // Test if it is a connector
    if (null != prop.get("ConnectorBundle-Name")) {
        LOGGER.info("Discovered ICF bundle in JAR: " + prop.get("ConnectorBundle-Name") + " version: "
                + prop.get("ConnectorBundle-Version"));
        return true;
    }

    LOGGER.debug("Provided file {} is not iCF bundle jar", file.getAbsolutePath());
    return false;
}

From source file:org.openmrs.module.webservices.rest.web.RestUtil.java

/**
 * Gets a list of classes in a given package. Note that interfaces are not returned.
 * /*from  ww w .j  a  v  a 2 s . co m*/
 * @param pkgname the package name.
 * @param suffix the ending text on name. eg "Resource.class"
 * @return the list of classes.
 */
public static ArrayList<Class<?>> getClassesForPackage(String pkgname, String suffix) throws IOException {
    ArrayList<Class<?>> classes = new ArrayList<Class<?>>();

    //Get a File object for the package
    File directory = null;
    String relPath = pkgname.replace('.', '/');
    Enumeration<URL> resources = OpenmrsClassLoader.getInstance().getResources(relPath);
    while (resources.hasMoreElements()) {

        URL resource = resources.nextElement();
        if (resource == null) {
            throw new RuntimeException("No resource for " + relPath);
        }

        try {
            directory = new File(resource.toURI());
        } catch (URISyntaxException e) {
            throw new RuntimeException(pkgname + " (" + resource
                    + ") does not appear to be a valid URL / URI.  Strange, since we got it from the system...",
                    e);
        } catch (IllegalArgumentException ex) {
            //ex.printStackTrace();
        }

        //If folder exists, look for all resource class files in it.
        if (directory != null && directory.exists()) {

            //Get the list of the files contained in the package
            String[] files = directory.list();

            for (int i = 0; i < files.length; i++) {

                //We are only interested in Resource.class files
                if (files[i].endsWith(suffix)) {

                    //Remove the .class extension
                    String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6);

                    try {
                        Class<?> cls = Class.forName(className);
                        if (!cls.isInterface())
                            classes.add(cls);
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException("ClassNotFoundException loading " + className);
                    }
                }
            }
        } else {

            //Directory does not exist, look in jar file.
            try {
                String fullPath = resource.getFile();
                String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
                JarFile jarFile = new JarFile(jarPath);

                Enumeration<JarEntry> entries = jarFile.entries();
                while (entries.hasMoreElements()) {
                    JarEntry entry = entries.nextElement();

                    String entryName = entry.getName();

                    if (!entryName.endsWith(suffix))
                        continue;

                    if (entryName.startsWith(relPath)
                            && entryName.length() > (relPath.length() + "/".length())) {
                        String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");

                        try {
                            Class<?> cls = Class.forName(className);
                            if (!cls.isInterface())
                                classes.add(cls);
                        } catch (ClassNotFoundException e) {
                            throw new RuntimeException("ClassNotFoundException loading " + className);
                        }
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(
                        pkgname + " (" + directory + ") does not appear to be a valid package", e);
            }
        }
    }

    return classes;
}

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 {//w w w .j  a  v a 2  s. 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();
}

From source file:org.cytoscape.app.internal.manager.AppManager.java

private boolean checkIfCytoscapeApp(File file) {
    JarFile jarFile = null;/*from  w  ww . j  ava  2s  .c o  m*/

    try {
        jarFile = new JarFile(file);

        Manifest manifest = jarFile.getManifest();

        // Check the manifest file 
        if (manifest != null) {
            if (manifest.getMainAttributes().getValue("Cytoscape-App-Name") != null) {

                jarFile.close();
                return true;
            }
        }

        jarFile.close();
    } catch (ZipException e) {
        // Do nothing; skip file
        // e.printStackTrace();
    } catch (IOException e) {
        // Do nothing; skip file
        // e.printStackTrace();
    } finally {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (IOException e) {
            }
        }
    }

    return false;
}

From source file:org.eclipse.jubula.client.ui.rcp.widgets.autconfig.JavaAutConfigComponent.java

/** 
 * The action of the JAR name field./*from   ww w  .  j ava2 s  .c o  m*/
 * @return <code>null</code> if the new value is valid. Otherwise, returns
 *         a status parameter indicating the cause of the problem.
 */
DialogStatusParameter modifyJarFieldAction() {

    DialogStatusParameter error = null;
    boolean isEmpty = m_jarTextField.getText().length() == 0;
    if (isValid(m_jarTextField, true) && !isEmpty) {
        if (checkLocalhostServer()) {
            String filename = m_jarTextField.getText();
            File file = new File(filename);
            String workingDir = StringUtils.defaultString(getConfigValue(AutConfigConstants.WORKING_DIR));
            if (!file.isAbsolute() && workingDir.length() != 0) {

                filename = workingDir + "/" + filename; //$NON-NLS-1$
                file = new File(filename);
            }
            try {
                if (!file.exists()) {
                    error = createWarningStatus(
                            NLS.bind(Messages.AUTConfigComponentFileNotFound, file.getCanonicalPath()));
                } else {
                    JarFile jarFile = new JarFile(file);
                    Manifest jarManifest = jarFile.getManifest();
                    if (jarManifest == null) {
                        // no manifest for JAR
                        error = createErrorStatus(Messages.AUTConfigComponentNoManifest);
                    } else if (jarManifest.getMainAttributes().getValue(MAIN_CLASS) == null) {

                        // no main class defined in JAR manifest
                        error = createErrorStatus(Messages.AUTConfigComponentNoMainClass);
                    }
                }
            } catch (ZipException ze) {
                // given file is not a jar file
                error = createErrorStatus(NLS.bind(Messages.AUTConfigComponentFileNotJar, filename));
            } catch (IOException e) {
                // could not find jar file
                error = createWarningStatus(NLS.bind(Messages.AUTConfigComponentFileNotFound, filename));
            }
        }
    } else if (!isEmpty) {
        error = createErrorStatus(Messages.AUTConfigComponentWrongJAR);
    }

    putConfigValue(AutConfigConstants.JAR_FILE, m_jarTextField.getText());

    return error;
}