Example usage for java.util.jar JarFile MANIFEST_NAME

List of usage examples for java.util.jar JarFile MANIFEST_NAME

Introduction

In this page you can find the example usage for java.util.jar JarFile MANIFEST_NAME.

Prototype

String MANIFEST_NAME

To view the source code for java.util.jar JarFile MANIFEST_NAME.

Click Source Link

Document

The JAR manifest file name.

Usage

From source file:org.kepler.kar.KARFile.java

/**
 * Returns only valid KAREntries contained in this KARFile. To get all of
 * the JarEntries use the entries() method.
 * /*from www .  j av  a 2  s . c om*/
 * @return List<KAREntry> of all valid KAREntries in this KARFile.
 */
public List<KAREntry> karEntries() {
    if (isDebugging)
        log.debug("karEntries()");
    Enumeration<JarEntry> entries = entries();
    Vector<KAREntry> karEntries = new Vector<KAREntry>();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        if (isDebugging)
            log.debug(entry.getName());
        if (entry.getName().equals("MANIFEST.MF") || entry.getName().equals("META-INF/")
                || entry.getName().equals(JarFile.MANIFEST_NAME)) {
            // skip manifest entries
        } else {
            KAREntry karEntry = new KAREntry(entry);
            if (karEntry.isValid()) {
                if (isDebugging)
                    log.debug("karEntry.isValid() == true");
                karEntries.add(karEntry);
            } else {
                if (isDebugging)
                    log.debug("karEntry.isValid() == false");
            }
        }
    }
    return karEntries;
}

From source file:org.lnicholls.galleon.app.AppDescriptor.java

public AppDescriptor(File jar) throws IOException, AppException {
    mJar = jar;/*from w ww. jav  a2  s . c om*/

    JarFile zipFile = new JarFile(jar);
    Enumeration entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        String name = entry.getName();
        if (name.toUpperCase().equals(JarFile.MANIFEST_NAME)) {
            InputStream in = null;
            try {
                in = zipFile.getInputStream(entry);
                Manifest manifest = new Manifest(in);
                Attributes attributes = manifest.getMainAttributes();
                if (attributes.getValue("Main-Class") != null) {
                    mClassName = (String) attributes.getValue("Main-Class");
                    if (attributes.getValue("HME-Arguments") != null)
                        mArguments = (String) attributes.getValue("HME-Arguments");
                    if (attributes.getValue(TITLE) != null)
                        mTitle = (String) attributes.getValue(TITLE);
                    if (attributes.getValue(RELEASE_DATE) != null)
                        mReleaseDate = (String) attributes.getValue(RELEASE_DATE);
                    if (attributes.getValue(DESCRIPTION) != null)
                        mDescription = (String) attributes.getValue(DESCRIPTION);
                    if (attributes.getValue(DOCUMENTATION) != null)
                        mDocumentation = (String) attributes.getValue(DOCUMENTATION);
                    if (attributes.getValue(AUTHOR_NAME) != null)
                        mAuthorName = (String) attributes.getValue(AUTHOR_NAME);
                    if (attributes.getValue(AUTHOR_EMAIL) != null)
                        mAuthorEmail = (String) attributes.getValue(AUTHOR_EMAIL);
                    if (attributes.getValue(AUTHOR_HOMEPAGE) != null)
                        mAuthorHomepage = (String) attributes.getValue(AUTHOR_HOMEPAGE);
                    if (attributes.getValue(VERSION) != null)
                        mVersion = (String) attributes.getValue(VERSION);
                    if (attributes.getValue(CONFIGURATION) != null)
                        mConfiguration = (String) attributes.getValue(CONFIGURATION);
                    if (attributes.getValue(CONFIGURATION_PANEL) != null)
                        mConfigurationPanel = (String) attributes.getValue(CONFIGURATION_PANEL);
                    if (attributes.getValue(TAGS) != null)
                        mTags = (String) attributes.getValue(TAGS);
                }

                if (mTitle == null) {
                    mTitle = jar.getName().substring(0, jar.getName().indexOf('.'));
                }
            } catch (Exception ex) {
                Tools.logException(AppDescriptor.class, ex, "Cannot get descriptor: " + jar.getAbsolutePath());
            } finally {
                if (in != null) {
                    try {
                        in.close();
                        in = null;
                    } catch (Exception ex) {
                    }
                }
            }
            break;
        }
    }
    zipFile.close();
}

From source file:org.openspaces.pu.container.servicegrid.PUServiceBeanImpl.java

