List of usage examples for java.util.jar Manifest Manifest
public Manifest()
From source file:co.cask.cdap.internal.app.services.http.AppFabricTestBase.java
/** * Deploys an application with (optionally) a defined app name and app version */// w ww. j a va 2 s . c o m protected HttpResponse deploy(Class<?> application, @Nullable String apiVersion, @Nullable String namespace, @Nullable String appVersion, @Nullable Config appConfig) throws Exception { namespace = namespace == null ? Id.Namespace.DEFAULT.getId() : namespace; apiVersion = apiVersion == null ? Constants.Gateway.API_VERSION_3_TOKEN : apiVersion; appVersion = appVersion == null ? String.format("1.0.%d", System.currentTimeMillis()) : appVersion; Manifest manifest = new Manifest(); manifest.getMainAttributes().put(ManifestFields.BUNDLE_VERSION, appVersion); File artifactJar = buildAppArtifact(application, application.getSimpleName(), manifest); File expandDir = tmpFolder.newFolder(); BundleJarUtil.unJar(Locations.toLocation(artifactJar), expandDir); // Add webapp File webAppFile = new File(expandDir, "webapp/default/netlens/src/1.txt"); webAppFile.getParentFile().mkdirs(); Files.write("dummy data", webAppFile, Charsets.UTF_8); BundleJarUtil.createJar(expandDir, artifactJar); HttpEntityEnclosingRequestBase request; String versionedApiPath = getVersionedAPIPath("apps/", apiVersion, namespace); request = getPost(versionedApiPath); request.setHeader(Constants.Gateway.API_KEY, "api-key-example"); request.setHeader("X-Archive-Name", String.format("%s-%s.jar", application.getSimpleName(), appVersion)); if (appConfig != null) { request.setHeader("X-App-Config", GSON.toJson(appConfig)); } request.setEntity(new FileEntity(artifactJar)); return execute(request); }
From source file:com.taobao.android.builder.tools.sign.LocalSignedJarBuilder.java
/** * Creates a {@link SignedJarBuilder} with a given output stream, and signing information. * <p/>If either <code>key</code> or <code>certificate</code> is <code>null</code> then * the archive will not be signed./*from ww w. j a v a 2 s . com*/ * * @param out the {@link OutputStream} where to write the Jar archive. * @param key the {@link PrivateKey} used to sign the archive, or <code>null</code>. * @param certificate the {@link X509Certificate} used to sign the archive, or * <code>null</code>. * @throws IOException * @throws NoSuchAlgorithmException */ public LocalSignedJarBuilder(@NonNull OutputStream out, @Nullable PrivateKey key, @Nullable X509Certificate certificate, @Nullable String builtBy, @Nullable String createdBy, @Nullable String signFile) throws IOException, NoSuchAlgorithmException { mOutputJar = new JarOutputStream(new BufferedOutputStream(out)); mOutputJar.setLevel(9); mKey = key; mCertificate = certificate; mSignFile = signFile; if (mKey != null && mCertificate != null) { mManifest = new Manifest(); Attributes main = mManifest.getMainAttributes(); main.putValue("Manifest-Version", "1.0"); if (builtBy != null) { main.putValue("Built-By", builtBy); } if (createdBy != null) { main.putValue("Created-By", createdBy); } mMessageDigest = MessageDigest.getInstance(DIGEST_ALGORITHM); } }
From source file:rita.widget.SourceCode.java
private void createCompileButton() { ImageIcon imgIcon = new ImageIcon(getClass().getResource("/images/sourcecode/bytecode.png")); this.compileButton = new JButton(imgIcon); this.compileButton.setToolTipText(Language.get("compileButton.tooltip")); final File basePathRobots = new File(Settings.getRobotsPath()); compileButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { // guardar el codigo fuente File sourcePath = saveSourceCode(); // COMPILA EN EL DIRECTORIO POR DEFAULT + LA RUTA DEL PACKAGE Collection<File> inFiles = createClassFiles(sourcePath); if (inFiles != null) { /* transformar el codigo fuente, que no tiene errores, para que los println aparezcan en una ventana. * La transformacin no deberia generar errores. *//*ww w. j av a 2s. c om*/ writeSourceFile(sourcePath, AgregadorDeConsola.getInstance().transformar(readSourceFile(sourcePath))); // volver a compilar, ahora con el codigo transformado inFiles = createClassFiles(sourcePath); if (inFiles != null) { createJarFile(inFiles); System.out.println("INSTALLPATH=" + Settings.getInstallPath()); System.out.println("SE ENVIA ROBOT:" + HelperEditor.currentRobotPackage + "." + HelperEditor.currentRobotName); // si quiere seleccionar enemigos if (Settings.getProperty("level.default").equals(Language.get("level.four"))) { try { DialogSelectEnemies.getInstance(); } catch (NoEnemiesException e2) { new MessageDialog(Language.get("robot.noEnemies"), MessageType.ERROR); } return; } else { callBatalla(null, null); } } else { System.out.println("Error en codigo transformado por AgregadorDeConsola"); } } } catch (Exception e1) { e1.printStackTrace(); } } /** Recibe un archivo conteniendo codigo fuente java, y crea el .class correspondiente * @param sourcePath El archivo .java * @return Un archivo conteniendo el path al .class generado, o null si no fue posible compilar porque hubo errores en el codigo fuente. */ private Collection<File> createClassFiles(File sourcePath) throws Exception, IOException { Collection<File> f = CompileString.compile(sourcePath, basePathRobots); if (CompileString.hasError()) { int cantErrores = 0; for (Diagnostic<?> diag : CompileString.diagnostics) { if (!diag.getKind().equals(Kind.WARNING)) { int line = (int) diag.getLineNumber(); int col = (int) diag.getColumnNumber(); if (line > 0 && col > 0) { highlightCode(line, col); cantErrores++; } } } if (cantErrores > 0) { new MessageDialog(Language.get("compile.error"), MessageType.ERROR); } return null; } else { return f; } } /* crea un jar con todas las clases del robot. el nombre del jar es el nombre del robot */ private void createJarFile(Collection<File> inFiles) throws FileNotFoundException, IOException { File jarFile = new File(basePathRobots, HelperEditor.currentRobotName + ".jar"); if (jarFile.exists()) { jarFile.delete(); } System.out.println("Path del JAR ==" + jarFile); jarFile.createNewFile(); FileOutputStream fos = new FileOutputStream(jarFile); BufferedOutputStream bo = new BufferedOutputStream(fos); Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); JarOutputStream jarOutput = new JarOutputStream(fos, manifest); int basePathLength = basePathRobots.getAbsolutePath().length() + 1; // +1 para incluir al "/" final byte[] buf = new byte[1024]; int anz; try { // para todas las clases... for (File inFile : inFiles) { BufferedInputStream bi = new BufferedInputStream(new FileInputStream(inFile)); try { String relative = inFile.getAbsolutePath().substring(basePathLength); // copia y agrega el archivo .class al jar JarEntry je2 = new JarEntry(relative); jarOutput.putNextEntry(je2); while ((anz = bi.read(buf)) != -1) { jarOutput.write(buf, 0, anz); } jarOutput.closeEntry(); } finally { try { bi.close(); } catch (IOException ignored) { } } } } finally { try { jarOutput.close(); } catch (IOException ignored) { } try { fos.close(); } catch (IOException ignored) { } try { bo.close(); } catch (IOException ignored) { } } } }); compileButton.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { e.getComponent().setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } @Override public void mouseExited(MouseEvent e) { e.getComponent().setCursor(Cursor.getDefaultCursor()); } }); compileButton.setBounds(MIN_WIDTH, 0, MAX_WIDTH - MIN_WIDTH, BUTTON_HEIGHT); compileButton.setFont(smallButtonFont); compileButton.setAlignmentX(LEFT_ALIGNMENT); compileButton.setText(Language.get("compileButton.title")); }
From source file:org.apache.sling.maven.slingstart.PreparePackageMojo.java
private Manifest getRunModesManifest(Feature feature) throws MojoExecutionException { Map<String, StringBuilder> runModes = new HashMap<>(); for (RunMode rm : feature.getRunModes()) { for (ArtifactGroup ag : rm.getArtifactGroups()) { int startOrder = ag.getStartLevel(); // For subsystems the start level on the artifact group is used as start order. for (org.apache.sling.provisioning.model.Artifact a : ag) { Artifact artifact = ModelUtils.getArtifact(this.project, this.mavenSession, this.artifactHandlerManager, this.resolver, a.getGroupId(), a.getArtifactId(), a.getVersion(), a.getType(), a.getClassifier()); File artifactFile = artifact.getFile(); String entryName = getEntryName(artifactFile, startOrder); String[] runModeNames = rm.getNames(); if (runModeNames == null) runModeNames = new String[] { ALL_RUNMODES_KEY }; for (String runModeName : runModeNames) { StringBuilder sb = runModes.get(runModeName); if (sb == null) { sb = new StringBuilder(); runModes.put(runModeName, sb); } else { sb.append('|'); }// ww w . j ava 2 s.c o m sb.append(entryName); } } } } Manifest mf = new Manifest(); Attributes attrs = mf.getMainAttributes(); attrs.putValue("Manifest-Version", "1.0"); // Manifest does not work without this value attrs.putValue("About-This-Manifest", "This is not a real manifest, it is used as information when this archive is transformed into a real subsystem .esa file"); for (Map.Entry<String, StringBuilder> entry : runModes.entrySet()) { attrs.putValue(entry.getKey().replace(':', '_'), entry.getValue().toString()); } return mf; }
From source file:org.apache.sling.maven.slingstart.PreparePackageMojo.java
private int createSubsystemManifest(Feature feature, Map<String, Integer> startOrderMap, ZipOutputStream os) throws IOException { int subsystemStartLevel = -1; ZipEntry ze = new ZipEntry("SUBSYSTEM-MANIFEST-BASE.MF"); try {/*from w w w . j a v a 2 s . c om*/ os.putNextEntry(ze); Manifest mf = new Manifest(); Attributes attributes = mf.getMainAttributes(); attributes.putValue("Manifest-Version", "1.0"); // Manifest does not work without this value attributes.putValue("Subsystem-SymbolicName", feature.getName()); attributes.putValue("Subsystem-Version", "1"); // Version must be an integer (cannot be a long), TODO better idea? attributes.putValue("Subsystem-Type", feature.getType()); for (Section section : feature.getAdditionalSections("subsystem-manifest")) { String sl = section.getAttributes().get("startLevel"); try { subsystemStartLevel = Integer.parseInt(sl); } catch (NumberFormatException nfe) { // Not a valid start level } BufferedReader br = new BufferedReader(new StringReader(section.getContents())); String line = null; while ((line = br.readLine()) != null) { int idx = line.indexOf(':'); if (idx > 0) { String key = line.substring(0, idx); String value; idx++; if (line.length() > idx) value = line.substring(idx); else value = ""; attributes.putValue(key.trim(), value.trim()); } } } mf.write(os); } finally { os.closeEntry(); } return subsystemStartLevel; }
From source file:com.googlecode.mycontainer.maven.plugin.ExecMojo.java
/** * Create a jar with just a manifest containing a Main-Class entry for * SurefireBooter and a Class-Path entry for all classpath elements. Copied * from surefire (ForkConfiguration#createJar()) * /*from w w w . jav a 2 s . c o m*/ * @param classPath * List<String> of all classpath elements. * @return * @throws IOException */ private File createJar(List classPath, String mainClass) throws IOException { File file = File.createTempFile("maven-exec", ".jar"); file.deleteOnExit(); FileOutputStream fos = new FileOutputStream(file); JarOutputStream jos = new JarOutputStream(fos); jos.setLevel(JarOutputStream.STORED); JarEntry je = new JarEntry("META-INF/MANIFEST.MF"); jos.putNextEntry(je); Manifest man = new Manifest(); // we can't use StringUtils.join here since we need to add a '/' to // the end of directory entries - otherwise the jvm will ignore them. String cp = ""; for (Iterator it = classPath.iterator(); it.hasNext();) { String el = (String) it.next(); // NOTE: if File points to a directory, this entry MUST end in '/'. cp += UrlUtils.getURL(new File(el)).toExternalForm() + " "; } man.getMainAttributes().putValue("Manifest-Version", "1.0"); man.getMainAttributes().putValue("Class-Path", cp.trim()); man.getMainAttributes().putValue("Main-Class", mainClass); man.write(jos); jos.close(); return file; }
From source file:co.cask.cdap.internal.app.services.http.handlers.ArtifactHttpHandlerTest.java
@Test public void testPluginWithEndpoints() throws Exception { // add an app for plugins to extend Id.Artifact wordCount1Id = Id.Artifact.from(Id.Namespace.DEFAULT, "wordcount", "1.0.0"); Assert.assertEquals(HttpResponseStatus.OK.getCode(), addAppArtifact(wordCount1Id, WordCountApp.class).getStatusLine().getStatusCode()); // add some plugins. // plugins-3.0.0 extends wordcount[1.0.0,2.0.0) Manifest manifest = new Manifest(); manifest.getMainAttributes().put(ManifestFields.EXPORT_PACKAGE, CallablePlugin.class.getPackage().getName()); Id.Artifact plugins3Id = Id.Artifact.from(Id.Namespace.DEFAULT, "plugins3", "1.0.0"); Set<ArtifactRange> plugins3Parents = Sets.newHashSet(new ArtifactRange(Id.Namespace.DEFAULT, "wordcount", new ArtifactVersion("1.0.0"), new ArtifactVersion("2.0.0"))); Assert.assertEquals(HttpResponseStatus.OK.getCode(), addPluginArtifact(plugins3Id, CallablePlugin.class, manifest, plugins3Parents).getStatusLine() .getStatusCode());//from w w w. ja va2 s. c o m Set<PluginInfo> expectedInfos = Sets .newHashSet(new PluginInfo("CallablePlugin", "interactive", "This is plugin with endpoint", CallablePlugin.class.getName(), new ArtifactSummary("plugins3", "1.0.0"), ImmutableMap.<String, PluginPropertyField>of(), ImmutableSet.<String>of("ping"))); Assert.assertEquals(expectedInfos, getPluginInfos(wordCount1Id, "interactive", "CallablePlugin")); // test plugin with endpoint Assert.assertEquals("hello", GSON.fromJson(callPluginMethod(plugins3Id, "interactive", "CallablePlugin", "ping", "user", ArtifactScope.USER, 200).getResponseBodyAsString(), String.class)); manifest = new Manifest(); manifest.getMainAttributes().put(ManifestFields.EXPORT_PACKAGE, CallingPlugin.class.getPackage().getName()); Id.Artifact plugins4Id = Id.Artifact.from(Id.Namespace.DEFAULT, "plugins4", "1.0.0"); Set<ArtifactRange> plugins4Parents = Sets.newHashSet(new ArtifactRange(Id.Namespace.DEFAULT, "wordcount", new ArtifactVersion("1.0.0"), new ArtifactVersion("2.0.0"))); Assert.assertEquals(HttpResponseStatus.OK.getCode(), addPluginArtifact(plugins4Id, CallingPlugin.class, manifest, plugins4Parents).getStatusLine() .getStatusCode()); // test plugin with endpoint having endpoint-context parameter Assert.assertEquals("hi user", GSON.fromJson(callPluginMethod(plugins4Id, "interactive", "CallingPlugin", "ping", "user", ArtifactScope.USER, 200).getResponseBodyAsString(), String.class)); // test plugin that accepts list of data and aggregates and returns result map manifest = new Manifest(); manifest.getMainAttributes().put(ManifestFields.EXPORT_PACKAGE, PluginWithPojo.class.getPackage().getName()); Id.Artifact plugins5Id = Id.Artifact.from(Id.Namespace.DEFAULT, "aggregator", "1.0.0"); Set<ArtifactRange> plugins5Parents = Sets.newHashSet(new ArtifactRange(Id.Namespace.DEFAULT, "wordcount", new ArtifactVersion("1.0.0"), new ArtifactVersion("2.0.0"))); Assert.assertEquals(HttpResponseStatus.OK.getCode(), addPluginArtifact(plugins5Id, PluginWithPojo.class, manifest, plugins5Parents).getStatusLine() .getStatusCode()); // test plugin with endpoint having endpoint-context parameter List<TestData> data = ImmutableList.of(new TestData(1, 10), new TestData(1, 20), new TestData(3, 15), new TestData(4, 5), new TestData(3, 15)); Map<Long, Long> expectedResult = new HashMap<>(); expectedResult.put(1L, 30L); expectedResult.put(3L, 30L); expectedResult.put(4L, 5L); String response = callPluginMethod(plugins5Id, "interactive", "aggregator", "aggregate", GSON.toJson(data), ArtifactScope.USER, 200).getResponseBodyAsString(); Assert.assertEquals(expectedResult, GSON.fromJson(response, new TypeToken<Map<Long, Long>>() { }.getType())); // test calling a non-existent plugin method "bing" callPluginMethod(plugins4Id, "interactive", "CallingPlugin", "bing", "user", ArtifactScope.USER, 404); manifest = new Manifest(); manifest.getMainAttributes().put(ManifestFields.EXPORT_PACKAGE, InvalidPlugin.class.getPackage().getName()); Id.Artifact invalidPluginId = Id.Artifact.from(Id.Namespace.DEFAULT, "invalid", "1.0.0"); Set<ArtifactRange> invalidPluginParents = Sets.newHashSet(new ArtifactRange(Id.Namespace.DEFAULT, "wordcount", new ArtifactVersion("1.0.0"), new ArtifactVersion("2.0.0"))); Assert.assertEquals(HttpResponseStatus.BAD_REQUEST.getCode(), addPluginArtifact(invalidPluginId, InvalidPlugin.class, manifest, invalidPluginParents) .getStatusLine().getStatusCode()); // test adding plugin artifact which has endpoint method containing 3 params (invalid) manifest = new Manifest(); manifest.getMainAttributes().put(ManifestFields.EXPORT_PACKAGE, InvalidPluginMethodParams.class.getPackage().getName()); invalidPluginId = Id.Artifact.from(Id.Namespace.DEFAULT, "invalidParams", "1.0.0"); invalidPluginParents = Sets.newHashSet(new ArtifactRange(Id.Namespace.DEFAULT, "wordcount", new ArtifactVersion("1.0.0"), new ArtifactVersion("2.0.0"))); Assert.assertEquals(HttpResponseStatus.BAD_REQUEST.getCode(), addPluginArtifact(invalidPluginId, InvalidPluginMethodParams.class, manifest, invalidPluginParents) .getStatusLine().getStatusCode()); // test adding plugin artifact which has endpoint method containing 2 params // but 2nd param is not EndpointPluginContext (invalid) manifest = new Manifest(); manifest.getMainAttributes().put(ManifestFields.EXPORT_PACKAGE, InvalidPluginMethodParamType.class.getPackage().getName()); invalidPluginId = Id.Artifact.from(Id.Namespace.DEFAULT, "invalidParamType", "1.0.0"); invalidPluginParents = Sets.newHashSet(new ArtifactRange(Id.Namespace.DEFAULT, "wordcount", new ArtifactVersion("1.0.0"), new ArtifactVersion("2.0.0"))); Assert.assertEquals(HttpResponseStatus.BAD_REQUEST.getCode(), addPluginArtifact(invalidPluginId, InvalidPluginMethodParamType.class, manifest, invalidPluginParents).getStatusLine().getStatusCode()); // test adding plugin artifact which has endpoint methods containing 2 params // but 2nd param is implementation and extensions of EndpointPluginContext, should succeed manifest = new Manifest(); manifest.getMainAttributes().put(ManifestFields.EXPORT_PACKAGE, PluginEndpointContextTestPlugin.class.getPackage().getName()); Id.Artifact validPluginId = Id.Artifact.from(Id.Namespace.DEFAULT, "extender", "1.0.0"); Set<ArtifactRange> validPluginParents = Sets.newHashSet(new ArtifactRange(Id.Namespace.DEFAULT, "wordcount", new ArtifactVersion("1.0.0"), new ArtifactVersion("2.0.0"))); Assert.assertEquals(HttpResponseStatus.OK.getCode(), addPluginArtifact(validPluginId, PluginEndpointContextTestPlugin.class, manifest, validPluginParents).getStatusLine().getStatusCode()); }
From source file:de.fhg.igd.mapviewer.server.file.FileTiler.java
/** * Creates a Jar archive that includes the given list of files * /*w w w .j a va 2 s . com*/ * @param archiveFile the name of the jar archive file * @param tobeJared the files to be included in the jar file * * @return if the operation was successful */ public static boolean createJarArchive(File archiveFile, List<File> tobeJared) { try { byte buffer[] = new byte[BUFFER_SIZE]; // Open archive file FileOutputStream stream = new FileOutputStream(archiveFile); JarOutputStream out = new JarOutputStream(stream, new Manifest()); for (int i = 0; i < tobeJared.size(); i++) { if (tobeJared.get(i) == null || !tobeJared.get(i).exists() || tobeJared.get(i).isDirectory()) continue; // Just in case... log.debug("Adding " + tobeJared.get(i).getName()); // Add archive entry JarEntry jarAdd = new JarEntry(tobeJared.get(i).getName()); jarAdd.setTime(tobeJared.get(i).lastModified()); out.putNextEntry(jarAdd); // Write file to archive FileInputStream in = new FileInputStream(tobeJared.get(i)); while (true) { int nRead = in.read(buffer, 0, buffer.length); if (nRead <= 0) break; out.write(buffer, 0, nRead); } in.close(); } out.close(); stream.close(); log.info("Adding completed OK"); return true; } catch (Exception e) { log.error("Creating jar file failed", e); return false; } }
From source file:org.eclipse.ebr.maven.BundleMojo.java
private File generateSourceBundleManifest() throws MojoExecutionException { try {//from w w w . j ava2 s . c o m generateSourceBundleL10nFile(); final Manifest mf = new Manifest(); final Attributes attributes = mf.getMainAttributes(); if (attributes.getValue(Name.MANIFEST_VERSION) == null) { attributes.put(Name.MANIFEST_VERSION, "1.0"); } final String expandedVersion = getExpandedVersion(); attributes.putValue(BUNDLE_VERSION, expandedVersion); attributes.putValue(BUNDLE_MANIFESTVERSION, "2"); attributes.putValue(BUNDLE_SYMBOLICNAME, getSourceBundleSymbolicName()); attributes.putValue(BUNDLE_NAME, I18N_KEY_PREFIX + I18N_KEY_BUNDLE_NAME); attributes.putValue(BUNDLE_VENDOR, I18N_KEY_PREFIX + I18N_KEY_BUNDLE_VENDOR); //attributes.putValue(BUNDLE_LOCALIZATION, BUNDLE_LOCALIZATION_DEFAULT_BASENAME); attributes.putValue("Eclipse-SourceBundle", project.getArtifactId() + ";version=\"" + expandedVersion + "\";roots:=\".\""); attributes.putValue(CREATED_BY, "Eclipse Bundle Recipe Maven Plug-in"); final File mfile = getSourceBundleManifestFile(); mfile.getParentFile().mkdirs(); final BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(mfile)); try { mf.write(os); } finally { os.close(); } return mfile; } catch (final Exception e) { throw new MojoExecutionException("Error generating source bundle manifest: " + e.getMessage(), e); } }
From source file:com.taobao.android.apatch.ApkPatch.java
@SuppressWarnings("deprecation") protected Manifest getMeta() { Manifest manifest = new Manifest(); Attributes main = manifest.getMainAttributes(); main.putValue("Manifest-Version", "1.0"); main.putValue("Created-By", "1.0 (ApkPatch)"); main.putValue("Created-Time", new Date(System.currentTimeMillis()).toGMTString()); main.putValue("From-File", baseFiles.get(0).getName()); main.putValue("To-File", newFiles.get(0).getName()); main.putValue("Patch-Name", name); main.putValue(name + "-Patch-Classes", Formater.dotStringList(classes)); main.putValue(name + "-Prepare-Classes", Formater.dotStringList(prepareClasses)); main.putValue(name + "-Used-Methods", Formater.dotStringList(usedMethods)); main.putValue(name + "-Modified-Classes", Formater.dotStringList(modifiedClasses)); main.putValue(name + "-Used-Classes", Formater.dotStringList(usedClasses)); main.putValue(name + "-add-classes", Formater.dotStringList(addClasses)); return manifest; }