List of usage examples for java.util.jar JarEntry isDirectory
public boolean isDirectory()
From source file:org.kitodo.serviceloader.KitodoServiceLoader.java
/** * Checks, whether a passed jarFile has frontend files or not. Returns true, * when the jar contains a folder with the name "resources". * * @param jarPath/*w w w.j a va2s . c o m*/ * jarFile that will be checked for frontend files * @param destinationFolder * destination path, where the frontend files will be extracted * to * */ private void extractFrontEndFiles(String jarPath, File destinationFolder) throws IOException { if (!destinationFolder.exists()) { destinationFolder.mkdir(); } try (JarFile jar = new JarFile(jarPath)) { Enumeration jarEntries = jar.entries(); while (jarEntries.hasMoreElements()) { JarEntry currentJarEntry = (JarEntry) jarEntries.nextElement(); if (currentJarEntry.getName().contains(RESOURCES_FOLDER) || currentJarEntry.getName().contains(POM_PROPERTIES_FILE)) { File resourceFile = new File(destinationFolder + File.separator + currentJarEntry.getName()); if (currentJarEntry.isDirectory()) { resourceFile.mkdirs(); continue; } if (currentJarEntry.getName().contains(POM_PROPERTIES_FILE)) { resourceFile.getParentFile().mkdirs(); } try (InputStream is = jar.getInputStream(currentJarEntry); FileOutputStream fos = new FileOutputStream(resourceFile)) { while (is.available() > 0) { fos.write(is.read()); } } } } } }
From source file:com.slamd.admin.JobPack.java
/** * Extracts the contents of the job pack and registers the included jobs with * the SLAMD server.//from w w w . j a v a2 s .co m * * @throws SLAMDServerException If a problem occurs while processing the job * pack JAR file. */ public void processJobPack() throws SLAMDServerException { byte[] fileData = null; File tempFile = null; String fileName = null; String separator = System.getProperty("file.separator"); if (filePath == null) { // First, get the request and ensure it is multipart content. HttpServletRequest request = requestInfo.request; if (!FileUpload.isMultipartContent(request)) { throw new SLAMDServerException("Request does not contain multipart " + "content"); } // Iterate through the request fields to get to the file data. Iterator iterator = fieldList.iterator(); while (iterator.hasNext()) { FileItem fileItem = (FileItem) iterator.next(); String fieldName = fileItem.getFieldName(); if (fieldName.equals(Constants.SERVLET_PARAM_JOB_PACK_FILE)) { fileData = fileItem.get(); fileName = fileItem.getName(); } } // Make sure that a file was actually uploaded. if (fileData == null) { throw new SLAMDServerException("No file data was found in the " + "request."); } // Write the JAR file data to a temp file, since that's the only way we // can parse it. if (separator == null) { separator = "/"; } tempFile = new File(jobClassDirectory + separator + fileName); try { FileOutputStream outputStream = new FileOutputStream(tempFile); outputStream.write(fileData); outputStream.flush(); outputStream.close(); } catch (IOException ioe) { try { tempFile.delete(); } catch (Exception e) { } ioe.printStackTrace(); slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe)); throw new SLAMDServerException("I/O error writing temporary JAR " + "file: " + ioe, ioe); } } else { tempFile = new File(filePath); if ((!tempFile.exists()) || (!tempFile.isFile())) { throw new SLAMDServerException("Specified job pack file \"" + filePath + "\" does not exist"); } try { fileName = tempFile.getName(); int fileLength = (int) tempFile.length(); fileData = new byte[fileLength]; FileInputStream inputStream = new FileInputStream(tempFile); int bytesRead = 0; while (bytesRead < fileLength) { bytesRead += inputStream.read(fileData, bytesRead, fileLength - bytesRead); } inputStream.close(); } catch (Exception e) { slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(e)); throw new SLAMDServerException("Error reading job pack file \"" + filePath + "\" -- " + e, e); } } StringBuilder htmlBody = requestInfo.htmlBody; // Parse the jar file JarFile jarFile = null; Manifest manifest = null; Enumeration jarEntries = null; try { jarFile = new JarFile(tempFile, true); manifest = jarFile.getManifest(); jarEntries = jarFile.entries(); } catch (IOException ioe) { try { if (filePath == null) { tempFile.delete(); } } catch (Exception e) { } ioe.printStackTrace(); slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe)); throw new SLAMDServerException("Unable to parse the JAR file: " + ioe, ioe); } ArrayList<String> dirList = new ArrayList<String>(); ArrayList<String> fileNameList = new ArrayList<String>(); ArrayList<byte[]> fileDataList = new ArrayList<byte[]>(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = (JarEntry) jarEntries.nextElement(); String entryName = jarEntry.getName(); if (jarEntry.isDirectory()) { dirList.add(entryName); } else { try { int entrySize = (int) jarEntry.getSize(); byte[] entryData = new byte[entrySize]; InputStream inputStream = jarFile.getInputStream(jarEntry); extractFileData(inputStream, entryData); fileNameList.add(entryName); fileDataList.add(entryData); } catch (IOException ioe) { try { jarFile.close(); if (filePath == null) { tempFile.delete(); } } catch (Exception e) { } ioe.printStackTrace(); slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe)); throw new SLAMDServerException("I/O error parsing JAR entry " + entryName + " -- " + ioe, ioe); } catch (SLAMDServerException sse) { try { jarFile.close(); if (filePath == null) { tempFile.delete(); } } catch (Exception e) { } sse.printStackTrace(); throw sse; } } } // If we have gotten here, then we have read all the data from the JAR file. // Delete the temporary file to prevent possible (although unlikely) // conflicts with data contained in the JAR. try { jarFile.close(); if (filePath == null) { tempFile.delete(); } } catch (Exception e) { } // Create the directory structure specified in the JAR file. if (!dirList.isEmpty()) { htmlBody.append("<B>Created the following directories</B>" + Constants.EOL); htmlBody.append("<BR>" + Constants.EOL); htmlBody.append("<UL>" + Constants.EOL); for (int i = 0; i < dirList.size(); i++) { File dirFile = new File(jobClassDirectory + separator + dirList.get(i)); try { dirFile.mkdirs(); htmlBody.append(" <LI>" + dirFile.getAbsolutePath() + "</LI>" + Constants.EOL); } catch (Exception e) { htmlBody.append("</UL>" + Constants.EOL); e.printStackTrace(); slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(e)); throw new SLAMDServerException( "Unable to create directory \"" + dirFile.getAbsolutePath() + " -- " + e, e); } } htmlBody.append("</UL>" + Constants.EOL); htmlBody.append("<BR><BR>" + Constants.EOL); } // Write all the files to disk. If we have gotten this far, then there // should not be any failures, but if there are, then we will have to // leave things in a "dirty" state. if (!fileNameList.isEmpty()) { htmlBody.append("<B>Created the following files</B>" + Constants.EOL); htmlBody.append("<BR>" + Constants.EOL); htmlBody.append("<UL>" + Constants.EOL); for (int i = 0; i < fileNameList.size(); i++) { File dataFile = new File(jobClassDirectory + separator + fileNameList.get(i)); try { // Make sure the parent directory exists. dataFile.getParentFile().mkdirs(); } catch (Exception e) { } try { FileOutputStream outputStream = new FileOutputStream(dataFile); outputStream.write(fileDataList.get(i)); outputStream.flush(); outputStream.close(); htmlBody.append(" <LI>" + dataFile.getAbsolutePath() + "</LI>" + Constants.EOL); } catch (IOException ioe) { htmlBody.append("</UL>" + Constants.EOL); ioe.printStackTrace(); slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe)); throw new SLAMDServerException("Unable to write file " + dataFile.getAbsolutePath() + ioe, ioe); } } htmlBody.append("</UL>" + Constants.EOL); htmlBody.append("<BR><BR>" + Constants.EOL); } // Finally, parse the manifest to get the names of the classes that should // be registered with the SLAMD server. Attributes manifestAttributes = manifest.getMainAttributes(); Attributes.Name key = new Attributes.Name(Constants.JOB_PACK_MANIFEST_REGISTER_JOBS_ATTR); String registerClassesStr = (String) manifestAttributes.get(key); if ((registerClassesStr == null) || (registerClassesStr.length() == 0)) { htmlBody.append("<B>No job classes registered</B>" + Constants.EOL); } else { ArrayList<String> successList = new ArrayList<String>(); ArrayList<String> failureList = new ArrayList<String>(); StringTokenizer tokenizer = new StringTokenizer(registerClassesStr, ", \t\r\n"); while (tokenizer.hasMoreTokens()) { String className = tokenizer.nextToken(); try { JobClass jobClass = slamdServer.loadJobClass(className); slamdServer.addJobClass(jobClass); successList.add(className); } catch (Exception e) { failureList.add(className + ": " + e); } } if (!successList.isEmpty()) { htmlBody.append("<B>Registered Job Classes</B>" + Constants.EOL); htmlBody.append("<UL>" + Constants.EOL); for (int i = 0; i < successList.size(); i++) { htmlBody.append(" <LI>" + successList.get(i) + "</LI>" + Constants.EOL); } htmlBody.append("</UL>" + Constants.EOL); htmlBody.append("<BR><BR>" + Constants.EOL); } if (!failureList.isEmpty()) { htmlBody.append("<B>Unable to Register Job Classes</B>" + Constants.EOL); htmlBody.append("<UL>" + Constants.EOL); for (int i = 0; i < failureList.size(); i++) { htmlBody.append(" <LI>" + failureList.get(i) + "</LI>" + Constants.EOL); } htmlBody.append("</UL>" + Constants.EOL); htmlBody.append("<BR><BR>" + Constants.EOL); } } }
From source file:fr.gael.dhus.server.http.TomcatServer.java
public void install(WebApplication web_application) throws TomcatException { try {// w w w . j a v a 2 s .com String folder = web_application.getName() == "" ? "ROOT" : web_application.getName(); if (web_application.hasWarStream()) { InputStream stream = web_application.getWarStream(); if (stream == null) { throw new TomcatException("Cannot install WebApplication " + web_application.getName() + ". The referenced war " + "file does not exist."); } JarInputStream jis = new JarInputStream(stream); File destDir = new File(tomcatpath, "webapps/" + folder); byte[] buffer = new byte[4096]; JarEntry file; while ((file = jis.getNextJarEntry()) != null) { File f = new File(destDir + java.io.File.separator + file.getName()); if (file.isDirectory()) { // if its a directory, create it f.mkdirs(); continue; } if (!f.getParentFile().exists()) { f.getParentFile().mkdirs(); } java.io.FileOutputStream fos = new java.io.FileOutputStream(f); int read; while ((read = jis.read(buffer)) != -1) { fos.write(buffer, 0, read); } fos.flush(); fos.close(); } jis.close(); } web_application.configure(new File(tomcatpath, "webapps/" + folder).getPath()); StandardEngine engine = (StandardEngine) cat.getServer().findServices()[0].getContainer(); Container container = engine.findChild(engine.getDefaultHost()); StandardContext ctx = new StandardContext(); String url = (web_application.getName() == "" ? "" : "/") + web_application.getName(); ctx.setName(url); ctx.setPath(url); ctx.setDocBase(new File(tomcatpath, "webapps/" + folder).getPath()); ctx.addLifecycleListener(new DefaultWebXmlListener()); ctx.setConfigFile(getWebappConfigFile(new File(tomcatpath, "webapps/" + folder).getPath(), url)); ContextConfig ctxCfg = new ContextConfig(); ctx.addLifecycleListener(ctxCfg); ctxCfg.setDefaultWebXml("fr/gael/dhus/server/http/global-web.xml"); container.addChild(ctx); contexts.add(ctx); List<WebServlet> servlets = web_application.getServlets(); for (WebServlet servlet : servlets) { addServlet(ctx, servlet.getServletName(), servlet.getUrlPattern(), servlet.getServlet(), servlet.isLoadOnStartup()); } List<String> welcomeFiles = web_application.getWelcomeFiles(); for (String welcomeFile : welcomeFiles) { ctx.addWelcomeFile(welcomeFile); } if (web_application.getAllow() != null || web_application.getDeny() != null) { RemoteIpValve valve = new RemoteIpValve(); valve.setRemoteIpHeader("x-forwarded-for"); valve.setProxiesHeader("x-forwarded-by"); valve.setProtocolHeader("x-forwarded-proto"); ctx.addValve(valve); RemoteAddrValve valve_addr = new RemoteAddrValve(); valve_addr.setAllow(web_application.getAllow()); valve_addr.setDeny(web_application.getDeny()); ctx.addValve(valve_addr); } } catch (Exception e) { throw new TomcatException("Cannot install service", e); } }
From source file:fr.gael.dhus.server.http.TomcatServer.java
public void install(fr.gael.dhus.server.http.WebApplication web_application) throws TomcatException { logger.info("Installing webapp " + web_application); String appName = web_application.getName(); String folder;/*from w ww . ja v a 2s . co m*/ if (appName.trim().isEmpty()) { folder = "ROOT"; } else { folder = appName; } try { if (web_application.hasWarStream()) { InputStream stream = web_application.getWarStream(); if (stream == null) { throw new TomcatException("Cannot install webApplication " + web_application.getName() + ". The referenced war file does not exist."); } JarInputStream jis = new JarInputStream(stream); File destDir = new File(tomcatpath, "webapps/" + folder); byte[] buffer = new byte[4096]; JarEntry file; while ((file = jis.getNextJarEntry()) != null) { File f = new File(destDir + java.io.File.separator + file.getName()); if (file.isDirectory()) { // if its a directory, create it f.mkdirs(); continue; } if (!f.getParentFile().exists()) { f.getParentFile().mkdirs(); } java.io.FileOutputStream fos = new java.io.FileOutputStream(f); int read; while ((read = jis.read(buffer)) != -1) { fos.write(buffer, 0, read); } fos.flush(); fos.close(); } jis.close(); } web_application.configure(new File(tomcatpath, "webapps/" + folder).getPath()); StandardEngine engine = (StandardEngine) cat.getServer().findServices()[0].getContainer(); Container container = engine.findChild(engine.getDefaultHost()); StandardContext ctx = new StandardContext(); String url = (web_application.getName() == "" ? "" : "/") + web_application.getName(); ctx.setName(url); ctx.setPath(url); ctx.setDocBase(new File(tomcatpath, "webapps/" + folder).getPath()); ctx.addLifecycleListener(new DefaultWebXmlListener()); ctx.setConfigFile(getWebappConfigFile(new File(tomcatpath, "webapps/" + folder).getPath(), url)); ContextConfig ctxCfg = new ContextConfig(); ctx.addLifecycleListener(ctxCfg); ctxCfg.setDefaultWebXml("fr/gael/dhus/server/http/global-web.xml"); container.addChild(ctx); List<String> welcomeFiles = web_application.getWelcomeFiles(); for (String welcomeFile : welcomeFiles) { ctx.addWelcomeFile(welcomeFile); } if (web_application.getAllow() != null || web_application.getDeny() != null) { RemoteIpValve valve = new RemoteIpValve(); valve.setRemoteIpHeader("x-forwarded-for"); valve.setProxiesHeader("x-forwarded-by"); valve.setProtocolHeader("x-forwarded-proto"); ctx.addValve(valve); RemoteAddrValve valve_addr = new RemoteAddrValve(); valve_addr.setAllow(web_application.getAllow()); valve_addr.setDeny(web_application.getDeny()); ctx.addValve(valve_addr); } web_application.checkInstallation(); } catch (Exception e) { throw new TomcatException("Cannot install webApplication " + web_application.getName(), e); } }
From source file:org.drools.guvnor.server.RepositoryPackageService.java
private JarInputStream typesForModel(List<String> res, AssetItem asset) throws IOException { JarInputStream jis;/*from w w w . j a v a 2 s . c o m*/ jis = new JarInputStream(asset.getBinaryContentAttachment()); JarEntry entry = null; while ((entry = jis.getNextJarEntry()) != null) { if (!entry.isDirectory()) { if (entry.getName().endsWith(".class")) { res.add(ModelContentHandler.convertPathToName(entry.getName())); } } } return jis; }
From source file:org.apache.sling.osgi.obr.Repository.java
File spoolModified(InputStream ins) throws IOException { JarInputStream jis = new JarInputStream(ins); // immediately handle the manifest JarOutputStream jos;//from w ww .j a v a2 s . c o m Manifest manifest = jis.getManifest(); if (manifest == null) { throw new IOException("Missing Manifest !"); } String symbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName"); if (symbolicName == null || symbolicName.length() == 0) { throw new IOException("Missing Symbolic Name in Manifest !"); } String version = manifest.getMainAttributes().getValue("Bundle-Version"); Version v = Version.parseVersion(version); if (v.getQualifier().indexOf("SNAPSHOT") >= 0) { String tStamp; synchronized (DATE_FORMAT) { tStamp = DATE_FORMAT.format(new Date()); } version = v.getMajor() + "." + v.getMinor() + "." + v.getMicro() + "." + v.getQualifier().replaceAll("SNAPSHOT", tStamp); manifest.getMainAttributes().putValue("Bundle-Version", version); } File bundle = new File(this.repoLocation, symbolicName + "-" + v + ".jar"); OutputStream out = null; try { out = new FileOutputStream(bundle); 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()) { spool(jis, jos); } jos.closeEntry(); jis.closeEntry(); entryIn = jis.getNextJarEntry(); } // close the JAR file now to force writing jos.close(); } finally { IOUtils.closeQuietly(out); } return bundle; }
From source file:com.smartitengineering.cms.maven.tools.plugin.StartMojo.java
protected void extract(File jarFile, File outDir) { try {//from w w w . j a v a2 s . c om getLog().info(new StringBuilder("Extracting ").append(jarFile.getAbsolutePath()).append(" to ") .append(outDir.getAbsolutePath()).toString()); java.util.jar.JarFile jar = new java.util.jar.JarFile(jarFile); java.util.Enumeration enumeration = jar.entries(); while (enumeration.hasMoreElements()) { java.util.jar.JarEntry file = (java.util.jar.JarEntry) enumeration.nextElement(); final String str = new StringBuilder(outDir.getAbsolutePath()).append(File.separator) .append(file.getName()).toString(); File f = new File(str); if (file.isDirectory()) { f.mkdir(); continue; } getLog().debug(new StringBuilder("Extracting ").append(file.getName()).append(" to ").append(str) .toString()); java.io.InputStream is = jar.getInputStream(file); // get the input stream java.io.FileOutputStream fos = new java.io.FileOutputStream(f); IOUtils.copy(is, fos); fos.close(); is.close(); } } catch (Exception ex) { throw new IllegalStateException(ex); } }
From source file:org.wso2.carbon.mss.examples.petstore.security.ldap.server.ApacheDirectoryServerActivator.java
private void copyResources() throws IOException, EmbeddingLDAPException { final File jarFile = new File( this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath()); final String repositoryDirectory = "repository"; final File destinationRoot = new File(getCarbonHome()); //Check whether ladap configs are already configured File repository = new File(getCarbonHome() + File.separator + repositoryDirectory); if (!repository.exists()) { JarFile jar = null;/*from w w w. ja v a 2s . c o m*/ try { jar = new JarFile(jarFile); final Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); // Skip if the entry is not about the 'repository' directory. if (!entry.getName().startsWith(repositoryDirectory)) { continue; } // If the entry is a directory create the relevant directory in the destination. File destination = new File(destinationRoot, entry.getName()); if (entry.isDirectory()) { if (destination.mkdirs()) { continue; } } InputStream in = null; OutputStream out = null; try { // If the entry is a file, copy the file to the destination in = jar.getInputStream(entry); out = new FileOutputStream(destination); IOUtils.copy(in, out); IOUtils.closeQuietly(in); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } } } finally { if (jar != null) { jar.close(); } } } }
From source file:org.apache.tajo.catalog.store.XMLCatalogSchemaManager.java
protected String[] listJarResources(URL dirURL, FilenameFilter filter) throws IOException, URISyntaxException { String[] files = new String[0]; String spec = dirURL.getFile(); int seperator = spec.indexOf("!/"); if (seperator == -1) { return files; }/* w w w .ja va2 s .co m*/ URL jarFileURL = new URL(spec.substring(0, seperator)); Set<String> filesSet = new HashSet<>(); try (JarFile jarFile = new JarFile(jarFileURL.toURI().getPath())) { Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.isDirectory()) { continue; } String entryName = entry.getName(); if (entryName.indexOf(schemaPath) > -1 && filter.accept(null, entryName)) { filesSet.add(entryName); } } } if (!filesSet.isEmpty()) { files = new String[filesSet.size()]; files = filesSet.toArray(files); } return files; }
From source file:org.deventropy.shared.utils.DirectoryArchiverUtilTest.java
private void checkJarArchive(final File archiveFile, final File sourceDirectory, final String pathPrefix) throws IOException { JarFile jarFile = null;// ww w .j a v a 2 s . c o m try { jarFile = new JarFile(archiveFile); final Manifest manifest = jarFile.getManifest(); assertNotNull("Manifest should be present", manifest); assertEquals("Manifest version should be 1.0", "1.0", manifest.getMainAttributes().getValue(Attributes.Name.MANIFEST_VERSION)); final ArchiveEntries archiveEntries = createArchiveEntries(sourceDirectory, pathPrefix); final Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { final JarEntry jarEntry = entries.nextElement(); if (MANIFEST_FILE_ENTRY_NAME.equalsIgnoreCase(jarEntry.getName())) { // It is the manifest file, not added by use continue; } if (jarEntry.isDirectory()) { assertTrue("Directory in jar should be from us [" + jarEntry.getName() + "]", archiveEntries.dirs.contains(jarEntry.getName())); archiveEntries.dirs.remove(jarEntry.getName()); } else { assertTrue("File in jar should be from us [" + jarEntry.getName() + "]", archiveEntries.files.containsKey(jarEntry.getName())); final byte[] inflatedMd5 = getMd5Digest(jarFile.getInputStream(jarEntry), false); assertArrayEquals("MD5 hash of files should equal [" + jarEntry.getName() + "]", archiveEntries.files.get(jarEntry.getName()), inflatedMd5); archiveEntries.files.remove(jarEntry.getName()); } } // Check that all files and directories have been accounted for assertTrue("All directories should be in the jar", archiveEntries.dirs.isEmpty()); assertTrue("All files should be in the jar", archiveEntries.files.isEmpty()); } finally { if (null != jarFile) { jarFile.close(); } } }