private void startPU(String springXml) throws IOException, ClassNotFoundException {
    if (logger.isDebugEnabled()) {
        logger.debug(logMessage("Starting PU with [" + springXml + "]"));
    }/*from   w  w w  . ja v a 2  s.  co m*/

    String puName = (String) context.getInitParameter("puName");
    String puPath = (String) context.getInitParameter("puPath");
    String codeserver = context.getExportCodebase();

    org.openspaces.pu.sla.SLA sla = getSLA(getServiceBeanContext());

    Integer instanceId = this.instanceId;
    Integer backupId = this.backupId;

    // Derive instanceId and backupId if not explicitly set
    if (instanceId == null) {
        boolean hasBackups = sla.getNumberOfBackups() > 0;
        if (hasBackups) {
            instanceId = clusterGroup;
            //the first instance is primary so no backupid
            if (context.getServiceBeanConfig().getInstanceID().intValue() > 1) {
                backupId = (context.getServiceBeanConfig().getInstanceID().intValue() - 1);
            }
        } else {
            instanceId = context.getServiceBeanConfig().getInstanceID().intValue();
        }
    }

    //set cluster info
    clusterInfo = new ClusterInfo();
    String clusterSchema = sla.getClusterSchema();
    if (clusterSchema != null) {
        clusterInfo.setSchema(clusterSchema);
        int slaMax = getSLAMax(context);
        int numberOfInstances = Math.max(slaMax, sla.getNumberOfInstances());
        clusterInfo.setNumberOfInstances(numberOfInstances);
    } else {
        clusterInfo.setNumberOfInstances(sla.getNumberOfInstances());
    }
    clusterInfo.setNumberOfBackups(sla.getNumberOfBackups());
    clusterInfo.setInstanceId(instanceId);
    clusterInfo.setBackupId(backupId);
    clusterInfo.setName(puName);

    ClusterInfoParser.guessSchema(clusterInfo);

    logger.info(logMessage("ClusterInfo [" + clusterInfo + "]"));

    MarshalledObject beanLevelPropertiesMarshObj = (MarshalledObject) getServiceBeanContext()
            .getInitParameter("beanLevelProperties");
    BeanLevelProperties beanLevelProperties;
    if (beanLevelPropertiesMarshObj != null) {
        beanLevelProperties = (BeanLevelProperties) beanLevelPropertiesMarshObj.get();
        logger.info(logMessage("BeanLevelProperties " + beanLevelProperties));
    } else {
        beanLevelProperties = new BeanLevelProperties();
    }
    beanLevelProperties.getContextProperties()
            .putAll(ClusterInfoPropertyPlaceholderConfigurer.createProperties(clusterInfo));

    // set a generic work location that can be used by container providers
    File workLocation = new File(SystemInfo.singleton().locations().work());
    workLocation.mkdirs();

    beanLevelProperties.getContextProperties().setProperty("com.gs.work", workLocation.getAbsolutePath());

    boolean downloadPU = false;
    //create PU Container
    ProcessingUnitContainerProvider factory;
    // identify if this is a web app
    final InputStream webXml = openUrlStream(codeserver + puPath + "/WEB-INF/web.xml");
    // identify if this is a .NET one
    final InputStream puConfig = openUrlStream(codeserver + puPath + "/pu.config");
    // identify if this is a .NET interop one
    final InputStream puInteropConfig = openUrlStream(codeserver + puPath + "/pu.interop.config");

    String processingUnitContainerProviderClass;
    if (webXml != null) {
        webXml.close();
        downloadPU = true;
        String jeeContainer = JeeProcessingUnitContainerProvider.getJeeContainer(beanLevelProperties);
        String[] classesToLoad = null;
        if ("jetty".equals(jeeContainer)) {
            // pre load the jetty server class so the static shutdown thread will be loaded under it
            classesToLoad = new String[] { "org.eclipse.jetty.server.Server" };
        }
        // setup class loaders correcly
        try {
            Thread.currentThread().setContextClassLoader(CommonClassLoader.getInstance());
            ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(
                    new String[] { JeeProcessingUnitContainerProvider.getJeeContainerJarPath(jeeContainer) }));
            ((ServiceClassLoader) contextClassLoader)
                    .setParentClassLoader(SharedServiceData.getJeeClassLoader(jeeContainer, classesToLoad));
        } catch (Exception e) {
            throw new CannotCreateContainerException("Failed to configure JEE class loader", e);
        } finally {
            Thread.currentThread().setContextClassLoader(contextClassLoader);
        }

        String className = StringUtils.capitalize(jeeContainer) + "JeeProcessingUnitContainerProvider";
        processingUnitContainerProviderClass = "org.openspaces.pu.container.jee." + jeeContainer + "."
                + className;
    } else if (puConfig != null) {
        puConfig.close();
        downloadPU = true;
        processingUnitContainerProviderClass = DotnetProcessingUnitContainerProvider.class.getName();
    } else if (puInteropConfig != null) {
        puInteropConfig.close();
        downloadPU = true;
        processingUnitContainerProviderClass = IntegratedProcessingUnitContainerProvider.class.getName();
    } else {
        processingUnitContainerProviderClass = IntegratedProcessingUnitContainerProvider.class.getName();
        if (beanLevelProperties.getContextProperties().getProperty("pu.download", "true")
                .equalsIgnoreCase("true")) {
            downloadPU = true;
        }
    }

    if (beanLevelProperties != null) {
        processingUnitContainerProviderClass = beanLevelProperties.getContextProperties().getProperty(
                ProcessingUnitContainerProvider.CONTAINER_CLASS_PROP, processingUnitContainerProviderClass);
    }

    if (downloadPU) {
        String deployName = puName + "_" + clusterInfo.getRunningNumberOffset1();

        String deployedProcessingUnitsLocation = workLocation.getAbsolutePath() + "/processing-units";

        int uuid = Math.abs(new Random().nextInt());

        deployPath = new File(
                deployedProcessingUnitsLocation + "/" + deployName.replace('.', '_') + "_" + uuid);
        FileSystemUtils.deleteRecursively(deployPath);
        deployPath.mkdirs();

        // backward compatible
        beanLevelProperties.getContextProperties().setProperty("jee.deployPath", deployPath.getAbsolutePath());
        beanLevelProperties.getContextProperties().setProperty("dotnet.deployPath",
                deployPath.getAbsolutePath());

        beanLevelProperties.getContextProperties().setProperty(
                ProcessingUnitContainerProvider.CONTEXT_PROPERTY_DEPLOY_PATH, deployPath.getAbsolutePath());

        try {
            if (isOnGsmHost()) {
                copyPu(puPath, deployPath);
            } else {
                long size = downloadAndExtractPU(puName, puPath, codeserver, deployPath,
                        new File(deployedProcessingUnitsLocation));
                logDownloadSize(size);
            }
        } catch (MalformedURLException mle) {
            logger.warn("Could not determine if GSC and GSM are on the same host", mle);
            // fallback to download
            long size = downloadAndExtractPU(puName, puPath, codeserver, deployPath,
                    new File(deployedProcessingUnitsLocation));
            logDownloadSize(size);
        } catch (UnknownHostException unhe) {
            logger.warn("Could not determine if GSC and GSM are on the same host", unhe);
            // fallback to download
            long size = downloadAndExtractPU(puName, puPath, codeserver, deployPath,
                    new File(deployedProcessingUnitsLocation));
            logDownloadSize(size);
        } catch (RemoteException re) {
            logger.warn("Could not determine if GSC and GSM are on the same host", re);
            // fallback to download
            long size = downloadAndExtractPU(puName, puPath, codeserver, deployPath,
                    new File(deployedProcessingUnitsLocation));
            logDownloadSize(size);
        }

        // go over listed files that needs to be resolved with properties
        for (Map.Entry entry : beanLevelProperties.getContextProperties().entrySet()) {
            String key = (String) entry.getKey();
            if (key.startsWith("com.gs.resolvePlaceholder")) {
                String path = (String) entry.getValue();
                File input = new File(deployPath, path);
                if (logger.isDebugEnabled()) {
                    logger.debug("Resolving placeholder for file [" + input.getAbsolutePath() + "]");
                }
                BeanLevelPropertiesUtils.resolvePlaceholders(beanLevelProperties, input);
            }
        }
    }

    boolean sharedLibEnabled;
    if (beanLevelProperties.getContextProperties().containsKey("pu.shared-lib.enable")) {
        sharedLibEnabled = beanLevelProperties.getContextProperties().getProperty("pu.shared-lib")
                .equals("true");
    } else {
        sharedLibEnabled = System.getProperty("com.gs.pu.shared-lib.enable", "false").equals("true");
    }

    final boolean disableManifestClassPathJars = Boolean.getBoolean("com.gs.pu.manifest.classpath.disable");
    final boolean disableManifestClassPathCommonPuJars = Boolean
            .getBoolean("com.gs.pu.manifest.classpath.common.disable");

    // this is used to inject the manifest jars to the webapp classloader (if exists)
    List<URL> manifestClassPathJars = new ArrayList<URL>();

    CommonClassLoader commonClassLoader = CommonClassLoader.getInstance();
    // handles class loader libraries
    if (downloadPU) {
        List<URL> libUrls = new ArrayList<URL>();
        File libDir = new File(deployPath, "lib");
        if (libDir.exists()) {
            File[] libFiles = BootIOUtils.listFiles(libDir);
            for (File libFile : libFiles) {
                libUrls.add(libFile.toURI().toURL());
            }
        }

        if (!disableManifestClassPathJars) {
            File manifestFile = new File(deployPath, JarFile.MANIFEST_NAME);

            if (manifestFile.isFile()) {
                try {
                    InputStream manifestStream = new FileInputStream(manifestFile);
                    manifestClassPathJars = getManifestClassPathJars(puName, manifestStream);
                    libUrls.addAll(manifestClassPathJars);
                } catch (IOException e) {
                    if (logger.isWarnEnabled()) {
                        logger.warn(failedReadingManifest(puName), e);
                    }
                }
            }

        }

        // add to common class loader
        List<URL> sharedlibUrls = new ArrayList<URL>();
        File sharedlibDir = new File(deployPath, "shared-lib");
        if (sharedlibDir.exists()) {
            File[] sharedlibFiles = BootIOUtils.listFiles(sharedlibDir);
            for (File sharedlibFile : sharedlibFiles) {
                sharedlibUrls.add(sharedlibFile.toURI().toURL());
            }
        }
        sharedlibDir = new File(deployPath, "WEB-INF/shared-lib");
        if (sharedlibDir.exists()) {
            File[] sharedlibFiles = BootIOUtils.listFiles(sharedlibDir);
            for (File sharedlibFile : sharedlibFiles) {
                sharedlibUrls.add(sharedlibFile.toURI().toURL());
            }
        }

        if (sharedLibEnabled) {
            ((ServiceClassLoader) contextClassLoader).setSlashPath(deployPath.toURI().toURL());
            ((ServiceClassLoader) contextClassLoader).setLibPath(libUrls.toArray(new URL[libUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Service Class Loader "
                        + Arrays.toString(((ServiceClassLoader) contextClassLoader).getURLs())));
            }

            commonClassLoader.addComponent(puName, sharedlibUrls.toArray(new URL[sharedlibUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Common Class Loader " + sharedlibUrls));
            }
        } else {
            if (sharedlibUrls.size() > 0) {
                logger.warn("Using old 'shared-lib' directory, will add jars under it as if it was 'lib'");
            }
            libUrls.addAll(sharedlibUrls);

            // add pu-common jar files
            String gsLibOpt = Locator.getLibOptional();
            String gsPuCommon = System.getProperty("com.gs.pu-common", gsLibOpt + "pu-common");

            final String gsLibOptSecurity = Locator.getLibOptionalSecurity();
            libUrls.addAll(Arrays.asList(BootUtil.toURLs(new String[] { gsPuCommon, gsLibOptSecurity })));

            if (ScalaIdentifier.isScalaLibInClassPath()) {
                String gsLibPlatform = Locator.getLibPlatform();
                // note that we assume BootUtil.toURLs does not work recursively here
                // i.e, only gs-openspaces-scala.jar will be added and not all the files under /lib
                String gsLibPlatformScala = gsLibPlatform + "scala";
                libUrls.addAll(Arrays.asList(BootUtil.toURLs(new String[] { gsLibPlatformScala })));
            }

            if (!disableManifestClassPathJars && !disableManifestClassPathCommonPuJars) {
                URLClassLoader urlClassLoader = new URLClassLoader(BootUtil.toURLs(new String[] { gsPuCommon }),
                        null /* parent */);
                InputStream puCommonManifestMF = urlClassLoader.getResourceAsStream(JarFile.MANIFEST_NAME);
                if (puCommonManifestMF != null) {
                    List<URL> manifestClassPathComonPuJars = getManifestClassPathJars(puName,
                            puCommonManifestMF);
                    manifestClassPathJars.addAll(manifestClassPathComonPuJars);
                    libUrls.addAll(manifestClassPathComonPuJars);
                }
            }

            ((ServiceClassLoader) contextClassLoader).setSlashPath(deployPath.toURI().toURL());
            ((ServiceClassLoader) contextClassLoader).setLibPath(libUrls.toArray(new URL[libUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Service Class Loader "
                        + Arrays.toString(((ServiceClassLoader) contextClassLoader).getURLs())));
            }
        }
        try {
            prepareWebApplication(deployPath, clusterInfo, beanLevelProperties);
        } catch (Exception e) {
            throw new CannotCreateContainerException("Failed to bootstrap web application", e);
        }
    } else {
        // add to service class loader
        List<URL> libUrls = new ArrayList<URL>();
        WebsterFile libDir = new WebsterFile(new URL(codeserver + puPath + "/lib"));
        File[] libFiles = libDir.listFiles();
        for (int i = 0; i < libFiles.length; i++) {
            libUrls.add(new URL(codeserver + puPath + "/lib/" + libFiles[i].getName()));
        }

        if (!disableManifestClassPathJars) {
            InputStream manifestStream = readManifestFromCodeServer(puName, puPath, codeserver, workLocation);
            if (manifestStream != null) {
                manifestClassPathJars = getManifestClassPathJars(puName, manifestStream);
                libUrls.addAll(manifestClassPathJars);
            }
        }

        // add to common class loader
        WebsterFile sharedlibDir = new WebsterFile(new URL(codeserver + puPath + "/shared-lib"));
        File[] sharedlibFiles = sharedlibDir.listFiles();
        List<URL> sharedlibUrls = new ArrayList<URL>();
        for (File sharedlibFile : sharedlibFiles) {
            sharedlibUrls.add(new URL(codeserver + puPath + "/shared-lib/" + sharedlibFile.getName()));
        }
        sharedlibDir = new WebsterFile(new URL(codeserver + puPath + "/WEB-INF/shared-lib"));
        sharedlibFiles = sharedlibDir.listFiles();
        for (File sharedlibFile : sharedlibFiles) {
            sharedlibUrls.add(new URL(codeserver + puPath + "/WEB-INF/shared-lib/" + sharedlibFile.getName()));
        }

        if (sharedLibEnabled) {
            ((ServiceClassLoader) contextClassLoader).setSlashPath(new URL(codeserver + puPath + "/"));
            ((ServiceClassLoader) contextClassLoader).setLibPath(libUrls.toArray(new URL[libUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Service Class Loader "
                        + Arrays.toString(((ServiceClassLoader) contextClassLoader).getURLs())));
            }

            commonClassLoader.addComponent(puName, sharedlibUrls.toArray(new URL[sharedlibUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Common Class Loader " + sharedlibUrls));
            }
        } else {
            if (sharedlibUrls.size() > 0) {
                logger.warn("Using old 'shared-lib' directory, will add jars under it as if it was 'lib'");
            }
            libUrls.addAll(sharedlibUrls);
            ((ServiceClassLoader) contextClassLoader).setSlashPath(new URL(codeserver + puPath + "/"));
            ((ServiceClassLoader) contextClassLoader).setLibPath(libUrls.toArray(new URL[libUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Service Class Loader "
                        + Arrays.toString(((ServiceClassLoader) contextClassLoader).getURLs())));
            }
        }
    }

    // handle mule os if there is one class loader
    try {
        contextClassLoader.loadClass("org.mule.api.MuleContext");
        ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(new String[] {
                SystemInfo.singleton().locations().lib() + "/optional/openspaces/mule-os.jar" }));
    } catch (Throwable e) {
        // no mule
    }

    //apply the following only if the pu has the rest element
    if (springXml.contains("<os-core:rest")) {
        String jeeContainer = JeeProcessingUnitContainerProvider.getJeeContainer(beanLevelProperties);
        // pre load the jetty server class so the static shutdown thread will be loaded under it

        String[] classesToLoad = new String[] { "org.eclipse.jetty.server.Server" };
        String jettyJars = System.getProperty("com.gigaspaces.rest.jetty",
                JeeProcessingUnitContainerProvider.getJeeContainerJarPath(jeeContainer));
        // setup class loaders correctly
        try {
            Thread.currentThread().setContextClassLoader(CommonClassLoader.getInstance());
            ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(new String[] { jettyJars,
                    SystemInfo.singleton().locations().lib()
                            + "/platform/jetty/org.apache.jasper.glassfish-2.2.2.v201112011158.jar",
                    SystemInfo.singleton().locations().lib() + "/optional/spring/spring-web-4.1.1.RELEASE.jar",
                    SystemInfo.singleton().locations().lib()
                            + "/optional/spring/spring-webmvc-4.1.1.RELEASE.jar",
                    SystemInfo.singleton().locations().lib() + "/optional/jackson/jackson-core-2.3.0.jar",
                    SystemInfo.singleton().locations().lib() + "/optional/jackson/jackson-databind-2.3.0.jar",
                    SystemInfo.singleton().locations().lib()
                            + "/optional/jackson/jackson-annotations-2.3.0.jar",
                    SystemInfo.singleton().locations().lib() + "/platform/rest/xap-rest.jar" }));
            ((ServiceClassLoader) contextClassLoader)
                    .setParentClassLoader(SharedServiceData.getJeeClassLoader(jeeContainer, classesToLoad));
        } catch (Exception e) {
            throw new CannotCreateContainerException("Failed to configure class loader", e);
        } finally {
            //TODO check if we need this
            Thread.currentThread().setContextClassLoader(contextClassLoader);
        }
    }

    //apply the following only if the pu has the mapdb-blob-store element
    if (springXml.contains("<blob-store:mapdb-blob-store")) {
        String mapdbJar = System.getProperty("com.gigaspaces.blobstore.mapdb",
                SystemInfo.singleton().locations().lib() + "/optional/blobstore/mapdb-blobstore.jar");

        Thread.currentThread().setContextClassLoader(CommonClassLoader.getInstance());
        ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(new String[] { mapdbJar }));
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }

    //apply the following only if the pu has the rocksdb-blob-store element
    if (springXml.contains("<blob-store:rocksdb-blob-store")
            || springXml.contains("class=\"com.gigaspaces.blobstore.rocksdb.RocksDBBlobStoreHandler\"")) {
        String rocksdbJar = System.getProperty("com.gigaspaces.blobstore.rocksdb",
                SystemInfo.singleton().locations().lib() + "/optional/blobstore/rocksdb-blobstore.jar");

        Thread.currentThread().setContextClassLoader(CommonClassLoader.getInstance());
        ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(new String[] { rocksdbJar }));
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }

    final Map<String, String> puTags = buildPuTags(clusterInfo);
    MetricRegistrator puMetricRegistrator = metricManager.createRegistrator("pu", puTags);
    this.metricRegistrators = metricManager.registerProcessMetrics(puTags);
    this.metricRegistrators.add(puMetricRegistrator);
    for (Map.Entry<String, String> entry : puTags.entrySet())
        beanLevelProperties.getContextProperties().setProperty("metrics." + entry.getKey(), entry.getValue());
    //inject quiesce state changed event in order let space know to be initialized in quiesced mode
    if (quiesceDetails != null && quiesceDetails.getStatus() == QuiesceState.QUIESCED) {
        beanLevelProperties.getContextProperties().setProperty("quiesce.token",
                quiesceDetails.getToken().toString());
        beanLevelProperties.getContextProperties().setProperty("quiesce.description",
                quiesceDetails.getDescription());
    }
    factory = createContainerProvider(processingUnitContainerProviderClass);
    factory.setDeployPath(deployPath);
    factory.setClassLoader(contextClassLoader);
    factory.setManifestUrls(manifestClassPathJars);

    // only load the spring xml file if it is not a web application (if it is a web application, we will load it with the Bootstrap servlet context loader)
    if (webXml == null && factory instanceof ApplicationContextProcessingUnitContainerProvider) {
        if (StringUtils.hasText(springXml)) {
            // GS-9350: if this is a processing unit with gateway declarations, always try to
            // re-load the pu.xml to support "hot-deploy" (refresh)
            if (springXml.contains("os-gateway:")) {
                String deployPath = beanLevelProperties.getContextProperties().getProperty("deployPath");
                if (StringUtils.hasText(deployPath)) {
                    String newSpringXml = readFile(deployPath + "/META-INF/spring/pu.xml");
                    if (StringUtils.hasText(newSpringXml)) {
                        springXml = newSpringXml; //override with new one
                    }
                }
            }
            Resource resource = new ByteArrayResource(springXml.getBytes());
            ((ApplicationContextProcessingUnitContainerProvider) factory).addConfigLocation(resource);
        }
    }
    factory.setClusterInfo(clusterInfo);
    factory.setBeanLevelProperties(beanLevelProperties);
    factory.setMetricRegistrator(puMetricRegistrator);

    container = factory.createContainer();

    // set the context class loader to the web app class loader if there is one
    // this menas that from now on, and the exported service, will use the context class loader
    ClassLoader webAppClassLoader = SharedServiceData.removeWebAppClassLoader(clusterInfo.getUniqueName());
    if (webAppClassLoader != null) {
        contextClassLoader = webAppClassLoader;
    }
    Thread.currentThread().setContextClassLoader(contextClassLoader);

    buildMembersAliveIndicators();
    buildUndeployingEventListeners();
    buildDumpProcessors();

    ArrayList<Object> serviceDetails = buildServiceDetails();

    buildServiceMonitors();

    buildInvocableServices();

    this.puDetails = new PUDetails(context.getParentServiceID(), clusterInfo, beanLevelProperties,
            serviceDetails.toArray(new Object[serviceDetails.size()]));

    if (container instanceof ApplicationContextProcessingUnitContainer) {
        ApplicationContext applicationContext = ((ApplicationContextProcessingUnitContainer) container)
                .getApplicationContext();

        // inject the application context to all the monitors and schedule them
        // currently use the number of threads in relation to the number of monitors
        int numberOfThreads = watchTasks.size() / 5;
        if (numberOfThreads == 0) {
            numberOfThreads = 1;
        }
        executorService = Executors.newScheduledThreadPool(numberOfThreads);
        for (WatchTask watchTask : watchTasks) {
            if (watchTask.getMonitor() instanceof ApplicationContextMonitor) {
                ((ApplicationContextMonitor) watchTask.getMonitor()).setApplicationContext(applicationContext);
            }
            executorService.scheduleAtFixedRate(watchTask, watchTask.getMonitor().getPeriod(),
                    watchTask.getMonitor().getPeriod(), TimeUnit.MILLISECONDS);
        }
    }
}

