List of usage examples for java.util.jar JarFile JarFile
public JarFile(File file) throws IOException
From source file:nl.geodienstencentrum.maven.plugin.sass.AbstractSassMojo.java
/** * Extract the Bourbon assets to the build directory. * @param destinationDir directory for the Bourbon resources *//* w w w . java2 s .c o m*/ private void extractBourbonResources(String destinationDir) { final Log log = this.getLog(); try { File destDir = new File(destinationDir); if (destDir.isDirectory()) { // skip extracting Bourbon, as it seems to hav been done log.info("Bourbon resources seems to have been extracted before."); return; } log.info("Extracting Bourbon resources to: " + destinationDir); destDir.mkdirs(); // find the jar with the Bourbon directory in the classloader URL urlJar = this.getClass().getClassLoader().getResource("scss-report.xsl"); String resourceFilePath = urlJar.getFile(); int index = resourceFilePath.indexOf("!"); String jarFileURI = resourceFilePath.substring(0, index); File jarFile = new File(new URI(jarFileURI)); JarFile jar = new JarFile(jarFile); // extract app/assets/stylesheets to destinationDir for (Enumeration<JarEntry> enums = jar.entries(); enums.hasMoreElements();) { JarEntry entry = enums.nextElement(); if (entry.getName().contains("app/assets/stylesheets")) { // shorten the path a bit index = entry.getName().indexOf("app/assets/stylesheets"); String fileName = destinationDir + File.separator + entry.getName().substring(index); File f = new File(fileName); if (fileName.endsWith("/")) { f.mkdirs(); } else { FileOutputStream fos = new FileOutputStream(f); try { IOUtil.copy(jar.getInputStream(entry), fos); } finally { IOUtil.close(fos); } } } } } catch (IOException | URISyntaxException ex) { log.error("Error extracting Bourbon resources.", ex); } }
From source file:org.apache.nifi.web.server.JettyServer.java
/** * Identifies all known UI extensions and stores them in the specified map. * * @param uiExtensions extensions/*from www .j a v a 2 s . com*/ * @param warFile war */ private void identifyUiExtensionsForComponents(final Map<UiExtensionType, List<String>> uiExtensions, final File warFile) { try (final JarFile jarFile = new JarFile(warFile)) { // locate the ui extensions readUiExtensions(uiExtensions, UiExtensionType.ContentViewer, jarFile, jarFile.getJarEntry("META-INF/nifi-content-viewer")); readUiExtensions(uiExtensions, UiExtensionType.ProcessorConfiguration, jarFile, jarFile.getJarEntry("META-INF/nifi-processor-configuration")); readUiExtensions(uiExtensions, UiExtensionType.ControllerServiceConfiguration, jarFile, jarFile.getJarEntry("META-INF/nifi-controller-service-configuration")); readUiExtensions(uiExtensions, UiExtensionType.ReportingTaskConfiguration, jarFile, jarFile.getJarEntry("META-INF/nifi-reporting-task-configuration")); } catch (IOException ioe) { logger.warn(String.format("Unable to inspect %s for a UI extensions.", warFile)); } }
From source file:com.taobao.android.builder.tasks.app.bundle.ProcessAwbAndroidResources.java
@Override protected void doFullTaskAction() throws IOException { // we have to clean the source folder output in case the package name changed. File srcOut = getSourceOutputDir(); if (srcOut != null) { // FileUtils.emptyFolder(srcOut); srcOut.delete();//from w w w . j a v a2 s . c o m srcOut.mkdirs(); } getTextSymbolOutputDir().mkdirs(); getPackageOutputFile().getParentFile().mkdirs(); @Nullable File resOutBaseNameFile = getPackageOutputFile(); // If are in instant run mode and we have an instant run enabled manifest File instantRunManifest = getInstantRunManifestFile(); File manifestFileToPackage = instantRunBuildContext.isInInstantRunMode() && instantRunManifest != null && instantRunManifest.exists() ? instantRunManifest : getManifestFile(); //awb???? addAaptOptions(); AaptPackageProcessBuilder aaptPackageCommandBuilder = new AaptPackageProcessBuilder(manifestFileToPackage, getAaptOptions()).setAssetsFolder(getAssetsDir()).setResFolder(getResDir()) .setLibraries(getLibraries()).setPackageForR(getPackageForR()) .setSourceOutputDir(absolutePath(srcOut)) .setSymbolOutputDir(absolutePath(getTextSymbolOutputDir())) .setResPackageOutput(absolutePath(resOutBaseNameFile)) .setProguardOutput(absolutePath(getProguardOutputFile())).setType(getType()) .setDebuggable(getDebuggable()).setPseudoLocalesEnabled(getPseudoLocalesEnabled()) .setResourceConfigs(getResourceConfigs()).setSplits(getSplits()) .setPreferredDensity(getPreferredDensity()); @NonNull AtlasBuilder builder = (AtlasBuilder) getBuilder(); // MergingLog mergingLog = new MergingLog(getMergeBlameLogFolder()); // // ProcessOutputHandler processOutputHandler = new ParsingProcessOutputHandler( // new ToolOutputParser(new AaptOutputParser(), getILogger()), // builder.getErrorReporter()); ProcessOutputHandler processOutputHandler = new LoggedProcessOutputHandler(getILogger()); try { builder.processAwbResources(aaptPackageCommandBuilder, getEnforceUniquePackageName(), processOutputHandler, getMainSymbolFile()); if (resOutBaseNameFile != null) { if (instantRunBuildContext.isInInstantRunMode()) { instantRunBuildContext.addChangedFile(FileType.RESOURCES, resOutBaseNameFile); // get the new manifest file CRC JarFile jarFile = new JarFile(resOutBaseNameFile); String currentIterationCRC = null; try { ZipEntry entry = jarFile.getEntry(SdkConstants.ANDROID_MANIFEST_XML); if (entry != null) { currentIterationCRC = String.valueOf(entry.getCrc()); } } finally { jarFile.close(); } // check the manifest file binary format. File crcFile = new File(instantRunSupportDir, "manifest.crc"); if (crcFile.exists() && currentIterationCRC != null) { // compare its content with the new binary file crc. String previousIterationCRC = Files.readFirstLine(crcFile, Charsets.UTF_8); if (!currentIterationCRC.equals(previousIterationCRC)) { instantRunBuildContext.close(); //instantRunBuildContext.setVerifierResult(InstantRunVerifierStatus // .BINARY_MANIFEST_FILE_CHANGE); } } // write the new manifest file CRC. Files.createParentDirs(crcFile); Files.write(currentIterationCRC, crcFile, Charsets.UTF_8); } } } catch (Exception e) { e.printStackTrace(); throw new GradleException("process res exception", e); } }
From source file:org.argouml.moduleloader.ModuleLoader2.java
/** * Find and enable a module from a given directory. * * @param dirname//from w w w . j a v a2 s . c om * The name of the directory. */ private void huntModulesFromNamedDirectory(String dirname) { File extensionDir = new File(dirname); if (extensionDir.isDirectory()) { File[] files = extensionDir.listFiles(new JarFileFilter()); for (File file : files) { JarFile jarfile = null; // Try-catch only the JarFile instantiation so we // don't accidentally mask anything in ArgoJarClassLoader // or processJarFile. try { jarfile = new JarFile(file); if (jarfile != null) { ClassLoader classloader = new URLClassLoader(new URL[] { file.toURI().toURL(), }, getClass().getClassLoader()); try { processJarFile(classloader, file); } catch (ClassNotFoundException e) { LOG.log(Level.SEVERE, "The class is not found.", e); return; } } } catch (IOException ioe) { LOG.log(Level.SEVERE, "Cannot open Jar file " + file, ioe); } } } }
From source file:com.opengamma.examples.simulated.tool.ExampleDatabasePopulator.java
private static String unpackJar(URL resource) { String file = resource.getPath(); if (file.contains(".jar!/")) { s_logger.info("Unpacking zip file located within a jar file: {}", resource); String jarFileName = StringUtils.substringBefore(file, "!/"); if (jarFileName.startsWith("file:/")) { jarFileName = jarFileName.substring(5); if (SystemUtils.IS_OS_WINDOWS) { jarFileName = StringUtils.stripStart(jarFileName, "/"); }// w ww .j a v a2 s . co m } else if (jarFileName.startsWith("file:/")) { jarFileName = jarFileName.substring(6); } jarFileName = StringUtils.replace(jarFileName, "%20", " "); String innerFileName = StringUtils.substringAfter(file, "!/"); innerFileName = StringUtils.replace(innerFileName, "%20", " "); s_logger.info("Unpacking zip file found jar file: {}", jarFileName); s_logger.info("Unpacking zip file found zip file: {}", innerFileName); try { JarFile jar = new JarFile(jarFileName); JarEntry jarEntry = jar.getJarEntry(innerFileName); try (InputStream in = jar.getInputStream(jarEntry)) { File tempFile = File.createTempFile("simulated-examples-database-populator-", ".zip"); tempFile.deleteOnExit(); try (OutputStream out = new FileOutputStream(tempFile)) { IOUtils.copy(in, out); } file = tempFile.getCanonicalPath(); } } catch (IOException ex) { throw new OpenGammaRuntimeException("Unable to open file within jar file: " + resource, ex); } s_logger.debug("Unpacking zip file extracted to: {}", file); } return file; }
From source file:com.github.maven_nar.AbstractDependencyMojo.java
public final NarInfo getNarInfo(final Artifact dependency) throws MojoExecutionException { // FIXME reported to maven developer list, isSnapshot changes behaviour // of getBaseVersion, called in pathOf. dependency.isSnapshot();/*from w w w . j ava2s .c o m*/ if (dependency.getFile().isDirectory()) { getLog().debug("Dependency is not packaged: " + dependency.getFile()); return new NarInfo(dependency.getGroupId(), dependency.getArtifactId(), dependency.getBaseVersion(), getLog(), dependency.getFile()); } final File file = new File(getLocalRepository().getBasedir(), getLocalRepository().pathOf(dependency)); if (!file.exists()) { getLog().debug("Dependency nar file does not exist: " + file); return null; } ZipInputStream zipStream = null; try { zipStream = new ZipInputStream(new FileInputStream(file)); if (zipStream.getNextEntry() == null) { getLog().debug("Skipping unreadable artifact: " + file); return null; } } catch (IOException e) { throw new MojoExecutionException("Error while testing for zip file " + file, e); } finally { IOUtils.closeQuietly(zipStream); } JarFile jar = null; try { jar = new JarFile(file); final NarInfo info = new NarInfo(dependency.getGroupId(), dependency.getArtifactId(), dependency.getBaseVersion(), getLog()); if (!info.exists(jar)) { getLog().debug("Dependency nar file does not contain this artifact: " + file); return null; } info.read(jar); return info; } catch (final IOException e) { throw new MojoExecutionException("Error while reading " + file, e); } finally { IOUtils.closeQuietly(jar); } }
From source file:edu.uci.ics.asterix.event.service.AsterixEventServiceUtil.java
private static void replaceInJar(File sourceJar, String origFile, File replacementFile) throws IOException { String srcJarAbsPath = sourceJar.getAbsolutePath(); String srcJarSuffix = srcJarAbsPath.substring(srcJarAbsPath.lastIndexOf(File.separator) + 1); String srcJarName = srcJarSuffix.split(".jar")[0]; String destJarName = srcJarName + "-managix"; String destJarSuffix = destJarName + ".jar"; File destJar = new File(sourceJar.getParentFile().getAbsolutePath() + File.separator + destJarSuffix); // File destJar = new File(sourceJar.getAbsolutePath() + ".modified"); JarFile sourceJarFile = new JarFile(sourceJar); Enumeration<JarEntry> entries = sourceJarFile.entries(); JarOutputStream jos = new JarOutputStream(new FileOutputStream(destJar)); byte[] buffer = new byte[2048]; int read;//w ww . j av a 2 s . c o m while (entries.hasMoreElements()) { JarEntry entry = (JarEntry) entries.nextElement(); String name = entry.getName(); if (name.equals(origFile)) { continue; } InputStream jarIs = sourceJarFile.getInputStream(entry); jos.putNextEntry(entry); while ((read = jarIs.read(buffer)) != -1) { jos.write(buffer, 0, read); } jarIs.close(); } sourceJarFile.close(); JarEntry entry = new JarEntry(origFile); jos.putNextEntry(entry); FileInputStream fis = new FileInputStream(replacementFile); while ((read = fis.read(buffer)) != -1) { jos.write(buffer, 0, read); } fis.close(); jos.close(); sourceJar.delete(); destJar.renameTo(sourceJar); destJar.setExecutable(true); }
From source file:com.greenpepper.maven.plugin.SpecificationRunnerMojo.java
private void extractHtmlReportSummary() throws IOException, URISyntaxException { final String path = "html-summary-report"; final File jarFile = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath()); forceMkdir(reportsDirectory);//from w ww . ja va2 s .c o m if (jarFile.isFile()) { // Run with JAR file JarFile jar = new JarFile(jarFile); Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar while (entries.hasMoreElements()) { JarEntry jarEntry = entries.nextElement(); String name = jarEntry.getName(); if (name.startsWith(path)) { //filter according to the path File file = getFile(reportsDirectory, substringAfter(name, path)); if (jarEntry.isDirectory()) { forceMkdir(file); } else { forceMkdir(file.getParentFile()); if (!file.exists()) { copyInputStreamToFile(jar.getInputStream(jarEntry), file); } } } } jar.close(); } else { // Run with IDE URL url = getClass().getResource("/" + path); if (url != null) { File apps = FileUtils.toFile(url); if (apps.isDirectory()) { copyDirectory(apps, reportsDirectory); } else { throw new IllegalStateException( format("Internal resource '%s' should be a directory.", apps.getAbsolutePath())); } } else { throw new IllegalStateException(format("Internal resource '/%s' should be here.", path)); } } }
From source file:com.peterbochs.PeterBochsDebugger.java
public static void main(String[] args) { WebServiceUtil.log("peter-bochs", "start", null, null, null); try {/* w ww . ja v a 2 s. c o m*/ UIManager.setLookAndFeel("com.peterswing.white.PeterSwingWhiteLookAndFeel"); } catch (Exception e) { e.printStackTrace(); } if (args.length == 0) { String errorMessage = "Wrong number of argument\n\n"; errorMessage += "\nIn Linux/Mac : java -jar peter-bochs-debugger.jar bochs -f bochsrc.bxrc"; errorMessage += "\nIn windows : java -jar peter-bochs-debugger.jar c:\\program files\\bochs2.4.3\\bochsdbg.exe -q -f bochsrc.bxrc"; errorMessage += "\n!!! if using peter-bochs in windows, you need to pass the full path of bochs exe and -q to the parameter. (!!! relative path of bochs exe will not work)"; errorMessage += "\n!!! to use \"experimental feature\", please add \"-debug\" to the parameter list"; System.out.println(errorMessage); JOptionPane.showMessageDialog(null, errorMessage); System.exit(1); } else { if (args[0].equals("-version") || args[0].equals("-v")) { System.out.println(Global.version); System.exit(1); } } for (String str : args) { if (str.contains("bochsrc") || str.contains(".bxrc")) { bochsrc = str; } } String osName = System.getProperty("os.name").toLowerCase(); if (osName.toLowerCase().contains("windows")) { os = OSType.win; } else if (osName.toLowerCase().contains("mac")) { os = OSType.mac; } else { os = OSType.linux; } if (os == OSType.mac) { com.apple.eawt.Application macApp = com.apple.eawt.Application.getApplication(); // System.setProperty("dock:name", "Your Application Name"); macApp.setDockIconImage(new ImageIcon( PeterBochsDebugger.class.getClassLoader().getResource("com/peterbochs/icons/peter.png")) .getImage()); // java.awt.PopupMenu menu = new java.awt.PopupMenu(); // menu.add(new MenuItem("test")); // macApp.setDockMenu(menu); macApp.addApplicationListener(new MacAboutBoxHandler()); } if (ArrayUtils.contains(args, "-debug")) { Global.debug = true; args = (String[]) ArrayUtils.removeElement(args, "-debug"); } else { Global.debug = false; } try { if (PeterBochsDebugger.class.getProtectionDomain().getCodeSource().getLocation().getFile() .endsWith(".jar")) { JarFile jarFile = new JarFile( PeterBochsDebugger.class.getProtectionDomain().getCodeSource().getLocation().getFile()); if (System.getProperty("os.name").toLowerCase().contains("linux")) { if (System.getProperty("os.arch").contains("64")) { if (Global.debug) { System.out.println("Loading linux 64 bits jogl"); } CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/linux_amd64/libgluegen-rt.so")), new File("libgluegen-rt.so")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/linux_amd64/libjogl_awt.so")), new File("libjogl_awt.so")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/linux_amd64/libjogl_cg.so")), new File("libjogl_cg.so")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/linux_amd64/libjogl.so")), new File("libjogl.so")); } else { if (Global.debug) { System.out.println("Loading linux 32 bits jogl"); } CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/linux_i586/libgluegen-rt.so")), new File("libgluegen-rt.so")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/linux_i586/libjogl_awt.so")), new File("libjogl_awt.so")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/linux_i586/libjogl_cg.so")), new File("libjogl_cg.so")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/linux_i586/libjogl.so")), new File("libjogl.so")); } try { File f = new File("."); Runtime.getRuntime().load(f.getAbsolutePath() + File.separator + "libjogl.so"); System.out.println("Loading " + f.getAbsolutePath() + File.separator + "libjogl.so"); Runtime.getRuntime().load(f.getAbsolutePath() + File.separator + "libjogl_awt.so"); Runtime.getRuntime().load(f.getAbsolutePath() + File.separator + "libjogl_cg.so"); Runtime.getRuntime().load(f.getAbsolutePath() + File.separator + "libgluegen-rt.so"); } catch (UnsatisfiedLinkError e) { e.printStackTrace(); System.err.println("Native code library failed to load.\n" + e); System.err.println( "Solution : Please add \"-Djava.library.path=.\" to start peter-bochs\n" + e); } } else if (System.getProperty("os.name").toLowerCase().contains("windows")) { CommonLib.writeFile(jarFile.getInputStream(new JarEntry("com/peterbochs/exe/PauseBochs.exe")), new File("PauseBochs.exe")); CommonLib.writeFile(jarFile.getInputStream(new JarEntry("com/peterbochs/exe/StopBochs.exe")), new File("StopBochs.exe")); CommonLib.writeFile(jarFile.getInputStream(new JarEntry("com/peterbochs/exe/ndisasm.exe")), new File("ndisasm.exe")); if (System.getProperty("os.arch").contains("64")) { if (Global.debug) { System.out.println("Loading windows 64 bits jogl"); } CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/windows_amd64/jogl.dll")), new File("jogl.dll")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/windows_amd64/jogl_awt.dll")), new File("jogl_awt.dll")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/windows_amd64/jogl_cg.dll")), new File("jogl_cg.dll")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/windows_amd64/gluegen-rt.dll")), new File("gluegen-rt.dll")); } else { if (Global.debug) { System.out.println("Loading windows 32 bits jogl"); } CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/windows_i586/jogl.dll")), new File("jogl.dll")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/windows_i586/jogl_awt.dll")), new File("jogl_awt.dll")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/windows_i586/jogl_cg.dll")), new File("jogl_cg.dll")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/windows_i586/gluegen-rt.dll")), new File("gluegen-rt.dll")); } try { File f = new File("."); System.load(f.getAbsolutePath() + File.separator + "jogl.dll"); System.load(f.getAbsolutePath() + File.separator + "jogl_awt.dll"); System.load(f.getAbsolutePath() + File.separator + "jogl_cg.dll"); System.load(f.getAbsolutePath() + File.separator + "gluegen-rt.dll"); } catch (UnsatisfiedLinkError e) { e.printStackTrace(); System.err.println("Native code library failed to load.\n" + e); System.err.println( "Solution : Please add \"-Djava.library.path=.\" to start peter-bochs\n" + e); } } } } catch (IOException e) { e.printStackTrace(); } if (ArrayUtils.contains(args, "-loadBreakpoint")) { Setting.getInstance().setLoadBreakpointAtStartup(true); args = (String[]) ArrayUtils.removeElement(args, "-loadBreakpoint"); } else if (ArrayUtils.contains(args, "-loadbreakpoint")) { Setting.getInstance().setLoadBreakpointAtStartup(true); args = (String[]) ArrayUtils.removeElement(args, "-loadbreakpoint"); } for (int x = 0; x < args.length; x++) { if (args[x].toLowerCase().startsWith("-osdebug")) { Global.osDebug = CommonLib.string2long(args[x].replaceAll("-.*=", "")); args = (String[]) ArrayUtils.removeElement(args, args[x]); x = -1; } else if (args[x].toLowerCase().startsWith("-profilingmemoryport")) { Global.profilingMemoryPort = (int) CommonLib.string2long(args[x].replaceAll("-.*=", "")); args = (String[]) ArrayUtils.removeElement(args, args[x]); x = -1; } else if (args[x].toLowerCase().startsWith("-profilingjmpport")) { Global.profilingJmpPort = (int) CommonLib.string2long(args[x].replaceAll("-.*=", "")); args = (String[]) ArrayUtils.removeElement(args, args[x]); x = -1; } else if (args[x].toLowerCase().startsWith("-loadelf")) { Global.elfPaths = args[x].replaceAll("-loadelf=", "").split(","); Setting.getInstance().setLoadSystemMapAtStartup(true); args = (String[]) ArrayUtils.removeElement(args, args[x]); x = -1; } else if (args[x].toLowerCase().startsWith("-loadmap")) { System.out.println("-loadmap is not deprecated, please use -loadelf."); } } arguments = args; SwingUtilities.invokeLater(new Runnable() { public void run() { PeterBochsDebugger inst = new PeterBochsDebugger(); PeterBochsDebugger.instance = inst; new Thread("preventSetVisibleHang thread") { public void run() { try { Thread.sleep(10000); if (preventSetVisibleHang) { System.out.println( "setVisible(true) cause system hang, this probably a swing bug, so force exit, please restart"); System.exit(-1); } } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); if (Global.debug) { System.out.println("setVisible(true)"); } inst.setVisible(true); preventSetVisibleHang = false; if (Global.debug) { System.out.println("end setVisible(true)"); } } }); }
From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.TestContainerLaunch.java
private static List<String> getJarManifestClasspath(String path) throws Exception { List<String> classpath = new ArrayList<String>(); JarFile jarFile = new JarFile(path); Manifest manifest = jarFile.getManifest(); String cps = manifest.getMainAttributes().getValue("Class-Path"); StringTokenizer cptok = new StringTokenizer(cps); while (cptok.hasMoreTokens()) { String cpentry = cptok.nextToken(); classpath.add(cpentry);/*w w w . j ava 2 s .c o m*/ } return classpath; }