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.tools.library.builders.CodeGenTypeLibraryGenerator.java

private static void deleteTheGeneratedDependentTypesForV3(String dependentJarPath,
        TypeLibraryCodeGenContext codeGenCtx) {

    if (TypeLibraryUtilities.isEmptyString(dependentJarPath))
        return;/*w w w .  j  a v  a2 s.com*/

    String[] dependentLibrariesJarPaths = dependentJarPath.split(DEPENDENT_JARS_DELIMITER);

    if (dependentLibrariesJarPaths.length == 0)
        return;

    //identify the possible java types to be deleted
    List<String> javaTypesToDelete = new ArrayList<String>();
    //Need to check if ObjectFactory is being deleted.
    //One ObjectFactory per library.Need to get a set of all namespaces being referred.
    Set<String> dependentLibsNamespace = new HashSet<String>();

    for (String currDepLibraryJar : dependentLibrariesJarPaths) {
        String currLibraryName = getLibraryNameFromJarFilePath(currDepLibraryJar);
        //for referred libraries  the TypeInformation.xml from the related jar . this jar won't be available in classpath and hence has to be mnaually processed
        String typeInformationFileRelativePath = TypeLibraryConstants.META_INF_FOLDER + File.separator
                + currLibraryName + File.separator + TypeLibraryConstants.TYPE_INFORMATION_FILE_NAME;

        File theJarFile = new File(currDepLibraryJar);
        if (!theJarFile.exists())
            continue;

        JarFile jarFile = null;
        try {
            jarFile = new JarFile(currDepLibraryJar);
            JarEntry entry = jarFile.getJarEntry(typeInformationFileRelativePath);
            if (entry == null)
                entry = jarFile.getJarEntry(typeInformationFileRelativePath.replace("\\", "/"));
            if (entry == null) {
                getLogger().log(Level.WARNING,
                        "Could not find the TypeInformation.xml file for the dependent library represented by the jar : "
                                + currDepLibraryJar);
                continue;
            }
            InputStream inputStream = jarFile.getInputStream(entry);

            if (inputStream != null) {

                TypeLibraryType typeLibraryType = JAXB.unmarshal(inputStream, TypeLibraryType.class);
                if (typeLibraryType != null) {
                    dependentLibsNamespace.add(typeLibraryType.getLibraryNamespace());
                    for (TypeInformationType typeInformationType : typeLibraryType.getType())
                        javaTypesToDelete.add(typeInformationType.getJavaTypeName());
                }

            }

        } catch (IOException e) {
            getLogger().log(Level.WARNING,
                    "Exception while parsing the TypeInformation.xml of jar " + currDepLibraryJar, e);
        }
    }

    deleteJavaTypes(javaTypesToDelete, codeGenCtx);
    findPackageForObjectFactoriesAndDelete(codeGenCtx, dependentLibsNamespace);
}

From source file:org.apache.sling.maven.bundlesupport.AbstractBundleInstallMojo.java

/**
 * Get the manifest from the File.//from   w  ww . j  ava2s  .  c  om
 * @param bundleFile The bundle jar
 * @return The manifest.
 * @throws IOException
 */
protected Manifest getManifest(final File bundleFile) throws IOException {
    JarFile file = null;
    try {
        file = new JarFile(bundleFile);
        return file.getManifest();
    } finally {
        if (file != null) {
            try {
                file.close();
            } catch (IOException ignore) {
            }
        }
    }
}

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

/**
 * Old type library jar(NOT in workspace) has the dir structure \types\<xsd>
 * and the new one has meta-src\types\<typeLibName>\<xsd>.
 *
 * @param jarURL the jar url/*w  w w  .  ja va2  s . co  m*/
 * @param projectName the project name
 * @return true, if is new typ library
 * @throws IOException Signals that an I/O exception has occurred.
 */
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(
            SOATypeLibraryConstants.TYPES_LOCATION_IN_JAR + WorkspaceUtil.PATH_SEPERATOR + projectName) != null;

}

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

