List of usage examples for java.util.jar JarInputStream getNextJarEntry
public JarEntry getNextJarEntry() throws IOException
From source file:com.ottogroup.bi.asap.repository.ComponentClassloader.java
/** * Handle resource lookups by first checking the managed JARs and hand * it over to the parent if no entry exits * @see java.lang.ClassLoader#getResourceAsStream(java.lang.String) *//*from w w w .j a va 2s . c o m*/ public InputStream getResourceAsStream(String name) { // lookup the name of the JAR file holding the resource String jarFileName = this.resourcesJarMapping.get(name); // if there is no such file, hand over the request to the parent class loader if (StringUtils.isBlank(jarFileName)) return super.getResourceAsStream(name); // try to find the resource inside the jar it is associated with JarInputStream jarInput = null; try { // open a stream on jar which contains the class jarInput = new JarInputStream(new FileInputStream(jarFileName)); // ... and iterate through all entries JarEntry jarEntry = null; while ((jarEntry = jarInput.getNextJarEntry()) != null) { // extract the name of the jar entry and check if it is equal to the provided name String entryFileName = jarEntry.getName(); if (StringUtils.equals(name, entryFileName)) { // load bytes from jar entry and return it as stream byte[] data = loadBytes(jarInput); if (data != null) return new ByteArrayInputStream(data); } } } catch (IOException e) { logger.error("Failed to read resource '" + name + "' from JAR file '" + jarFileName + "'. Error: " + e.getMessage()); } finally { try { jarInput.close(); } catch (IOException e) { logger.error("Failed to close open JAR file '" + jarFileName + "'. Error: " + e.getMessage()); } } return null; }
From source file:ezbake.deployer.publishers.EzAzkabanPublisher.java
/** * This will publish the artifact to Azkaban for scheduled running. The artifact should be of the format * <p/>/*from ww w .ja v a 2s . co m*/ * <p/> * The artifact at this point in time will already have included the SSL certs. * <p/> * Its up to the publisher to reorganize the tar file if needed for its PaaS * * @param artifact The artifact to deploy * @param callerToken - The token of the user or application that initiated this call * @throws DeploymentException - On any exceptions */ @Override public void publish(DeploymentArtifact artifact, EzSecurityToken callerToken) throws DeploymentException { File unzippedPack = null; File azkabanZip = null; ZipOutputStream zipOutputStream = null; String flowName; final BatchJobInfo jobInfo = artifact.getMetadata().getManifest().getBatchJobInfo(); // Get the Azkaban authentication token final AuthenticationResult authenticatorResult; try { authenticatorResult = new AuthenticationManager(new URI(azConf.getAzkabanUrl()), azConf.getUsername(), azConf.getPassword()).login(); } catch (URISyntaxException e) { throw new DeploymentException(e.getMessage()); } if (authenticatorResult.hasError()) { log.error("Could not log into Azkaban: " + authenticatorResult.getError()); throw new DeploymentException(authenticatorResult.getError()); } log.info("Successfully logged into Azkaban. Now creating .zip to upload"); try { // Unzip the artifact unzippedPack = UnzipUtil.unzip(new File(unzipDir), ByteBuffer.wrap(artifact.getArtifact())); log.info("Unzipped artifact to: " + unzippedPack.getAbsolutePath()); // Create a .zip file to submit to Azkaban azkabanZip = File.createTempFile("ezbatch_", ".zip"); log.info("Created temporary zip file: " + azkabanZip.getCanonicalPath()); zipOutputStream = new ZipOutputStream(new FileOutputStream(azkabanZip)); // Copy the configs from the artifact to the top level of the zip. This should contain the Azkaban // .jobs and .properties final String configDir = UnzipUtil.getConfDirectory(unzippedPack).get(); final File configDirFile = new File(configDir); for (File f : FileUtils.listFiles(configDirFile, TrueFileFilter.TRUE, TrueFileFilter.TRUE)) { zipOutputStream.putNextEntry(new ZipArchiveEntry(f.getCanonicalPath().replaceFirst(configDir, ""))); IOUtils.copy(new FileInputStream(f), zipOutputStream); zipOutputStream.closeEntry(); } log.info("Copied configs to the .zip"); // Copy the jars from bin/ in the artifact to lib/ in the .zip file and other things to the jar as needed final String dirPrefix = unzippedPack.getAbsolutePath() + "/bin/"; for (File f : FileUtils.listFiles(new File(dirPrefix), TrueFileFilter.TRUE, TrueFileFilter.TRUE)) { zipOutputStream .putNextEntry(new ZipArchiveEntry(f.getCanonicalPath().replaceFirst(dirPrefix, "lib/"))); final JarInputStream jarInputStream = new JarInputStream(new FileInputStream(f)); final JarOutputStream jarOutputStream = new JarOutputStream(zipOutputStream); JarEntry je; while ((je = jarInputStream.getNextJarEntry()) != null) { jarOutputStream.putNextEntry(je); IOUtils.copy(jarInputStream, jarOutputStream); jarOutputStream.closeEntry(); } log.info("Created Jar file"); // Add the SSL certs to the jar final String sslPath = UnzipUtil.getSSLPath(configDirFile).get(); for (File sslFile : FileUtils.listFiles(new File(sslPath), TrueFileFilter.TRUE, TrueFileFilter.TRUE)) { if (sslFile.isFile()) { jarOutputStream.putNextEntry(new JarArchiveEntry("ssl/" + sslFile.getName())); IOUtils.copy(new FileInputStream(sslFile), jarOutputStream); jarOutputStream.closeEntry(); } } log.info("Added SSL certs to jar"); // Add the application.properties to the jar file so the jobs can read it final File appProps = new File(configDir, "application.properties"); final Properties adjustedProperties = new Properties(); adjustedProperties.load(new FileInputStream(appProps)); adjustedProperties.setProperty("ezbake.security.ssl.dir", "/ssl/"); jarOutputStream.putNextEntry(new JarArchiveEntry("application.properties")); adjustedProperties.store(jarOutputStream, null); jarOutputStream.closeEntry(); jarOutputStream.finish(); zipOutputStream.closeEntry(); } // Check to see if there are any .job files. If there aren't, this is an external job and we need to create // one for the .zip file final Collection<File> jobFiles = FileUtils.listFiles(configDirFile, new String[] { "job" }, false); if (jobFiles.isEmpty()) { // If there are no job files present then we need to create one for the user final StringBuilder sb = new StringBuilder( "type=hadoopJava\n" + "job.class=ezbatch.amino.api.EzFrameworkDriver\n" + "classpath=./lib/*\n" + "main.args=-d /ezbatch/amino/config"); for (File xmlConfig : FileUtils.listFiles(configDirFile, new String[] { "xml" }, false)) { sb.append(" -c ").append(xmlConfig.getName()); } zipOutputStream.putNextEntry(new ZipEntry("Analytic.job")); IOUtils.copy(new StringReader(sb.toString()), zipOutputStream); zipOutputStream.closeEntry(); log.info("There was no .job file so one was created for the .zip"); flowName = "Analytic"; } else { flowName = jobInfo.getFlowName(); if (flowName == null) { log.warn("Manifest did not contain flow_name. Guessing what it should be"); flowName = FilenameUtils.getBaseName(jobFiles.toArray(new File[jobFiles.size()])[0].getName()); log.info("Guessing the flow name should be:" + flowName); } } zipOutputStream.finish(); log.info("Finished creating .zip"); // Now that we've created the zip to upload, attempt to create a project for it to be uploaded to. Every .zip // file needs to be uploaded to a project, and the project may or may not already exist. final String projectName = ArtifactHelpers.getAppId(artifact) + "_" + ArtifactHelpers.getServiceId(artifact); final ProjectManager projectManager = new ProjectManager(authenticatorResult.getSessionId(), new URI(azConf.getAzkabanUrl())); final ManagerResult managerResult = projectManager.createProject(projectName, "EzBatch Deployed"); // If the project already exists, it will return an error, but really it's not a problem if (managerResult.hasError()) { if (!managerResult.getMessage().contains("already exists")) { log.error("Could not create project: " + managerResult.getMessage()); throw new DeploymentException(managerResult.getMessage()); } else { log.info("Reusing the existing project: " + projectName); } } else { log.info("Created new project: " + projectName); log.info("Path: " + managerResult.getPath()); } // Upload the .zip file to the project final UploadManager uploader = new UploadManager(authenticatorResult.getSessionId(), azConf.getAzkabanUrl(), projectName, azkabanZip); final UploaderResult uploaderResult = uploader.uploadZip(); if (uploaderResult.hasError()) { log.error("Could not upload the zip file: " + uploaderResult.getError()); throw new DeploymentException(uploaderResult.getError()); } log.info("Successfully submitted zip file to Azkaban"); // Schedule the jar to run. If the start times aren't provided, it will run in 2 minutes final ScheduleManager scheduler = new ScheduleManager(authenticatorResult.getSessionId(), new URI(azConf.getAzkabanUrl())); // Add the optional parameters if they are present if (jobInfo.isSetStartDate()) { scheduler.setScheduleDate(jobInfo.getStartDate()); } if (jobInfo.isSetStartTime()) { scheduler.setScheduleTime(jobInfo.getStartTime()); } if (jobInfo.isSetRepeat()) { scheduler.setPeriod(jobInfo.getRepeat()); } final SchedulerResult schedulerResult = scheduler.scheduleFlow(projectName, flowName, uploaderResult.getProjectId()); if (schedulerResult.hasError()) { log.error("Failure to schedule job: " + schedulerResult.getError()); throw new DeploymentException(schedulerResult.getError()); } log.info("Successfully scheduled flow: " + flowName); } catch (Exception ex) { log.error("No Nos!", ex); throw new DeploymentException(ex.getMessage()); } finally { IOUtils.closeQuietly(zipOutputStream); FileUtils.deleteQuietly(azkabanZip); FileUtils.deleteQuietly(unzippedPack); } }
From source file:com.ottogroup.bi.asap.repository.ComponentClassloader.java
/** * Find class inside managed jars or hand over the parent * @see java.lang.ClassLoader#findClass(java.lang.String) *//*from w w w . j ava 2 s . c o m*/ protected Class<?> findClass(String name) throws ClassNotFoundException { // find in already loaded classes to make things shorter Class<?> clazz = findLoadedClass(name); if (clazz != null) return clazz; // check if the class searched for is contained inside managed jars, // otherwise hand over the request to the parent class loader String jarFileName = this.classesJarMapping.get(name); if (StringUtils.isBlank(jarFileName)) { super.findClass(name); } // try to find class inside jar the class name is associated with JarInputStream jarInput = null; try { // open a stream on jar which contains the class jarInput = new JarInputStream(new FileInputStream(jarFileName)); // ... and iterate through all entries JarEntry jarEntry = null; while ((jarEntry = jarInput.getNextJarEntry()) != null) { // extract the name of the jar entry and check if it has suffix '.class' and thus contains // the search for implementation String entryFileName = jarEntry.getName(); if (entryFileName.endsWith(".class")) { // replace slashes by dots, remove suffix and compare the result with the searched for class name entryFileName = entryFileName.substring(0, entryFileName.length() - 6).replace('/', '.'); if (name.equalsIgnoreCase(entryFileName)) { // load bytes from jar entry and define a class over it byte[] data = loadBytes(jarInput); if (data != null) { return defineClass(name, data, 0, data.length); } // if the jar entry does not contain any data, throw an exception throw new ClassNotFoundException("Class '" + name + "' not found"); } } } } catch (IOException e) { // if any io error occurs: throw an exception throw new ClassNotFoundException("Class '" + name + "' not found"); } finally { try { jarInput.close(); } catch (IOException e) { logger.error("Failed to close open JAR file '" + jarFileName + "'. Error: " + e.getMessage()); } } // if no such class exists, throw an exception throw new ClassNotFoundException("Class [" + name + "] not found"); }
From source file:org.vafer.jdependency.Clazzpath.java
public ClazzpathUnit addClazzpathUnit(final InputStream pInputStream, final String pId) throws IOException { final JarInputStream inputStream = new JarInputStream(pInputStream); try {//from ww w.ja v a 2 s.c om final JarEntry[] entryHolder = new JarEntry[1]; return addClazzpathUnit(new Iterable<Resource>() { public Iterator<Resource> iterator() { return new Iterator<Resource>() { public boolean hasNext() { try { do { entryHolder[0] = inputStream.getNextJarEntry(); } while (entryHolder[0] != null && !Resource.isValidName(entryHolder[0].getName())); } catch (IOException e) { throw new RuntimeException(e); } return entryHolder[0] != null; } public Resource next() { return new Resource(entryHolder[0].getName()) { @Override InputStream getInputStream() { return inputStream; } }; } public void remove() { throw new UnsupportedOperationException(); } }; } }, pId, false); } finally { inputStream.close(); } }
From source file:lineage2.gameserver.scripts.Scripts.java
/** * Method load.//www . jav a2s .co m */ private void load() { _log.info("Scripts: Loading..."); List<Class<?>> classes = new ArrayList<>(); boolean result = false; File f = new File("../libs/lineage2-scripts.jar"); if (f.exists()) { JarInputStream stream = null; try { stream = new JarInputStream(new FileInputStream(f)); JarEntry entry = null; while ((entry = stream.getNextJarEntry()) != null) { if (entry.getName().contains(ClassUtils.INNER_CLASS_SEPARATOR) || !entry.getName().endsWith(".class")) { continue; } String name = entry.getName().replace(".class", "").replace("/", "."); Class<?> clazz = Class.forName(name); if (Modifier.isAbstract(clazz.getModifiers())) { continue; } classes.add(clazz); } result = true; } catch (Exception e) { _log.error("Fail to load scripts.jar!", e); classes.clear(); } finally { IOUtils.closeQuietly(stream); } } if (!result) { result = load(classes, ""); } if (!result) { _log.error("Scripts: Failed loading scripts!"); Runtime.getRuntime().exit(0); return; } _log.info("Scripts: Loaded " + classes.size() + " classes."); Class<?> clazz; for (int i = 0; i < classes.size(); i++) { clazz = classes.get(i); _classes.put(clazz.getName(), clazz); } }
From source file:cn.com.ebmp.freesql.io.ResolverUtil.java
/** * Recursively list all resources under the given URL that appear to define * a Java class. Matching resources will have a name that ends in ".class" * and have a relative path such that each segment of the path is a valid * Java identifier. The resource paths returned will be relative to the URL * and begin with the specified path.//ww w. j a v a 2 s. com * * @param url * The URL of the parent resource to search. * @param path * The path with which each matching resource path must begin, * relative to the URL. * @return A list of matching resources. The list may be empty. * @throws IOException */ protected List<String> listClassResources(URL url, String path) throws IOException { log.debug("Listing classes in " + url); InputStream is = null; try { List<String> resources = new ArrayList<String>(); // First, try to find the URL of a JAR file containing the requested // resource. If a JAR // file is found, then we'll list child resources by reading the // JAR. URL jarUrl = findJarForResource(url, path); if (jarUrl != null) { is = jarUrl.openStream(); resources = listClassResources(new JarInputStream(is), path); } else { List<String> children = new ArrayList<String>(); try { if (isJar(url)) { // Some versions of JBoss VFS might give a JAR stream // even if the resource // referenced by the URL isn't actually a JAR is = url.openStream(); JarInputStream jarInput = new JarInputStream(is); for (JarEntry entry; (entry = jarInput.getNextJarEntry()) != null;) { log.debug("Jar entry: " + entry.getName()); if (isRelevantResource(entry.getName())) { children.add(entry.getName()); } } } else { // Some servlet containers allow reading from // "directory" resources like a // text file, listing the child resources one per line. is = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); for (String line; (line = reader.readLine()) != null;) { log.debug("Reader entry: " + line); if (isRelevantResource(line)) { children.add(line); } } } } catch (FileNotFoundException e) { /* * For file URLs the openStream() call might fail, depending * on the servlet container, because directories can't be * opened for reading. If that happens, then list the * directory directly instead. */ if ("file".equals(url.getProtocol())) { File file = new File(url.getFile()); log.debug("Listing directory " + file.getAbsolutePath()); if (file.isDirectory()) { children = Arrays.asList(file.list(new FilenameFilter() { public boolean accept(File dir, String name) { return isRelevantResource(name); } })); } } else { // No idea where the exception came from so rethrow it throw e; } } // The URL prefix to use when recursively listing child // resources String prefix = url.toExternalForm(); if (!prefix.endsWith("/")) prefix = prefix + "/"; // Iterate over each immediate child, adding classes and // recursing into directories for (String child : children) { String resourcePath = path + "/" + child; if (child.endsWith(".class")) { log.debug("Found class file: " + resourcePath); resources.add(resourcePath); } else { URL childUrl = new URL(prefix + child); resources.addAll(listClassResources(childUrl, resourcePath)); } } } return resources; } finally { try { is.close(); } catch (Exception e) { } } }
From source file:fr.gael.dhus.server.http.TomcatServer.java
public void install(WebApplication web_application) throws TomcatException { try {/* www . j a va 2 s . co m*/ 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 w w. j a v a2 s .c o 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; jis = new JarInputStream(asset.getBinaryContentAttachment()); JarEntry entry = null;/*w w w . j av a 2 s. c o m*/ 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.maven.plugins.help.EvaluateMojo.java
/** * @param xstreamObject not null//from www .j a v a2 s . c om * @param jarFile not null * @param packageFilter a package name to filter. */ private void addAlias(XStream xstreamObject, File jarFile, String packageFilter) { JarInputStream jarStream = null; try { jarStream = new JarInputStream(new FileInputStream(jarFile)); JarEntry jarEntry = jarStream.getNextJarEntry(); while (jarEntry != null) { if (jarEntry.getName().toLowerCase(Locale.ENGLISH).endsWith(".class")) { String name = jarEntry.getName().substring(0, jarEntry.getName().indexOf(".")); name = name.replaceAll("/", "\\."); if (name.contains(packageFilter)) { try { Class<?> clazz = ClassUtils.getClass(name); String alias = StringUtils.lowercaseFirstLetter(ClassUtils.getShortClassName(clazz)); xstreamObject.alias(alias, clazz); if (!clazz.equals(Model.class)) { xstreamObject.omitField(clazz, "modelEncoding"); // unnecessary field } } catch (ClassNotFoundException e) { getLog().error(e); } } } jarStream.closeEntry(); jarEntry = jarStream.getNextJarEntry(); } } catch (IOException e) { if (getLog().isDebugEnabled()) { getLog().debug("IOException: " + e.getMessage(), e); } } finally { IOUtil.close(jarStream); } }