List of usage examples for java.util.jar JarEntry getName
public String getName()
From source file:org.orbisgis.framework.BundleTools.java
private static void parseJar(File jarFilePath, Set<String> packages) throws IOException { try (JarFile jar = new JarFile(jarFilePath)) { Enumeration<? extends JarEntry> entryEnum = jar.entries(); while (entryEnum.hasMoreElements()) { JarEntry entry = entryEnum.nextElement(); if (!entry.isDirectory()) { final String path = entry.getName(); if (path.endsWith(".class")) { // Extract folder String parentPath = (new File(path)).getParent(); if (parentPath != null) { packages.add(parentPath.replace(File.separator, ".")); }//from w w w . ja v a 2s .co m } } } } }
From source file:org.lpe.common.util.system.LpeSystemUtils.java
/** * Extracts a file/folder identified by the URL that resides in the * classpath, into the destiation folder. * //from w ww. ja v a 2s .c o m * @param url * URL of the JAR file * @param dirOfInterest * the name of the directory of interest * @param dest * destination folder * * @throws IOException * ... * @throws URISyntaxException * ... */ public static void extractJARtoTemp(URL url, String dirOfInterest, String dest) throws IOException, URISyntaxException { if (!url.getProtocol().equals("jar")) { throw new IllegalArgumentException("Cannot locate the JAR file."); } // create a temp lib directory File tempJarDirFile = new File(dest); if (!tempJarDirFile.exists()) { boolean ok = tempJarDirFile.mkdir(); if (!ok) { logger.warn("Could not create directory {}", tempJarDirFile.getAbsolutePath()); } } else { FileUtils.cleanDirectory(tempJarDirFile); } String urlStr = url.getFile(); // if (urlStr.startsWith("jar:file:") || urlStr.startsWith("jar:") || // urlStr.startsWith("file:")) { // urlStr = urlStr.replaceFirst("jar:", ""); // urlStr = urlStr.replaceFirst("file:", ""); // } if (urlStr.contains("!")) { final int endIndex = urlStr.indexOf("!"); urlStr = urlStr.substring(0, endIndex); } URI uri = new URI(urlStr); final File jarFile = new File(uri); logger.debug("Unpacking jar file {}...", jarFile.getAbsolutePath()); java.util.jar.JarFile jar = null; InputStream is = null; OutputStream fos = null; try { jar = new JarFile(jarFile); java.util.Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { java.util.jar.JarEntry file = (JarEntry) entries.nextElement(); String destFileName = dest + File.separator + file.getName(); if (destFileName.indexOf(dirOfInterest + File.separator) < 0 && destFileName.indexOf(dirOfInterest + "/") < 0) { continue; } logger.debug("unpacking {}...", file.getName()); java.io.File f = new java.io.File(destFileName); if (file.isDirectory()) { // if its a directory, create it boolean ok = f.mkdir(); if (!ok) { logger.warn("Could not create directory {}", f.getAbsolutePath()); } continue; } is = new BufferedInputStream(jar.getInputStream(file)); fos = new BufferedOutputStream(new FileOutputStream(f)); LpeStreamUtils.pipe(is, fos); } logger.debug("Unpacking jar file done."); } catch (IOException e) { throw e; } finally { if (jar != null) { jar.close(); } if (fos != null) { fos.close(); } if (is != null) { is.close(); } } }
From source file:org.apache.hadoop.streaming.StreamUtil.java
static void unJar(File jarFile, File toDir) throws IOException { JarFile jar = new JarFile(jarFile); try {/*w w w .j av a 2 s . c o m*/ Enumeration entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry) entries.nextElement(); if (!entry.isDirectory()) { InputStream in = jar.getInputStream(entry); try { File file = new File(toDir, entry.getName()); file.getParentFile().mkdirs(); OutputStream out = new FileOutputStream(file); try { byte[] buffer = new byte[8192]; int i; while ((i = in.read(buffer)) != -1) { out.write(buffer, 0, i); } } finally { out.close(); } } finally { in.close(); } } } } finally { jar.close(); } }
From source file:com.icesoft.faces.webapp.parser.JspPageToDocument.java
static String[] scanJar(JarURLConnection conn, String namespaceURL) throws IOException { JarFile jarFile = null;//from w w w . j a v a 2s . co m String resourcePath = conn.getJarFileURL().toString(); if (log.isTraceEnabled()) { log.trace("Fallback Scanning Jar " + resourcePath); } jarFile = conn.getJarFile(); Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { try { JarEntry entry = (JarEntry) entries.nextElement(); String name = entry.getName(); if (!name.startsWith("META-INF/")) { continue; } if (!name.endsWith(".tld")) { continue; } InputStream stream = jarFile.getInputStream(entry); try { String uri = getUriFromTld(resourcePath, stream); if ((uri != null) && (uri.equals(namespaceURL))) { return (new String[] { resourcePath, name }); } } catch (JasperException jpe) { if (log.isDebugEnabled()) { log.debug(jpe.getMessage(), jpe); } } finally { if (stream != null) { stream.close(); } } } catch (Throwable t) { if (log.isDebugEnabled()) { log.debug(t.getMessage(), t); } } } return null; }
From source file:eu.trentorise.opendata.josman.Josmans.java
/** * * Extracts the files starting with dirPath from {@code file} to * {@code destDir}/*w ww . j a va 2 s .c om*/ * * @param dirPath the prefix used for filtering. If empty the whole jar * content is extracted. */ public static void copyDirFromJar(File jarFile, File destDir, String dirPath) { checkNotNull(jarFile); checkNotNull(destDir); checkNotNull(dirPath); String normalizedDirPath; if (dirPath.startsWith("/")) { normalizedDirPath = dirPath.substring(1); } else { normalizedDirPath = dirPath; } try { JarFile jar = new JarFile(jarFile); java.util.Enumeration enumEntries = jar.entries(); while (enumEntries.hasMoreElements()) { JarEntry jarEntry = (JarEntry) enumEntries.nextElement(); if (jarEntry.getName().startsWith(normalizedDirPath)) { File f = new File( destDir + File.separator + jarEntry.getName().substring(normalizedDirPath.length())); if (jarEntry.isDirectory()) { // if its a directory, create it f.mkdirs(); continue; } else { f.getParentFile().mkdirs(); } InputStream is = jar.getInputStream(jarEntry); // get the input stream FileOutputStream fos = new FileOutputStream(f); IOUtils.copy(is, fos); fos.close(); is.close(); } } } catch (Exception ex) { throw new RuntimeException("Error while extracting jar file! Jar source: " + jarFile.getAbsolutePath() + " destDir = " + destDir.getAbsolutePath(), ex); } }
From source file:com.zb.jcseg.core.JcsegTaskConfig.java
public static void unJar(JarFile jar, File toDir) throws IOException { try {/*from w w w .j a v a 2 s. c om*/ Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry) entries.nextElement(); if (!entry.isDirectory()) { InputStream in = jar.getInputStream(entry); try { File file = new File(toDir, 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 = in.read(buffer)) != -1) { out.write(buffer, 0, i); } } finally { out.close(); } } finally { in.close(); } } } } finally { jar.close(); } }
From source file:com.taobao.android.builder.tools.proguard.AtlasProguardHelper.java
public static Set<String> getClassList(List<File> files) throws IOException { Set<String> sets = new HashSet<>(); for (File file : files) { JarFile jarFile = new JarFile(file); Enumeration<JarEntry> entryEnumeration = jarFile.entries(); while (entryEnumeration.hasMoreElements()) { JarEntry jarEntry = entryEnumeration.nextElement(); if (null == jarEntry) { continue; }//from ww w. ja v a 2 s. c o m String name = jarEntry.getName(); if (name.endsWith(".class")) { name = name.substring(0, name.length() - 6); sets.add(name); } } } return sets; }
From source file:com.arcusys.liferay.vaadinplugin.util.ControlPanelPortletUtil.java
/** * Extracts the jarEntry from the jarFile to the target directory. * * @param jarFile/*from w w w. j a v a 2s. c o m*/ * @param jarEntry * @param targetDir * @return true if extraction was successful, false otherwise */ public static boolean extractJarEntry(JarFile jarFile, JarEntry jarEntry, String targetDir) { boolean extractSuccessful = false; File file = new File(targetDir); if (!file.exists()) { file.mkdir(); } if (jarEntry != null) { InputStream inputStream = null; try { inputStream = jarFile.getInputStream(jarEntry); file = new File(targetDir + jarEntry.getName()); if (jarEntry.isDirectory()) { file.mkdir(); } else { int size; byte[] buffer = new byte[2048]; FileOutputStream fileOutputStream = new FileOutputStream(file); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream, buffer.length); try { while ((size = inputStream.read(buffer, 0, buffer.length)) != -1) { bufferedOutputStream.write(buffer, 0, size); } bufferedOutputStream.flush(); } finally { bufferedOutputStream.close(); } } extractSuccessful = true; } catch (Exception e) { log.warn(e); } finally { close(inputStream); } } return extractSuccessful; }
From source file:org.mrgeo.utils.DependencyLoader.java
private static Set<Dependency> loadDependenciesFromJar(final String jarname) throws IOException { try {//from w w w . jav a2s .c o m String jar = jarname; URL url; JarURLConnection conn; try { url = new URL(jar); conn = (JarURLConnection) url.openConnection(); } catch (MalformedURLException e) { jar = (new File(jar)).toURI().toString(); if (!jar.startsWith("jar:")) { jar = "jar:" + jar; } if (!jar.contains("!/")) { jar += "!/"; } url = new URL(jar); conn = (JarURLConnection) url.openConnection(); } log.debug("Looking in " + jar + " for dependency file"); JarFile jf = conn.getJarFile(); for (Enumeration<JarEntry> i = jf.entries(); i.hasMoreElements();) { JarEntry je = i.nextElement(); String name = je.getName(); if (name.endsWith("dependencies.properties")) { log.debug("Found dependency for " + jar + " -> " + name); URL resource = new URL(jar + name); InputStream is = resource.openStream(); Set<Dependency> deps = readDependencies(is); is.close(); return deps; } } } catch (IOException e) { e.printStackTrace(); throw new IOException("Error Loading dependency properties file", e); } throw new IOException("No dependency properties file found in " + jarname); }
From source file:org.infoglue.deliver.portal.deploy.Deploy.java
/** * Prepare a portlet according to Pluto (switch web.xml) * //from w w w.j a va 2 s .c om * @param file .war to prepare * @param tmp the resulting updated .war * @param appName name of application (context name) * @return the portlet application definition (portlet.xml) * @throws IOException */ public static PortletApplicationDefinition prepareArchive(File file, File tmp, String appName) throws IOException { PortletApplicationDefinitionImpl portletApp = null; try { Mapping pdmXml = new Mapping(); try { URL url = Deploy.class.getResource("/" + PORTLET_MAPPING); pdmXml.loadMapping(url); } catch (Exception e) { throw new IOException("Failed to load mapping file " + PORTLET_MAPPING); } // Open the jar file. JarFile jar = new JarFile(file); // Extract and parse portlet.xml ZipEntry portletEntry = jar.getEntry(PORTLET_XML); if (portletEntry == null) { throw new IOException("Unable to find portlet.xml"); } InputStream pisDebug = jar.getInputStream(portletEntry); StringBuffer sb = new StringBuffer(); int i; while ((i = pisDebug.read()) > -1) { sb.append((char) i); } pisDebug.close(); InputSource xmlSource = new InputSource(new ByteArrayInputStream(sb.toString().getBytes("UTF-8"))); DOMParser parser = new DOMParser(); parser.parse(xmlSource); Document portletDocument = parser.getDocument(); //InputStream pis = jar.getInputStream(portletEntry); //Document portletDocument = XmlParser.parsePortletXml(pis); //pis.close(); InputStream pis = jar.getInputStream(portletEntry); ZipEntry webEntry = jar.getEntry(WEB_XML); InputStream wis = null; if (webEntry != null) { wis = jar.getInputStream(webEntry); /* webDocument = XmlParser.parseWebXml(wis); wis.close(); */ } Unmarshaller unmarshaller = new Unmarshaller(pdmXml); unmarshaller.setWhitespacePreserve(true); unmarshaller.setIgnoreExtraElements(true); unmarshaller.setIgnoreExtraAttributes(true); portletApp = (PortletApplicationDefinitionImpl) unmarshaller.unmarshal(portletDocument); // refill structure with necessary information Vector structure = new Vector(); structure.add(appName); structure.add(null); structure.add(null); portletApp.preBuild(structure); /* // now generate web part WebApplicationDefinitionImpl webApp = null; if (webDocument != null) { Unmarshaller unmarshallerWeb = new Unmarshaller(sdmXml); // modified by YCLI: START :: to ignore extra elements and // attributes unmarshallerWeb.setWhitespacePreserve(true); unmarshallerWeb.setIgnoreExtraElements(true); unmarshallerWeb.setIgnoreExtraAttributes(true); // modified by YCLI: END webApp = (WebApplicationDefinitionImpl) unmarshallerWeb.unmarshal(webDocument); } else { webApp = new WebApplicationDefinitionImpl(); DisplayNameImpl dispName = new DisplayNameImpl(); dispName.setDisplayName(appName); dispName.setLocale(Locale.ENGLISH); DisplayNameSetImpl dispSet = new DisplayNameSetImpl(); dispSet.add(dispName); webApp.setDisplayNames(dispSet); DescriptionImpl desc = new DescriptionImpl(); desc.setDescription("Automated generated Application Wrapper"); desc.setLocale(Locale.ENGLISH); DescriptionSetImpl descSet = new DescriptionSetImpl(); descSet.add(desc); webApp.setDescriptions(descSet); } org.apache.pluto.om.ControllerFactory controllerFactory = new org.apache.pluto.portalImpl.om.ControllerFactoryImpl(); ServletDefinitionListCtrl servletDefinitionSetCtrl = (ServletDefinitionListCtrl) controllerFactory .get(webApp.getServletDefinitionList()); Collection servletMappings = webApp.getServletMappings(); Iterator portlets = portletApp.getPortletDefinitionList().iterator(); while (portlets.hasNext()) { PortletDefinition portlet = (PortletDefinition) portlets.next(); // check if already exists ServletDefinition servlet = webApp.getServletDefinitionList() .get(portlet.getName()); if (servlet != null) { ServletDefinitionCtrl _servletCtrl = (ServletDefinitionCtrl) controllerFactory .get(servlet); _servletCtrl.setServletClass("org.apache.pluto.core.PortletServlet"); } else { servlet = servletDefinitionSetCtrl.add(portlet.getName(), "org.apache.pluto.core.PortletServlet"); } ServletDefinitionCtrl servletCtrl = (ServletDefinitionCtrl) controllerFactory .get(servlet); DisplayNameImpl dispName = new DisplayNameImpl(); dispName.setDisplayName(portlet.getName() + " Wrapper"); dispName.setLocale(Locale.ENGLISH); DisplayNameSetImpl dispSet = new DisplayNameSetImpl(); dispSet.add(dispName); servletCtrl.setDisplayNames(dispSet); DescriptionImpl desc = new DescriptionImpl(); desc.setDescription("Automated generated Portlet Wrapper"); desc.setLocale(Locale.ENGLISH); DescriptionSetImpl descSet = new DescriptionSetImpl(); descSet.add(desc); servletCtrl.setDescriptions(descSet); ParameterSet parameters = servlet.getInitParameterSet(); ParameterSetCtrl parameterSetCtrl = (ParameterSetCtrl) controllerFactory .get(parameters); Parameter parameter1 = parameters.get("portlet-class"); if (parameter1 == null) { parameterSetCtrl.add("portlet-class", portlet.getClassName()); } else { ParameterCtrl parameterCtrl = (ParameterCtrl) controllerFactory.get(parameter1); parameterCtrl.setValue(portlet.getClassName()); } Parameter parameter2 = parameters.get("portlet-guid"); if (parameter2 == null) { parameterSetCtrl.add("portlet-guid", portlet.getId().toString()); } else { ParameterCtrl parameterCtrl = (ParameterCtrl) controllerFactory.get(parameter2); parameterCtrl.setValue(portlet.getId().toString()); } boolean found = false; Iterator mappings = servletMappings.iterator(); while (mappings.hasNext()) { ServletMappingImpl servletMapping = (ServletMappingImpl) mappings.next(); if (servletMapping.getServletName().equals(portlet.getName())) { found = true; servletMapping.setUrlPattern("/" + portlet.getName().replace(' ', '_') + "/*"); } } if (!found) { ServletMappingImpl servletMapping = new ServletMappingImpl(); servletMapping.setServletName(portlet.getName()); servletMapping.setUrlPattern("/" + portlet.getName().replace(' ', '_') + "/*"); servletMappings.add(servletMapping); } SecurityRoleRefSet servletSecurityRoleRefs = ((ServletDefinitionImpl) servlet) .getInitSecurityRoleRefSet(); SecurityRoleRefSetCtrl servletSecurityRoleRefSetCtrl = (SecurityRoleRefSetCtrl) controllerFactory .get(servletSecurityRoleRefs); SecurityRoleSet webAppSecurityRoles = webApp.getSecurityRoles(); SecurityRoleRefSet portletSecurityRoleRefs = portlet.getInitSecurityRoleRefSet(); Iterator p = portletSecurityRoleRefs.iterator(); while (p.hasNext()) { SecurityRoleRef portletSecurityRoleRef = (SecurityRoleRef) p.next(); if (portletSecurityRoleRef.getRoleLink() == null && webAppSecurityRoles.get(portletSecurityRoleRef.getRoleName()) == null) { logger.info("Note: The web application has no security role defined which matches the role name \"" + portletSecurityRoleRef.getRoleName() + "\" of the security-role-ref element defined for the wrapper-servlet with the name '" + portlet.getName() + "'."); break; } SecurityRoleRef servletSecurityRoleRef = servletSecurityRoleRefs .get(portletSecurityRoleRef.getRoleName()); if (null != servletSecurityRoleRef) { logger.info("Note: Replaced already existing element of type <security-role-ref> with value \"" + portletSecurityRoleRef.getRoleName() + "\" for subelement of type <role-name> for the wrapper-servlet with the name '" + portlet.getName() + "'."); servletSecurityRoleRefSetCtrl.remove(servletSecurityRoleRef); } servletSecurityRoleRefSetCtrl.add(portletSecurityRoleRef); } } */ /* * TODO is this necessary? TagDefinitionImpl portletTagLib = new * TagDefinitionImpl(); Collection taglibs = * webApp.getCastorTagDefinitions(); taglibs.add(portletTagLib); */ // Duplicate jar-file with replaced web.xml FileOutputStream fos = new FileOutputStream(tmp); JarOutputStream tempJar = new JarOutputStream(fos); byte[] buffer = new byte[1024]; int bytesRead; for (Enumeration entries = jar.entries(); entries.hasMoreElements();) { JarEntry entry = (JarEntry) entries.nextElement(); JarEntry newEntry = new JarEntry(entry.getName()); tempJar.putNextEntry(newEntry); if (entry.getName().equals(WEB_XML)) { // Swap web.xml /* log.debug("Swapping web.xml"); OutputFormat of = new OutputFormat(); of.setIndenting(true); of.setIndent(4); // 2-space indention of.setLineWidth(16384); of.setDoctype(Constants.WEB_PORTLET_PUBLIC_ID, Constants.WEB_PORTLET_DTD); XMLSerializer serializer = new XMLSerializer(tempJar, of); Marshaller marshaller = new Marshaller(serializer.asDocumentHandler()); marshaller.setMapping(sdmXml); marshaller.marshal(webApp); */ PortletAppDescriptorService portletAppDescriptorService = new StreamPortletAppDescriptorServiceImpl( appName, pis, null); File tmpf = File.createTempFile("infoglue-web-xml", null); WebAppDescriptorService webAppDescriptorService = new StreamWebAppDescriptorServiceImpl(appName, wis, new FileOutputStream(tmpf)); org.apache.pluto.driver.deploy.Deploy d = new org.apache.pluto.driver.deploy.Deploy( webAppDescriptorService, portletAppDescriptorService); d.updateDescriptors(); FileInputStream fis = new FileInputStream(tmpf); while ((bytesRead = fis.read(buffer)) != -1) { tempJar.write(buffer, 0, bytesRead); } tmpf.delete(); } else { InputStream entryStream = jar.getInputStream(entry); if (entryStream != null) { while ((bytesRead = entryStream.read(buffer)) != -1) { tempJar.write(buffer, 0, bytesRead); } } } } tempJar.flush(); tempJar.close(); fos.flush(); fos.close(); /* * String strTo = dirDelim + "WEB-INF" + dirDelim + "tld" + dirDelim + * "portlet.tld"; String strFrom = "webapps" + dirDelim + strTo; * * copy(strFrom, webAppsDir + webModule + strTo); */ } catch (Exception e) { log.error("Failed to prepare archive", e); throw new IOException(e.getMessage()); } return portletApp; }