List of usage examples for java.util.jar JarEntry JarEntry
public JarEntry(JarEntry je)
JarEntry
with fields taken from the specified JarEntry
object. From source file:org.apache.hadoop.hbase.TestClassFinder.java
/** * Makes a jar out of some class files. Unfortunately it's very tedious. * @param filesInJar Files created via compileTestClass. * @return path to the resulting jar file. *//*from w w w . j a v a2 s . c o m*/ private static String packageAndLoadJar(FileAndPath... filesInJar) throws Exception { // First, write the bogus jar file. String path = basePath + "jar" + jarCounter.incrementAndGet() + ".jar"; Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); FileOutputStream fos = new FileOutputStream(path); JarOutputStream jarOutputStream = new JarOutputStream(fos, manifest); // Directory entries for all packages have to be added explicitly for // resources to be findable via ClassLoader. Directory entries must end // with "/"; the initial one is expected to, also. Set<String> pathsInJar = new HashSet<String>(); for (FileAndPath fileAndPath : filesInJar) { String pathToAdd = fileAndPath.path; while (pathsInJar.add(pathToAdd)) { int ix = pathToAdd.lastIndexOf('/', pathToAdd.length() - 2); if (ix < 0) { break; } pathToAdd = pathToAdd.substring(0, ix); } } for (String pathInJar : pathsInJar) { jarOutputStream.putNextEntry(new JarEntry(pathInJar)); jarOutputStream.closeEntry(); } for (FileAndPath fileAndPath : filesInJar) { File file = fileAndPath.file; jarOutputStream.putNextEntry(new JarEntry(fileAndPath.path + file.getName())); byte[] allBytes = new byte[(int) file.length()]; FileInputStream fis = new FileInputStream(file); fis.read(allBytes); fis.close(); jarOutputStream.write(allBytes); jarOutputStream.closeEntry(); } jarOutputStream.close(); fos.close(); // Add the file to classpath. File jarFile = new File(path); assertTrue(jarFile.exists()); URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class }); method.setAccessible(true); method.invoke(urlClassLoader, new Object[] { jarFile.toURI().toURL() }); return jarFile.getAbsolutePath(); }
From source file:org.apache.hadoop.hbase.util.ClassLoaderTestHelper.java
/** * Jar a list of files into a jar archive. * * @param archiveFile the target jar archive * @param tobejared a list of files to be jared *///from w ww. ja va 2 s .c om private static boolean createJarArchive(File archiveFile, File[] tobeJared) { try { byte buffer[] = new byte[BUFFER_SIZE]; // Open archive file FileOutputStream stream = new FileOutputStream(archiveFile); JarOutputStream out = new JarOutputStream(stream, new Manifest()); for (int i = 0; i < tobeJared.length; i++) { if (tobeJared[i] == null || !tobeJared[i].exists() || tobeJared[i].isDirectory()) { continue; } // Add archive entry JarEntry jarAdd = new JarEntry(tobeJared[i].getName()); jarAdd.setTime(tobeJared[i].lastModified()); out.putNextEntry(jarAdd); // Write file to archive FileInputStream in = new FileInputStream(tobeJared[i]); while (true) { int nRead = in.read(buffer, 0, buffer.length); if (nRead <= 0) break; out.write(buffer, 0, nRead); } in.close(); } out.close(); stream.close(); LOG.info("Adding classes to jar file completed"); return true; } catch (Exception ex) { LOG.error("Error: " + ex.getMessage()); return false; } }
From source file:org.apache.hadoop.hbase.util.ClassLoaderTestHelper.java
/** * Add a list of jar files to another jar file under a specific folder. * It is used to generated coprocessor jar files which can be loaded by * the coprocessor class loader. It is for testing usage only so we * don't be so careful about stream closing in case any exception. * * @param targetJar the target jar file// www.ja v a 2 s .co m * @param libPrefix the folder where to put inner jar files * @param srcJars the source inner jar files to be added * @throws Exception if anything doesn't work as expected */ public static void addJarFilesToJar(File targetJar, String libPrefix, File... srcJars) throws Exception { FileOutputStream stream = new FileOutputStream(targetJar); JarOutputStream out = new JarOutputStream(stream, new Manifest()); byte buffer[] = new byte[BUFFER_SIZE]; for (File jarFile : srcJars) { // Add archive entry JarEntry jarAdd = new JarEntry(libPrefix + jarFile.getName()); jarAdd.setTime(jarFile.lastModified()); out.putNextEntry(jarAdd); // Write file to archive FileInputStream in = new FileInputStream(jarFile); while (true) { int nRead = in.read(buffer, 0, buffer.length); if (nRead <= 0) break; out.write(buffer, 0, nRead); } in.close(); } out.close(); stream.close(); LOG.info("Adding jar file to outer jar file completed"); }
From source file:org.apache.hadoop.yarn.util.TestFSDownload.java
static LocalResource createJarFile(FileContext files, Path p, int len, Random r, LocalResourceVisibility vis) throws IOException, URISyntaxException { byte[] bytes = new byte[len]; r.nextBytes(bytes);/*from ww w. jav a 2 s .c o m*/ File archiveFile = new File(p.toUri().getPath() + ".jar"); archiveFile.createNewFile(); JarOutputStream out = new JarOutputStream(new FileOutputStream(archiveFile)); out.putNextEntry(new JarEntry(p.getName())); out.write(bytes); out.closeEntry(); out.close(); LocalResource ret = recordFactory.newRecordInstance(LocalResource.class); ret.setResource(URL.fromPath(new Path(p.toString() + ".jar"))); ret.setSize(len); ret.setType(LocalResourceType.ARCHIVE); ret.setVisibility(vis); ret.setTimestamp(files.getFileStatus(new Path(p.toString() + ".jar")).getModificationTime()); return ret; }
From source file:org.apache.phoenix.end2end.UserDefinedFunctionsIT.java
/** * Compiles the test class with bogus code into a .class file. * Upon finish, the bogus jar will be left at dynamic.jar.dir location *//* w w w. j a va2 s . c o m*/ private static void compileTestClass(String className, String program, int counter) throws Exception { String javaFileName = className + ".java"; File javaFile = new File(javaFileName); String classFileName = className + ".class"; File classFile = new File(classFileName); String jarName = "myjar" + counter + ".jar"; String jarPath = "." + File.separator + jarName; File jarFile = new File(jarPath); try { String packageName = "org.apache.phoenix.end2end"; FileOutputStream fos = new FileOutputStream(javaFileName); fos.write(program.getBytes()); fos.close(); JavaCompiler jc = ToolProvider.getSystemJavaCompiler(); int result = jc.run(null, null, null, javaFileName); assertEquals(0, result); Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); FileOutputStream jarFos = new FileOutputStream(jarPath); JarOutputStream jarOutputStream = new JarOutputStream(jarFos, manifest); String pathToAdd = packageName.replace('.', '/') + '/'; String jarPathStr = new String(pathToAdd); Set<String> pathsInJar = new HashSet<String>(); while (pathsInJar.add(jarPathStr)) { int ix = jarPathStr.lastIndexOf('/', jarPathStr.length() - 2); if (ix < 0) { break; } jarPathStr = jarPathStr.substring(0, ix); } for (String pathInJar : pathsInJar) { jarOutputStream.putNextEntry(new JarEntry(pathInJar)); jarOutputStream.closeEntry(); } jarOutputStream.putNextEntry(new JarEntry(pathToAdd + classFile.getName())); byte[] allBytes = new byte[(int) classFile.length()]; FileInputStream fis = new FileInputStream(classFile); fis.read(allBytes); fis.close(); jarOutputStream.write(allBytes); jarOutputStream.closeEntry(); jarOutputStream.close(); jarFos.close(); assertTrue(jarFile.exists()); Connection conn = driver.connect(url, EMPTY_PROPS); Statement stmt = conn.createStatement(); stmt.execute("add jars '" + jarFile.getAbsolutePath() + "'"); } finally { if (javaFile != null) javaFile.delete(); if (classFile != null) classFile.delete(); if (jarFile != null) jarFile.delete(); } }
From source file:org.apache.pig.impl.util.JarManager.java
/** * Adds a stream to a Jar file./* w w w. j a v a2 s . c o m*/ * * @param os * the OutputStream of the Jar file to which the stream will be added. * @param name * the name of the stream. * @param is * the stream to add. * @param contents * the current contents of the Jar file. (We use this to avoid adding two streams * with the same name. * @param timestamp * timestamp of the entry * @throws IOException */ private static void addStream(JarOutputStream os, String name, InputStream is, Map<String, String> contents, long timestamp) throws IOException { if (contents.get(name) != null) { return; } contents.put(name, ""); JarEntry entry = new JarEntry(name); entry.setTime(timestamp); os.putNextEntry(entry); byte buffer[] = new byte[4096]; int rc; while ((rc = is.read(buffer)) > 0) { os.write(buffer, 0, rc); } }
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 {// ww w . ja va2s. co m 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:org.apache.pluto.util.assemble.io.JarStreamingAssembly.java
private static JarEntry smartClone(JarEntry originalJarEntry) { final JarEntry newJarEntry = new JarEntry(originalJarEntry.getName()); newJarEntry.setComment(originalJarEntry.getComment()); newJarEntry.setExtra(originalJarEntry.getExtra()); newJarEntry.setMethod(originalJarEntry.getMethod()); newJarEntry.setTime(originalJarEntry.getTime()); //Must set size and CRC for STORED entries if (newJarEntry.getMethod() == ZipEntry.STORED) { newJarEntry.setSize(originalJarEntry.getSize()); newJarEntry.setCrc(originalJarEntry.getCrc()); }/*from w w w . j av a2 s .c om*/ return newJarEntry; }
From source file:org.apache.reef.util.JARFileMaker.java
private JARFileMaker add(final File inputFile, final String prefix) throws IOException { final String fileNameInJAR = createPathInJar(inputFile, prefix); LOG.log(Level.FINEST, "Add {0} as {1}", new Object[] { inputFile, fileNameInJAR }); final JarEntry entry = new JarEntry(fileNameInJAR); entry.setTime(inputFile.lastModified()); this.jarOutputStream.putNextEntry(entry); if (inputFile.isDirectory()) { this.jarOutputStream.closeEntry(); for (final File nestedFile : CollectionUtils.nullToEmpty(inputFile.listFiles())) { this.add(nestedFile, fileNameInJAR); }/*from w w w .j ava 2 s.c o m*/ } else { try (final BufferedInputStream in = new BufferedInputStream(new FileInputStream(inputFile))) { IOUtils.copy(in, this.jarOutputStream); } catch (final FileNotFoundException ex) { LOG.log(Level.WARNING, "Skip the file: " + inputFile, ex); } finally { this.jarOutputStream.closeEntry(); } } return this; }
From source file:org.apache.sling.maven.bundlesupport.AbstractBundleDeployMojo.java
/** * Change the version in jar// ww w. ja v a 2s . c o m * * @param newVersion * @param file * @return * @throws MojoExecutionException */ protected File changeVersion(File file, String oldVersion, String newVersion) throws MojoExecutionException { String fileName = file.getName(); int pos = fileName.indexOf(oldVersion); fileName = fileName.substring(0, pos) + newVersion + fileName.substring(pos + oldVersion.length()); JarInputStream jis = null; JarOutputStream jos; OutputStream out = null; JarFile sourceJar = null; try { // now create a temporary file and update the version sourceJar = new JarFile(file); final Manifest manifest = sourceJar.getManifest(); manifest.getMainAttributes().putValue("Bundle-Version", newVersion); jis = new JarInputStream(new FileInputStream(file)); final File destJar = new File(file.getParentFile(), fileName); out = new FileOutputStream(destJar); jos = new JarOutputStream(out, manifest); jos.setMethod(JarOutputStream.DEFLATED); jos.setLevel(Deflater.BEST_COMPRESSION); JarEntry entryIn = jis.getNextJarEntry(); while (entryIn != null) { JarEntry entryOut = new JarEntry(entryIn.getName()); entryOut.setTime(entryIn.getTime()); entryOut.setComment(entryIn.getComment()); jos.putNextEntry(entryOut); if (!entryIn.isDirectory()) { IOUtils.copy(jis, jos); } jos.closeEntry(); jis.closeEntry(); entryIn = jis.getNextJarEntry(); } // close the JAR file now to force writing jos.close(); return destJar; } catch (IOException ioe) { throw new MojoExecutionException("Unable to update version in jar file.", ioe); } finally { if (sourceJar != null) { try { sourceJar.close(); } catch (IOException ex) { // close } } IOUtils.closeQuietly(jis); IOUtils.closeQuietly(out); } }