List of usage examples for java.util.jar JarInputStream getNextJarEntry
public JarEntry getNextJarEntry() throws IOException
From source file:com.cloudera.sqoop.orm.TestClassWriter.java
/** * Run a test to verify that we can generate code and it emits the output * files where we expect them./*www. j a va2s.c o m*/ */ private void runGenerationTest(String[] argv, String classNameToCheck) { File codeGenDirFile = new File(CODE_GEN_DIR); File classGenDirFile = new File(JAR_GEN_DIR); try { options = new ImportTool().parseArguments(argv, null, options, true); } catch (Exception e) { LOG.error("Could not parse options: " + e.toString()); } CompilationManager compileMgr = new CompilationManager(options); ClassWriter writer = new ClassWriter(options, manager, HsqldbTestServer.getTableName(), compileMgr); try { writer.generate(); compileMgr.compile(); compileMgr.jar(); } catch (IOException ioe) { LOG.error("Got IOException: " + ioe.toString()); fail("Got IOException: " + ioe.toString()); } String classFileNameToCheck = classNameToCheck.replace('.', File.separatorChar); LOG.debug("Class file to check for: " + classFileNameToCheck); // Check that all the files we expected to generate (.java, .class, .jar) // exist. File tableFile = new File(codeGenDirFile, classFileNameToCheck + ".java"); assertTrue("Cannot find generated source file for table!", tableFile.exists()); LOG.debug("Found generated source: " + tableFile); File tableClassFile = new File(classGenDirFile, classFileNameToCheck + ".class"); assertTrue("Cannot find generated class file for table!", tableClassFile.exists()); LOG.debug("Found generated class: " + tableClassFile); File jarFile = new File(compileMgr.getJarFilename()); assertTrue("Cannot find compiled jar", jarFile.exists()); LOG.debug("Found generated jar: " + jarFile); // check that the .class file made it into the .jar by enumerating // available entries in the jar file. boolean foundCompiledClass = false; try { JarInputStream jis = new JarInputStream(new FileInputStream(jarFile)); LOG.debug("Jar file has entries:"); while (true) { JarEntry entry = jis.getNextJarEntry(); if (null == entry) { // no more entries. break; } if (entry.getName().equals(classFileNameToCheck + ".class")) { foundCompiledClass = true; LOG.debug(" * " + entry.getName()); } else { LOG.debug(" " + entry.getName()); } } jis.close(); } catch (IOException ioe) { fail("Got IOException iterating over Jar file: " + ioe.toString()); } assertTrue("Cannot find .class file " + classFileNameToCheck + ".class in jar file", foundCompiledClass); LOG.debug("Found class in jar - test success!"); }
From source file:org.openspaces.maven.plugin.CreatePUProjectMojo.java
/** * Extracts the project files to the project directory. *///from w w w.ja va 2 s .co m private void extract(URL url) throws Exception { packageDirs = packageName.replaceAll("\\.", "/"); String puTemplate = DIR_TEMPLATES + "/" + template + "/"; int length = puTemplate.length() - 1; BufferedInputStream bis = new BufferedInputStream(url.openStream()); JarInputStream jis = new JarInputStream(bis); JarEntry je; byte[] buf = new byte[1024]; int n; while ((je = jis.getNextJarEntry()) != null) { String jarEntryName = je.getName(); PluginLog.getLog().debug("JAR entry: " + jarEntryName); if (je.isDirectory() || !jarEntryName.startsWith(puTemplate)) { continue; } String targetFileName = projectDir + jarEntryName.substring(length); // convert the ${gsGroupPath} to directory targetFileName = StringUtils.replace(targetFileName, FILTER_GROUP_PATH, packageDirs); PluginLog.getLog().debug("Extracting entry " + jarEntryName + " to " + targetFileName); // read the bytes to the buffer ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); while ((n = jis.read(buf, 0, 1024)) > -1) { byteStream.write(buf, 0, n); } // replace property references with the syntax ${property_name} // to their respective property values. String data = byteStream.toString(); data = StringUtils.replace(data, FILTER_GROUP_ID, packageName); data = StringUtils.replace(data, FILTER_ARTIFACT_ID, projectDir.getName()); data = StringUtils.replace(data, FILTER_GROUP_PATH, packageDirs); // write the entire converted file content to the destination file. File f = new File(targetFileName); File dir = f.getParentFile(); if (!dir.exists()) { dir.mkdirs(); } FileWriter writer = new FileWriter(f); writer.write(data); jis.closeEntry(); writer.close(); } jis.close(); }
From source file:de.tudarmstadt.ukp.dkpro.core.maltparser.MaltParser.java
private String getRealName(URL aUrl) throws IOException { JarEntry je = null;//from ww w . j a v a2s .c om JarInputStream jis = null; try { jis = new JarInputStream(aUrl.openConnection().getInputStream()); while ((je = jis.getNextJarEntry()) != null) { String entryName = je.getName(); if (entryName.endsWith(".info")) { int indexUnderScore = entryName.lastIndexOf('_'); int indexSeparator = entryName.lastIndexOf(File.separator); if (indexSeparator == -1) { indexSeparator = entryName.lastIndexOf('/'); } if (indexSeparator == -1) { indexSeparator = entryName.lastIndexOf('\\'); } int indexDot = entryName.lastIndexOf('.'); if (indexUnderScore == -1 || indexDot == -1) { throw new IllegalStateException( "Could not find the configuration name and type from the URL '" + aUrl.toString() + "'. "); } return entryName.substring(indexSeparator + 1, indexUnderScore) + ".mco"; } } throw new IllegalStateException( "Could not find the configuration name and type from the URL '" + aUrl.toString() + "'. "); } finally { IOUtils.closeQuietly(jis); } }
From source file:org.apache.pluto.util.assemble.ear.EarAssembler.java
public void assembleInternal(AssemblerConfig config) throws UtilityException, IOException { File source = config.getSource(); File dest = config.getDestination(); JarInputStream earIn = new JarInputStream(new FileInputStream(source)); JarOutputStream earOut = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(dest), BUFLEN)); try {//from w w w . jav a2s . c om JarEntry entry; // Iterate over entries in the EAR archive while ((entry = earIn.getNextJarEntry()) != null) { // If a war file is encountered, assemble it into a // ByteArrayOutputStream and write the assembled bytes // back to the EAR archive. if (entry.getName().toLowerCase().endsWith(".war")) { if (LOG.isDebugEnabled()) { LOG.debug("Assembling war file " + entry.getName()); } // keep a handle to the AssemblySink so we can write out // JarEntry metadata and the bytes later. AssemblySink warBytesOut = getAssemblySink(config, entry); JarOutputStream warOut = new JarOutputStream(warBytesOut); JarStreamingAssembly.assembleStream(new JarInputStream(earIn), warOut, config.getDispatchServletClass()); JarEntry warEntry = new JarEntry(entry); // Write out the assembled JarEntry metadata warEntry.setSize(warBytesOut.getByteCount()); warEntry.setCrc(warBytesOut.getCrc()); warEntry.setCompressedSize(-1); earOut.putNextEntry(warEntry); // Write out the assembled WAR file to the EAR warBytesOut.writeTo(earOut); earOut.flush(); earOut.closeEntry(); earIn.closeEntry(); } else { earOut.putNextEntry(entry); IOUtils.copy(earIn, earOut); earOut.flush(); earOut.closeEntry(); earIn.closeEntry(); } } } finally { earOut.close(); earIn.close(); } }
From source file:com.ikon.util.cl.BinaryClassLoader.java
/** * Create internal classes and resources cache *//*from ww w. j ava 2 s . c o m*/ private void createCache(byte[] buf) throws IOException { ByteArrayInputStream bais = null; JarInputStream jis = null; byte[] buffer = new byte[1024 * 4]; try { bais = new ByteArrayInputStream(buf); jis = new JarInputStream(bais); Attributes attr = jis.getManifest().getMainAttributes(); mainClassName = attr != null ? attr.getValue(Attributes.Name.MAIN_CLASS) : null; for (JarEntry entry = null; (entry = jis.getNextJarEntry()) != null;) { String name = entry.getName(); if (!entry.isDirectory()) { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); for (int n = 0; -1 != (n = jis.read(buffer));) { byteStream.write(buffer, 0, n); } if (name.endsWith(".class")) { String className = name.substring(0, name.indexOf('.')).replace('/', '.'); resources.put(className, byteStream.toByteArray()); } else { resources.put(name, byteStream.toByteArray()); } byteStream.close(); } } } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(jis); IOUtils.closeQuietly(bais); } }
From source file:org.drools.guvnor.server.RepositoryModuleService.java
private JarInputStream typesForModel(List<String> res, AssetItem asset) throws IOException { if (!asset.isBinary()) { return null; }//from www.j a v a2 s . c om if (asset.getBinaryContentAttachment() == null) { return null; } JarInputStream jis; jis = new JarInputStream(asset.getBinaryContentAttachment()); JarEntry entry = null; while ((entry = jis.getNextJarEntry()) != null) { if (!entry.isDirectory()) { if (entry.getName().endsWith(".class") && !entry.getName().endsWith("package-info.class")) { res.add(ModelContentHandler.convertPathToName(entry.getName())); } } } return jis; }
From source file:org.drools.guvnor.server.contenthandler.soa.JarFileContentHandler.java
private String getClassesFromJar(AssetItem assetItem) throws IOException { Map<String, String> nonCollidingImports = new HashMap<String, String>(); String assetPackageName = assetItem.getModuleName(); //Setup class-loader to check for class visibility JarInputStream cljis = new JarInputStream(assetItem.getBinaryContentAttachment()); List<JarInputStream> jarInputStreams = new ArrayList<JarInputStream>(); jarInputStreams.add(cljis);//from ww w.j ava 2s . c o m ClassLoaderBuilder clb = new ClassLoaderBuilder(jarInputStreams); ClassLoader cl = clb.buildClassLoader(); //Reset stream to read classes JarInputStream jis = new JarInputStream(assetItem.getBinaryContentAttachment()); JarEntry entry = null; //Get Class names from JAR, only the first occurrence of a given Class leaf name will be inserted. Thus //"org.apache.commons.lang.NumberUtils" will be imported but "org.apache.commons.lang.math.NumberUtils" //will not, assuming it follows later in the JAR structure. while ((entry = jis.getNextJarEntry()) != null) { if (!entry.isDirectory()) { if (entry.getName().endsWith(".class") && entry.getName().indexOf('$') == -1 && !entry.getName().endsWith("package-info.class")) { String fullyQualifiedName = convertPathToName(entry.getName()); if (isClassVisible(cl, fullyQualifiedName, assetPackageName)) { String leafName = getLeafName(fullyQualifiedName); if (!nonCollidingImports.containsKey(leafName)) { nonCollidingImports.put(leafName, fullyQualifiedName); } } } } } //Build list of classes StringBuffer classes = new StringBuffer(); for (String value : nonCollidingImports.values()) { classes.append(value + "\n"); } return classes.toString(); }
From source file:com.egreen.tesla.server.api.component.Component.java
private void init() throws FileNotFoundException, IOException, ConfigurationException { //Init url/*from www . ja va 2 s . c om*/ this.jarFile = new URL("jar", "", "file:" + file.getAbsolutePath() + "!/"); final FileInputStream fileInputStream = new FileInputStream(file); JarInputStream jarFile = new JarInputStream(fileInputStream); JarFile jf = new JarFile(file); setConfiguraton(jf);//Configuration load jf.getEntry(TESLAR_WIDGET_MAINIFIESTXML); JarEntry jarEntry; while (true) { jarEntry = jarFile.getNextJarEntry(); if (jarEntry == null) { break; } if (jarEntry.getName().endsWith(".class") && !jarEntry.getName().contains("$")) { final String JarNameClass = jarEntry.getName().replaceAll("/", "\\."); String className = JarNameClass.replace(".class", ""); LOGGER.info(className); controllerClassMapper.put(className, className); } else if (jarEntry.getName().startsWith("webapp")) { final String JarNameClass = jarEntry.getName(); LOGGER.info(JarNameClass); saveEntry(jf.getInputStream(jarEntry), JarNameClass); } } }
From source file:com.ottogroup.bi.asap.repository.CachedComponentClassLoader.java
/** * Initializes the class loader by pointing it to folder holding managed JAR files * @param componentFolder/* www. j a v a 2 s .c o m*/ * @throws IOException * @throws RequiredInputMissingException */ public void initialize(final String componentFolder) throws IOException, RequiredInputMissingException { /////////////////////////////////////////////////////////////////// // validate input if (StringUtils.isBlank(componentFolder)) throw new RequiredInputMissingException("Missing required value for parameter 'componentFolder'"); File folder = new File(componentFolder); if (!folder.isDirectory()) throw new IOException("Provided input '" + componentFolder + "' does not reference a valid folder"); File[] jarFiles = folder.listFiles(); if (jarFiles == null || jarFiles.length < 1) throw new RequiredInputMissingException("No JAR files found in folder '" + componentFolder + "'"); // /////////////////////////////////////////////////////////////////// logger.info("Initializing component classloader [folder=" + componentFolder + "]"); // step through jar files, ensure it is a file and iterate through its contents for (File jarFile : jarFiles) { if (jarFile.isFile()) { JarInputStream jarInputStream = null; try { jarInputStream = new JarInputStream(new FileInputStream(jarFile)); JarEntry jarEntry = null; while ((jarEntry = jarInputStream.getNextJarEntry()) != null) { String jarEntryName = jarEntry.getName(); // if the current file references a class implementation, replace slashes by dots, strip // away the class suffix and add a reference to the classes-2-jar mapping if (StringUtils.endsWith(jarEntryName, ".class")) { jarEntryName = jarEntryName.substring(0, jarEntryName.length() - 6).replace('/', '.'); this.byteCode.put(jarEntryName, loadBytes(jarInputStream)); } else { // ...and add a mapping for resource to jar file as well this.resources.put(jarEntryName, loadBytes(jarInputStream)); } } } catch (Exception e) { logger.error("Failed to read from JAR file '" + jarFile.getAbsolutePath() + "'. Error: " + e.getMessage()); } finally { try { jarInputStream.close(); } catch (Exception e) { logger.error("Failed to close open JAR file '" + jarFile.getAbsolutePath() + "'. Error: " + e.getMessage()); } } } } logger.info("Analyzing " + this.byteCode.size() + " classes for component annotation"); // load classes from jars marked component files and extract the deployment descriptors for (String cjf : this.byteCode.keySet()) { try { Class<?> c = loadClass(cjf); AsapComponent pc = c.getAnnotation(AsapComponent.class); if (pc != null) { this.managedComponents.put(getManagedComponentKey(pc.name(), pc.version()), new ComponentDescriptor(c.getName(), pc.type(), pc.name(), pc.version(), pc.description())); logger.info("pipeline component found [type=" + pc.type() + ", name=" + pc.name() + ", version=" + pc.version() + "]"); ; } } catch (Throwable e) { //logger.info("Failed to load class '"+cjf+"'. Error: " + e.getMessage()); } } }
From source file:org.drools.guvnor.server.contenthandler.ModelContentHandler.java
private Set<String> getImportsFromJar(AssetItem assetItem) throws IOException { Set<String> imports = new HashSet<String>(); Map<String, String> nonCollidingImports = new HashMap<String, String>(); String assetPackageName = assetItem.getModuleName(); //Setup class-loader to check for class visibility JarInputStream cljis = new JarInputStream(assetItem.getBinaryContentAttachment()); List<JarInputStream> jarInputStreams = new ArrayList<JarInputStream>(); jarInputStreams.add(cljis);/*w w w . j a va 2 s. co m*/ ClassLoaderBuilder clb = new ClassLoaderBuilder(jarInputStreams); ClassLoader cl = clb.buildClassLoader(); //Reset stream to read classes JarInputStream jis = new JarInputStream(assetItem.getBinaryContentAttachment()); JarEntry entry = null; //Get Class names from JAR, only the first occurrence of a given Class leaf name will be inserted. Thus //"org.apache.commons.lang.NumberUtils" will be imported but "org.apache.commons.lang.math.NumberUtils" //will not, assuming it follows later in the JAR structure. while ((entry = jis.getNextJarEntry()) != null) { if (!entry.isDirectory()) { if (entry.getName().endsWith(".class") && !entry.getName().endsWith("package-info.class")) { final String fullyQualifiedName = convertPathToName(entry.getName()); final String fullyQualifiedClassName = convertPathToClassName(entry.getName()); if (isClassVisible(cl, fullyQualifiedClassName, assetPackageName)) { String leafName = getLeafName(fullyQualifiedName); if (!nonCollidingImports.containsKey(leafName)) { nonCollidingImports.put(leafName, fullyQualifiedName); } } } } } //Build list of imports for (String value : nonCollidingImports.values()) { String line = "import " + value; imports.add(line); } return imports; }