List of usage examples for java.util.jar JarInputStream JarInputStream
public JarInputStream(InputStream in) throws IOException
JarInputStream
and reads the optional manifest. From source file:org.springframework.data.hadoop.mapreduce.ExecutionUtils.java
private static void unjar(Resource jar, File baseDir) throws IOException { JarInputStream jis = new JarInputStream(jar.getInputStream()); JarEntry entry = null;//from ww w . j a v a2 s .c o m try { while ((entry = jis.getNextJarEntry()) != null) { if (!entry.isDirectory()) { File file = new File(baseDir, entry.getName()); if (!file.getParentFile().mkdirs()) { if (!file.getParentFile().isDirectory()) { throw new IOException("Mkdirs failed to create " + file.getParentFile().toString()); } } OutputStream out = new FileOutputStream(file); try { byte[] buffer = new byte[8192]; int i; while ((i = jis.read(buffer)) != -1) { out.write(buffer, 0, i); } } finally { IOUtils.closeStream(out); } } } } finally { IOUtils.closeStream(jis); } }
From source file:com.izforge.izpack.compiler.packager.impl.AbstractPackagerTest.java
/** * Helper to return a stream to the content of a jar entry. * * @param name the name of the entry/*w w w. j a v a 2 s .com*/ * @param jar the jar * @return a stream to the content * @throws IOException for any I/O error */ private InputStream getJarEntry(String name, File jar) throws IOException { JarInputStream input = new JarInputStream(new FileInputStream(jar)); JarEntry entry; while ((entry = input.getNextJarEntry()) != null) { if (entry.getName().equals(name)) { return input; } } fail("Failed to find jar entry: " + name); return null; }
From source file:org.apache.sling.maven.bundlesupport.AbstractBundleDeployMojo.java
/** * Change the version in jar//from ww w . j a va 2 s .c om * * @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); } }
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./* w w w .ja va 2 s. co 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:com.kotcrab.vis.editor.module.editor.PluginLoaderModule.java
private void loadPluginsDescriptors(Array<FileHandle> pluginsFolders) throws IOException { for (FileHandle folder : pluginsFolders) { FileHandle[] files = folder.list((dir, name) -> name.endsWith("jar")); if (files.length > 1 || files.length == 0) { Log.error(TAG, "Failed (invalid directory structure): " + folder.name()); failedPlugins.add(new FailedPluginDescriptor(folder, new IllegalStateException( "Plugin directory must contain only one jar (required libs must be stored in 'lib' subdirectory"))); continue; }//from w ww.j a v a 2 s . com FileHandle pluginJar = files[0]; try { JarInputStream jarStream = new JarInputStream(new FileInputStream(pluginJar.file())); Manifest mf = jarStream.getManifest(); jarStream.close(); PluginDescriptor desc = new PluginDescriptor(pluginJar, mf); allPlugins.add(desc); } catch (IOException e) { Log.error(TAG, "Failed (IO exception): " + folder.name()); failedPlugins.add(new FailedPluginDescriptor(folder, e)); Log.exception(e); } catch (EditorException e) { Log.error(TAG, "Failed: " + folder.name()); failedPlugins.add(new FailedPluginDescriptor(folder, e)); Log.exception(e); } } }
From source file:ezbake.deployer.publishers.EzAzkabanPublisher.java
/** * This will publish the artifact to Azkaban for scheduled running. The artifact should be of the format * <p/>// w ww.j a v a 2 s . com * <p/> * The artifact at this point in time will already have included the SSL certs. * <p/> * Its up to the publisher to reorganize the tar file if needed for its PaaS * * @param artifact The artifact to deploy * @param callerToken - The token of the user or application that initiated this call * @throws DeploymentException - On any exceptions */ @Override public void publish(DeploymentArtifact artifact, EzSecurityToken callerToken) throws DeploymentException { File unzippedPack = null; File azkabanZip = null; ZipOutputStream zipOutputStream = null; String flowName; final BatchJobInfo jobInfo = artifact.getMetadata().getManifest().getBatchJobInfo(); // Get the Azkaban authentication token final AuthenticationResult authenticatorResult; try { authenticatorResult = new AuthenticationManager(new URI(azConf.getAzkabanUrl()), azConf.getUsername(), azConf.getPassword()).login(); } catch (URISyntaxException e) { throw new DeploymentException(e.getMessage()); } if (authenticatorResult.hasError()) { log.error("Could not log into Azkaban: " + authenticatorResult.getError()); throw new DeploymentException(authenticatorResult.getError()); } log.info("Successfully logged into Azkaban. Now creating .zip to upload"); try { // Unzip the artifact unzippedPack = UnzipUtil.unzip(new File(unzipDir), ByteBuffer.wrap(artifact.getArtifact())); log.info("Unzipped artifact to: " + unzippedPack.getAbsolutePath()); // Create a .zip file to submit to Azkaban azkabanZip = File.createTempFile("ezbatch_", ".zip"); log.info("Created temporary zip file: " + azkabanZip.getCanonicalPath()); zipOutputStream = new ZipOutputStream(new FileOutputStream(azkabanZip)); // Copy the configs from the artifact to the top level of the zip. This should contain the Azkaban // .jobs and .properties final String configDir = UnzipUtil.getConfDirectory(unzippedPack).get(); final File configDirFile = new File(configDir); for (File f : FileUtils.listFiles(configDirFile, TrueFileFilter.TRUE, TrueFileFilter.TRUE)) { zipOutputStream.putNextEntry(new ZipArchiveEntry(f.getCanonicalPath().replaceFirst(configDir, ""))); IOUtils.copy(new FileInputStream(f), zipOutputStream); zipOutputStream.closeEntry(); } log.info("Copied configs to the .zip"); // Copy the jars from bin/ in the artifact to lib/ in the .zip file and other things to the jar as needed final String dirPrefix = unzippedPack.getAbsolutePath() + "/bin/"; for (File f : FileUtils.listFiles(new File(dirPrefix), TrueFileFilter.TRUE, TrueFileFilter.TRUE)) { zipOutputStream .putNextEntry(new ZipArchiveEntry(f.getCanonicalPath().replaceFirst(dirPrefix, "lib/"))); final JarInputStream jarInputStream = new JarInputStream(new FileInputStream(f)); final JarOutputStream jarOutputStream = new JarOutputStream(zipOutputStream); JarEntry je; while ((je = jarInputStream.getNextJarEntry()) != null) { jarOutputStream.putNextEntry(je); IOUtils.copy(jarInputStream, jarOutputStream); jarOutputStream.closeEntry(); } log.info("Created Jar file"); // Add the SSL certs to the jar final String sslPath = UnzipUtil.getSSLPath(configDirFile).get(); for (File sslFile : FileUtils.listFiles(new File(sslPath), TrueFileFilter.TRUE, TrueFileFilter.TRUE)) { if (sslFile.isFile()) { jarOutputStream.putNextEntry(new JarArchiveEntry("ssl/" + sslFile.getName())); IOUtils.copy(new FileInputStream(sslFile), jarOutputStream); jarOutputStream.closeEntry(); } } log.info("Added SSL certs to jar"); // Add the application.properties to the jar file so the jobs can read it final File appProps = new File(configDir, "application.properties"); final Properties adjustedProperties = new Properties(); adjustedProperties.load(new FileInputStream(appProps)); adjustedProperties.setProperty("ezbake.security.ssl.dir", "/ssl/"); jarOutputStream.putNextEntry(new JarArchiveEntry("application.properties")); adjustedProperties.store(jarOutputStream, null); jarOutputStream.closeEntry(); jarOutputStream.finish(); zipOutputStream.closeEntry(); } // Check to see if there are any .job files. If there aren't, this is an external job and we need to create // one for the .zip file final Collection<File> jobFiles = FileUtils.listFiles(configDirFile, new String[] { "job" }, false); if (jobFiles.isEmpty()) { // If there are no job files present then we need to create one for the user final StringBuilder sb = new StringBuilder( "type=hadoopJava\n" + "job.class=ezbatch.amino.api.EzFrameworkDriver\n" + "classpath=./lib/*\n" + "main.args=-d /ezbatch/amino/config"); for (File xmlConfig : FileUtils.listFiles(configDirFile, new String[] { "xml" }, false)) { sb.append(" -c ").append(xmlConfig.getName()); } zipOutputStream.putNextEntry(new ZipEntry("Analytic.job")); IOUtils.copy(new StringReader(sb.toString()), zipOutputStream); zipOutputStream.closeEntry(); log.info("There was no .job file so one was created for the .zip"); flowName = "Analytic"; } else { flowName = jobInfo.getFlowName(); if (flowName == null) { log.warn("Manifest did not contain flow_name. Guessing what it should be"); flowName = FilenameUtils.getBaseName(jobFiles.toArray(new File[jobFiles.size()])[0].getName()); log.info("Guessing the flow name should be:" + flowName); } } zipOutputStream.finish(); log.info("Finished creating .zip"); // Now that we've created the zip to upload, attempt to create a project for it to be uploaded to. Every .zip // file needs to be uploaded to a project, and the project may or may not already exist. final String projectName = ArtifactHelpers.getAppId(artifact) + "_" + ArtifactHelpers.getServiceId(artifact); final ProjectManager projectManager = new ProjectManager(authenticatorResult.getSessionId(), new URI(azConf.getAzkabanUrl())); final ManagerResult managerResult = projectManager.createProject(projectName, "EzBatch Deployed"); // If the project already exists, it will return an error, but really it's not a problem if (managerResult.hasError()) { if (!managerResult.getMessage().contains("already exists")) { log.error("Could not create project: " + managerResult.getMessage()); throw new DeploymentException(managerResult.getMessage()); } else { log.info("Reusing the existing project: " + projectName); } } else { log.info("Created new project: " + projectName); log.info("Path: " + managerResult.getPath()); } // Upload the .zip file to the project final UploadManager uploader = new UploadManager(authenticatorResult.getSessionId(), azConf.getAzkabanUrl(), projectName, azkabanZip); final UploaderResult uploaderResult = uploader.uploadZip(); if (uploaderResult.hasError()) { log.error("Could not upload the zip file: " + uploaderResult.getError()); throw new DeploymentException(uploaderResult.getError()); } log.info("Successfully submitted zip file to Azkaban"); // Schedule the jar to run. If the start times aren't provided, it will run in 2 minutes final ScheduleManager scheduler = new ScheduleManager(authenticatorResult.getSessionId(), new URI(azConf.getAzkabanUrl())); // Add the optional parameters if they are present if (jobInfo.isSetStartDate()) { scheduler.setScheduleDate(jobInfo.getStartDate()); } if (jobInfo.isSetStartTime()) { scheduler.setScheduleTime(jobInfo.getStartTime()); } if (jobInfo.isSetRepeat()) { scheduler.setPeriod(jobInfo.getRepeat()); } final SchedulerResult schedulerResult = scheduler.scheduleFlow(projectName, flowName, uploaderResult.getProjectId()); if (schedulerResult.hasError()) { log.error("Failure to schedule job: " + schedulerResult.getError()); throw new DeploymentException(schedulerResult.getError()); } log.info("Successfully scheduled flow: " + flowName); } catch (Exception ex) { log.error("No Nos!", ex); throw new DeploymentException(ex.getMessage()); } finally { IOUtils.closeQuietly(zipOutputStream); FileUtils.deleteQuietly(azkabanZip); FileUtils.deleteQuietly(unzippedPack); } }
From source file:org.apache.geode.internal.DeployedJar.java
/** * Scan the JAR file and attempt to register any function classes found. *///from w ww . j a va2s . c o m public synchronized void registerFunctions() throws ClassNotFoundException { final boolean isDebugEnabled = logger.isDebugEnabled(); if (isDebugEnabled) { logger.debug("Registering functions with DeployedJar: {}", this); } ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(this.getJarContent()); JarInputStream jarInputStream = null; try { Collection<String> functionClasses = findFunctionsInThisJar(); jarInputStream = new JarInputStream(byteArrayInputStream); JarEntry jarEntry = jarInputStream.getNextJarEntry(); while (jarEntry != null) { if (jarEntry.getName().endsWith(".class")) { final String className = PATTERN_SLASH.matcher(jarEntry.getName()).replaceAll("\\.") .substring(0, jarEntry.getName().length() - 6); if (functionClasses.contains(className)) { if (isDebugEnabled) { logger.debug("Attempting to load class: {}, from JAR file: {}", jarEntry.getName(), this.file.getAbsolutePath()); } try { Class<?> clazz = ClassPathLoader.getLatest().forName(className); Collection<Function> registerableFunctions = getRegisterableFunctionsFromClass(clazz); for (Function function : registerableFunctions) { FunctionService.registerFunction(function); if (isDebugEnabled) { logger.debug("Registering function class: {}, from JAR file: {}", className, this.file.getAbsolutePath()); } this.registeredFunctions.add(function); } } catch (ClassNotFoundException | NoClassDefFoundError cnfex) { logger.error("Unable to load all classes from JAR file: {}", this.file.getAbsolutePath(), cnfex); throw cnfex; } } else { if (isDebugEnabled) { logger.debug("No functions found in class: {}, from JAR file: {}", jarEntry.getName(), this.file.getAbsolutePath()); } } } jarEntry = jarInputStream.getNextJarEntry(); } } catch (IOException ioex) { logger.error("Exception when trying to read class from ByteArrayInputStream", ioex); } finally { if (jarInputStream != null) { try { jarInputStream.close(); } catch (IOException ioex) { logger.error("Exception attempting to close JAR input stream", ioex); } } } }
From source file:eu.chocolatejar.eclipse.plugin.cleaner.ArtifactParser.java
private Manifest readManifestfromJarOrDirectory(File file) { try {//from www. jav a 2 s.co m Manifest bundleManifest = null; try (final FileInputStream is = new FileInputStream(file)) { final boolean isJar = "jar".equalsIgnoreCase(FilenameUtils.getExtension(file.getName())); if (isJar) { try (final JarInputStream jis = new JarInputStream(is)) { bundleManifest = jis.getManifest(); } } else { bundleManifest = new Manifest(is); } } return bundleManifest; } catch (IOException e) { logger.debug("Unable to read manifest from jar or directory.", e); return null; } }
From source file:net.ftb.util.FileUtils.java
/** * deletes the META-INF//from w ww . jav a2 s .c o m */ public static void killMetaInf() { File inputFile = new File(Settings.getSettings().getInstallPath() + "/" + ModPack.getSelectedPack().getDir() + "/minecraft/bin", "minecraft.jar"); File outputTmpFile = new File(Settings.getSettings().getInstallPath() + "/" + ModPack.getSelectedPack().getDir() + "/minecraft/bin", "minecraft.jar.tmp"); try { JarInputStream input = new JarInputStream(new FileInputStream(inputFile)); JarOutputStream output = new JarOutputStream(new FileOutputStream(outputTmpFile)); JarEntry entry; while ((entry = input.getNextJarEntry()) != null) { if (entry.getName().contains("META-INF")) { continue; } output.putNextEntry(entry); byte buffer[] = new byte[1024]; int amo; while ((amo = input.read(buffer, 0, 1024)) != -1) { output.write(buffer, 0, amo); } output.closeEntry(); } input.close(); output.close(); if (!inputFile.delete()) { Logger.logError("Failed to delete Minecraft.jar."); return; } outputTmpFile.renameTo(inputFile); } catch (FileNotFoundException e) { Logger.logError("Error while killing META-INF", e); } catch (IOException e) { Logger.logError("Error while killing META-INF", e); } }
From source file:com.flexive.shared.FxDropApplication.java
private JarInputStream getJarStream() throws IOException { try {/*from w ww. ja v a 2s. co m*/ return resourceURL != null ? new JarInputStream(new URL(resourceURL).openStream()) : null; } catch (MalformedURLException e) { //try again using JBoss v5 vfszip ... try { return new JarInputStream(new URL("vfszip:" + resourceURL).openStream()); } catch (MalformedURLException e2) { //try again using JBoss v6 M3+ vfs ... try { final InputStream in = new URL("vfs:" + resourceURL).openStream(); return in instanceof JarInputStream ? (JarInputStream) in // JBoss 7 already returns a virtual JAR stream : new JarInputStream(in); // otherwise wrap returned connection } catch (MalformedURLException e3) { throw new IllegalArgumentException("Cannot create JAR stream for URL " + resourceURL); } } } }