List of usage examples for java.util.jar JarFile getInputStream
public synchronized InputStream getInputStream(ZipEntry ze) throws IOException
From source file:org.mule.util.JarUtils.java
public static LinkedHashMap readJarFileEntries(File jarFile) throws Exception { LinkedHashMap entries = new LinkedHashMap(); JarFile jarFileWrapper = null; if (jarFile != null) { logger.debug("Reading jar entries from " + jarFile.getAbsolutePath()); try {/*w w w . ja v a 2s .co m*/ jarFileWrapper = new JarFile(jarFile); Enumeration iter = jarFileWrapper.entries(); while (iter.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) iter.nextElement(); InputStream entryStream = jarFileWrapper.getInputStream(zipEntry); ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream(); try { IOUtils.copy(entryStream, byteArrayStream); entries.put(zipEntry.getName(), byteArrayStream.toByteArray()); logger.debug("Read jar entry " + zipEntry.getName() + " from " + jarFile.getAbsolutePath()); } finally { byteArrayStream.close(); } } } finally { if (jarFileWrapper != null) { try { jarFileWrapper.close(); } catch (Exception ignore) { logger.debug(ignore); } } } } return entries; }
From source file:org.jiemamy.utils.ResourceTraversal.java
/** * ???/* www . j a va2s. co m*/ * * @param jarFile JarFile * @param handler ? * @throws IOException ???? * @throws TraversalHandlerException ??????? * @throws IllegalArgumentException ?{@code null}??? */ public static void forEach(JarFile jarFile, ResourceHandler handler) throws IOException, TraversalHandlerException { Validate.notNull(jarFile); Validate.notNull(handler); Enumeration<JarEntry> enumeration = jarFile.entries(); while (enumeration.hasMoreElements()) { JarEntry entry = enumeration.nextElement(); if (!entry.isDirectory()) { String entryName = entry.getName().replace('\\', '/'); InputStream is = jarFile.getInputStream(entry); try { handler.processResource(entryName, is); } finally { IOUtils.closeQuietly(is); } } } }
From source file:de.xirp.plugin.PluginLoader.java
/** * Looks for plugins in the plugins directory. Plugins which needs * are not full filled are not accepted. * //from w w w . j a va 2 s.co m * @param manager * instance of the plugin manager which is used for * notifying the application about the loading * progress. */ protected static void searchPlugins(PluginManager manager) { logClass.info(I18n.getString("PluginLoader.log.searchPlugins")); //$NON-NLS-1$ // Get all Files in the Plugin Directory with // Filetype jar File pluginDir = new File(Constants.PLUGIN_DIR); File[] fileList = pluginDir.listFiles(new FilenameFilter() { public boolean accept(@SuppressWarnings("unused") File dir, String filename) { return filename.endsWith(".jar"); //$NON-NLS-1$ } }); if (fileList != null) { double perFile = 1.0 / fileList.length; double cnt = 0; try { // Iterate over all jars and try to find // the plugin.properties file // The file is loaded and Information // extracted to PluginInfo // Plugin is added to List of Plugins for (File f : fileList) { String path = f.getAbsolutePath(); if (!plugins.containsKey(path)) { manager.throwLoaderProgressEvent( I18n.getString("PluginLoader.progress.searchingInFile", f.getName()), cnt); //$NON-NLS-1$ JarFile jar = new JarFile(path); JarEntry entry = jar.getJarEntry("plugin.properties"); //$NON-NLS-1$ if (entry != null) { InputStream input = jar.getInputStream(entry); Properties props = new Properties(); props.load(input); String mainClass = props.getProperty("plugin.mainclass"); //$NON-NLS-1$ PluginInfo info = new PluginInfo(path, mainClass, props); String packageName = ClassUtils.getPackageName(mainClass) + "." //$NON-NLS-1$ + AbstractPlugin.DEFAULT_BUNDLE_NAME; String bundleBaseName = packageName.replaceAll("\\.", "/"); //$NON-NLS-1$ //$NON-NLS-2$ for (Enumeration<JarEntry> entries = jar.entries(); entries.hasMoreElements();) { JarEntry ent = entries.nextElement(); String name = ent.getName(); if (name.indexOf(bundleBaseName) != -1) { String locale = name .substring(name.indexOf(AbstractPlugin.DEFAULT_BUNDLE_NAME)); locale = locale.replaceAll(AbstractPlugin.DEFAULT_BUNDLE_NAME + "_", //$NON-NLS-1$ ""); //$NON-NLS-1$ locale = locale.substring(0, locale.indexOf(".properties")); //$NON-NLS-1$ Locale loc = new Locale(locale); info.addAvailableLocale(loc); } } PluginManager.extractAll(info); if (isPlugin(info)) { plugins.put(mainClass, info); } } } cnt += perFile; } } catch (IOException e) { logClass.error( I18n.getString("PluginLoader.log.errorSearchingforPlugins") + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$ } } checkAllNeeds(); logClass.info(I18n.getString("PluginLoader.log.searchPluginsCompleted") + Constants.LINE_SEPARATOR); //$NON-NLS-1$ }
From source file:com.cisco.dbds.utils.configfilehandler.ConfigFileHandler.java
/** * Load jar cong file./* w ww . j a v a2 s . c o m*/ * * @param Utilclass the utilclass */ public static void loadJarCongFile(Class Utilclass) { try { String path = Utilclass.getResource("").getPath(); path = path.substring(6, path.length() - 1); path = path.split("!")[0]; System.out.println(path); JarFile jarFile = new JarFile(path); final Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { final JarEntry entry = entries.nextElement(); if (entry.getName().contains(".properties")) { System.out.println("Jar File Property File: " + entry.getName()); JarEntry fileEntry = jarFile.getJarEntry(entry.getName()); InputStream input = jarFile.getInputStream(fileEntry); setSystemvariable(input); InputStreamReader isr = new InputStreamReader(input); BufferedReader reader = new BufferedReader(isr); String line; while ((line = reader.readLine()) != null) { System.out.println("Jar file" + line); } reader.close(); } } jarFile.close(); } catch (Exception e) { System.out.println("Jar file reading Error"); } }
From source file:org.jsweet.transpiler.candies.CandyDescriptor.java
public static CandyDescriptor fromCandyJar(JarFile jarFile, String jsOutputDirPath) throws IOException { JarEntry pomEntry = null;/*from w ww . j a v a 2 s . c o m*/ Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry current = entries.nextElement(); if (current.getName().endsWith("pom.xml")) { pomEntry = current; } } String pomContent = IOUtils.toString(jarFile.getInputStream(pomEntry)); // take only general part int dependenciesIndex = pomContent.indexOf("<dependencies>"); String pomGeneralPart = dependenciesIndex > 0 ? pomContent.substring(0, dependenciesIndex) : pomContent; // extract candy model version from <groupId></groupId> Matcher matcher = MODEL_VERSION_PATTERN.matcher(pomGeneralPart); String modelVersion = "unknown"; if (matcher.find()) { modelVersion = matcher.group(1); } // extract name from <artifactId></artifactId> matcher = ARTIFACT_ID_PATTERN.matcher(pomGeneralPart); String name = "unknown"; if (matcher.find()) { name = matcher.group(1); } matcher = VERSION_PATTERN.matcher(pomGeneralPart); String version = "unknown"; if (matcher.find()) { version = matcher.group(1); } long lastUpdateTimestamp = jarFile.getEntry("META-INF/MANIFEST.MF").getTime(); String transpilerVersion = null; ZipEntry metadataEntry = jarFile.getEntry("META-INF/candy-metadata.json"); if (metadataEntry != null) { String metadataContent = IOUtils.toString(jarFile.getInputStream(metadataEntry)); @SuppressWarnings("unchecked") Map<String, ?> metadata = gson.fromJson(metadataContent, Map.class); transpilerVersion = (String) metadata.get("transpilerVersion"); } String jsDirPath = "META-INF/resources/webjars/" + name + "/" + version; ZipEntry jsDirEntry = jarFile.getEntry(jsDirPath); List<String> jsFilesPaths = new LinkedList<>(); if (jsDirEntry != null) { // collects js files jarFile.stream() // .filter(entry -> entry.getName().startsWith(jsDirPath) && entry.getName().endsWith(".js")) // .map(entry -> entry.getName()) // .forEach(jsFilesPaths::add); } return new CandyDescriptor( // name, // version, // lastUpdateTimestamp, // modelVersion, // transpilerVersion, // jsOutputDirPath, // jsDirPath, // jsFilesPaths); }
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 w w. j a v a2s.com*/ } 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:ch.rasc.embeddedtc.plugin.PackageTcWarMojo.java
private static void extractJarToArchive(JarFile file, ArchiveOutputStream aos) throws IOException { Enumeration<? extends JarEntry> entries = file.entries(); while (entries.hasMoreElements()) { JarEntry j = entries.nextElement(); if (!"META-INF/MANIFEST.MF".equals(j.getName())) { aos.putArchiveEntry(new JarArchiveEntry(j.getName())); IOUtils.copy(file.getInputStream(j), aos); aos.closeArchiveEntry();/*ww w.j a v a 2 s . c o m*/ } } }
From source file:itdelatrisu.opsu.Utils.java
public static void unpackFromJar(@NotNull JarFile jarfile, @NotNull File unpackedFile, @NotNull String filename) throws IOException { InputStream in = jarfile.getInputStream(jarfile.getEntry(filename)); OutputStream out = new FileOutputStream(unpackedFile); byte[] buffer = new byte[65536]; int bufferSize; while ((bufferSize = in.read(buffer, 0, buffer.length)) != -1) { out.write(buffer, 0, bufferSize); }// w w w . ja va2 s .c om in.close(); out.close(); }
From source file:azkaban.jobtype.connectors.teradata.TeraDataWalletInitializer.java
/** * As of TDCH 1.4.1, integration with Teradata wallet only works with hadoop jar command line command. * This is mainly because TDCH depends on the behavior of hadoop jar command line which extracts jar file * into hadoop tmp folder.//from ww w . j av a 2s . c om * * This method will extract tdchJarfile and place it into temporary folder, and also add jvm shutdown hook * to delete the directory when JVM shuts down. * @param tdchJarFile TDCH jar file. */ public static void initialize(File tmpDir, File tdchJarFile) { synchronized (TeraDataWalletInitializer.class) { if (tdchJarExtractedDir != null) { return; } if (tdchJarFile == null) { throw new IllegalArgumentException("TDCH jar file cannot be null."); } if (!tdchJarFile.exists()) { throw new IllegalArgumentException( "TDCH jar file does not exist. " + tdchJarFile.getAbsolutePath()); } try { //Extract TDCH jar. File unJarDir = createUnjarDir( new File(tmpDir.getAbsolutePath() + File.separator + UNJAR_DIR_NAME)); JarFile jar = new JarFile(tdchJarFile); Enumeration<JarEntry> enumEntries = jar.entries(); while (enumEntries.hasMoreElements()) { JarEntry srcFile = enumEntries.nextElement(); File destFile = new File(unJarDir + File.separator + srcFile.getName()); if (srcFile.isDirectory()) { // if its a directory, create it destFile.mkdir(); continue; } InputStream is = jar.getInputStream(srcFile); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(destFile)); IOUtils.copy(is, os); close(os); close(is); } jar.close(); tdchJarExtractedDir = unJarDir; } catch (IOException e) { throw new RuntimeException("Failed while extracting TDCH jar file.", e); } } logger.info("TDCH jar has been extracted into directory: " + tdchJarExtractedDir.getAbsolutePath()); }
From source file:JarUtil.java
/** * Adds the given file to the specified JAR file. * /* w w w .ja v a2 s. c om*/ * @param file * the file that should be added * @param jarFile * The JAR to which the file should be added * @param parentDir * the parent directory of the file, this is used to calculate * the path witin the JAR file. When null is given, the file will * be added into the root of the JAR. * @param compress * True when the jar file should be compressed * @throws FileNotFoundException * when the jarFile does not exist * @throws IOException * when a file could not be written or the jar-file could not * read. */ public static void addToJar(File file, File jarFile, File parentDir, boolean compress) throws FileNotFoundException, IOException { File tmpJarFile = File.createTempFile("tmp", ".jar", jarFile.getParentFile()); JarOutputStream out = new JarOutputStream(new FileOutputStream(tmpJarFile)); if (compress) { out.setLevel(ZipOutputStream.DEFLATED); } else { out.setLevel(ZipOutputStream.STORED); } // copy contents of old jar to new jar: JarFile inputFile = new JarFile(jarFile); JarInputStream in = new JarInputStream(new FileInputStream(jarFile)); CRC32 crc = new CRC32(); byte[] buffer = new byte[512 * 1024]; JarEntry entry = (JarEntry) in.getNextEntry(); while (entry != null) { InputStream entryIn = inputFile.getInputStream(entry); add(entry, entryIn, out, crc, buffer); entryIn.close(); entry = (JarEntry) in.getNextEntry(); } in.close(); inputFile.close(); int sourceDirLength; if (parentDir == null) { sourceDirLength = file.getAbsolutePath().lastIndexOf(File.separatorChar) + 1; } else { sourceDirLength = file.getAbsolutePath().lastIndexOf(File.separatorChar) + 1 - parentDir.getAbsolutePath().length(); } addFile(file, out, crc, sourceDirLength, buffer); out.close(); // remove old jar file and rename temp file to old one: if (jarFile.delete()) { if (!tmpJarFile.renameTo(jarFile)) { throw new IOException( "Unable to rename temporary JAR file to [" + jarFile.getAbsolutePath() + "]."); } } else { throw new IOException("Unable to delete old JAR file [" + jarFile.getAbsolutePath() + "]."); } }