From source file:org.openspaces.pu.container.servicegrid.PUServiceBeanImpl.java

private InputStream readManifestFromCodeServer(String puName, String puPath, String codeserver,
        File workLocation) {/*from  ww  w. ja v a 2  s  .  c  om*/
    try {
        URL manifestURL = new URL(codeserver + puPath + "/" + JarFile.MANIFEST_NAME);
        return manifestURL.openStream();
    } catch (IOException e) {
        if (logger.isDebugEnabled()) {
            logger.debug(failedReadingManifest(puName), e);
        }
        return null;
    }
}

From source file:org.pentaho.osgi.platform.plugin.deployer.impl.PluginZipFileProcessor.java

public void process(Supplier<ZipInputStream> zipInputStreamProvider, ZipOutputStream zipOutputStream)
        throws IOException {
    File dir = Files.createTempDir();
    PluginMetadata pluginMetadata = null;
    try {/*  w  w  w.j  a va 2 s  .c om*/
        pluginMetadata = new PluginMetadataImpl(dir);
    } catch (ParserConfigurationException e) {
        throw new IOException(e);
    }
    Manifest manifest = null;
    ZipInputStream zipInputStream = zipInputStreamProvider.get();
    try {
        logger.debug("Processing plugin - Name: {} SymbolicName: {} Version: {}", this.name, this.symbolicName,
                this.version);
        ZipEntry zipEntry;

        byte[] pluginSpringXmlBytes = null;
        String pluginSpringXmlName = null;
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            String name = zipEntry.getName();

            byte[] bytes = getEntryBytes(zipInputStream);
            // [BACKLOG-14815]
            // Ensures the plugin.xml file is read before plugin.spring.xml. This is needed so
            // {@link org.pentaho.osgi.platform.plugin.deployer.impl.handlers.SpringFileHandler#handle()}
            // can get the proper bundleName and set the service entry point.
            if (pluginSpringXmlBytes == null && name != null && name.endsWith(PLUGIN_SPRING_XML_FILENAME)) {
                pluginSpringXmlBytes = bytes; // Store plugin.spring.xml for processing after plugin.xml
                pluginSpringXmlName = name;
            } else {
                processEntry(zipOutputStream, pluginMetadata, zipEntry.isDirectory(), name, bytes);
            }
        }

        if (pluginSpringXmlBytes != null) {
            processEntry(zipOutputStream, pluginMetadata, false, pluginSpringXmlName, pluginSpringXmlBytes);
        }

    } finally {
        IOUtils.closeQuietly(zipInputStream);
    }

    // Write blueprint to disk, picked up with others later
    int tries = 100;
    File blueprintDir = new File(
            dir.getAbsolutePath() + "/" + BLUEPRINT.substring(0, BLUEPRINT.lastIndexOf('/')));
    while (!blueprintDir.exists() && tries-- > 0) {
        blueprintDir.mkdirs();
    }
    FileOutputStream blueprintOutputStream = null;
    try {
        blueprintOutputStream = new FileOutputStream(dir.getAbsolutePath() + "/" + BLUEPRINT);
        pluginMetadata.writeBlueprint(name, blueprintOutputStream);
    } finally {
        if (blueprintOutputStream != null) {
            blueprintOutputStream.close();
        }
    }

    Set<String> createdEntries = new HashSet<String>();

    // 1. Write Manifest Directory
    String manifestFolder = JarFile.MANIFEST_NAME.split("/")[0] + "/";
    ZipEntry manifestFolderEntry = new ZipEntry(manifestFolder);
    zipOutputStream.putNextEntry(manifestFolderEntry);
    zipOutputStream.closeEntry();
    createdEntries.add(manifestFolder);

    // 2. Write Manifest
    ZipEntry manifestEntry = new ZipEntry(JarFile.MANIFEST_NAME);
    zipOutputStream.putNextEntry(manifestEntry);
    pluginMetadata.getManifestUpdater().write(manifest, zipOutputStream, name, symbolicName, version);
    zipOutputStream.closeEntry();
    createdEntries.add(JarFile.MANIFEST_NAME);

    // Handlers may have written files to disk which need to be added.
    Stack<File> dirStack = new Stack<File>();
    dirStack.push(dir);
    int len = 0;
    byte[] buffer = new byte[1024];
    try {
        while (dirStack.size() > 0) {
            File currentDir = dirStack.pop();
            String dirName = currentDir.getAbsolutePath().substring(dir.getAbsolutePath().length()) + "/";
            if (dirName.startsWith("/") || dirName.startsWith("\\")) {
                dirName = dirName.substring(1);
            }
            if (dirName.length() > 0 && !createdEntries.contains(dirName)) {
                ZipEntry zipEntry = new ZipEntry(dirName.replaceAll(Pattern.quote("\\"), "/"));
                zipOutputStream.putNextEntry(zipEntry);
                zipOutputStream.closeEntry();
            }
            File[] dirFiles = currentDir.listFiles();
            if (dirFiles != null) {
                for (File childFile : dirFiles) {
                    if (childFile.isDirectory()) {
                        dirStack.push(childFile);
                    } else {
                        String fileName = childFile.getAbsolutePath()
                                .substring(dir.getAbsolutePath().length() + 1);
                        FileInputStream fileInputStream = null;
                        try {
                            fileInputStream = new FileInputStream(childFile);
                            ZipEntry childZipEntry = new ZipEntry(
                                    fileName.replaceAll(Pattern.quote("\\"), "/"));
                            zipOutputStream.putNextEntry(childZipEntry);
                            while ((len = fileInputStream.read(buffer)) != -1) {
                                zipOutputStream.write(buffer, 0, len);
                            }
                            zipOutputStream.closeEntry();
                        } finally {
                            if (fileInputStream != null) {
                                fileInputStream.close();
                            }
                        }
                    }
                }
            }
        }
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
        recursiveDelete(dir);
    }
}

