List of usage examples for java.util.jar Manifest write
public void write(OutputStream out) throws IOException
From source file:org.rhq.plugins.jbossas.util.FileContentDelegate.java
/** * Write the SHA256 to the manifest using the RHQ-Sha256 attribute tag. * * @param deploymentFolder app deployment folder * @param sha SHA256//from www . j a v a 2 s .c o m * @throws IOException */ private void writeSHAToManifest(File deploymentFolder, String sha) throws IOException { File manifestFile = new File(deploymentFolder, MANIFEST_RELATIVE_PATH); Manifest manifest; if (manifestFile.exists()) { FileInputStream inputStream = new FileInputStream(manifestFile); try { manifest = new Manifest(inputStream); } finally { inputStream.close(); } } else { manifest = new Manifest(); manifestFile.getParentFile().mkdirs(); manifestFile.createNewFile(); } Attributes attribs = manifest.getMainAttributes(); //The main section of the manifest file does not get saved if both of //these two attributes are missing. Please see Attributes implementation. if (!attribs.containsKey(Attributes.Name.MANIFEST_VERSION.toString()) && !attribs.containsKey(Attributes.Name.SIGNATURE_VERSION.toString())) { attribs.putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0"); } attribs.putValue(RHQ_SHA_256, sha); FileOutputStream outputStream = new FileOutputStream(manifestFile); try { manifest.write(outputStream); } finally { outputStream.close(); } }
From source file:org.rhq.plugins.jbossas5.deploy.ManagedComponentDeployer.java
public void deploy(CreateResourceReport createResourceReport, ResourceType resourceType) { createResourceReport.setStatus(null); File archiveFile = null;// w w w .ja v a 2s . co m try { ResourcePackageDetails details = createResourceReport.getPackageDetails(); PackageDetailsKey key = details.getKey(); archiveFile = downloader.prepareArchive(key, resourceType); String archiveName = key.getName(); if (!DeploymentUtils.hasCorrectExtension(archiveName, resourceType)) { createResourceReport.setStatus(CreateResourceStatus.FAILURE); createResourceReport .setErrorMessage("Incorrect extension specified on filename [" + archiveName + "]"); return; } abortIfApplicationAlreadyDeployed(resourceType, archiveFile); Configuration deployTimeConfig = details.getDeploymentTimeConfiguration(); @SuppressWarnings({ "ConstantConditions" }) boolean deployExploded = deployTimeConfig.getSimple("deployExploded").getBooleanValue(); DeploymentManager deploymentManager = this.profileServiceConnection.getDeploymentManager(); boolean deployFarmed = deployTimeConfig.getSimple("deployFarmed").getBooleanValue(); if (deployFarmed) { Collection<ProfileKey> profileKeys = deploymentManager.getProfiles(); boolean farmSupported = false; for (ProfileKey profileKey : profileKeys) { if (profileKey.getName().equals(FARM_PROFILE_KEY.getName())) { farmSupported = true; break; } } if (!farmSupported) { throw new IllegalStateException("This application server instance is not a node in a cluster, " + "so it does not support farmed deployments. Supported deployment profiles are " + profileKeys + "."); } if (deployExploded) { throw new IllegalArgumentException( "Deploying farmed applications in exploded form is not supported by the Profile Service."); } deploymentManager.loadProfile(FARM_PROFILE_KEY); } String[] deploymentNames; try { deploymentNames = DeploymentUtils.deployArchive(deploymentManager, archiveFile, deployExploded); } finally { // Make sure to switch back to the 'applications' profile if we switched to the 'farm' profile above. if (deployFarmed) { deploymentManager.loadProfile(APPLICATIONS_PROFILE_KEY); } } if (deploymentNames == null || deploymentNames.length != 1) { throw new RuntimeException("deploy operation returned invalid result: " + deploymentNames); } // e.g.: vfszip:/C:/opt/jboss-6.0.0.Final/server/default/deploy/foo.war String deploymentName = deploymentNames[0]; // If deployed exploded, we need to store the SHA of source package in META-INF/MANIFEST.MF for correct // versioning. if (deployExploded) { MessageDigestGenerator sha256Generator = new MessageDigestGenerator(MessageDigestGenerator.SHA_256); String shaString = sha256Generator.calcDigestString(archiveFile); URI deploymentURI = URI.create(deploymentName); // e.g.: /C:/opt/jboss-6.0.0.Final/server/default/deploy/foo.war String deploymentPath = deploymentURI.getPath(); File deploymentFile = new File(deploymentPath); if (deploymentFile.isDirectory()) { File manifestFile = new File(deploymentFile, "META-INF/MANIFEST.MF"); Manifest manifest; if (manifestFile.exists()) { FileInputStream inputStream = new FileInputStream(manifestFile); try { manifest = new Manifest(inputStream); } finally { inputStream.close(); } } else { File metaInf = new File(deploymentFile, "META-INF"); if (!metaInf.exists()) if (!metaInf.mkdir()) throw new Exception("Could not create directory " + deploymentFile + "META-INF."); manifestFile = new File(metaInf, "MANIFEST.MF"); manifest = new Manifest(); } Attributes attribs = manifest.getMainAttributes(); attribs.putValue("RHQ-Sha256", shaString); FileOutputStream outputStream = new FileOutputStream(manifestFile); try { manifest.write(outputStream); } finally { outputStream.close(); } } else { LOG.error("Exploded deployment '" + deploymentFile + "' does not exist or is not a directory - unable to add RHQ versioning metadata to META-INF/MANIFEST.MF."); } } // Reload the management view to pickup the ManagedDeployment for the app we just deployed. ManagementView managementView = this.profileServiceConnection.getManagementView(); managementView.load(); ManagedDeployment managedDeployment = null; try { managedDeployment = managementView.getDeployment(deploymentName); } catch (NoSuchDeploymentException e) { LOG.error("Failed to find managed deployment '" + deploymentName + "' after deploying '" + archiveName + "', so cannot start the application."); createResourceReport.setStatus(CreateResourceStatus.INVALID_ARTIFACT); createResourceReport.setErrorMessage("Unable to start application '" + deploymentName + "' after deploying it, since lookup of the associated ManagedDeployment failed."); } if (managedDeployment != null) { DeploymentState state = managedDeployment.getDeploymentState(); if (state != DeploymentState.STARTED) { // The app failed to start - do not consider this a FAILURE, since it was at least deployed // successfully. However, set the status to INVALID_ARTIFACT and set an error message, so // the user is informed of the condition. createResourceReport.setStatus(CreateResourceStatus.INVALID_ARTIFACT); createResourceReport.setErrorMessage( "Failed to start application '" + deploymentName + "' after deploying it."); } } createResourceReport.setResourceName(archiveName); createResourceReport.setResourceKey(archiveName); if (createResourceReport.getStatus() == null) { // Deployment was 100% successful, including starting the app. createResourceReport.setStatus(CreateResourceStatus.SUCCESS); } } catch (Throwable t) { LOG.error("Error deploying application for request [" + createResourceReport + "].", t); createResourceReport.setStatus(CreateResourceStatus.FAILURE); createResourceReport.setException(t); } finally { if (archiveFile != null) { downloader.destroyArchive(archiveFile); } } }
From source file:org.sourcepit.common.maven.testing.ArtifactRepositoryFacade.java
private static File createStubJar(File dir) throws IOException { final File jarFile = File.createTempFile("stub", ".jar", dir); JarOutputStream jarOut = null; try {//from w ww . ja v a 2s .c o m jarOut = new JarOutputStream(new FileOutputStream(jarFile)); final JarEntry mfEntry = new JarEntry(JarFile.MANIFEST_NAME); jarOut.putNextEntry(mfEntry); final Manifest mf = new Manifest(); mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1"); mf.write(jarOut); jarOut.closeEntry(); } finally { IOUtils.closeQuietly(jarOut); } return jarFile; }
From source file:org.stem.ExternalNode.java
private void createNodeJar(File jarFile, String mainClass, File nodeDir) throws IOException { File conf = new File(nodeDir, "conf"); FileOutputStream fos = null;// ww w . j av a 2s . c om JarOutputStream jos = null; try { fos = new FileOutputStream(jarFile); jos = new JarOutputStream(fos); jos.setLevel(JarOutputStream.STORED); jos.putNextEntry(new JarEntry("META-INF/MANIFEST.MF")); Manifest man = new Manifest(); StringBuilder cp = new StringBuilder(); cp.append(new URL(conf.toURI().toASCIIString()).toExternalForm()); cp.append(' '); log.debug("Adding plugin artifact: " + ArtifactUtils.versionlessKey(mvnContext.pluginArtifact) + " to the classpath"); cp.append(new URL(mvnContext.pluginArtifact.getFile().toURI().toASCIIString()).toExternalForm()); cp.append(' '); log.debug("Adding: " + mvnContext.classesDir + " to the classpath"); cp.append(new URL(mvnContext.classesDir.toURI().toASCIIString()).toExternalForm()); cp.append(' '); for (Artifact artifact : mvnContext.pluginDependencies) { log.info("Adding plugin dependency artifact: " + ArtifactUtils.versionlessKey(artifact) + " to the classpath"); // NOTE: if File points to a directory, this entry MUST end in '/'. cp.append(new URL(artifact.getFile().toURI().toASCIIString()).toExternalForm()); cp.append(' '); } man.getMainAttributes().putValue("Manifest-Version", "1.0"); man.getMainAttributes().putValue("Class-Path", cp.toString().trim()); man.getMainAttributes().putValue("Main-Class", mainClass); man.write(jos); } finally { IOUtil.close(jos); IOUtil.close(fos); } }
From source file:org.talend.repository.services.export.BuildDataServiceHandler.java
@Override public IProcessor generateJobFiles(IProgressMonitor monitor) throws Exception { BuildCacheManager.getInstance().clearAllCaches(); // TESB-22307 if (GlobalServiceRegister.getDefault().isServiceRegistered(IESBService.class)) { IESBService soapService = (IESBService) GlobalServiceRegister.getDefault() .getService(IESBService.class); ServiceMavenJavaProcessor processor = (ServiceMavenJavaProcessor) soapService.createJavaProcessor(null, serviceItem.getProperty(), true); IFile pomFile = AggregatorPomsHelper.getItemPomFolder(serviceItem.getProperty()) .getFile(TalendMavenConstants.POM_FILE_NAME); CreateMavenDataServicePom pom = new CreateMavenDataServicePom(processor, pomFile); pom.create(monitor);/* w ww.j a v a2s . c o m*/ } // src\main\resources\feature\feature.xml FeaturesModel features = new FeaturesModel(getGroupId(), serviceName, serviceVersion); features.setConfigName(serviceName); features.setContexts(contextValues); ServiceConnection connection = (ServiceConnection) serviceItem.getConnection(); String useRegistry = connection.getAdditionalInfo().get(ServiceMetadataDialog.USE_SERVICE_REGISTRY); if (!"true".equals(useRegistry)) { String useCorrelation = connection.getAdditionalInfo() .get(ServiceMetadataDialog.USE_BUSINESS_CORRELATION); if ("true".equals(useCorrelation)) { features.addFeature(new FeatureModel(FeaturesModel.CORRELATION_FEATURE_NAME)); } } // add talend-data-mapper feature for (IRepositoryViewObject node : nodes) { ProcessItem processItem = (ProcessItem) node.getProperty().getItem(); if (null != EmfModelUtils.getComponentByName(processItem, "tHMap")) { features.addFeature(new FeatureModel(FeaturesModel.TALEND_DATA_MAPPER_FEATURE_NAME)); break; } } for (IRepositoryViewObject node : nodes) { features.addBundle(new BundleModel(PomIdsHelper.getJobGroupId(node.getProperty()), serviceExportManager.getNodeLabel(node) + "-bundle", PomIdsHelper.getJobVersion(node.getProperty()))); } final String artifactName = serviceName + "-control-bundle"; //$NON-NLS-1$ features.addBundle(new BundleModel(PomIdsHelper.getJobGroupId(serviceItem.getProperty()), artifactName, PomIdsHelper.getJobVersion(serviceItem.getProperty()))); IFile feature = talendProcessJavaProject .createSubFolder(monitor, talendProcessJavaProject.getResourcesFolder(), "feature") .getFile("feature.xml"); setFileContent(features.getContent(), feature, monitor); // resources\META-INF\MANIFEST.MF Manifest manifest = serviceExportManager.getManifest(serviceName, serviceVersion, additionalInfo); IFile mf = talendProcessJavaProject .createSubFolder(monitor, talendProcessJavaProject.getResourcesFolder(), "META-INF") .getFile("MANIFEST.MF"); // talendProcessJavaProject.getResourceSubFolder(monitor, "META-INF").getFile("MANIFEST.MF"); FileOutputStream outputStream = new FileOutputStream(mf.getLocation().toFile()); manifest.write(outputStream); outputStream.flush(); outputStream.close(); // resources\**.wsdl IFile wsdl = talendProcessJavaProject.getResourcesFolder().getFile(serviceWsdl.getName()); setFileContent(serviceWsdl.getContents(), wsdl, monitor); // resources\OSGI-INF\blueprint\blueprint.xml IFile blueprint = talendProcessJavaProject .createSubFolder(monitor, talendProcessJavaProject.getResourcesFolder(), "OSGI-INF/blueprint") .getFile("blueprint.xml"); // talendProcessJavaProject.getResourceSubFolder(monitor, "OSGI-INF/blueprint").getFile("blueprint.xml"); serviceExportManager.createBlueprint(blueprint.getLocation().toFile(), ports, additionalInfo, wsdl, serviceName); return null;// as not only one job code generated }
From source file:org.talend.repository.ui.wizards.exportjob.scriptsmanager.esb.JobJavaScriptOSGIForESBManager.java
private ExportFileResource genMetaInfoFolder(ExportFileResource libResource, ProcessItem processItem) throws IOException { ExportFileResource metaInfoResource = new ExportFileResource(null, FileConstants.META_INF_FOLDER_NAME); // generate the MANIFEST.MF file in the temp folder File manifestFile = new File(getTmpFolder() + PATH_SEPARATOR + FileConstants.MANIFEST_MF_FILE_NAME); FileOutputStream fos = null;//from w w w. jav a 2s . c o m try { Manifest manifest = getManifest(libResource, processItem); fos = new FileOutputStream(manifestFile); manifest.write(fos); } finally { if (fos != null) { fos.close(); } } metaInfoResource.addResources(Collections.singletonList(manifestFile.toURI().toURL())); return metaInfoResource; }
From source file:org.wso2.carbon.automation.engine.frameworkutils.CodeCoverageUtils.java
private synchronized static void addEmmaDynamicImportPackage(String jarFilePath) throws IOException { if (!jarFilePath.endsWith(".jar")) { throw new IllegalArgumentException( "Jar file should have the extension .jar. " + jarFilePath + " is invalid"); }/*w w w . j a v a 2 s .co m*/ JarFile jarFile = new JarFile(jarFilePath); Manifest manifest = jarFile.getManifest(); if (manifest == null) { throw new IllegalArgumentException(jarFilePath + " does not contain a MANIFEST.MF file"); } String fileSeparator = (File.separatorChar == '\\') ? "\\" : File.separator; String jarFileName = jarFilePath; if (jarFilePath.lastIndexOf(fileSeparator) != -1) { jarFileName = jarFilePath.substring(jarFilePath.lastIndexOf(fileSeparator) + 1); } ArchiveManipulator archiveManipulator = null; String tempExtractedDir = null; try { archiveManipulator = new ArchiveManipulator(); tempExtractedDir = System.getProperty("basedir") + File.separator + "target" + File.separator + jarFileName.substring(0, jarFileName.lastIndexOf('.')); ArchiveExtractorUtil.extractFile(jarFilePath, tempExtractedDir); } catch (Exception e) { log.error("Could not extract the file", e); } finally { jarFile.close(); } String dynamicImports = manifest.getMainAttributes().getValue("DynamicImport-Package"); if (dynamicImports != null) { manifest.getMainAttributes().putValue("DynamicImport-Package", dynamicImports + ",com.vladium.*"); } else { manifest.getMainAttributes().putValue("DynamicImport-Package", "com.vladium.*"); } File newManifest = new File( tempExtractedDir + File.separator + "META-INF" + File.separator + "MANIFEST.MF"); FileOutputStream manifestOut = null; try { manifestOut = new FileOutputStream(newManifest); manifest.write(manifestOut); } catch (IOException e) { log.error("Could not write content to new MANIFEST.MF file", e); } finally { if (manifestOut != null) { manifestOut.close(); } } if (tempExtractedDir != null) archiveManipulator.archiveDir(jarFilePath, tempExtractedDir); FileUtils.forceDelete(newManifest); }
From source file:org.wso2.carbon.integration.framework.utils.CodeCoverageUtils.java
private synchronized static void addEmmaDynamicImportPackage(String jarFilePath) throws IOException { if (!jarFilePath.endsWith(".jar")) { throw new IllegalArgumentException( "Jar file should have the extension .jar. " + jarFilePath + " is invalid"); }//from ww w .jav a2s. c o m JarFile jarFile = new JarFile(jarFilePath); Manifest manifest = jarFile.getManifest(); if (manifest == null) { throw new IllegalArgumentException(jarFilePath + " does not contain a MANIFEST.MF file"); } String fileSeparator = (File.separatorChar == '\\') ? "\\" : File.separator; String jarFileName = jarFilePath; if (jarFilePath.lastIndexOf(fileSeparator) != -1) { jarFileName = jarFilePath.substring(jarFilePath.lastIndexOf(fileSeparator) + 1); } ArchiveManipulator archiveManipulator; String tempExtractedDir; try { archiveManipulator = new ArchiveManipulator(); tempExtractedDir = System.getProperty("basedir") + File.separator + "target" + File.separator + jarFileName.substring(0, jarFileName.lastIndexOf('.')); new ArchiveManipulatorUtil().extractFile(jarFilePath, tempExtractedDir); } finally { jarFile.close(); } String dynamicImports = manifest.getMainAttributes().getValue("DynamicImport-Package"); if (dynamicImports != null) { manifest.getMainAttributes().putValue("DynamicImport-Package", dynamicImports + ",com.vladium.*"); } else { manifest.getMainAttributes().putValue("DynamicImport-Package", "com.vladium.*"); } File newManifest = new File( tempExtractedDir + File.separator + "META-INF" + File.separator + "MANIFEST.MF"); FileOutputStream manifestOut = null; try { manifestOut = new FileOutputStream(newManifest); manifest.write(manifestOut); } catch (IOException e) { log.error("Could not write content to new MANIFEST.MF file", e); } finally { if (manifestOut != null) { manifestOut.close(); } } archiveManipulator.archiveDir(jarFilePath, tempExtractedDir); FileManipulator.deleteDir(tempExtractedDir); }
From source file:org.wso2.carbon.server.extensions.FragmentBundleCreator.java
public void perform() { File[] files = getBundleConfigs(); if (files.length > 0) { for (File file : files) { String fragmentHostBundleName = getFragmentHostBundleName(file); String fragmentBundleName = getFragmentBundleName(file); try { Manifest mf = new Manifest(); Attributes attribs = mf.getMainAttributes(); attribs.putValue(LauncherConstants.MANIFEST_VERSION, "1.0"); attribs.putValue(LauncherConstants.BUNDLE_MANIFEST_VERSION, "2"); attribs.putValue(LauncherConstants.BUNDLE_NAME, fragmentBundleName); attribs.putValue(LauncherConstants.BUNDLE_SYMBOLIC_NAME, fragmentBundleName); attribs.putValue(LauncherConstants.BUNDLE_VERSION, FRAGMENT_BUNDLE_VERSION); attribs.putValue(LauncherConstants.FRAGMENT_HOST, fragmentHostBundleName); attribs.putValue(LauncherConstants.BUNDLE_CLASSPATH, "."); File dropinsFolder = new File(Utils.getCarbonComponentRepo(), "dropins"); String targetFilePath = dropinsFolder.getAbsolutePath() + File.separator + fragmentBundleName + "_" + FRAGMENT_BUNDLE_VERSION + ".jar"; String tempDirPath = Utils.JAR_TO_BUNDLE_DIR + File.separator + System.currentTimeMillis() + Math.random(); FileOutputStream mfos = null; try { if (file.isDirectory()) { FileUtils.copyDirectory(file, new File(tempDirPath)); } else { // is a single file.. Utils.copyFileToDir(file, new File(tempDirPath)); }/*from w ww. j ava 2 s. c om*/ String metaInfPath = tempDirPath + File.separator + "META-INF"; if (!new File(metaInfPath).mkdirs()) { throw new IOException("Failed to create the directory: " + metaInfPath); } mfos = new FileOutputStream(metaInfPath + File.separator + "MANIFEST.MF"); mf.write(mfos); Utils.archiveDir(targetFilePath, tempDirPath); Utils.deleteDir(new File(tempDirPath)); } finally { try { if (mfos != null) { mfos.close(); } } catch (IOException e) { log.error("Unable to close the OutputStream " + e.getMessage(), e); } } } catch (IOException e) { log.error("Error occured while creating the log4j prop fragment bundle.", e); } } } }
From source file:org.wso2.carbon.server.extensions.Log4jPropFileFragmentBundleCreator.java
public void perform() { //Get the log4j.properties file path. //Calculate the target fragment bundle file name with required manifest headers. //org.wso2.carbon.logging.propfile_1.0.0.jar try {/* w w w.j av a 2 s . c o m*/ Manifest mf = new Manifest(); Attributes attribs = mf.getMainAttributes(); attribs.putValue(LauncherConstants.MANIFEST_VERSION, "1.0"); attribs.putValue(LauncherConstants.BUNDLE_MANIFEST_VERSION, "2"); attribs.putValue(LauncherConstants.BUNDLE_NAME, FRAGMENT_BUNDLE_NAME); attribs.putValue(LauncherConstants.BUNDLE_SYMBOLIC_NAME, FRAGMENT_BUNDLE_NAME); attribs.putValue(LauncherConstants.BUNDLE_VERSION, FRAGMENT_BUNDLE_VERSION); attribs.putValue(LauncherConstants.FRAGMENT_HOST, FRAGMENT_HOST_BUNDLE_NAME); attribs.putValue(LauncherConstants.BUNDLE_CLASSPATH, "."); File confFolder = new File(Utils.getCarbonComponentRepo(), "../conf"); String loggingPropFilePath = confFolder.getAbsolutePath() + File.separator + LOG4J_PROP_FILE_NAME; File dropinsFolder = new File(Utils.getCarbonComponentRepo(), "dropins"); String targetFilePath = dropinsFolder.getAbsolutePath() + File.separator + FRAGMENT_BUNDLE_NAME + "_" + FRAGMENT_BUNDLE_VERSION + ".jar"; String tempDirPath = Utils.JAR_TO_BUNDLE_DIR + File.separator + System.currentTimeMillis() + Math.random(); FileOutputStream mfos = null; try { Utils.copyFileToDir(new File(loggingPropFilePath), new File(tempDirPath)); String metaInfPath = tempDirPath + File.separator + "META-INF"; if (!new File(metaInfPath).mkdirs()) { throw new IOException("Failed to create the directory: " + metaInfPath); } mfos = new FileOutputStream(metaInfPath + File.separator + "MANIFEST.MF"); mf.write(mfos); Utils.archiveDir(targetFilePath, tempDirPath); Utils.deleteDir(new File(tempDirPath)); } finally { try { if (mfos != null) { mfos.close(); } } catch (IOException e) { log.error("Unable to close the OutputStream " + e.getMessage(), e); } } } catch (IOException e) { log.error("Error occured while creating the log4j prop fragment bundle.", e); } //Utils.createBundle(log4jPropFile, targetFragmentBundle, mf); //To change body of implemented methods use File | Settings | File Templates. }