private File generateDefaultConf(Path localJarPath) throws IOException, FileNotFoundException {
    JarFile jar = null;/*from w  ww . j a  v a 2  s .co m*/
    try {
        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:com.sonicle.webtop.core.app.WebTopApp.java

public JarFileResource getJarResource(URL url) throws URISyntaxException, MalformedURLException, IOException {
    if (!url.getProtocol().equals("jar"))
        throw new MalformedURLException("Protocol must be 'jar'");

    String surl = url.toString();
    int ix = surl.lastIndexOf("!/");
    if (ix < 0)
        throw new MalformedURLException("URL must contains '!/'");

    String jarFileName, jarEntryName;
    try {//from  w  ww  .  j av a 2s  .  co  m
        jarFileName = URLDecoder.decode(surl.substring(4 + 5, ix), getSystemCharset().name());
        jarEntryName = surl.substring(ix + 2);
    } catch (UnsupportedEncodingException ex) {
        throw new WTRuntimeException(ex, "{0} encoding not supported", getSystemCharset().name());
    }

    File file = new File(jarFileName);
    return new JarFileResource(new JarFile(file), jarEntryName);
}

From source file:org.colombbus.tangara.Configuration.java

private boolean testExecutionMode() {
    executionMode = false;/*from   ww  w  . j  a  v a2  s .  com*/
    JarFile file = null;
    try {
        file = new JarFile(getTangaraPath());
        ZipEntry entry = file.getEntry(EXECUTION_PROPERTIES_FILENAME);
        if (entry != null) {
            executionMode = true;
            System.out.println("execution mode detected");
            Properties executionProperties = new Properties();
            InputStream ips = ClassLoader.getSystemResourceAsStream(EXECUTION_PROPERTIES_FILENAME);
            executionProperties.load(ips);
            if (executionProperties.containsKey("main-program")) {
                String mainTangaraFile = executionProperties.getProperty("main-program");
                System.out.println("main tangara file: " + mainTangaraFile);
                properties.setProperty("main-program", mainTangaraFile);
            } else {
                System.err.println("error : main program not specified");
            }
            if (executionProperties.containsKey("language")) {
                String language = executionProperties.getProperty("language");
                properties.setProperty("language", language);
                System.out.println("language: " + language);
            } else {
                System.err.println("error : language not specified");
            }
            if (executionProperties.containsKey("resources")) {
                String resources = executionProperties.getProperty("resources");
                properties.setProperty("program.resources", resources);
                System.out.println("resources: " + resources);
            } else {
                System.err.println("error : resources not specified");
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (file != null) {
            try {
                file.close();
            } catch (IOException e) {
                System.err.println("error while closing tangara JAR file");
            }
        }
    }
    return executionMode;
}

From source file:com.liferay.blade.cli.command.CreateCommandTest.java

@Test
public void testCreateWorkspaceGradleServiceBuilderProjectDefault() throws Exception {
    File workspace = new File(_rootDir, "workspace");

    File modulesDir = new File(workspace, "modules");

    String projectPath = modulesDir.getAbsolutePath();

    String[] args = { "create", "-d", projectPath, "-t", "service-builder", "-p", "com.liferay.sample",
            "sample" };

    _makeWorkspace(workspace);//w w  w  .  j a v a  2  s  . com

    TestUtil.runBlade(workspace, _extensionsDir, args);

    _checkFileExists(projectPath + "/sample/build.gradle");

    _checkFileDoesNotExists(projectPath + "/sample/settings.gradle");

    _checkFileExists(projectPath + "/sample/sample-api/build.gradle");

    _checkFileExists(projectPath + "/sample/sample-service/build.gradle");

    File file = _checkFileExists(projectPath + "/sample/sample-service/build.gradle");

    _contains(file, ".*compileOnly project\\(\":modules:sample:sample-api\"\\).*");

    BuildTask buildService = GradleRunnerUtil.executeGradleRunner(workspace.getPath(), "buildService");

    GradleRunnerUtil.verifyGradleRunnerOutput(buildService);

    BuildTask buildTask = GradleRunnerUtil.executeGradleRunner(workspace.getPath(), "jar");

    GradleRunnerUtil.verifyGradleRunnerOutput(buildTask);

    GradleRunnerUtil.verifyBuildOutput(projectPath + "/sample/sample-api", "com.liferay.sample.api-1.0.0.jar");
    GradleRunnerUtil.verifyBuildOutput(projectPath + "/sample/sample-service",
            "com.liferay.sample.service-1.0.0.jar");

    File serviceJar = new File(projectPath,
            "sample/sample-service/build/libs/com.liferay.sample.service-1.0.0.jar");

    _verifyImportPackage(serviceJar);

    try (JarFile serviceJarFile = new JarFile(serviceJar)) {
        Manifest manifest = serviceJarFile.getManifest();

        Attributes mainAttributes = manifest.getMainAttributes();

        String springContext = mainAttributes.getValue("Liferay-Spring-Context");

        Assert.assertTrue(springContext.equals("META-INF/spring"));
    }
}

From source file:org.corpus_tools.salt.util.VisJsVisualizer.java

private File createOutputResources(URI outputFileUri)
        throws SaltParameterException, SecurityException, FileNotFoundException, IOException {
    File outputFolder = null;// w w  w. ja  v  a  2  s . co m
    if (outputFileUri == null) {
        throw new SaltParameterException("Cannot store salt-vis, because the passed output uri is empty. ");
    }
    outputFolder = new File(outputFileUri.path());
    if (!outputFolder.exists()) {
        if (!outputFolder.mkdirs()) {
            throw new SaltException("Can't create folder " + outputFolder.getAbsolutePath());
        }
    }

    File cssFolderOut = new File(outputFolder, CSS_FOLDER_OUT);
    if (!cssFolderOut.exists()) {
        if (!cssFolderOut.mkdir()) {
            throw new SaltException("Can't create folder " + cssFolderOut.getAbsolutePath());
        }
    }

    File jsFolderOut = new File(outputFolder, JS_FOLDER_OUT);
    if (!jsFolderOut.exists()) {
        if (!jsFolderOut.mkdir()) {
            throw new SaltException("Can't create folder " + jsFolderOut.getAbsolutePath());
        }
    }

    File imgFolderOut = new File(outputFolder, IMG_FOLDER_OUT);
    if (!imgFolderOut.exists()) {
        if (!imgFolderOut.mkdirs()) {
            throw new SaltException("Can't create folder " + imgFolderOut.getAbsolutePath());
        }
    }

    copyResourceFile(
            getClass().getResourceAsStream(RESOURCE_FOLDER + System.getProperty("file.separator") + CSS_FILE),
            outputFolder.getPath(), CSS_FOLDER_OUT, CSS_FILE);

    copyResourceFile(
            getClass().getResourceAsStream(RESOURCE_FOLDER + System.getProperty("file.separator") + JS_FILE),
            outputFolder.getPath(), JS_FOLDER_OUT, JS_FILE);

    copyResourceFile(
            getClass()
                    .getResourceAsStream(RESOURCE_FOLDER + System.getProperty("file.separator") + JQUERY_FILE),
            outputFolder.getPath(), JS_FOLDER_OUT, JQUERY_FILE);

    ClassLoader classLoader = getClass().getClassLoader();
    CodeSource srcCode = VisJsVisualizer.class.getProtectionDomain().getCodeSource();
    URL codeSourceUrl = srcCode.getLocation();
    File codeSourseFile = new File(codeSourceUrl.getPath());

    if (codeSourseFile.isDirectory()) {
        File imgFolder = new File(classLoader.getResource(RESOURCE_FOLDER_IMG_NETWORK).getFile());
        File[] imgFiles = imgFolder.listFiles();
        if (imgFiles != null) {
            for (File imgFile : imgFiles) {
                InputStream inputStream = getClass()
                        .getResourceAsStream(System.getProperty("file.separator") + RESOURCE_FOLDER_IMG_NETWORK
                                + System.getProperty("file.separator") + imgFile.getName());
                copyResourceFile(inputStream, outputFolder.getPath(), IMG_FOLDER_OUT, imgFile.getName());
            }
        }
    } else if (codeSourseFile.getName().endsWith("jar")) {
        JarFile jarFile = new JarFile(codeSourseFile);
        Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (entry.getName().startsWith(RESOURCE_FOLDER_IMG_NETWORK) && !entry.isDirectory()) {

                copyResourceFile(jarFile.getInputStream(entry), outputFolder.getPath(), IMG_FOLDER_OUT,
                        entry.getName().replaceFirst(RESOURCE_FOLDER_IMG_NETWORK, ""));
            }

        }
        jarFile.close();

    }

    return outputFolder;
}

From source file:com.liferay.blade.cli.CreateCommandTest.java

@Test
public void testCreateWorkspaceGradleServiceBuilderProjectDefault() throws Exception {

    String[] args = { "create", "-d", "generated/test/workspace/modules", "-t", "service-builder", "-p",
            "com.liferay.sample", "sample" };

    File workspace = new File("generated/test/workspace");

    makeWorkspace(workspace);//ww  w .ja  v a2 s .co m

    new bladenofail().run(args);

    String projectPath = "generated/test/workspace/modules";

    checkFileExists(projectPath + "/sample/build.gradle");

    checkFileDoesNotExists(projectPath + "/sample/settings.gradle");

    checkFileExists(projectPath + "/sample/sample-api/build.gradle");

    checkFileExists(projectPath + "/sample/sample-service/build.gradle");

    contains(checkFileExists(projectPath + "/sample/sample-service/build.gradle"),
            ".*compileOnly project\\(\":modules:sample:sample-api\"\\).*");

    BuildTask buildService = GradleRunnerUtil.executeGradleRunner(workspace.getPath(), "buildService");
    GradleRunnerUtil.verifyGradleRunnerOutput(buildService);
    BuildTask buildtask = GradleRunnerUtil.executeGradleRunner(workspace.getPath(), "jar");
    GradleRunnerUtil.verifyGradleRunnerOutput(buildtask);
    GradleRunnerUtil.verifyBuildOutput(projectPath + "/sample/sample-api", "com.liferay.sample.api-1.0.0.jar");
    GradleRunnerUtil.verifyBuildOutput(projectPath + "/sample/sample-service",
            "com.liferay.sample.service-1.0.0.jar");

    File serviceJar = new File(
            projectPath + "/sample/sample-service/build/libs/com.liferay.sample.service-1.0.0.jar");

    verifyImportPackage(serviceJar);

    try (JarFile serviceJarFile = new JarFile(serviceJar)) {
        String springContext = serviceJarFile.getManifest().getMainAttributes()
                .getValue("Liferay-Spring-Context");

        assertTrue(springContext.equals("META-INF/spring"));
    }
}

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

protected List<ArtifactContentEntry> readFileEntries(File file, String filterPath, String repoId)
        throws IOException {
    Map<String, ArtifactContentEntry> artifactContentEntryMap = new HashMap<>();
    int filterDepth = StringUtils.countMatches(filterPath, "/");
    /*if ( filterDepth == 0 )
    {/*from   w w  w . ja  va 2s .  c om*/
    filterDepth = 1;
    }*/
    JarFile jarFile = new JarFile(file);
    try {
        Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries();
        while (jarEntryEnumeration.hasMoreElements()) {
            JarEntry currentEntry = jarEntryEnumeration.nextElement();
            String cleanedEntryName = StringUtils.endsWith(currentEntry.getName(), "/") ? //
                    StringUtils.substringBeforeLast(currentEntry.getName(), "/") : currentEntry.getName();
            String entryRootPath = getRootPath(cleanedEntryName);
            int depth = StringUtils.countMatches(cleanedEntryName, "/");
            if (StringUtils.isEmpty(filterPath) //
                    && !artifactContentEntryMap.containsKey(entryRootPath) //
                    && depth == filterDepth) {

                artifactContentEntryMap.put(entryRootPath,
                        new ArtifactContentEntry(entryRootPath, !currentEntry.isDirectory(), depth, repoId));
            } else {
                if (StringUtils.startsWith(cleanedEntryName, filterPath) //
                        && (depth == filterDepth || (!currentEntry.isDirectory() && depth == filterDepth))) {
                    artifactContentEntryMap.put(cleanedEntryName, new ArtifactContentEntry(cleanedEntryName,
                            !currentEntry.isDirectory(), depth, repoId));
                }
            }
        }

        if (StringUtils.isNotEmpty(filterPath)) {
            Map<String, ArtifactContentEntry> filteredArtifactContentEntryMap = new HashMap<>();

            for (Map.Entry<String, ArtifactContentEntry> entry : artifactContentEntryMap.entrySet()) {
                filteredArtifactContentEntryMap.put(entry.getKey(), entry.getValue());
            }

            List<ArtifactContentEntry> sorted = getSmallerDepthEntries(filteredArtifactContentEntryMap);
            if (sorted == null) {
                return Collections.emptyList();
            }
            Collections.sort(sorted, ArtifactContentEntryComparator.INSTANCE);
            return sorted;
        }
    } finally {
        if (jarFile != null) {
            jarFile.close();
        }
    }
    List<ArtifactContentEntry> sorted = new ArrayList<>(artifactContentEntryMap.values());
    Collections.sort(sorted, ArtifactContentEntryComparator.INSTANCE);
    return sorted;
}