From source file:org.pentaho.osgi.platform.plugin.deployer.impl.PluginZipFileProcessor.java

public void processManifest(ZipOutputStream zipOutputStream) throws IOException {
    Manifest manifest = null;//from   w  ww.  j ava  2  s .co m

    String manifestFolder = JarFile.MANIFEST_NAME.split("/")[0] + "/";
    ZipEntry manifestFolderEntry = new ZipEntry(manifestFolder);
    zipOutputStream.putNextEntry(manifestFolderEntry);
    zipOutputStream.closeEntry();

    ZipEntry manifestEntry = new ZipEntry(JarFile.MANIFEST_NAME);
    zipOutputStream.putNextEntry(manifestEntry);
    new ManifestUpdaterImpl().write(manifest, zipOutputStream, name, symbolicName, version);
    zipOutputStream.closeEntry();

    zipOutputStream.flush();

    zipOutputStream.close();
}

From source file:org.rhq.core.clientapi.descriptor.PluginTransformer.java

private String getVersionFromPluginJarManifest(URL pluginJarUrl) throws IOException {
    JarInputStream jarInputStream = new JarInputStream(pluginJarUrl.openStream());
    Manifest manifest = jarInputStream.getManifest();
    if (manifest == null) {
        // BZ 682116 (ips, 03/25/11): The manifest file is not in the standard place as the 2nd entry of the JAR,
        // but we want to be flexible and support JARs that have a manifest file somewhere else, so scan the entire
        // JAR for one.
        JarEntry jarEntry;//  w w  w. jav a2s.  com
        while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
            if (JarFile.MANIFEST_NAME.equalsIgnoreCase(jarEntry.getName())) {
                manifest = new Manifest(jarInputStream);
                break;
            }
        }
    }
    try {
        jarInputStream.close();
    } catch (IOException e) {
        LOG.error("Failed to close plugin jar input stream for plugin jar [" + pluginJarUrl + "].", e);
    }
    if (manifest != null) {
        Attributes attributes = manifest.getMainAttributes();
        return attributes.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
    } else {
        return null;
    }
}

