List of usage examples for java.util.jar JarEntry isDirectory
public boolean isDirectory()
From source file:org.eclipse.winery.generators.ia.Generator.java
/** * Generates the IA project.// www. j a v a2 s . c o m * * @return The ZIP file containing the maven/eclipse project to be * downloaded by the user. */ public File generateProject() { try { Path workingDirPath = this.workingDir.toPath(); Files.createDirectories(workingDirPath); // directory to store the template files to generate the java files from Path javaTemplateDir = workingDirPath.resolve("../java"); Files.createDirectories(javaTemplateDir); // Copy template project and template java files String s = this.getClass().getResource("").getPath(); if (s.contains("jar!")) { Generator.logger.trace("we work on a jar file"); Generator.logger.trace("Location of the current class: {}", s); // we have a jar file // format: file:/location...jar!...path-in-the-jar // we only want to have location :) int excl = s.lastIndexOf("!"); s = s.substring(0, excl); s = s.substring("file:".length()); try (JarFile jf = new JarFile(s);) { Enumeration<JarEntry> entries = jf.entries(); while (entries.hasMoreElements()) { JarEntry je = entries.nextElement(); String name = je.getName(); if (name.startsWith(Generator.TEMPLATE_PROJECT_FOLDER + "/") && (name.length() > (Generator.TEMPLATE_PROJECT_FOLDER.length() + 1))) { // strip "template/" from the beginning to have paths without "template" starting relatively from the working dir name = name.substring(Generator.TEMPLATE_PROJECT_FOLDER.length() + 1); if (je.isDirectory()) { // directory found Path dir = workingDirPath.resolve(name); Files.createDirectory(dir); } else { Path file = workingDirPath.resolve(name); try (InputStream is = jf.getInputStream(je);) { Files.copy(is, file, StandardCopyOption.REPLACE_EXISTING); } } } else if (name.startsWith(Generator.TEMPLATE_JAVA_FOLDER + "/") && (name.length() > (Generator.TEMPLATE_JAVA_FOLDER.length() + 1))) { if (!je.isDirectory()) { // we copy the file directly into javaTemplateDir File f = new File(name); Path file = javaTemplateDir.resolve(f.getName()); try (InputStream is = jf.getInputStream(je);) { Files.copy(is, file, StandardCopyOption.REPLACE_EXISTING); } } } } } } else { // we're running in debug mode, we can work on the plain file system File templateProjectDir = new File( this.getClass().getResource("/" + Generator.TEMPLATE_PROJECT_FOLDER).getFile()); FileUtils.copyDirectory(templateProjectDir, this.workingDir); File javaTemplatesDir = new File( this.getClass().getResource("/" + Generator.TEMPLATE_JAVA_FOLDER).getFile()); FileUtils.copyDirectory(javaTemplatesDir, javaTemplateDir.toFile()); } // Create Java Code Folder String[] splitPkg = this.javaPackage.split("\\."); String javaFolderString = this.workingDir.getAbsolutePath() + File.separator + "src" + File.separator + "main" + File.separator + "java"; for (int i = 0; i < splitPkg.length; i++) { javaFolderString += File.separator + splitPkg[i]; } // Copy TEMPLATE_JAVA_ABSTRACT_IA_SERVICE Path templateAbstractIAService = javaTemplateDir.resolve(Generator.TEMPLATE_JAVA_ABSTRACT_IA_SERVICE); File javaAbstractIAService = new File(javaFolderString + File.separator + "AbstractIAService.java"); Files.createDirectories(javaAbstractIAService.toPath().getParent()); Files.copy(templateAbstractIAService, javaAbstractIAService.toPath(), StandardCopyOption.REPLACE_EXISTING); // Copy and rename TEMPLATE_JAVA_TEMPLATE_SERVICE Path templateJavaService = javaTemplateDir.resolve(Generator.TEMPLATE_JAVA_TEMPLATE_SERVICE); File javaService = new File(javaFolderString + File.separator + this.name + ".java"); Files.createDirectories(javaService.toPath().getParent()); Files.copy(templateJavaService, javaService.toPath(), StandardCopyOption.REPLACE_EXISTING); this.generateJavaFile(javaService); this.updateFilesRecursively(this.workingDir); return this.packageProject(); } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:org.hyperic.hq.product.server.session.PluginManagerImpl.java
private Map<String, Reader> getXmlReaderMap(JarFile jarFile) throws IOException { final Map<String, Reader> rtn = new HashMap<String, Reader>(); final Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { final JarEntry entry = entries.nextElement(); if (entry.isDirectory()) { continue; }/*from ww w . j av a 2s . c om*/ if (!entry.getName().toLowerCase().endsWith(".xml")) { continue; } InputStream is = null; try { is = jarFile.getInputStream(entry); final BufferedReader br = new BufferedReader(new InputStreamReader(is)); final StringBuilder buf = new StringBuilder(); String tmp; while (null != (tmp = br.readLine())) { buf.append(tmp); } rtn.put(entry.getName(), new NoCloseStringReader(buf.toString())); } finally { close(is); } } return rtn; }
From source file:org.hyperic.hq.product.server.session.PluginManagerImpl.java
private void processJarEntries(JarFile jarFile, String jarFilename, String filename) throws PluginDeployException, IOException { final Map<String, JDOMException> xmlFailures = new HashMap<String, JDOMException>(); boolean hasPluginRootElement = false; final Enumeration<JarEntry> entries = jarFile.entries(); final Map<String, Reader> xmlReaders = getXmlReaderMap(jarFile); while (entries.hasMoreElements()) { Reader reader = null;/* w w w . j av a 2 s . co m*/ String currXml = null; try { final JarEntry entry = entries.nextElement(); if (entry.isDirectory()) { continue; } if (!entry.getName().toLowerCase().endsWith(".xml")) { continue; } currXml = entry.getName(); reader = xmlReaders.get(currXml); final Document doc = getDocument(reader, xmlReaders); if (doc.getRootElement().getName().toLowerCase().equals("plugin")) { hasPluginRootElement = true; } currXml = null; } catch (JDOMException e) { log.debug(e, e); xmlFailures.put(currXml, e); } } if (!hasPluginRootElement) { final File toRemove = new File(jarFilename); if (toRemove != null && toRemove.exists()) { toRemove.delete(); } if (!xmlFailures.isEmpty()) { for (final Entry<String, JDOMException> entry : xmlFailures.entrySet()) { final String xml = entry.getKey(); JDOMException ex = entry.getValue(); log.error("could not parse " + xml, ex); } throw new PluginDeployException("plugin.manager.file.xml.wellformed.error", xmlFailures.keySet().toString()); } else { throw new PluginDeployException("plugin.manager.no.plugin.root.element", filename); } } }
From source file:com.datatorrent.stram.webapp.OperatorDiscoverer.java
public void buildTypeGraph() { Map<String, JarFile> openJarFiles = new HashMap<String, JarFile>(); Map<String, File> openClassFiles = new HashMap<String, File>(); // use global cache to load resource in/out of the same jar as the classes Set<String> resourceCacheSet = new HashSet<>(); try {// w w w . ja v a 2 s . com for (String path : pathsToScan) { File f = null; try { f = new File(path); if (!f.exists() || f.isDirectory() || (!f.getName().endsWith("jar") && !f.getName().endsWith("class"))) { continue; } if (GENERATED_CLASSES_JAR.equals(f.getName())) { continue; } if (f.getName().endsWith("class")) { typeGraph.addNode(f); openClassFiles.put(path, f); } else { JarFile jar = new JarFile(path); openJarFiles.put(path, jar); java.util.Enumeration<JarEntry> entriesEnum = jar.entries(); while (entriesEnum.hasMoreElements()) { final java.util.jar.JarEntry jarEntry = entriesEnum.nextElement(); String entryName = jarEntry.getName(); if (jarEntry.isDirectory()) { continue; } if (entryName.endsWith("-javadoc.xml")) { try { processJavadocXml(jar.getInputStream(jarEntry)); // break; } catch (Exception ex) { LOG.warn("Cannot process javadoc {} : ", entryName, ex); } } else if (entryName.endsWith(".class")) { TypeGraph.TypeGraphVertex newNode = typeGraph.addNode(jarEntry, jar); // check if any visited resources belong to this type for (Iterator<String> iter = resourceCacheSet.iterator(); iter.hasNext();) { String entry = iter.next(); if (entry.startsWith(entryName.substring(0, entryName.length() - 6))) { newNode.setHasResource(true); iter.remove(); } } } else { String className = entryName; boolean foundClass = false; // check if this resource belongs to any visited type while (className.contains("/")) { className = className.substring(0, className.lastIndexOf('/')); TypeGraph.TypeGraphVertex tgv = typeGraph.getNode(className.replace('/', '.')); if (tgv != null) { tgv.setHasResource(true); foundClass = true; break; } } if (!foundClass) { resourceCacheSet.add(entryName); } } } } } catch (IOException ex) { LOG.warn("Cannot process file {}", f, ex); } } typeGraph.trim(); } finally { for (Entry<String, JarFile> entry : openJarFiles.entrySet()) { try { entry.getValue().close(); } catch (IOException e) { DTThrowable.wrapIfChecked(e); } } } }
From source file:com.ecyrd.jspwiki.ui.TemplateManager.java
/** * List all installed i18n language properties * //from ww w . j av a 2 s . c o m * @param pageContext * @return map of installed Languages (with help of Juan Pablo Santos Rodriguez) * @since 2.7.x */ public Map listLanguages(PageContext pageContext) { LinkedHashMap<String, String> resultMap = new LinkedHashMap<String, String>(); String clientLanguage = ((HttpServletRequest) pageContext.getRequest()).getLocale().toString(); JarInputStream jarStream = null; try { JarEntry entry; InputStream inputStream = pageContext.getServletContext().getResourceAsStream(I18NRESOURCE_PATH); jarStream = new JarInputStream(inputStream); while ((entry = jarStream.getNextJarEntry()) != null) { String name = entry.getName(); if (!entry.isDirectory() && name.startsWith(I18NRESOURCE_PREFIX) && name.endsWith(I18NRESOURCE_SUFFIX)) { name = name.substring(I18NRESOURCE_PREFIX.length(), name.lastIndexOf(I18NRESOURCE_SUFFIX)); Locale locale = new Locale(name.substring(0, 2), ((name.indexOf("_") == -1) ? "" : name.substring(3, 5))); String defaultLanguage = ""; if (clientLanguage.startsWith(name)) { defaultLanguage = LocaleSupport.getLocalizedMessage(pageContext, I18NDEFAULT_LOCALE); } resultMap.put(name, locale.getDisplayName(locale) + " " + defaultLanguage); } } } catch (IOException ioe) { if (log.isDebugEnabled()) log.debug("Could not search jar file '" + I18NRESOURCE_PATH + "'for properties files due to an IOException: \n" + ioe.getMessage()); } finally { if (jarStream != null) { try { jarStream.close(); } catch (IOException e) { } } } return resultMap; }
From source file:org.jahia.utils.maven.plugin.osgi.BuildFrameworkPackageListMojo.java
private void scanJar(Map<String, Map<String, Map<String, VersionLocation>>> packageVersionCounts, File jarFile, String defaultVersion) throws IOException { JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jarFile)); Manifest jarManifest = jarInputStream.getManifest(); // Map<String, String> manifestVersions = new HashMap<String,String>(); String specificationVersion = null; if (jarManifest == null) { getLog().warn("No MANIFEST.MF file found for dependency " + jarFile); } else {//w ww . ja v a 2s. c om if (jarManifest.getMainAttributes() == null) { getLog().warn("No main attributes found in MANIFEST.MF file found for dependency " + jarFile); } else { specificationVersion = jarManifest.getMainAttributes().getValue("Specification-Version"); if (defaultVersion == null) { if (jarManifest.getMainAttributes().getValue("Bundle-Version") != null) { } else if (specificationVersion != null) { defaultVersion = specificationVersion; } else { defaultVersion = jarManifest.getMainAttributes().getValue("Implementation-Version"); } } String exportPackageHeaderValue = jarManifest.getMainAttributes().getValue("Export-Package"); if (exportPackageHeaderValue != null) { ManifestElement[] manifestElements = new ManifestElement[0]; try { manifestElements = ManifestElement.parseHeader("Export-Package", exportPackageHeaderValue); } catch (BundleException e) { getLog().warn("Error while parsing Export-Package header value for jar " + jarFile, e); } for (ManifestElement manifestElement : manifestElements) { String[] packageNames = manifestElement.getValueComponents(); String version = manifestElement.getAttribute("version"); for (String packageName : packageNames) { updateVersionLocationCounts(packageVersionCounts, jarFile.getCanonicalPath(), version, version, packageName); } } } for (Map.Entry<String, Attributes> manifestEntries : jarManifest.getEntries().entrySet()) { String packageName = manifestEntries.getKey().replaceAll("/", "."); if (packageName.endsWith(".class")) { continue; } if (packageName.endsWith(".")) { packageName = packageName.substring(0, packageName.length() - 1); } if (packageName.endsWith(".*")) { packageName = packageName.substring(0, packageName.length() - 1); } int lastDotPos = packageName.lastIndexOf("."); String lastPackage = packageName; if (lastDotPos > -1) { lastPackage = packageName.substring(lastDotPos + 1); } if (lastPackage.length() > 0 && Character.isUpperCase(lastPackage.charAt(0))) { // ignore non package version continue; } if (StringUtils.isEmpty(packageName) || packageName.startsWith("META-INF") || packageName.startsWith("OSGI-INF") || packageName.startsWith("OSGI-OPT") || packageName.startsWith("WEB-INF") || packageName.startsWith("org.osgi")) { // ignore private package names continue; } String packageVersion = null; if (manifestEntries.getValue().getValue("Specification-Version") != null) { packageVersion = manifestEntries.getValue().getValue("Specification-Version"); } else { packageVersion = manifestEntries.getValue().getValue("Implementation-Version"); } if (packageVersion != null) { getLog().info("Found package version in " + jarFile.getName() + " MANIFEST : " + packageName + " v" + packageVersion); updateVersionLocationCounts(packageVersionCounts, jarFile.getCanonicalPath(), packageVersion, specificationVersion, packageName); // manifestVersions.put(packageName, packageVersion); } } } } JarEntry jarEntry = null; // getLog().debug("Processing file " + artifact.getFile() + "..."); while ((jarEntry = jarInputStream.getNextJarEntry()) != null) { if (!jarEntry.isDirectory()) { String entryName = jarEntry.getName(); String entryPackage = ""; int lastSlash = entryName.lastIndexOf("/"); if (lastSlash > -1) { entryPackage = entryName.substring(0, lastSlash); entryPackage = entryPackage.replaceAll("/", "."); if (StringUtils.isNotEmpty(entryPackage) && !entryPackage.startsWith("META-INF") && !entryPackage.startsWith("OSGI-INF") && !entryPackage.startsWith("OSGI-OPT") && !entryPackage.startsWith("WEB-INF") && !entryPackage.startsWith("org.osgi")) { updateVersionLocationCounts(packageVersionCounts, jarFile.getCanonicalPath(), defaultVersion, specificationVersion, entryPackage); } } } } jarInputStream.close(); }
From source file:org.jahia.utils.maven.plugin.osgi.DependenciesMojo.java
protected int processJarInputStream(String jarFilePath, boolean externalDependency, String packageDirectory, String version, boolean optional, ParsingContext parsingContext, String logPrefix, int scanned, JarInputStream jarInputStream) throws IOException { JarEntry jarEntry; while ((jarEntry = jarInputStream.getNextJarEntry()) != null) { if (jarEntry.isDirectory()) { continue; }/*w ww. j a v a 2s.c o m*/ String entryName = jarEntry.getName(); if (entryName.startsWith(packageDirectory)) { String packageName = entryName.substring(packageDirectory.length()); if (!packageName.contains("/.")) { processLocalPackageEntry(packageName, "/", jarFilePath, version, optional, parsingContext); } } if (excludeJarEntry(entryName)) { continue; } ByteArrayOutputStream entryOutputStream = new ByteArrayOutputStream(); IOUtils.copy(jarInputStream, entryOutputStream); if (Parsers.getInstance().canParseForPhase(0, jarEntry.getName())) { getLog().debug(logPrefix + " scanning JAR entry: " + jarEntry.getName()); Parsers.getInstance().parse(0, jarEntry.getName(), new ByteArrayInputStream(entryOutputStream.toByteArray()), jarFilePath, externalDependency, optional, version, getLogger(), parsingContext); scanned++; } if (Parsers.getInstance().canParseForPhase(1, jarEntry.getName())) { getLog().debug(logPrefix + " scanning JAR entry: " + jarEntry.getName()); if (processNonTldFile(jarEntry.getName(), new ByteArrayInputStream(entryOutputStream.toByteArray()), jarFilePath, optional, version, parsingContext)) { scanned++; } } } return scanned; }
From source file:UnpackedJarFile.java
public Manifest getManifest() throws IOException { if (isClosed) { throw new IllegalStateException("NestedJarFile is closed"); }//from www.ja v a 2s . c o m if (!manifestLoaded) { JarEntry manifestEntry = getBaseEntry("META-INF/MANIFEST.MF"); if (manifestEntry != null && !manifestEntry.isDirectory()) { InputStream in = null; try { in = baseJar.getInputStream(manifestEntry); manifest = new Manifest(in); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore } } } } manifestLoaded = true; } return manifest; }
From source file:org.apache.openejb.config.DeploymentLoader.java
public static Map<String, URL> getWebDescriptors(final File warFile) throws IOException { final Map<String, URL> descriptors = new TreeMap<String, URL>(); // xbean resource finder has a bug when you use any uri but "META-INF" // and the jar file does not contain a directory entry for the uri if (warFile.isFile()) { // only to discover module type so xml file filtering is enough final URL jarURL = new URL("jar", "", -1, warFile.toURI().toURL() + "!/"); try {//from w w w. ja va 2s. c o m final JarFile jarFile = new JarFile(warFile); for (final JarEntry entry : Collections.list(jarFile.entries())) { final String entryName = entry.getName(); if (!entry.isDirectory() && entryName.startsWith("WEB-INF/") && (KNOWN_DESCRIPTORS.contains(entryName.substring("WEB-INF/".length())) || entryName.endsWith(".xml"))) { // + web.xml, web-fragment.xml... descriptors.put(entryName, new URL(jarURL, entry.getName())); } } } catch (final IOException e) { // most likely an invalid jar file } } else if (warFile.isDirectory()) { final File webInfDir = new File(warFile, "WEB-INF"); if (webInfDir.isDirectory()) { final File[] files = webInfDir.listFiles(); if (files != null) { for (final File file : files) { if (!file.isDirectory()) { descriptors.put(file.getName(), file.toURI().toURL()); } } } } // handle some few file(s) which can be in META-INF too final File webAppDdDir = new File(webInfDir, "classes/" + ddDir); if (webAppDdDir.isDirectory()) { final File[] files = webAppDdDir.listFiles(); if (files != null) { for (final File file : files) { final String name = file.getName(); if (!descriptors.containsKey(name)) { descriptors.put(name, file.toURI().toURL()); } else { logger.warning("Can't have a " + name + " in WEB-INF and WEB-INF/classes/META-INF, second will be ignored"); } } } } } return descriptors; }
From source file:org.kitodo.serviceloader.KitodoServiceLoader.java
/** * Loads bean classes and registers them to the FacesContext. Afterwards * they can be used in all frontend files */// w w w . ja va 2s. co m private void loadBeans() { Path moduleFolder = FileSystems.getDefault().getPath(modulePath); try (DirectoryStream<Path> stream = Files.newDirectoryStream(moduleFolder, JAR)) { for (Path f : stream) { try (JarFile jarFile = new JarFile(f.toString())) { if (hasFrontendFiles(jarFile)) { Enumeration<JarEntry> e = jarFile.entries(); URL[] urls = { new URL("jar:file:" + f.toString() + "!/") }; try (URLClassLoader cl = URLClassLoader.newInstance(urls)) { while (e.hasMoreElements()) { JarEntry je = e.nextElement(); /* * IMPORTANT: Naming convention: the name of the * java class has to be in upper camel case or * "pascal case" and must be equal to the file * name of the corresponding facelet file * concatenated with the word "Form". * * Example: template filename "sample.xhtml" => * "SampleForm.java" * * That is the reason for the following check * (e.g. whether the JarEntry name ends with * "Form.class") */ if (je.isDirectory() || !je.getName().endsWith("Form.class")) { continue; } String className = je.getName().substring(0, je.getName().length() - 6); className = className.replace('/', '.'); Class c = cl.loadClass(className); String beanName = className.substring(className.lastIndexOf('.') + 1).trim(); FacesContext facesContext = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) facesContext.getExternalContext() .getSession(false); session.getServletContext().setAttribute(beanName, c.newInstance()); } } } } } } catch (Exception e) { logger.error(ERROR, e.getMessage()); } }