List of usage examples for java.util.jar JarFile JarFile
public JarFile(File file) throws IOException
From source file:com.eucalyptus.simpleworkflow.common.client.WorkflowClientStandalone.java
private void processJar(File f) throws Exception { final JarFile jar = new JarFile(f); final Properties props = new Properties(); final List<JarEntry> jarList = Collections.list(jar.entries()); LOG.trace("-> Trying to load component info from " + f.getAbsolutePath()); for (final JarEntry j : jarList) { try {//from w ww .ja va2s . c o m if (j.getName().matches(".*\\.class.{0,1}")) { handleClassFile(f, j); } } catch (RuntimeException ex) { LOG.error(ex, ex); jar.close(); throw ex; } } jar.close(); }
From source file:org.b3log.latke.ioc.ClassPathResolver.java
/** * Resolve the given jar file URL into a JarFile object. * * @param jarFileUrl jarFileUrl// w ww. ja v a 2 s.c om * @return the JarFile * @throws IOException IOException */ private static JarFile getJarFile(final String jarFileUrl) throws IOException { if (jarFileUrl.startsWith(FILE_URL_PREFIX)) { try { return new JarFile(toURI(jarFileUrl).getSchemeSpecificPart()); } catch (final URISyntaxException ex) { // Fallback for URLs that are not valid URIs (should hardly ever // happen). return new JarFile(jarFileUrl.substring(FILE_URL_PREFIX.length())); } } else { return new JarFile(jarFileUrl); } }
From source file:com.hurence.logisland.plugin.PluginManager.java
private static void installPlugin(String artifact, String logislandHome) { Optional<ModuleInfo> moduleInfo = findPluginMeta().entrySet().stream() .filter(e -> artifact.equals(e.getKey().getArtifact())).map(Map.Entry::getKey).findFirst(); if (moduleInfo.isPresent()) { System.err/*ww w .j a v a 2 s. co m*/ .println("A component already matches the artifact " + artifact + ". Please remove it first."); System.exit(-1); } try { IvySettings settings = new IvySettings(); settings.load(new File(logislandHome, "conf/ivy.xml")); Ivy ivy = Ivy.newInstance(settings); ivy.bind(); System.out.println("\nDownloading dependencies. Please hold on...\n"); String parts[] = Arrays.stream(artifact.split(":")).map(String::trim).toArray(a -> new String[a]); if (parts.length != 3) { throw new IllegalArgumentException( "Unrecognized artifact format. It should be groupId:artifactId:version"); } ModuleRevisionId revisionId = new ModuleRevisionId(new ModuleId(parts[0], parts[1]), parts[2]); Set<ArtifactDownloadReport> toBePackaged = downloadArtifacts(ivy, revisionId, new String[] { "default", "compile", "runtime" }); ArtifactDownloadReport artifactJar = toBePackaged.stream() .filter(a -> a.getArtifact().getModuleRevisionId().equals(revisionId)).findFirst() .orElseThrow(() -> new IllegalStateException("Unable to find artifact " + artifact + ". Please check the name is correct and the repositories on ivy.xml are correctly configured")); Manifest manifest = new JarFile(artifactJar.getLocalFile()).getManifest(); File libDir = new File(logislandHome, "lib"); if (manifest.getMainAttributes().containsKey(ManifestAttributes.MODULE_ARTIFACT)) { org.apache.commons.io.FileUtils.copyFileToDirectory(artifactJar.getLocalFile(), libDir); //we have a logisland plugin. Just copy it System.out.println(String.format("Found logisland plugin %s version %s\n" + "It will provide:", manifest.getMainAttributes().getValue(ManifestAttributes.MODULE_NAME), manifest.getMainAttributes().getValue(ManifestAttributes.MODULE_VERSION))); Arrays.stream(manifest.getMainAttributes().getValue(ManifestAttributes.MODULE_EXPORTS).split(",")) .map(String::trim).forEach(s -> System.out.println("\t" + s)); } else { System.out.println("Repackaging artifact and its dependencies"); Set<ArtifactDownloadReport> environment = downloadArtifacts(ivy, revisionId, new String[] { "provided" }); Set<ArtifactDownloadReport> excluded = toBePackaged.stream() .filter(adr -> excludeGroupIds.stream() .anyMatch(s -> s.matches(adr.getArtifact().getModuleRevisionId().getOrganisation())) || excludedArtifactsId.stream().anyMatch( s -> s.matches(adr.getArtifact().getModuleRevisionId().getName()))) .collect(Collectors.toSet()); toBePackaged.removeAll(excluded); environment.addAll(excluded); Repackager rep = new Repackager(artifactJar.getLocalFile(), new LogislandPluginLayoutFactory()); rep.setMainClass(""); File destFile = new File(libDir, "logisland-component-" + artifactJar.getLocalFile().getName()); rep.repackage(destFile, callback -> toBePackaged.stream().filter(adr -> adr.getLocalFile() != null) .filter(adr -> !adr.getArtifact().getModuleRevisionId().equals(revisionId)) .map(adr -> new Library(adr.getLocalFile(), LibraryScope.COMPILE)).forEach(library -> { try { callback.library(library); } catch (IOException e) { throw new UncheckedIOException(e); } })); Thread.currentThread().setContextClassLoader(new URLClassLoader( environment.stream().filter(adr -> adr.getLocalFile() != null).map(adr -> { try { return adr.getLocalFile().toURI().toURL(); } catch (Exception e) { throw new RuntimeException(e); } }).toArray(a -> new URL[a]), Thread.currentThread().getContextClassLoader())); //now clean up package and write the manifest String newArtifact = "com.hurence.logisland.repackaged:" + parts[1] + ":" + parts[2]; LogislandRepackager.execute(destFile.getAbsolutePath(), "BOOT-INF/lib-provided", parts[2], newArtifact, "Logisland Component for " + artifact, "Logisland Component for " + artifact, new String[] { "org.apache.kafka.*" }, new String[0], "org.apache.kafka.connect.connector.Connector"); } System.out.println("Install done!"); } catch (Exception e) { System.err.println("Unable to install artifact " + artifact); e.printStackTrace(); System.exit(-1); } }
From source file:org.broadleafcommerce.common.extensibility.InstrumentationRuntimeFactory.java
private static boolean validateAgentJarManifest(File agentJarFile, String agentClassName) { try {//from w w w. j av a 2 s . c o m JarFile jar = new JarFile(agentJarFile); Manifest manifest = jar.getManifest(); if (manifest == null) { return false; } Attributes attributes = manifest.getMainAttributes(); String ac = attributes.getValue("Agent-Class"); if (ac != null && ac.equals(agentClassName)) { return true; } } catch (Exception e) { if (LOG.isTraceEnabled()) { LOG.trace("Unexpected exception occured.", e); } } return false; }
From source file:org.deventropy.shared.utils.DirectoryArchiverUtilTest.java
private void checkJarArchive(final File archiveFile, final File sourceDirectory, final String pathPrefix) throws IOException { JarFile jarFile = null;// w w w.ja va 2 s .c om try { jarFile = new JarFile(archiveFile); final Manifest manifest = jarFile.getManifest(); assertNotNull("Manifest should be present", manifest); assertEquals("Manifest version should be 1.0", "1.0", manifest.getMainAttributes().getValue(Attributes.Name.MANIFEST_VERSION)); final ArchiveEntries archiveEntries = createArchiveEntries(sourceDirectory, pathPrefix); final Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { final JarEntry jarEntry = entries.nextElement(); if (MANIFEST_FILE_ENTRY_NAME.equalsIgnoreCase(jarEntry.getName())) { // It is the manifest file, not added by use continue; } if (jarEntry.isDirectory()) { assertTrue("Directory in jar should be from us [" + jarEntry.getName() + "]", archiveEntries.dirs.contains(jarEntry.getName())); archiveEntries.dirs.remove(jarEntry.getName()); } else { assertTrue("File in jar should be from us [" + jarEntry.getName() + "]", archiveEntries.files.containsKey(jarEntry.getName())); final byte[] inflatedMd5 = getMd5Digest(jarFile.getInputStream(jarEntry), false); assertArrayEquals("MD5 hash of files should equal [" + jarEntry.getName() + "]", archiveEntries.files.get(jarEntry.getName()), inflatedMd5); archiveEntries.files.remove(jarEntry.getName()); } } // Check that all files and directories have been accounted for assertTrue("All directories should be in the jar", archiveEntries.dirs.isEmpty()); assertTrue("All files should be in the jar", archiveEntries.files.isEmpty()); } finally { if (null != jarFile) { jarFile.close(); } } }
From source file:com.jhash.oimadmin.Utils.java
public static void extractJarFile(String directory, String jarFileName) { File baseDir = new File(directory); if (baseDir.exists()) { if (!baseDir.isDirectory()) { throw new InvalidParameterException("Destination directory " + directory + " to expand Jar file " + jarFileName + " is not a directory"); }// w ww . ja v a 2s.c o m if (!baseDir.canWrite() || !baseDir.canWrite() || !baseDir.canExecute()) { throw new InvalidParameterException("Destination directory " + directory + " to expand Jar file " + jarFileName + " does not have rwx access for user"); } } else { baseDir.mkdirs(); } try (JarFile jar = new JarFile(jarFileName)) { Enumeration enumEntries = jar.entries(); while (enumEntries.hasMoreElements()) { JarEntry file = (JarEntry) enumEntries.nextElement(); File f = new File(directory + File.separator + file.getName()); if (file.isDirectory()) { // if its a directory, create it f.mkdirs(); continue; } try (java.io.InputStream is = jar.getInputStream(file); java.io.FileOutputStream fos = new java.io.FileOutputStream(f)) { // get the input stream while (is.available() > 0) { // write contents of 'is' to 'fos' fos.write(is.read()); } fos.close(); is.close(); } catch (Exception exception) { throw new OIMAdminException("Failed to write the jar file entry " + file + " to location " + f, exception); } } } catch (Exception exception) { throw new OIMAdminException("Failed to extract jar file " + jarFileName + " to directory " + directory, exception); } }
From source file:ch.rasc.embeddedtc.plugin.PackageTcWarMojo.java
@Override public void execute() throws MojoExecutionException { Path warExecFile = Paths.get(this.buildDirectory, this.finalName); try {/*from ww w . j a va2s . c o m*/ Files.deleteIfExists(warExecFile); Files.createDirectories(warExecFile.getParent()); try (OutputStream os = Files.newOutputStream(warExecFile); ArchiveOutputStream aos = new ArchiveStreamFactory() .createArchiveOutputStream(ArchiveStreamFactory.JAR, os)) { // If project is a war project add the war to the project if ("war".equalsIgnoreCase(this.project.getPackaging())) { File projectArtifact = this.project.getArtifact().getFile(); if (projectArtifact != null && Files.exists(projectArtifact.toPath())) { aos.putArchiveEntry(new JarArchiveEntry(projectArtifact.getName())); try (InputStream is = Files.newInputStream(projectArtifact.toPath())) { IOUtils.copy(is, aos); } aos.closeArchiveEntry(); } } // Add extraWars into the jar if (this.extraWars != null) { for (Dependency extraWarDependency : this.extraWars) { ArtifactRequest request = new ArtifactRequest(); request.setArtifact(new DefaultArtifact(extraWarDependency.getGroupId(), extraWarDependency.getArtifactId(), extraWarDependency.getType(), extraWarDependency.getVersion())); request.setRepositories(this.projectRepos); ArtifactResult result; try { result = this.repoSystem.resolveArtifact(this.repoSession, request); } catch (ArtifactResolutionException e) { throw new MojoExecutionException(e.getMessage(), e); } File extraWarFile = result.getArtifact().getFile(); aos.putArchiveEntry(new JarArchiveEntry(extraWarFile.getName())); try (InputStream is = Files.newInputStream(extraWarFile.toPath())) { IOUtils.copy(is, aos); } aos.closeArchiveEntry(); } } // Add extraResources into the jar. Folder /extra if (this.extraResources != null) { for (Resource extraResource : this.extraResources) { DirectoryScanner directoryScanner = new DirectoryScanner(); directoryScanner.setBasedir(extraResource.getDirectory()); directoryScanner.setExcludes(extraResource.getExcludes() .toArray(new String[extraResource.getExcludes().size()])); if (!extraResource.getIncludes().isEmpty()) { directoryScanner.setIncludes(extraResource.getIncludes() .toArray(new String[extraResource.getIncludes().size()])); } else { // include everything by default directoryScanner.setIncludes(new String[] { "**" }); } directoryScanner.scan(); for (String includeFile : directoryScanner.getIncludedFiles()) { aos.putArchiveEntry( new JarArchiveEntry(Runner.EXTRA_RESOURCES_DIR + "/" + includeFile)); Path extraFile = Paths.get(extraResource.getDirectory(), includeFile); try (InputStream is = Files.newInputStream(extraFile)) { IOUtils.copy(is, aos); } aos.closeArchiveEntry(); } } } Set<String> includeArtifacts = new HashSet<>(); includeArtifacts.add("org.apache.tomcat:tomcat-jdbc"); includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-core"); includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-websocket"); includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-logging-juli"); includeArtifacts.add("org.yaml:snakeyaml"); includeArtifacts.add("com.beust:jcommander"); if (this.includeJSPSupport) { includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-jasper"); includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-el"); includeArtifacts.add("org.eclipse.jdt.core.compiler:ecj"); } for (Artifact pluginArtifact : this.pluginArtifacts) { String artifactName = pluginArtifact.getGroupId() + ":" + pluginArtifact.getArtifactId(); if (includeArtifacts.contains(artifactName)) { try (JarFile jarFile = new JarFile(pluginArtifact.getFile())) { extractJarToArchive(jarFile, aos); } } } if (this.extraDependencies != null) { for (Dependency dependency : this.extraDependencies) { ArtifactRequest request = new ArtifactRequest(); request.setArtifact(new DefaultArtifact(dependency.getGroupId(), dependency.getArtifactId(), dependency.getType(), dependency.getVersion())); request.setRepositories(this.projectRepos); ArtifactResult result; try { result = this.repoSystem.resolveArtifact(this.repoSession, request); } catch (ArtifactResolutionException e) { throw new MojoExecutionException(e.getMessage(), e); } try (JarFile jarFile = new JarFile(result.getArtifact().getFile())) { extractJarToArchive(jarFile, aos); } } } if (this.includeJSPSupport) { addFile(aos, "/conf/web.xml", "conf/web.xml"); } else { addFile(aos, "/conf/web_wo_jsp.xml", "conf/web.xml"); } addFile(aos, "/conf/logging.properties", "conf/logging.properties"); if (this.includeTcNativeWin32 != null) { aos.putArchiveEntry(new JarArchiveEntry("tcnative-1.dll.32")); Files.copy(Paths.get(this.includeTcNativeWin32), aos); aos.closeArchiveEntry(); } if (this.includeTcNativeWin64 != null) { aos.putArchiveEntry(new JarArchiveEntry("tcnative-1.dll.64")); Files.copy(Paths.get(this.includeTcNativeWin64), aos); aos.closeArchiveEntry(); } String[] runnerClasses = { "ch.rasc.embeddedtc.runner.CheckConfig$CheckConfigOptions", "ch.rasc.embeddedtc.runner.CheckConfig", "ch.rasc.embeddedtc.runner.Config", "ch.rasc.embeddedtc.runner.Shutdown", "ch.rasc.embeddedtc.runner.Context", "ch.rasc.embeddedtc.runner.DeleteDirectory", "ch.rasc.embeddedtc.runner.ObfuscateUtil$ObfuscateOptions", "ch.rasc.embeddedtc.runner.ObfuscateUtil", "ch.rasc.embeddedtc.runner.Runner$1", "ch.rasc.embeddedtc.runner.Runner$2", "ch.rasc.embeddedtc.runner.Runner$StartOptions", "ch.rasc.embeddedtc.runner.Runner$StopOptions", "ch.rasc.embeddedtc.runner.Runner$RunnerShutdownHook", "ch.rasc.embeddedtc.runner.Runner" }; for (String rc : runnerClasses) { String classAsPath = rc.replace('.', '/') + ".class"; try (InputStream is = getClass().getResourceAsStream("/" + classAsPath)) { aos.putArchiveEntry(new JarArchiveEntry(classAsPath)); IOUtils.copy(is, aos); aos.closeArchiveEntry(); } } Manifest manifest = new Manifest(); Manifest.Attribute mainClassAtt = new Manifest.Attribute(); mainClassAtt.setName("Main-Class"); mainClassAtt.setValue(Runner.class.getName()); manifest.addConfiguredAttribute(mainClassAtt); aos.putArchiveEntry(new JarArchiveEntry("META-INF/MANIFEST.MF")); manifest.write(aos); aos.closeArchiveEntry(); aos.putArchiveEntry(new JarArchiveEntry(Runner.TIMESTAMP_FILENAME)); aos.write(String.valueOf(System.currentTimeMillis()).getBytes(StandardCharsets.UTF_8)); aos.closeArchiveEntry(); } } catch (IOException | ArchiveException | ManifestException e) { throw new MojoExecutionException(e.getMessage(), e); } }
From source file:com.basistech.bbhmp.RosapiBundleCollectorMojo.java
private boolean isJarFragment(File outputFile) throws MojoExecutionException, MojoFailureException { JarFile jar;/*from ww w . j a v a 2 s. c om*/ try { jar = new JarFile(outputFile); } catch (IOException e) { throw new MojoExecutionException( "Failed to open dependency we just copied " + outputFile.getAbsolutePath(), e); } final Manifest manifest; try { manifest = jar.getManifest(); } catch (IOException e) { throw new MojoFailureException( "Failed to read manifest from dependency we just copied " + outputFile.getAbsolutePath(), e); } final Attributes mattr = manifest.getMainAttributes(); // getValue is case-insensitive. String mfVersion = mattr.getValue("Bundle-ManifestVersion"); /* * '2' is the only legitimate bundle manifest version. Version 1 is long obsolete, and not supported * in current containers. There's no plan on the horizon for a version 3. No version at all indicates * that the jar file is not an OSGi bundle at all. */ if (!"2".equals(mfVersion)) { throw new MojoFailureException("Bundle-ManifestVersion is not '2' from dependency we just copied " + outputFile.getAbsolutePath()); } String host = mattr.getValue("Fragment-Host"); return host != null; }
From source file:UnpackedJarFile.java
public static File toTempFile(URL url) throws IOException { InputStream in = null;/*from w ww . jav a 2s .c o m*/ OutputStream out = null; JarFile jarFile = null; try { if (url.getProtocol().equalsIgnoreCase("jar")) { // url.openStream() locks the jar file and does not release the lock even after the stream is closed. // This problem is avoided by using JarFile APIs. File file = new File(url.getFile().substring(5, url.getFile().indexOf("!/"))); String path = url.getFile().substring(url.getFile().indexOf("!/") + 2); jarFile = new JarFile(file); JarEntry jarEntry = jarFile.getJarEntry(path); if (jarEntry != null) { in = jarFile.getInputStream(jarEntry); } else { throw new FileNotFoundException("JarEntry " + path + " not found in " + file); } } else { in = url.openStream(); } int index = url.getPath().lastIndexOf("."); String extension = null; if (index > 0) { extension = url.getPath().substring(index); } File tempFile = createTempFile(extension); out = new FileOutputStream(tempFile); writeAll(in, out); return tempFile; } finally { close(out); close(in); close(jarFile); } }
From source file:com.evolveum.midpoint.test.ldap.OpenDJController.java
/** * Extract template from class/*from w w w .java 2 s . co m*/ */ private void extractTemplate(File dst, String templateName) throws IOException, URISyntaxException { LOGGER.info("Extracting OpenDJ template...."); if (!dst.exists()) { LOGGER.debug("Creating target dir {}", dst.getPath()); dst.mkdirs(); } templateRoot = new File(DATA_TEMPLATE_DIR, templateName); String templateRootPath = DATA_TEMPLATE_DIR + "/" + templateName; // templateRoot.getPath does not work on Windows, as it puts "\" into the path name (leading to problems with getSystemResource) // Determing if we need to extract from JAR or directory if (templateRoot.isDirectory()) { LOGGER.trace("Need to do directory copy."); MiscUtil.copyDirectory(templateRoot, dst); return; } LOGGER.debug("Try to localize OpenDJ Template in JARs as " + templateRootPath); URL srcUrl = ClassLoader.getSystemResource(templateRootPath); LOGGER.debug("srcUrl " + srcUrl); // sample: // file:/C:/.m2/repository/test-util/1.9-SNAPSHOT/test-util-1.9-SNAPSHOT.jar!/test-data/opendj.template // output: // /C:/.m2/repository/test-util/1.9-SNAPSHOT/test-util-1.9-SNAPSHOT.jar // // beware that in the URL there can be spaces encoded as %20, e.g. // file:/C:/Documents%20and%20Settings/user/.m2/repository/com/evolveum/midpoint/infra/test-util/2.1-SNAPSHOT/test-util-2.1-SNAPSHOT.jar!/test-data/opendj.template // if (srcUrl.getPath().contains("!/")) { URI srcFileUri = new URI(srcUrl.getPath().split("!/")[0]); // e.g. file:/C:/Documents%20and%20Settings/user/.m2/repository/com/evolveum/midpoint/infra/test-util/2.1-SNAPSHOT/test-util-2.1-SNAPSHOT.jar File srcFile = new File(srcFileUri); JarFile jar = new JarFile(srcFile); LOGGER.debug("Extracting OpenDJ from JAR file {} to {}", srcFile.getPath(), dst.getPath()); Enumeration<JarEntry> entries = jar.entries(); JarEntry e; byte buf[] = new byte[655360]; while (entries.hasMoreElements()) { e = entries.nextElement(); // skip other files if (!e.getName().contains(templateRootPath)) { continue; } // prepare destination file String filepath = e.getName().substring(templateRootPath.length()); File dstFile = new File(dst, filepath); // test if directory if (e.isDirectory()) { LOGGER.debug("Create directory: {}", dstFile.getAbsolutePath()); dstFile.mkdirs(); continue; } LOGGER.debug("Extract {} to {}", filepath, dstFile.getAbsolutePath()); // Find file on classpath InputStream is = ClassLoader.getSystemResourceAsStream(e.getName()); // InputStream is = jar.getInputStream(e); //old way // Copy content OutputStream out = new FileOutputStream(dstFile); int len; while ((len = is.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); is.close(); } jar.close(); } else { try { File file = new File(srcUrl.toURI()); File[] files = file.listFiles(); for (File subFile : files) { if (subFile.isDirectory()) { MiscUtil.copyDirectory(subFile, new File(dst, subFile.getName())); } else { MiscUtil.copyFile(subFile, new File(dst, subFile.getName())); } } } catch (Exception ex) { throw new IOException(ex); } } LOGGER.debug("OpenDJ Extracted"); }