From source file:org.sourcepit.common.manifest.util.ManifestUtils.java

public static Manifest readJarManifest(File jarFile) throws IOException {
    final URI manifestUri = URI
            .createURI("jar:" + URI.createFileURI(jarFile.getAbsolutePath()) + "!/" + JarFile.MANIFEST_NAME);

    final ManifestResource resource = new GenericManifestResourceImpl(manifestUri);

    ZipInputStream jarIn = null;/*from ww w .j av a  2  s.c o  m*/
    try {
        jarIn = new ZipInputStream(new BufferedInputStream(FileUtils.openInputStream(jarFile)));
        ZipEntry zipEntry = jarIn.getNextEntry();
        while (zipEntry != null) {
            if (JarFile.MANIFEST_NAME.equals(zipEntry.getName())) {
                resource.load(jarIn, null);
                break;
            }
            zipEntry = jarIn.getNextEntry();
        }
    } finally {
        IOUtils.closeQuietly(jarIn);
    }

    return (Manifest) resource.getContents().get(0);

}

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 ww w  . j a v  a2  s  .c  om*/
        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.sourcepit.osgifier.core.packaging.Repackager.java

private void rePackageJarFile(File srcJarFile, final Manifest manifest, BundleLocalization localization,
        final JarOutputStream destJarOut, Collection<String> pathFilters) throws IOException {
    destJarOut.putNextEntry(new JarEntry(JarFile.MANIFEST_NAME));
    writeManifest(manifest, destJarOut);
    destJarOut.closeEntry();//from  www  .ja  v  a  2s. co m

    if (localization != null) {
        final Set<String> paths = BundleLocalizationWriter.write(destJarOut, manifest, localization).keySet();
        pathFilters = pathFilters == null ? new HashSet<String>() : new HashSet<String>(pathFilters);
        for (String path : paths) {
            pathFilters.add("!" + path);
        }
    }

    final PathMatcher pathMatcher = pathFilters == null ? DEFAULT_CONTENT_MATCHER
            : createJarContentMatcher(pathFilters);

    new IOOperation<JarInputStream>(jarIn(buffIn(fileIn(srcJarFile)))) {
        @Override
        protected void run(JarInputStream srcJarIn) throws IOException {
            copyJarContents(srcJarIn, destJarOut, pathMatcher);
        }
    }.run();
}