List of usage examples for java.util.jar JarOutputStream closeEntry
public void closeEntry() throws IOException
From source file:com.ikanow.aleph2.analytics.spark.services.SparkCompilerService.java
/** Compiles a scala class * @param script// w w w.j av a 2s.com * @param clazz_name * @return * @throws IOException * @throws InstantiationException * @throws IllegalAccessException * @throws ClassNotFoundException */ public Tuple2<ClassLoader, Object> buildClass(final String script, final String clazz_name, final Optional<IBucketLogger> logger) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException { final String relative_dir = "./script_classpath/"; new File(relative_dir).mkdirs(); final File source_file = new File(relative_dir + clazz_name + ".scala"); FileUtils.writeStringToFile(source_file, script); final String this_path = LiveInjector.findPathJar(this.getClass(), "./dummy.jar"); final File f = new File(this_path); final File fp = new File(f.getParent()); final String classpath = Arrays.stream(fp.listFiles()).map(ff -> ff.toString()) .filter(ff -> ff.endsWith(".jar")).collect(Collectors.joining(":")); // Need this to make the URL classloader be used, not the system classloader (which doesn't know about Aleph2..) final Settings s = new Settings(); s.classpath().value_$eq(System.getProperty("java.class.path") + classpath); s.usejavacp().scala$tools$nsc$settings$AbsSettings$AbsSetting$$internalSetting_$eq(true); final StoreReporter reporter = new StoreReporter(); final Global g = new Global(s, reporter); final Run r = g.new Run(); r.compile(JavaConverters.asScalaBufferConverter(Arrays.<String>asList(source_file.toString())).asScala() .toList()); if (reporter.hasErrors() || reporter.hasWarnings()) { final String errors = "Compiler: Errors/warnings (**to get to user script line substract 22**): " + JavaConverters.asJavaSetConverter(reporter.infos()).asJava().stream() .map(info -> info.toString()).collect(Collectors.joining(" ;; ")); logger.ifPresent(l -> l.log(reporter.hasErrors() ? Level.ERROR : Level.DEBUG, false, () -> errors, () -> "SparkScalaInterpreterTopology", () -> "compile")); //ERROR: if (reporter.hasErrors()) { System.err.println(errors); } } // Move any class files (eg including sub-classes) Arrays.stream(fp.listFiles()).filter(ff -> ff.toString().endsWith(".class")) .forEach(Lambdas.wrap_consumer_u(ff -> { FileUtils.moveFile(ff, new File(relative_dir + ff.getName())); })); // Create a JAR file... Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); final JarOutputStream target = new JarOutputStream(new FileOutputStream("./script_classpath.jar"), manifest); Arrays.stream(new File(relative_dir).listFiles()).forEach(Lambdas.wrap_consumer_i(ff -> { JarEntry entry = new JarEntry(ff.getName()); target.putNextEntry(entry); try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(ff))) { byte[] buffer = new byte[1024]; while (true) { int count = in.read(buffer); if (count == -1) break; target.write(buffer, 0, count); } target.closeEntry(); } })); target.close(); final String created = "Created = " + new File("./script_classpath.jar").toURI().toURL() + " ... " + Arrays.stream(new File(relative_dir).listFiles()).map(ff -> ff.toString()) .collect(Collectors.joining(";")); logger.ifPresent(l -> l.log(Level.DEBUG, true, () -> created, () -> "SparkScalaInterpreterTopology", () -> "compile")); final Tuple2<ClassLoader, Object> o = Lambdas.get(Lambdas.wrap_u(() -> { _cl.set(new java.net.URLClassLoader( Arrays.asList(new File("./script_classpath.jar").toURI().toURL()).toArray(new URL[0]), Thread.currentThread().getContextClassLoader())); Object o_ = _cl.get().loadClass("ScriptRunner").newInstance(); return Tuples._2T(_cl.get(), o_); })); return o; }
From source file:edu.stanford.muse.email.JarDocCache.java
@Override public synchronized void saveHeader(Document d, String prefix, int msgNum) throws FileNotFoundException, IOException { JarOutputStream jos = getHeadersJarOS(prefix); // create the bytes ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream headerOOS = new ObjectOutputStream(baos); headerOOS.writeObject(d);//from w w w .ja va2s .c o m byte buf[] = baos.toByteArray(); ZipEntry ze = new ZipEntry(msgNum + ".header"); ze.setMethod(ZipEntry.DEFLATED); jos.putNextEntry(ze); jos.write(buf, 0, buf.length); jos.closeEntry(); jos.flush(); }
From source file:com.migratebird.script.repository.impl.ArchiveScriptLocation.java
/** * Writes the entry with the given name and content to the given {@link JarOutputStream} * * @param jarOutputStream {@link OutputStream} to the jar file * @param name Name of the jar file entry * @param timestamp Last modification date of the entry * @param entryContentReader Reader giving access to the content of the jar entry * @throws IOException In case of disk IO problems *//*from w w w . j ava 2 s .co m*/ protected void writeJarEntry(JarOutputStream jarOutputStream, String name, long timestamp, Reader entryContentReader) throws IOException { JarEntry jarEntry = new JarEntry(name); jarEntry.setTime(timestamp); jarOutputStream.putNextEntry(jarEntry); InputStream scriptInputStream = new ReaderInputStream(entryContentReader); byte[] buffer = new byte[1024]; int len; while ((len = scriptInputStream.read(buffer, 0, buffer.length)) > -1) { jarOutputStream.write(buffer, 0, len); } scriptInputStream.close(); jarOutputStream.closeEntry(); }
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 v a2s .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:com.speed.ob.api.ClassStore.java
public void init(JarInputStream jarIn, File output, File in) throws IOException { ZipEntry entry;/*ww w . j ava 2 s .c o m*/ JarOutputStream out = new JarOutputStream(new FileOutputStream(new File(output, in.getName()))); while ((entry = jarIn.getNextEntry()) != null) { byte[] data = IOUtils.toByteArray(jarIn); if (entry.getName().endsWith(".class")) { ClassReader reader = new ClassReader(data); ClassNode cn = new ClassNode(); reader.accept(cn, ClassReader.EXPAND_FRAMES); store.put(cn.name, cn); } else if (!entry.isDirectory()) { Logger.getLogger(getClass().getName()).finer("Storing " + entry.getName() + " in output file"); JarEntry je = new JarEntry(entry.getName()); out.putNextEntry(je); out.write(data); out.closeEntry(); } } out.close(); }
From source file:org.dspace.installer_edm.InstallerCrosswalk.java
/** * Aade contenido archivo class a nuevo archivo class en el jar * * @param jarOutputStream flujo de escritura para el jar * @throws IOException//from w w w. j av a2 s. c o m */ protected void addClass2Jar(JarOutputStream jarOutputStream) throws IOException { File file = new File(myInstallerWorkDirPath + fileSeparator + edmCrossWalkClass); byte[] fileData = new byte[(int) file.length()]; DataInputStream dis = new DataInputStream(new FileInputStream(file)); dis.readFully(fileData); dis.close(); jarOutputStream.putNextEntry(new JarEntry(edmCrossWalkClass)); jarOutputStream.write(fileData); jarOutputStream.closeEntry(); }
From source file:gov.redhawk.rap.internal.PluginProviderServlet.java
private void addFiles(final JarOutputStream out, final IPath path, final File... listFiles) throws IOException { for (final File f : listFiles) { if (f.getName().charAt(0) == '.') { continue; } else if (f.getName().equals("MANIFEST.MF")) { continue; }//w ww . ja v a 2s. co m final IPath filePath = path.append(f.getName()); String str = filePath.toString(); if (str.startsWith("/")) { str = str.substring(1); } if (f.isDirectory()) { if (!str.endsWith("/")) { str = str + "/"; } final JarEntry entry = new JarEntry(str); entry.setSize(0); entry.setTime(f.lastModified()); out.putNextEntry(entry); out.closeEntry(); addFiles(out, filePath, f.listFiles()); } else { final JarEntry entry = new JarEntry(str); entry.setSize(f.length()); entry.setTime(f.lastModified()); out.putNextEntry(entry); final FileInputStream istream = new FileInputStream(f); try { IOUtils.copy(istream, out); } finally { istream.close(); } out.closeEntry(); } } }
From source file:com.headwire.aem.tooling.intellij.eclipse.stub.JarBuilder.java
public InputStream buildJar(final IFolder sourceDir) throws CoreException { ByteArrayOutputStream store = new ByteArrayOutputStream(); JarOutputStream zos = null; InputStream manifestInput = null; try {/*from w w w . j av a 2s .co m*/ IResource manifestResource = sourceDir.findMember(JarFile.MANIFEST_NAME); if (manifestResource == null || manifestResource.getType() != IResource.FILE) { throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "No file named " + JarFile.MANIFEST_NAME + " found under " + sourceDir)); } manifestInput = ((IFile) manifestResource).getContents(); Manifest manifest = new Manifest(manifestInput); zos = new JarOutputStream(store); zos.setLevel(Deflater.NO_COMPRESSION); // manifest first final ZipEntry anEntry = new ZipEntry(JarFile.MANIFEST_NAME); zos.putNextEntry(anEntry); manifest.write(zos); zos.closeEntry(); zipDir(sourceDir, zos, ""); } catch (IOException e) { throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e)); } finally { IOUtils.closeQuietly(zos); IOUtils.closeQuietly(manifestInput); } return new ByteArrayInputStream(store.toByteArray()); }
From source file:UnpackedJarFile.java
public static void copyToPackedJar(JarFile inputJar, File outputFile) throws IOException { if (inputJar.getClass() == JarFile.class) { // this is a plain old jar... nothign special copyFile(new File(inputJar.getName()), outputFile); } else if (inputJar instanceof NestedJarFile && ((NestedJarFile) inputJar).isPacked()) { NestedJarFile nestedJarFile = (NestedJarFile) inputJar; JarFile baseJar = nestedJarFile.getBaseJar(); String basePath = nestedJarFile.getBasePath(); if (baseJar instanceof UnpackedJarFile) { // our target jar is just a file in upacked jar (a plain old directory)... now // we just need to find where it is and copy it to the outptu copyFile(((UnpackedJarFile) baseJar).getFile(basePath), outputFile); } else {//from ww w .j a v a2 s .c o m // out target is just a plain old jar file directly accessabel from the file system copyFile(new File(baseJar.getName()), outputFile); } } else { // copy out the module contents to a standalone jar file (entry by entry) JarOutputStream out = null; try { out = new JarOutputStream(new FileOutputStream(outputFile)); byte[] buffer = new byte[4096]; Enumeration entries = inputJar.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); InputStream in = inputJar.getInputStream(entry); try { out.putNextEntry(new ZipEntry(entry.getName())); try { int count; while ((count = in.read(buffer)) > 0) { out.write(buffer, 0, count); } } finally { out.closeEntry(); } } finally { close(in); } } } finally { close(out); } } }
From source file:org.apache.sqoop.integration.connectorloading.ClasspathTest.java
private void addFileToJar(File source, JarOutputStream target) throws Exception { JarEntry entry = new JarEntry(source.getName()); entry.setTime(source.lastModified()); target.putNextEntry(entry);/* w w w . jav a 2 s.com*/ BufferedInputStream in = new BufferedInputStream(new FileInputStream(source)); long bufferSize = source.length(); if (bufferSize < Integer.MIN_VALUE || bufferSize > Integer.MAX_VALUE) { throw new RuntimeException("file to large to be added to jar"); } byte[] buffer = new byte[(int) bufferSize]; while (true) { int count = in.read(buffer); if (count == -1) break; target.write(buffer, 0, count); } target.closeEntry(); if (in != null) in.close(); }