List of usage examples for java.util.jar JarFile getName
public String getName()
From source file:net.minecraftforge.fml.relauncher.libraries.LibraryManager.java
private static Pair<Artifact, byte[]> extractPacked(JarFile jar, ModList modlist, File... modDirs) throws IOException { Attributes attrs;/*from w w w . j av a2 s .c o m*/ if (jar.getManifest() == null) return null; JarEntry manifest_entry = jar.getJarEntry(JarFile.MANIFEST_NAME); if (manifest_entry == null) manifest_entry = jar.stream() .filter(e -> JarFile.MANIFEST_NAME.equals(e.getName().toUpperCase(Locale.ENGLISH))).findFirst() .get(); //We know that getManifest returned non-null so we know there is *some* entry that matches the manifest file. So we dont need to empty check. attrs = jar.getManifest().getMainAttributes(); String modSide = attrs.getValue(LibraryManager.MODSIDE); if (modSide != null && !"BOTH".equals(modSide) && !FMLLaunchHandler.side().name().equals(modSide)) return null; if (attrs.containsKey(MODCONTAINSDEPS)) { for (String dep : attrs.getValue(MODCONTAINSDEPS).split(" ")) { if (!dep.endsWith(".jar")) { FMLLog.log.error("Contained Dep is not a jar file: {}", dep); throw new IllegalStateException("Invalid contained dep, Must be jar: " + dep); } if (jar.getJarEntry(dep) == null && jar.getJarEntry("META-INF/libraries/" + dep) != null) dep = "META-INF/libraries/" + dep; JarEntry depEntry = jar.getJarEntry(dep); if (depEntry == null) { FMLLog.log.error("Contained Dep is not in the jar: {}", dep); throw new IllegalStateException("Invalid contained dep, Missing from jar: " + dep); } String depEndName = new File(dep).getName(); // extract last part of name if (skipContainedDeps.contains(dep) || skipContainedDeps.contains(depEndName)) { FMLLog.log.error("Skipping dep at request: {}", dep); continue; } Attributes meta = null; byte[] data = null; byte[] manifest_data = null; JarEntry metaEntry = jar.getJarEntry(dep + ".meta"); if (metaEntry != null) { manifest_data = readAll(jar.getInputStream(metaEntry)); meta = new Manifest(new ByteArrayInputStream(manifest_data)).getMainAttributes(); } else { data = readAll(jar.getInputStream(depEntry)); try (ZipInputStream zi = new ZipInputStream(new ByteArrayInputStream(data))) //We use zip input stream directly, as the current Oracle implementation of JarInputStream only works when the manifest is the First/Second entry in the jar... { ZipEntry ze = null; while ((ze = zi.getNextEntry()) != null) { if (ze.getName().equalsIgnoreCase(JarFile.MANIFEST_NAME)) { manifest_data = readAll(zi); meta = new Manifest(new ByteArrayInputStream(manifest_data)).getMainAttributes(); break; } } } } if (meta == null || !meta.containsKey(MAVEN_ARTIFACT)) //Ugh I really don't want to do backwards compatibility here, I want to force modders to provide information... TODO: Remove in 1.13? { boolean found = false; for (File dir : modDirs) { File target = new File(dir, depEndName); if (target.exists()) { FMLLog.log.debug("Found existing ContainDep extracted to {}, skipping extraction", target.getCanonicalPath()); found = true; } } if (!found) { File target = new File(modDirs[0], depEndName); FMLLog.log.debug("Extracting ContainedDep {} from {} to {}", dep, jar.getName(), target.getCanonicalPath()); try { Files.createParentDirs(target); try (FileOutputStream out = new FileOutputStream(target); InputStream in = data == null ? jar.getInputStream(depEntry) : new ByteArrayInputStream(data)) { ByteStreams.copy(in, out); } FMLLog.log.debug("Extracted ContainedDep {} from {} to {}", dep, jar.getName(), target.getCanonicalPath()); extractPacked(target, modlist, modDirs); } catch (IOException e) { FMLLog.log.error("An error occurred extracting dependency", e); } } } else { try { Artifact artifact = readArtifact(modlist.getRepository(), meta); File target = artifact.getFile(); if (target.exists()) { FMLLog.log.debug( "Found existing ContainedDep {}({}) from {} extracted to {}, skipping extraction", dep, artifact.toString(), target.getCanonicalPath(), jar.getName()); if (!ENABLE_AUTO_MOD_MOVEMENT) { Pair<?, ?> child = extractPacked(target, modlist, modDirs); //If we're not building a real list we have to re-build the dep list every run. So search down. if (child == null && metaEntry != null) //External meta with no internal name... If there is a internal name, we trust that that name is the correct one. { modlist.add(artifact); } } } else { FMLLog.log.debug("Extracting ContainedDep {}({}) from {} to {}", dep, artifact.toString(), jar.getName(), target.getCanonicalPath()); Files.createParentDirs(target); try (FileOutputStream out = new FileOutputStream(target); InputStream in = data == null ? jar.getInputStream(depEntry) : new ByteArrayInputStream(data)) { ByteStreams.copy(in, out); } FMLLog.log.debug("Extracted ContainedDep {}({}) from {} to {}", dep, artifact.toString(), jar.getName(), target.getCanonicalPath()); if (artifact.isSnapshot()) { SnapshotJson json = SnapshotJson.create(artifact.getSnapshotMeta()); json.add(new SnapshotJson.Entry(artifact.getTimestamp(), meta.getValue(MD5))); json.write(artifact.getSnapshotMeta()); } if (!DISABLE_EXTERNAL_MANIFEST) { File meta_target = new File(target.getAbsolutePath() + ".meta"); Files.write(manifest_data, meta_target); } Pair<?, ?> child = extractPacked(target, modlist, modDirs); if (child == null && metaEntry != null) //External meta with no internal name... If there is a internal name, we trust that that name is the correct one. { modlist.add(artifact); } } } catch (NumberFormatException nfe) { FMLLog.log.error(FMLLog.log.getMessageFactory().newMessage( "An error occurred extracting dependency. Invalid Timestamp: {}", meta.getValue(TIMESTAMP)), nfe); } catch (IOException e) { FMLLog.log.error("An error occurred extracting dependency", e); } } } } if (attrs.containsKey(MAVEN_ARTIFACT)) { Artifact artifact = readArtifact(modlist.getRepository(), attrs); modlist.add(artifact); return Pair.of(artifact, readAll(jar.getInputStream(manifest_entry))); } return null; }
From source file:org.olat.core.util.i18n.I18nManager.java
/** * Searches within a jar file for available languages. * //from w w w . jav a 2s .com * @param jarFile * @param checkForExecutables true: check if jar contains java or class files * and return an empty set if such executable files are found; false * don't check or care * @return Set of language keys, can be empty but never null */ public Set<String> sarchForAvailableLanguagesInJarFile(File jarFile, boolean checkForExecutables) { Set<String> foundLanguages = new TreeSet<String>(); JarFile jar = null; try { jar = new JarFile(jarFile); Enumeration<JarEntry> jarEntries = jar.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); String jarEntryName = jarEntry.getName(); // check for executables if (checkForExecutables && (jarEntryName.endsWith("java") || jarEntryName.endsWith("class"))) { return new TreeSet<String>(); } // search for core util in jar if (jarEntryName .indexOf(I18nModule.getCoreFallbackBundle().replace(".", "/") + "/" + I18N_DIRNAME) != -1) { // don't add overlayLocales as selectable // availableLanguages if (jarEntryName.indexOf("__") == -1 && jarEntryName.indexOf(I18nModule.LOCAL_STRINGS_FILE_PREFIX) != -1) { String lang = jarEntryName.substring( jarEntryName.indexOf(I18nModule.LOCAL_STRINGS_FILE_PREFIX) + I18nModule.LOCAL_STRINGS_FILE_PREFIX.length(), jarEntryName.lastIndexOf(".")); foundLanguages.add(lang); if (isLogDebugEnabled()) logDebug("Adding lang::" + lang + " from filename::" + jarEntryName + " in jar::" + jar.getName(), null); } } } } catch (IOException e) { throw new OLATRuntimeException("Error when looking up i18n files in jar::" + jarFile.getAbsolutePath(), e); } finally { IOUtils.closeQuietly(jar); } return foundLanguages; }
From source file:org.openmrs.module.web.WebModuleUtil.java
/** * Performs the webapp specific startup needs for modules Normal startup is done in * {@link ModuleFactory#startModule(Module)} If delayContextRefresh is true, the spring context * is not rerun. This will save a lot of time, but it also means that the calling method is * responsible for restarting the context if necessary (the calling method will also have to * call {@link #loadServlets(Module, ServletContext)} and * {@link #loadFilters(Module, ServletContext)}).<br> * <br>/*w w w . ja va 2s . com*/ * If delayContextRefresh is true and this module should have caused a context refresh, a true * value is returned. Otherwise, false is returned * * @param mod Module to start * @param servletContext the current ServletContext * @param delayContextRefresh true/false whether or not to do the context refresh * @return boolean whether or not the spring context need to be refreshed */ public static boolean startModule(Module mod, ServletContext servletContext, boolean delayContextRefresh) { if (log.isDebugEnabled()) { log.debug("trying to start module " + mod); } // only try and start this module if the api started it without a // problem. if (ModuleFactory.isModuleStarted(mod) && !mod.hasStartupError()) { String realPath = getRealPath(servletContext); if (realPath == null) { realPath = System.getProperty("user.dir"); } File webInf = new File(realPath + "/WEB-INF".replace("/", File.separator)); if (!webInf.exists()) { webInf.mkdir(); } copyModuleMessagesIntoWebapp(mod, realPath); log.debug("Done copying messages"); // flag to tell whether we added any xml/dwr/etc changes that necessitate a refresh // of the web application context boolean moduleNeedsContextRefresh = false; // copy the html files into the webapp (from /web/module/ in the module) // also looks for a spring context file. If found, schedules spring to be restarted JarFile jarFile = null; OutputStream outStream = null; InputStream inStream = null; try { File modFile = mod.getFile(); jarFile = new JarFile(modFile); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); log.debug("Entry name: " + name); if (name.startsWith("web/module/")) { // trim out the starting path of "web/module/" String filepath = name.substring(11); StringBuffer absPath = new StringBuffer(realPath + "/WEB-INF"); // If this is within the tag file directory, copy it into /WEB-INF/tags/module/moduleId/... if (filepath.startsWith("tags/")) { filepath = filepath.substring(5); absPath.append("/tags/module/"); } // Otherwise, copy it into /WEB-INF/view/module/moduleId/... else { absPath.append("/view/module/"); } // if a module id has a . in it, we should treat that as a /, i.e. files in the module // ui.springmvc should go in folder names like .../ui/springmvc/... absPath.append(mod.getModuleIdAsPath() + "/" + filepath); if (log.isDebugEnabled()) { log.debug("Moving file from: " + name + " to " + absPath); } // get the output file File outFile = new File(absPath.toString().replace("/", File.separator)); if (entry.isDirectory()) { if (!outFile.exists()) { outFile.mkdirs(); } } else { // make the parent directories in case it doesn't exist File parentDir = outFile.getParentFile(); if (!parentDir.exists()) { parentDir.mkdirs(); } //if (outFile.getName().endsWith(".jsp") == false) // outFile = new File(absPath.replace("/", File.separator) + MODULE_NON_JSP_EXTENSION); // copy the contents over to the webapp for non directories outStream = new FileOutputStream(outFile, false); inStream = jarFile.getInputStream(entry); OpenmrsUtil.copyFile(inStream, outStream); } } else if (name.equals("moduleApplicationContext.xml") || name.equals("webModuleApplicationContext.xml")) { moduleNeedsContextRefresh = true; } else if (name.equals(mod.getModuleId() + "Context.xml")) { String msg = "DEPRECATED: '" + name + "' should be named 'moduleApplicationContext.xml' now. Please update/upgrade. "; throw new ModuleException(msg, mod.getModuleId()); } } } catch (IOException io) { log.warn("Unable to copy files from module " + mod.getModuleId() + " to the web layer", io); } finally { if (jarFile != null) { try { jarFile.close(); } catch (IOException io) { log.warn("Couldn't close jar file: " + jarFile.getName(), io); } } if (inStream != null) { try { inStream.close(); } catch (IOException io) { log.warn("Couldn't close InputStream: " + io); } } if (outStream != null) { try { outStream.close(); } catch (IOException io) { log.warn("Couldn't close OutputStream: " + io); } } } // find and add the dwr code to the dwr-modules.xml file (if defined) InputStream inputStream = null; try { Document config = mod.getConfig(); Element root = config.getDocumentElement(); if (root.getElementsByTagName("dwr").getLength() > 0) { // get the dwr-module.xml file that we're appending our code to File f = new File(realPath + "/WEB-INF/dwr-modules.xml".replace("/", File.separator)); // testing if file exists if (!f.exists()) { // if it does not -> needs to be created createDwrModulesXml(realPath); } inputStream = new FileInputStream(f); Document dwrmodulexml = getDWRModuleXML(inputStream, realPath); Element outputRoot = dwrmodulexml.getDocumentElement(); // loop over all of the children of the "dwr" tag Node node = root.getElementsByTagName("dwr").item(0); Node current = node.getFirstChild(); while (current != null) { if ("allow".equals(current.getNodeName()) || "signatures".equals(current.getNodeName()) || "init".equals(current.getNodeName())) { ((Element) current).setAttribute("moduleId", mod.getModuleId()); outputRoot.appendChild(dwrmodulexml.importNode(current, true)); } current = current.getNextSibling(); } moduleNeedsContextRefresh = true; // save the dwr-modules.xml file. OpenmrsUtil.saveDocument(dwrmodulexml, f); } } catch (FileNotFoundException e) { throw new ModuleException(realPath + "/WEB-INF/dwr-modules.xml file doesn't exist.", e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException io) { log.error("Error while closing input stream", io); } } } // mark to delete the entire module web directory on exit // this will usually only be used when an improper shutdown has occurred. String folderPath = realPath + "/WEB-INF/view/module/" + mod.getModuleIdAsPath(); File outFile = new File(folderPath.replace("/", File.separator)); outFile.deleteOnExit(); // additional checks on module needing a context refresh if (moduleNeedsContextRefresh == false && mod.getAdvicePoints() != null && mod.getAdvicePoints().size() > 0) { // AOP advice points are only loaded during the context refresh now. // if the context hasn't been marked to be refreshed yet, mark it // now if this module defines some advice moduleNeedsContextRefresh = true; } // refresh the spring web context to get the just-created xml // files into it (if we copied an xml file) if (moduleNeedsContextRefresh && delayContextRefresh == false) { if (log.isDebugEnabled()) { log.debug("Refreshing context for module" + mod); } try { refreshWAC(servletContext, false, mod); log.debug("Done Refreshing WAC"); } catch (Exception e) { String msg = "Unable to refresh the WebApplicationContext"; mod.setStartupErrorMessage(msg, e); if (log.isWarnEnabled()) { log.warn(msg + " for module: " + mod.getModuleId(), e); } try { stopModule(mod, servletContext, true); ModuleFactory.stopModule(mod, true, true); //remove jar from classloader play } catch (Exception e2) { // exception expected with most modules here if (log.isWarnEnabled()) { log.warn("Error while stopping a module that had an error on refreshWAC", e2); } } // try starting the application context again refreshWAC(servletContext, false, mod); notifySuperUsersAboutModuleFailure(mod); } } if (!delayContextRefresh && ModuleFactory.isModuleStarted(mod)) { // only loading the servlets/filters if spring is refreshed because one // might depend on files being available in spring // if the caller wanted to delay the refresh then they are responsible for // calling these two methods on the module // find and cache the module's servlets //(only if the module started successfully previously) log.debug("Loading servlets and filters for module: " + mod); loadServlets(mod, servletContext); loadFilters(mod, servletContext); } // return true if the module needs a context refresh and we didn't do it here return (moduleNeedsContextRefresh && delayContextRefresh == true); } // we aren't processing this module, so a context refresh is not necessary return false; }
From source file:org.apache.tomcat.maven.plugin.tomcat8.run.RunMojo.java
@Override protected void enhanceContext(final Context context) throws MojoExecutionException { super.enhanceContext(context); try {/*from w w w.j a v a 2 s. co m*/ ClassLoaderEntriesCalculatorRequest request = new ClassLoaderEntriesCalculatorRequest() // .setDependencies(dependencies) // .setLog(getLog()) // .setMavenProject(project) // .setAddWarDependenciesInClassloader(addWarDependenciesInClassloader) // .setUseTestClassPath(useTestClasspath); final ClassLoaderEntriesCalculatorResult classLoaderEntriesCalculatorResult = classLoaderEntriesCalculator .calculateClassPathEntries(request); final List<String> classLoaderEntries = classLoaderEntriesCalculatorResult.getClassPathEntries(); final List<File> tmpDirectories = classLoaderEntriesCalculatorResult.getTmpDirectories(); final List<String> jarPaths = extractJars(classLoaderEntries); List<URL> urls = new ArrayList<URL>(jarPaths.size()); for (String jarPath : jarPaths) { try { urls.add(new File(jarPath).toURI().toURL()); } catch (MalformedURLException e) { throw new MojoExecutionException(e.getMessage(), e); } } getLog().debug("classLoaderEntriesCalculator urls: " + urls); final URLClassLoader urlClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()])); final ClassRealm pluginRealm = getTomcatClassLoader(); context.setResources( new MyDirContext(new File(project.getBuild().getOutputDirectory()).getAbsolutePath(), // getPath(), // getLog()) { @Override public WebResource getClassLoaderResource(String path) { log.debug("RunMojo#getClassLoaderResource: " + path); URL url = urlClassLoader.getResource(StringUtils.removeStart(path, "/")); // search in parent (plugin) classloader if (url == null) { url = pluginRealm.getResource(StringUtils.removeStart(path, "/")); } if (url == null) { // try in reactors List<WebResource> webResources = findResourcesInDirectories(path, // classLoaderEntriesCalculatorResult.getBuildDirectories()); // so we return the first one if (!webResources.isEmpty()) { return webResources.get(0); } } if (url == null) { return new EmptyResource(this, getPath()); } return urlToWebResource(url, path); } @Override public WebResource getResource(String path) { log.debug("RunMojo#getResource: " + path); return super.getResource(path); } @Override public WebResource[] getResources(String path) { log.debug("RunMojo#getResources: " + path); return super.getResources(path); } @Override protected WebResource[] getResourcesInternal(String path, boolean useClassLoaderResources) { log.debug("RunMojo#getResourcesInternal: " + path); return super.getResourcesInternal(path, useClassLoaderResources); } @Override public WebResource[] getClassLoaderResources(String path) { try { Enumeration<URL> enumeration = urlClassLoader .findResources(StringUtils.removeStart(path, "/")); List<URL> urlsFound = new ArrayList<URL>(); List<WebResource> webResources = new ArrayList<WebResource>(); while (enumeration.hasMoreElements()) { URL url = enumeration.nextElement(); urlsFound.add(url); webResources.add(urlToWebResource(url, path)); } log.debug("RunMojo#getClassLoaderResources: " + path + " found : " + urlsFound.toString()); webResources.addAll(findResourcesInDirectories(path, classLoaderEntriesCalculatorResult.getBuildDirectories())); return webResources.toArray(new WebResource[webResources.size()]); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } private List<WebResource> findResourcesInDirectories(String path, List<String> directories) { try { List<WebResource> webResources = new ArrayList<WebResource>(); for (String directory : directories) { File file = new File(directory, path); if (file.exists()) { webResources.add(urlToWebResource(file.toURI().toURL(), path)); } } return webResources; } catch (MalformedURLException e) { throw new RuntimeException(e.getMessage(), e); } } private WebResource urlToWebResource(URL url, String path) { JarFile jarFile = null; try { // url.getFile is // file:/Users/olamy/mvn-repo/org/springframework/spring-web/4.0.0.RELEASE/spring-web-4.0.0.RELEASE.jar!/org/springframework/web/context/ContextLoaderListener.class int idx = url.getFile().indexOf('!'); if (idx >= 0) { String filePath = StringUtils.removeStart(url.getFile().substring(0, idx), "file:"); jarFile = new JarFile(filePath); JarEntry jarEntry = jarFile.getJarEntry(StringUtils.removeStart(path, "/")); return new JarResource(this, // getPath(), // filePath, // url.getPath().substring(0, idx), // jarEntry, // "", // null); } else { return new FileResource(this, webAppPath, new File(url.getFile()), true); } } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { IOUtils.closeQuietly(jarFile); } } }); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { for (File tmpDir : tmpDirectories) { try { FileUtils.deleteDirectory(tmpDir); } catch (IOException e) { // ignore } } } }); if (classLoaderEntries != null) { WebResourceSet webResourceSet = new FileResourceSet() { @Override public WebResource getResource(String path) { if (StringUtils.startsWithIgnoreCase(path, "/WEB-INF/LIB")) { File file = new File(StringUtils.removeStartIgnoreCase(path, "/WEB-INF/LIB")); return new FileResource(context.getResources(), getPath(), file, true); } if (StringUtils.equalsIgnoreCase(path, "/WEB-INF/classes")) { return new FileResource(context.getResources(), getPath(), new File(project.getBuild().getOutputDirectory()), true); } File file = new File(project.getBuild().getOutputDirectory(), path); if (file.exists()) { return new FileResource(context.getResources(), getPath(), file, true); } //if ( StringUtils.endsWith( path, ".class" ) ) { // so we search the class file in the jars for (String jarPath : jarPaths) { File jar = new File(jarPath); if (!jar.exists()) { continue; } try (JarFile jarFile = new JarFile(jar)) { JarEntry jarEntry = (JarEntry) jarFile .getEntry(StringUtils.removeStart(path, "/")); if (jarEntry != null) { return new JarResource(context.getResources(), // getPath(), // jarFile.getName(), // jar.toURI().toString(), // jarEntry, // path, // jarFile.getManifest()); } } catch (IOException e) { getLog().debug("skip error building jar file: " + e.getMessage(), e); } } } return new EmptyResource(null, path); } @Override public String[] list(String path) { if (StringUtils.startsWithIgnoreCase(path, "/WEB-INF/LIB")) { return jarPaths.toArray(new String[jarPaths.size()]); } if (StringUtils.equalsIgnoreCase(path, "/WEB-INF/classes")) { return new String[] { new File(project.getBuild().getOutputDirectory()).getPath() }; } return super.list(path); } @Override public Set<String> listWebAppPaths(String path) { if (StringUtils.equalsIgnoreCase("/WEB-INF/lib/", path)) { // adding outputDirectory as well? return new HashSet<String>(jarPaths); } File filePath = new File(getWarSourceDirectory(), path); if (filePath.isDirectory()) { Set<String> paths = new HashSet<String>(); String[] files = filePath.list(); if (files == null) { return paths; } for (String file : files) { paths.add(file); } return paths; } else { return Collections.emptySet(); } } @Override public boolean mkdir(String path) { return super.mkdir(path); } @Override public boolean write(String path, InputStream is, boolean overwrite) { return super.write(path, is, overwrite); } @Override protected void checkType(File file) { //super.checkType( file ); } }; context.getResources().addJarResources(webResourceSet); } } catch (TomcatRunException e) { throw new MojoExecutionException(e.getMessage(), e); } }