List of usage examples for java.util.jar JarFile JarFile
public JarFile(File file) throws IOException
From source file:com.kantenkugel.discordbot.moduleutils.DocParser.java
private static void parse() { LOG.info("Parsing source-file"); try {//ww w .jav a2s. c o m JarFile file = new JarFile(LOCAL_SRC_PATH.toFile()); file.stream().filter(entry -> !entry.isDirectory() && entry.getName().startsWith(JDA_CODE_BASE) && entry.getName().endsWith(".java")).forEach(entry -> { try { parse(entry.getName(), file.getInputStream(entry)); } catch (IOException e) { e.printStackTrace(); } }); LOG.info("Done parsing source-file"); } catch (IOException e) { LOG.log(e); } }
From source file:org.ebayopensource.turmeric.eclipse.utils.wsdl.WSDLUtil.java
/** * Reading wsdl from the provided jar file. * The format for documetn base URI would be "jar:file:[JAR_FILE_LOCATION]!/[WSDL_JAR_ENTRY_PATH]" * * @param file the file/*w w w. ja v a 2 s .c o m*/ * @param jarEntryLocation the jar entry location * @return The instance of WSDL definition, or null is could not read it. * @throws WSDLException the wSDL exception * @throws IOException Signals that an I/O exception has occurred. */ public static Definition readWSDLFromJarFile(final File file, final String jarEntryLocation) throws WSDLException, IOException { InputStream wsdlStream = null; if (file.exists() && file.canRead()) { final JarFile jarFile = new JarFile(file); final JarEntry jarEntry = jarFile.getJarEntry(jarEntryLocation); if (jarEntry != null) { // found the wsdl file wsdlStream = jarFile.getInputStream(jarEntry); return WSDLUtil.readWSDL(StringUtil.toString(URL_PREFIX_JAR_FILE, file.getAbsolutePath(), JAR_FILE_SEPARATOR, jarEntryLocation), wsdlStream); } } return null; }
From source file:acmi.l2.clientmod.xdat.XdatEditor.java
private String readAppVersion() throws IOException, URISyntaxException { try (JarFile jarFile = new JarFile( Paths.get(getClass().getProtectionDomain().getCodeSource().getLocation().toURI()).toFile())) { Manifest manifest = jarFile.getManifest(); return manifest.getMainAttributes().getValue("Version"); }//from w w w. jav a 2 s.c o m }
From source file:de.metanome.backend.algorithm_loading.AlgorithmFinder.java
/** * Finds out which subclass of Algorithm is implemented by the source code in the * algorithmJarFile./*from w w w . ja v a 2 s . c o m*/ * * @param algorithmJarFile the algorithm's jar file * @return the interfaces of the algorithm implementation in algorithmJarFile * @throws java.io.IOException if the algorithm jar file could not be opened * @throws java.lang.ClassNotFoundException if the algorithm contains a not supported interface */ public Set<Class<?>> getAlgorithmInterfaces(File algorithmJarFile) throws IOException, ClassNotFoundException { JarFile jar = new JarFile(algorithmJarFile); Manifest man = jar.getManifest(); Attributes attr = man.getMainAttributes(); String className = attr.getValue(bootstrapClassTagName); URL[] url = { algorithmJarFile.toURI().toURL() }; ClassLoader loader = new URLClassLoader(url, Algorithm.class.getClassLoader()); Class<?> algorithmClass; try { algorithmClass = Class.forName(className, false, loader); } catch (ClassNotFoundException e) { System.out.println("Could not find class " + className); return new HashSet<>(); } finally { jar.close(); } return new HashSet<>(ClassUtils.getAllInterfaces(algorithmClass)); }
From source file:com.eviware.soapui.actions.MockAsWarActionTest.java
private void assertValidWarFile(String warFileName) throws IOException { JarFile jarFile = new JarFile(warFileName); try {//from www. j a va 2 s .co m for (String fileName : getExpectedWarContents()) { JarEntry jarEntry = jarFile.getJarEntry(fileName); assertNotNull(jarEntry); } } finally { jarFile.close(); } }
From source file:edu.stanford.muse.email.JarDocCache.java
private synchronized Set<String> getContents(String prefix) throws IOException { Set<String> contents = contentsMap.get(prefix); if (contents != null) return contents; // check if the file exists first, if it doesn't return null String filename = baseDir + File.separator + prefix + ".contents"; File f = new File(filename); Set<String> result = new LinkedHashSet<String>(); if (f.exists()) { JarFile jarFile;/*ww w . j a v a 2 s.co m*/ try { jarFile = new JarFile(filename); result = readJarFileEntries(jarFile); } catch (Exception e) { // not really a jar file. delete the sucker log.warn("Bad jar file! " + filename + " size " + new File(filename).length() + " bytes"); Util.print_exception(e, log); new File(filename).delete(); } } contentsMap.put(prefix, result); return result; }
From source file:com.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfiguratorTest.java
@Test public void testUpdateZipfile() throws Exception { // First, set up our zipfile test. // Create a manifest with a random header so that we can ensure it's preserved by the configurator. Manifest mf = new Manifest(); Attributes.Name mfTestHeader = Attributes.Name.IMPLEMENTATION_VENDOR; String mfTestValue = "someCrazyValue"; mf.getMainAttributes().put(mfTestHeader, mfTestValue); // Why do you need to add this header? See http://tech.puredanger.com/2008/01/07/jar-manifest-api/ - if you // don't add it, your manifest will be blank. mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); assertEquals(mfTestValue, mf.getMainAttributes().getValue(mfTestHeader)); File testWar = File.createTempFile("JenkinsServiceConfiguratorTest", ".war"); configurator.setWarTemplateFile(testWar.getAbsolutePath()); try {// w w w .j av a 2 s . c o m JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), mf); String specialFileName = "foo/bar.xml"; String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file."; // Make our configurator replace this file within the JAR. configurator.setWebXmlFilename(specialFileName); // Create several random files in the zip. for (int i = 0; i < 10; i++) { JarEntry curEntry = new JarEntry("folder/file" + i); jarOutStream.putNextEntry(curEntry); IOUtils.write(fileContents, jarOutStream); } // Push in our special file now. JarEntry specialEntry = new JarEntry(specialFileName); jarOutStream.putNextEntry(specialEntry); IOUtils.write(fileContents, jarOutStream); // Close the output stream now, time to do the test. jarOutStream.close(); // Configure this configurator with appropriate folders for testing. String expectedHomeDir = "/some/silly/random/homeDir"; String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/"; File webappsTargetDir = new File(webappsTarget); if (webappsTargetDir.exists()) { FileUtils.deleteDirectory(webappsTargetDir); } String expectedDestFile = webappsTarget + "s#test#jenkins.war"; configurator.setTargetJenkinsHomeBaseDir(expectedHomeDir); configurator.setTargetWebappsDir(webappsTarget); configurator.setJenkinsPath("/s/"); ProjectServiceConfiguration config = new ProjectServiceConfiguration(); config.setProjectIdentifier("test123"); Map<String, String> m = new HashMap<String, String>(); m.put(ProjectServiceConfiguration.PROJECT_ID, "test"); m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com"); config.setProperties(m); config.setProjectIdentifier("test"); // Now, run it against our test setup configurator.configure(config); // Confirm that the zipfile was updates as expected. File configuredWar = new File(expectedDestFile); assertTrue(configuredWar.exists()); try { JarFile configuredWarJar = new JarFile(configuredWar); Manifest extractedMF = configuredWarJar.getManifest(); assertEquals(mfTestValue, extractedMF.getMainAttributes().getValue(mfTestHeader)); // Make sure all of our entries are present, and contain the data we expected. JarEntry curEntry = null; Enumeration<JarEntry> entries = configuredWarJar.entries(); while (entries.hasMoreElements()) { curEntry = entries.nextElement(); // If this is the manifest, skip it. if (curEntry.getName().equals("META-INF/MANIFEST.MF")) { continue; } String entryContents = IOUtils.toString(configuredWarJar.getInputStream(curEntry)); if (curEntry.getName().equals(specialFileName)) { assertFalse(fileContents.equals(entryContents)); assertTrue(entryContents.contains(expectedHomeDir)); } else { // Make sure our content was unchanged. assertEquals(fileContents, entryContents); assertFalse(entryContents.contains(expectedHomeDir)); } } } finally { // Clean up our test file. configuredWar.delete(); } } finally { // Clean up our test file. testWar.delete(); } }
From source file:org.apache.flink.client.web.JobsServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String action = req.getParameter(ACTION_PARAM_NAME); if (action.equals(ACTION_LIST_VALUE)) { GregorianCalendar cal = new GregorianCalendar(); File[] files = destinationDir.listFiles(); Arrays.<File>sort(files, FILE_SORTER); resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType(CONTENT_TYPE_PLAIN); PrintWriter writer = resp.getWriter(); for (int i = 0; i < files.length; i++) { if (!files[i].getName().endsWith(".jar")) { continue; }//from w w w .j a v a 2 s . c o m JarFile jar = new JarFile(files[i]); Manifest manifest = jar.getManifest(); String assemblerClass = null; String descriptions = ""; if (manifest != null) { assemblerClass = manifest.getMainAttributes() .getValue(PackagedProgram.MANIFEST_ATTRIBUTE_ASSEMBLER_CLASS); if (assemblerClass == null) { assemblerClass = manifest.getMainAttributes() .getValue(PackagedProgram.MANIFEST_ATTRIBUTE_MAIN_CLASS); } } if (assemblerClass == null) { assemblerClass = ""; } else { String[] classes = assemblerClass.split(","); for (String c : classes) { try { String d = new PackagedProgram(files[i], c, new String[0]).getDescription(); if (d == null) { d = "No description provided."; } descriptions += "#_#" + d; } catch (ProgramInvocationException e) { descriptions += "#_#No description provided."; continue; } } assemblerClass = '\t' + assemblerClass; } cal.setTimeInMillis(files[i].lastModified()); writer.println(files[i].getName() + '\t' + (cal.get(GregorianCalendar.MONTH) + 1) + '/' + cal.get(GregorianCalendar.DAY_OF_MONTH) + '/' + cal.get(GregorianCalendar.YEAR) + ' ' + cal.get(GregorianCalendar.HOUR_OF_DAY) + ':' + cal.get(GregorianCalendar.MINUTE) + ':' + cal.get(GregorianCalendar.SECOND) + assemblerClass + descriptions); } } else if (action.equals(ACTION_DELETE_VALUE)) { String filename = req.getParameter(FILENAME_PARAM_NAME); if (filename == null || filename.length() == 0) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else { File f = new File(destinationDir, filename); if (!f.exists() || f.isDirectory()) { resp.setStatus(HttpServletResponse.SC_NOT_FOUND); } f.delete(); resp.setStatus(HttpServletResponse.SC_OK); } } else { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); } }
From source file:io.stallion.utils.ResourceHelpers.java
public static List<String> listFilesInDirectory(String plugin, String path) { String ending = ""; String starting = ""; if (path.contains("*")) { String[] parts = StringUtils.split(path, "*", 2); String base = parts[0];//from www . j ava 2 s . com if (!base.endsWith("/")) { path = new File(base).getParent(); starting = FilenameUtils.getName(base); } else { path = base; } ending = parts[1]; } Log.info("listFilesInDirectory Parsed Path {0} starting:{1} ending:{2}", path, starting, ending); URL url = PluginRegistry.instance().getJavaPluginByName().get(plugin).getClass().getResource(path); Log.info("URL: {0}", url); List<String> filenames = new ArrayList<>(); URL dirURL = getClassForPlugin(plugin).getResource(path); Log.info("Dir URL is {0}", dirURL); // Handle file based resource folder if (dirURL != null && dirURL.getProtocol().equals("file")) { String fullPath = dirURL.toString().substring(5); File dir = new File(fullPath); // In devMode, use the source resource folder, rather than the compiled version if (Settings.instance().getDevMode()) { String devPath = fullPath.replace("/target/classes/", "/src/main/resources/"); File devFolder = new File(devPath); if (devFolder.exists()) { dir = devFolder; } } Log.info("List files from folder {0}", dir.getAbsolutePath()); List<String> files = list(); for (String name : dir.list()) { if (!empty(ending) && !name.endsWith(ending)) { continue; } if (!empty(starting) && !name.endsWith("starting")) { continue; } // Skip special files, hidden files if (name.startsWith(".") || name.startsWith("~") || name.startsWith("#") || name.contains("_flymake.")) { continue; } filenames.add(path + name); } return filenames; } if (dirURL.getProtocol().equals("jar")) { /* A JAR path */ String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file JarFile jar = null; try { jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8")); } catch (IOException e) { throw new RuntimeException(e); } if (path.startsWith("/")) { path = path.substring(1); } Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar Set<String> result = new HashSet<String>(); //avoid duplicates in case it is a subdirectory while (entries.hasMoreElements()) { String name = entries.nextElement().getName(); Log.finer("Jar file entry: {0}", name); if (name.startsWith(path)) { //filter according to the path String entry = name.substring(path.length()); int checkSubdir = entry.indexOf("/"); if (checkSubdir >= 0) { // if it is a subdirectory, we just return the directory name entry = entry.substring(0, checkSubdir); } if (!empty(ending) && !name.endsWith(ending)) { continue; } if (!empty(starting) && !name.endsWith("starting")) { continue; } // Skip special files, hidden files if (name.startsWith(".") || name.startsWith("~") || name.startsWith("#") || name.contains("_flymake.")) { continue; } result.add(entry); } } return new ArrayList<>(result); } throw new UnsupportedOperationException("Cannot list files for URL " + dirURL); /* try { URL url1 = getClassForPlugin(plugin).getResource(path); Log.info("URL1 {0}", url1); if (url1 != null) { Log.info("From class folder contents {0}", IOUtils.toString(url1)); Log.info("From class folder contents as stream {0}", IOUtils.toString(getClassForPlugin(plugin).getResourceAsStream(path))); } URL url2 = getClassLoaderForPlugin(plugin).getResource(path); Log.info("URL1 {0}", url2); if (url2 != null) { Log.info("From classLoader folder contents {0}", IOUtils.toString(url2)); Log.info("From classLoader folder contents as stream {0}", IOUtils.toString(getClassLoaderForPlugin(plugin).getResourceAsStream(path))); } } catch (IOException e) { Log.exception(e, "error loading path " + path); } // Handle jar based resource folder try( InputStream in = getResourceAsStream(plugin, path); BufferedReader br = new BufferedReader( new InputStreamReader( in ) ) ) { String resource; while( (resource = br.readLine()) != null ) { Log.finer("checking resource for inclusion in directory scan: {0}", resource); if (!empty(ending) && !resource.endsWith(ending)) { continue; } if (!empty(starting) && !resource.endsWith("starting")) { continue; } // Skip special files, hidden files if (resource.startsWith(".") || resource.startsWith("~") || resource.startsWith("#") || resource.contains("_flymake.")) { continue; } Log.finer("added resource during directory scan: {0}", resource); filenames.add(path + resource); } } catch (IOException e) { throw new RuntimeException(e); } return filenames; */ }
From source file:org.amanzi.awe.scripting.utils.ScriptUtils.java
/** * @param pluginName/*ww w. j a va 2s . c o m*/ * @param loadPath * @throws ScriptingException */ private void makePluginLoadName(final String pluginName, final List<String> loadPath) throws ScriptingException { if (StringUtils.isEmpty(pluginName)) { LOGGER.warn("Plugin name is empty"); return; } String pluginPath = getPluginRoot(pluginName); if (StringUtils.isEmpty(pluginPath)) { LOGGER.warn("Plugin not found"); return; } // loadPath.add(pluginPath); JarFile jarFile = null; if (pluginPath.startsWith(PREFIX_FILE) && pluginPath.endsWith(POSTFIX_JAR)) { String path = prepareJarPath(pluginPath); try { jarFile = new JarFile(path); } catch (IOException e) { LOGGER.error("can't find jar file", e); } } if (jarFile == null) { File rootFolder = new File(pluginPath + JRUBY_PLUGI_LIB); if (rootFolder.exists()) { for (File file : rootFolder.listFiles()) { if (file.isDirectory()) { loadPath.add(file.getAbsolutePath()); } } } } else { JarEntry entry; for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) { entry = entries.nextElement(); LOGGER.info(entry.getName()); if (entry.isDirectory() && entry.getName().contains(JRUBY_PLUGI_LIB)) { loadPath.add(entry.getName().substring(0, entry.getName().length() - 1)); LOGGER.info("initialized with jar entry " + entry.getName()); } } } loadPath.add(JRUBY_PLUGI_LIB); }