List of usage examples for java.util.jar JarFile getEntry
public ZipEntry getEntry(String name)
From source file:com.taobao.android.builder.tasks.app.bundle.ProcessAwbAndroidResources.java
@Override protected void doFullTaskAction() throws IOException { // we have to clean the source folder output in case the package name changed. File srcOut = getSourceOutputDir(); if (srcOut != null) { // FileUtils.emptyFolder(srcOut); srcOut.delete();/*from w w w .j a v a2s .c om*/ srcOut.mkdirs(); } getTextSymbolOutputDir().mkdirs(); getPackageOutputFile().getParentFile().mkdirs(); @Nullable File resOutBaseNameFile = getPackageOutputFile(); // If are in instant run mode and we have an instant run enabled manifest File instantRunManifest = getInstantRunManifestFile(); File manifestFileToPackage = instantRunBuildContext.isInInstantRunMode() && instantRunManifest != null && instantRunManifest.exists() ? instantRunManifest : getManifestFile(); //awb???? addAaptOptions(); AaptPackageProcessBuilder aaptPackageCommandBuilder = new AaptPackageProcessBuilder(manifestFileToPackage, getAaptOptions()).setAssetsFolder(getAssetsDir()).setResFolder(getResDir()) .setLibraries(getLibraries()).setPackageForR(getPackageForR()) .setSourceOutputDir(absolutePath(srcOut)) .setSymbolOutputDir(absolutePath(getTextSymbolOutputDir())) .setResPackageOutput(absolutePath(resOutBaseNameFile)) .setProguardOutput(absolutePath(getProguardOutputFile())).setType(getType()) .setDebuggable(getDebuggable()).setPseudoLocalesEnabled(getPseudoLocalesEnabled()) .setResourceConfigs(getResourceConfigs()).setSplits(getSplits()) .setPreferredDensity(getPreferredDensity()); @NonNull AtlasBuilder builder = (AtlasBuilder) getBuilder(); // MergingLog mergingLog = new MergingLog(getMergeBlameLogFolder()); // // ProcessOutputHandler processOutputHandler = new ParsingProcessOutputHandler( // new ToolOutputParser(new AaptOutputParser(), getILogger()), // builder.getErrorReporter()); ProcessOutputHandler processOutputHandler = new LoggedProcessOutputHandler(getILogger()); try { builder.processAwbResources(aaptPackageCommandBuilder, getEnforceUniquePackageName(), processOutputHandler, getMainSymbolFile()); if (resOutBaseNameFile != null) { if (instantRunBuildContext.isInInstantRunMode()) { instantRunBuildContext.addChangedFile(FileType.RESOURCES, resOutBaseNameFile); // get the new manifest file CRC JarFile jarFile = new JarFile(resOutBaseNameFile); String currentIterationCRC = null; try { ZipEntry entry = jarFile.getEntry(SdkConstants.ANDROID_MANIFEST_XML); if (entry != null) { currentIterationCRC = String.valueOf(entry.getCrc()); } } finally { jarFile.close(); } // check the manifest file binary format. File crcFile = new File(instantRunSupportDir, "manifest.crc"); if (crcFile.exists() && currentIterationCRC != null) { // compare its content with the new binary file crc. String previousIterationCRC = Files.readFirstLine(crcFile, Charsets.UTF_8); if (!currentIterationCRC.equals(previousIterationCRC)) { instantRunBuildContext.close(); //instantRunBuildContext.setVerifierResult(InstantRunVerifierStatus // .BINARY_MANIFEST_FILE_CHANGE); } } // write the new manifest file CRC. Files.createParentDirs(crcFile); Files.write(currentIterationCRC, crcFile, Charsets.UTF_8); } } } catch (Exception e) { e.printStackTrace(); throw new GradleException("process res exception", e); } }
From source file:org.moe.cli.ParameterParserTest.java
@Test public void linkUniversalLibrary() throws Exception { File project = tmpDir.newFolder(); File outputJar = new File(project, "TestLib.jar"); // prepare file with ldFlags String flags = "-lTestLibrary"; File ldFlags = new File(project, "ldflags"); ldFlags.createNewFile();//from ww w . ja v a 2s.c o m PrintWriter write = new PrintWriter(ldFlags); write.print(flags); write.close(); ClassLoader cl = this.getClass().getClassLoader(); URL library = cl.getResource("natives/universal/libTestLibrary.a"); URL headersURL = cl.getResource("natives/Headers/TestFramework.h"); File headers = new File(headersURL.getPath()); URL bundle = cl.getResource("moe_logo.png"); CommandLine argc = parseArgs(new String[] { "--library", library.getPath(), "--headers", headers.getParentFile().getPath(), "--package-name", "org", "--output-file-path", outputJar.getPath(), "--ld-flags", ldFlags.getPath(), "--bundle", bundle.getPath() }); IExecutor executor = ExecutorManager.getExecutorByParams(argc); assertNotNull(executor); assertTrue(executor instanceof ThirdPartyLibraryLinkExecutor); // generate binding & prepare output jar executor.execute(); // check output jar file existence assertTrue(outputJar.exists()); JarFile jarFile = new JarFile(outputJar); Manifest manifest = jarFile.getManifest(); Attributes attributes = manifest.getMainAttributes(); String manifestLDFlags = attributes.getValue("MOE_CUSTOM_LINKER_FLAGS"); Set<String> realLDFlags = new HashSet<String>(Arrays.asList(flags.split(";"))); realLDFlags.add("-ObjC"); assertEquals(realLDFlags, new HashSet<String>(Arrays.asList(manifestLDFlags.split(";")))); String manifestSimFramework = attributes.getValue("MOE_ThirdpartyFramework_universal"); assertEquals(manifestSimFramework, "./lib/libTestLibrary.a"); String manifestBundle = attributes.getValue("MOE_BUNDLE_FILE_RESOURCES"); assertEquals(manifestBundle, "./bundle/moe_logo.png;"); assertNotNull(jarFile.getEntry("bundle/moe_logo.png")); assertNotNull(jarFile.getEntry("lib/libTestLibrary.a")); jarFile.close(); }
From source file:org.moe.cli.ParameterParserTest.java
@Test public void linkFramework() throws Exception { File project = tmpDir.newFolder(); File outputJar = new File(project, "TestFramework.jar"); // prepare file with ldFlags String flags = "-framework TestFramework"; File ldFlags = new File(project, "ldflags"); ldFlags.createNewFile();/*from w ww . j a v a 2s .co m*/ PrintWriter write = new PrintWriter(ldFlags); write.print(flags); write.close(); ClassLoader cl = this.getClass().getClassLoader(); URL simFramework = cl.getResource("natives/device/TestFramework.framework"); URL devFramework = cl.getResource("natives/simulator/TestFramework.framework"); URL bundle = cl.getResource("moe_logo.png"); CommandLine argc = parseArgs(new String[] { "--framework", String.format("%s:%s", simFramework.getPath(), devFramework.getPath()), "--package-name", "org", "--output-file-path", outputJar.getPath(), "--ld-flags", ldFlags.getPath(), "--bundle", bundle.getPath() }); IExecutor executor = ExecutorManager.getExecutorByParams(argc); assertNotNull(executor); assertTrue(executor instanceof ThirdPartyFrameworkLinkExecutor); // generate binding & prepare output jar executor.execute(); // check output jar file existence assertTrue(outputJar.exists()); JarFile jarFile = new JarFile(outputJar); Manifest manifest = jarFile.getManifest(); Attributes attributes = manifest.getMainAttributes(); String manifestLDFlags = attributes.getValue("MOE_CUSTOM_LINKER_FLAGS"); assertEquals(flags + ";", manifestLDFlags); String manifestBundle = attributes.getValue("MOE_BUNDLE_FILE_RESOURCES"); assertEquals(manifestBundle, "./bundle/moe_logo.png;"); String manifestFramework = attributes.getValue("MOE_ThirdpartyFramework_ios_simulator"); assertEquals(manifestFramework, "./lib/iphonesimulator/TestFramework.framework"); String manifestDevFramework = attributes.getValue("MOE_ThirdpartyFramework_ios_device"); assertEquals(manifestDevFramework, "./lib/iphoneos/TestFramework.framework"); assertNotNull(jarFile.getEntry("bundle/moe_logo.png")); assertNotNull(jarFile.getEntry("lib/iphonesimulator/TestFramework.framework")); assertNotNull(jarFile.getEntry("lib/iphoneos/TestFramework.framework")); jarFile.close(); }
From source file:org.colombbus.tangara.Configuration.java
private boolean testExecutionMode() { executionMode = false;/*from ww w. ja va 2s . c o m*/ JarFile file = null; try { file = new JarFile(getTangaraPath()); ZipEntry entry = file.getEntry(EXECUTION_PROPERTIES_FILENAME); if (entry != null) { executionMode = true; System.out.println("execution mode detected"); Properties executionProperties = new Properties(); InputStream ips = ClassLoader.getSystemResourceAsStream(EXECUTION_PROPERTIES_FILENAME); executionProperties.load(ips); if (executionProperties.containsKey("main-program")) { String mainTangaraFile = executionProperties.getProperty("main-program"); System.out.println("main tangara file: " + mainTangaraFile); properties.setProperty("main-program", mainTangaraFile); } else { System.err.println("error : main program not specified"); } if (executionProperties.containsKey("language")) { String language = executionProperties.getProperty("language"); properties.setProperty("language", language); System.out.println("language: " + language); } else { System.err.println("error : language not specified"); } if (executionProperties.containsKey("resources")) { String resources = executionProperties.getProperty("resources"); properties.setProperty("program.resources", resources); System.out.println("resources: " + resources); } else { System.err.println("error : resources not specified"); } } } catch (IOException e) { e.printStackTrace(); } finally { if (file != null) { try { file.close(); } catch (IOException e) { System.err.println("error while closing tangara JAR file"); } } } return executionMode; }
From source file:org.owasp.dependencycheck.analyzer.JarAnalyzer.java
/** * Given a path to a pom.xml within a JarFile, this method attempts to load * a sibling pom.properties if one exists. * * @param path the path to the pom.xml within the JarFile * @param jar the JarFile to load the pom.properties from * @return a Properties object or null if no pom.properties was found * @throws IOException thrown if there is an exception reading the * pom.properties//from ww w . j av a 2s .com */ private Properties retrievePomProperties(String path, final JarFile jar) throws IOException { Properties pomProperties = null; final String propPath = path.substring(0, path.length() - 7) + "pom.properies"; final ZipEntry propEntry = jar.getEntry(propPath); if (propEntry != null) { Reader reader = null; try { reader = new InputStreamReader(jar.getInputStream(propEntry), "UTF-8"); pomProperties = new Properties(); pomProperties.load(reader); LOGGER.debug("Read pom.properties: {}", propPath); } finally { if (reader != null) { try { reader.close(); } catch (IOException ex) { LOGGER.trace("close error", ex); } } } } return pomProperties; }
From source file:org.openmrs.module.ModuleFileParser.java
/** * Get the module/*from ww w . j ava 2s. co m*/ * * @return new module object */ public Module parse() throws ModuleException { Module module = null; JarFile jarfile = null; InputStream configStream = null; try { try { jarfile = new JarFile(moduleFile); } catch (IOException e) { throw new ModuleException( Context.getMessageSourceService().getMessage("Module.error.cannotGetJarFile"), moduleFile.getName(), e); } // look for config.xml in the root of the module ZipEntry config = jarfile.getEntry("config.xml"); if (config == null) { throw new ModuleException(Context.getMessageSourceService().getMessage("Module.error.noConfigFile"), moduleFile.getName()); } // get a config file stream try { configStream = jarfile.getInputStream(config); } catch (IOException e) { throw new ModuleException( Context.getMessageSourceService().getMessage("Module.error.cannotGetConfigFileStream"), moduleFile.getName(), e); } // turn the config file into an xml document Document configDoc = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { // When asked to resolve external entities (such as a // DTD) we return an InputSource // with no data at the end, causing the parser to ignore // the DTD. return new InputSource(new StringReader("")); } }); configDoc = db.parse(configStream); } catch (Exception e) { log.error("Error parsing config.xml: " + configStream.toString(), e); OutputStream out = null; String output = ""; try { out = new ByteArrayOutputStream(); // Now copy bytes from the URL to the output stream byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = configStream.read(buffer)) != -1) { out.write(buffer, 0, bytes_read); } output = out.toString(); } catch (Exception e2) { log.warn("Another error parsing config.xml", e2); } finally { try { out.close(); } catch (Exception e3) { } } log.error("config.xml content: " + output); throw new ModuleException( Context.getMessageSourceService().getMessage("Module.error.cannotParseConfigFile"), moduleFile.getName(), e); } Element rootNode = configDoc.getDocumentElement(); String configVersion = rootNode.getAttribute("configVersion").trim(); if (!validConfigVersions.contains(configVersion)) { throw new ModuleException( Context.getMessageSourceService().getMessage("Module.error.invalidConfigVersion", new Object[] { configVersion }, Context.getLocale()), moduleFile.getName()); } String name = getElement(rootNode, configVersion, "name").trim(); String moduleId = getElement(rootNode, configVersion, "id").trim(); String packageName = getElement(rootNode, configVersion, "package").trim(); String author = getElement(rootNode, configVersion, "author").trim(); String desc = getElement(rootNode, configVersion, "description").trim(); String version = getElement(rootNode, configVersion, "version").trim(); // do some validation if (name == null || name.length() == 0) { throw new ModuleException( Context.getMessageSourceService().getMessage("Module.error.nameCannotBeEmpty"), moduleFile.getName()); } if (moduleId == null || moduleId.length() == 0) { throw new ModuleException( Context.getMessageSourceService().getMessage("Module.error.idCannotBeEmpty"), name); } if (packageName == null || packageName.length() == 0) { throw new ModuleException( Context.getMessageSourceService().getMessage("Module.error.packageCannotBeEmpty"), name); } // create the module object module = new Module(name, moduleId, packageName, author, desc, version); // find and load the activator class module.setActivatorName(getElement(rootNode, configVersion, "activator").trim()); module.setRequireDatabaseVersion( getElement(rootNode, configVersion, "require_database_version").trim()); module.setRequireOpenmrsVersion(getElement(rootNode, configVersion, "require_version").trim()); module.setUpdateURL(getElement(rootNode, configVersion, "updateURL").trim()); module.setRequiredModulesMap(getRequiredModules(rootNode, configVersion)); module.setAwareOfModulesMap(getAwareOfModules(rootNode, configVersion)); module.setStartBeforeModulesMap(getStartBeforeModules(rootNode, configVersion)); module.setAdvicePoints(getAdvice(rootNode, configVersion, module)); module.setExtensionNames(getExtensions(rootNode, configVersion)); module.setPrivileges(getPrivileges(rootNode, configVersion)); module.setGlobalProperties(getGlobalProperties(rootNode, configVersion)); module.setMessages(getMessages(rootNode, configVersion, jarfile, moduleId, version)); module.setMappingFiles(getMappingFiles(rootNode, configVersion, jarfile)); module.setPackagesWithMappedClasses(getPackagesWithMappedClasses(rootNode, configVersion)); module.setConfig(configDoc); module.setMandatory(getMandatory(rootNode, configVersion, jarfile)); module.setFile(moduleFile); module.setConditionalResources(getConditionalResources(rootNode)); } finally { try { jarfile.close(); } catch (Exception e) { log.warn("Unable to close jarfile: " + jarfile, e); } if (configStream != null) { try { configStream.close(); } catch (Exception io) { log.error("Error while closing config stream for module: " + moduleFile.getAbsolutePath(), io); } } } return module; }
From source file:org.openmrs.module.ModuleFactory.java
/** * Execute all unrun changeSets in liquibase.xml for the given module * //from w ww. j a v a 2 s. c o m * @param module the module being executed on */ private static void runLiquibase(Module module) { JarFile jarFile = null; boolean liquibaseFileExists = false; try { try { jarFile = new JarFile(module.getFile()); } catch (IOException e) { throw new ModuleException("Unable to get jar file", module.getName(), e); } //check whether module has a liquibase.xml InputStream inStream = null; ZipEntry entry = null; try { inStream = ModuleUtil.getResourceFromApi(jarFile, module.getModuleId(), module.getVersion(), MODULE_CHANGELOG_FILENAME); if (inStream == null) { // Try the old way. Loading from the root of the omod entry = jarFile.getEntry(MODULE_CHANGELOG_FILENAME); } liquibaseFileExists = (inStream != null) || (entry != null); } finally { IOUtils.closeQuietly(inStream); } } finally { try { if (jarFile != null) { jarFile.close(); } } catch (IOException e) { log.warn("Unable to close jarfile: " + jarFile.getName()); } } if (liquibaseFileExists) { try { // run liquibase.xml by Liquibase API DatabaseUpdater.executeChangelog(MODULE_CHANGELOG_FILENAME, null, null, null, getModuleClassLoader(module)); } catch (InputRequiredException ire) { // the user would be stepped through the questions returned here. throw new ModuleException("Input during database updates is not yet implemented.", module.getName(), ire); } catch (DatabaseUpdateException e) { throw new ModuleException("Unable to update data model using liquibase.xml.", module.getName(), e); } catch (Exception e) { throw new ModuleException("Unable to update data model using liquibase.xml.", module.getName(), e); } } }
From source file:org.owasp.dependencycheck.analyzer.JarAnalyzer.java
/** * Retrieves the specified POM from a jar file and converts it to a Model. * * @param path the path to the pom.xml file within the jar file * @param jar the jar file to extract the pom from * @param dependency the dependency being analyzed * @return returns the POM object// w w w. jav a2s. c o m * @throws AnalysisException is thrown if there is an exception extracting * or parsing the POM {@link org.owasp.dependencycheck.xml.pom.Model} object */ private Model extractPom(String path, JarFile jar, Dependency dependency) throws AnalysisException { InputStream input = null; FileOutputStream fos = null; final File tmpDir = getNextTempDirectory(); final File file = new File(tmpDir, "pom.xml"); try { final ZipEntry entry = jar.getEntry(path); input = jar.getInputStream(entry); fos = new FileOutputStream(file); IOUtils.copy(input, fos); dependency.setActualFilePath(file.getAbsolutePath()); } catch (IOException ex) { LOGGER.warn("An error occurred reading '{}' from '{}'.", path, dependency.getFilePath()); LOGGER.error("", ex); } finally { closeStream(fos); closeStream(input); } return PomUtils.readPom(file); }
From source file:com.photon.phresco.util.PhrescoDynamicLoader.java
public InputStream getResourceAsStream(String fileName) throws PhrescoException { InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(fileName); if (resourceAsStream != null) { return resourceAsStream; }//from w w w .j av a 2s . c o m List<Artifact> artifacts = new ArrayList<Artifact>(); Artifact foundArtifact = null; String destFile = ""; JarFile jarfile = null; for (ArtifactGroup plugin : plugins) { List<ArtifactInfo> versions = plugin.getVersions(); for (ArtifactInfo artifactInfo : versions) { foundArtifact = createArtifact(plugin.getGroupId(), plugin.getArtifactId(), "jar", artifactInfo.getVersion()); artifacts.add(foundArtifact); } } try { URL artifactURLs = MavenArtifactResolver.resolveSingleArtifact(repoInfo.getGroupRepoURL(), repoInfo.getRepoUserName(), repoInfo.getRepoPassword(), artifacts); File jarFile = new File(artifactURLs.toURI()); if (jarFile.getName().equals(foundArtifact.getArtifactId() + "-" + foundArtifact.getVersion() + "." + foundArtifact.getType())) { jarfile = new JarFile(jarFile); for (Enumeration<JarEntry> em = jarfile.entries(); em.hasMoreElements();) { JarEntry jarEntry = em.nextElement(); if (jarEntry.getName().endsWith(fileName)) { destFile = jarEntry.getName(); } } } if (StringUtils.isNotEmpty(destFile)) { ZipEntry entry = jarfile.getEntry(destFile); return jarfile.getInputStream(entry); } } catch (Exception e) { e.printStackTrace(); throw new PhrescoException(e); } return null; }
From source file:org.moe.cli.ParameterParserTest.java
@Test public void linkLibrary() throws Exception { File project = tmpDir.newFolder(); File outputJar = new File(project, "TestLib.jar"); // prepare file with ldFlags String flags = "-lTestLibrary"; File ldFlags = new File(project, "ldflags"); ldFlags.createNewFile();// www. j a va 2 s . c o m PrintWriter write = new PrintWriter(ldFlags); write.print(flags); write.close(); ClassLoader cl = this.getClass().getClassLoader(); URL library = cl.getResource("natives/simulator/libTestLibrary.a"); URL deviceLibrary = cl.getResource("natives/device/libTestLibrary.a"); URL headersURL = cl.getResource("natives/Headers/TestFramework.h"); File headers = new File(headersURL.getPath()); URL bundle = cl.getResource("moe_logo.png"); CommandLine argc = parseArgs(new String[] { "--library", String.format("%s:%s", library.getPath(), deviceLibrary.getPath()), "--headers", headers.getParentFile().getPath(), "--package-name", "org", "--output-file-path", outputJar.getPath(), "--ld-flags", ldFlags.getPath(), "--bundle", bundle.getPath() }); IExecutor executor = ExecutorManager.getExecutorByParams(argc); assertNotNull(executor); assertTrue(executor instanceof ThirdPartyLibraryLinkExecutor); // generate binding & prepare output jar executor.execute(); // check output jar file existence assertTrue(outputJar.exists()); JarFile jarFile = new JarFile(outputJar); Manifest manifest = jarFile.getManifest(); Attributes attributes = manifest.getMainAttributes(); String manifestLDFlags = attributes.getValue("MOE_CUSTOM_LINKER_FLAGS"); Set<String> realLDFlags = new HashSet<String>(Arrays.asList(flags.split(";"))); realLDFlags.add("-ObjC"); assertEquals(realLDFlags, new HashSet<String>(Arrays.asList(manifestLDFlags.split(";")))); String manifestSimFramework = attributes.getValue("MOE_ThirdpartyFramework_ios_simulator"); assertEquals("./lib/iphonesimulator/libTestLibrary.a", manifestSimFramework); String manifestDevFramework = attributes.getValue("MOE_ThirdpartyFramework_ios_device"); assertEquals("./lib/iphoneos/libTestLibrary.a", manifestDevFramework); String manifestBundle = attributes.getValue("MOE_BUNDLE_FILE_RESOURCES"); assertEquals("./bundle/moe_logo.png;", manifestBundle); assertNotNull(jarFile.getEntry("bundle/moe_logo.png")); assertNotNull(jarFile.getEntry("lib/iphonesimulator/libTestLibrary.a")); assertNotNull(jarFile.getEntry("lib/iphoneos/libTestLibrary.a")); jarFile.close(); }