Search in sources :

Example 1 with ExtendedDeploymentContext

use of org.glassfish.internal.deployment.ExtendedDeploymentContext in project Payara by payara.

the class JavaEEDeployer method prepare.

/**
 * Prepares the application bits for running in the application server.
 * For certain cases, this is generating non portable
 * artifacts and other application specific tasks.
 * Failure to prepare should throw an exception which will cause the overall
 * deployment to fail.
 *
 * @param dc deployment context
 * @return true if the prepare phase was successful
 */
public boolean prepare(DeploymentContext dc) {
    try {
        ((ExtendedDeploymentContext) dc).prepareScratchDirs();
        // In jaxrpc it was required to run
        // Wscompile to generate the artifacts for clients too.
        // service-ref element can be in client in web.xml,  application-client.xml, sun-ejb-jar.xml
        // Fix for issue 16015
        BundleDescriptor bundleDesc = dc.getModuleMetaData(BundleDescriptor.class);
        if (bundleDesc.hasWebServiceClients()) {
            JAXRPCCodeGenFacade jaxrpcCodeGenFacade = jaxrpcCodeGenFacadeProvider.get();
            if (jaxrpcCodeGenFacade != null) {
                jaxrpcCodeGenFacade.run(habitat, dc, getModuleClassPath(dc), true);
            }
        }
        if (!dc.getCommandParameters(OpsParams.class).origin.isArtifactsPresent()) {
            // only generate artifacts when there is no artifacts present
            generateArtifacts(dc);
        }
        return true;
    } catch (Exception ex) {
        // re-throw all the exceptions as runtime exceptions
        throw new RuntimeException(ex.getMessage(), ex);
    }
}
Also used : BundleDescriptor(com.sun.enterprise.deployment.BundleDescriptor) JAXRPCCodeGenFacade(org.glassfish.internal.api.JAXRPCCodeGenFacade) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) IOException(java.io.IOException) DeploymentException(org.glassfish.deployment.common.DeploymentException)

Example 2 with ExtendedDeploymentContext

use of org.glassfish.internal.deployment.ExtendedDeploymentContext in project Payara by payara.

the class EarHandler method getClassLoader.

public ClassLoader getClassLoader(final ClassLoader parent, DeploymentContext context) {
    final ReadableArchive archive = context.getSource();
    final ApplicationHolder holder = getApplicationHolder(archive, context, true);
    // the ear classloader hierachy will be
    // ear lib classloader <- embedded rar classloader <-
    // ear classloader <- various module classloaders
    final DelegatingClassLoader embeddedConnCl;
    final EarClassLoader cl;
    // add the libraries packaged in the application library directory
    try {
        String compatProp = context.getAppProps().getProperty(DeploymentProperties.COMPATIBILITY);
        // let's see if it's defined in glassfish-application.xml
        if (compatProp == null) {
            GFApplicationXmlParser gfApplicationXmlParser = new GFApplicationXmlParser(context.getSource());
            compatProp = gfApplicationXmlParser.getCompatibilityValue();
            if (compatProp != null) {
                context.getAppProps().put(DeploymentProperties.COMPATIBILITY, compatProp);
            }
        }
        // let's see if it's defined in sun-application.xml
        if (compatProp == null) {
            SunApplicationXmlParser sunApplicationXmlParser = new SunApplicationXmlParser(context.getSourceDir());
            compatProp = sunApplicationXmlParser.getCompatibilityValue();
            if (compatProp != null) {
                context.getAppProps().put(DeploymentProperties.COMPATIBILITY, compatProp);
            }
        }
        if (System.getSecurityManager() != null) {
            // procee declared permissions
            earDeclaredPC = PermsArchiveDelegate.getDeclaredPermissions(SMGlobalPolicyUtil.CommponentType.ear, context);
            // process ee permissions
            processEEPermissions(context);
        }
        final URL[] earLibURLs = ASClassLoaderUtil.getAppLibDirLibraries(context.getSourceDir(), holder.app.getLibraryDirectory(), compatProp);
        final EarLibClassLoader earLibCl = AccessController.doPrivileged(new PrivilegedAction<EarLibClassLoader>() {

            @Override
            public EarLibClassLoader run() {
                return new EarLibClassLoader(earLibURLs, parent);
            }
        });
        String clDelegate = holder.app.getClassLoadingDelegate();
        // default to true if null
        if (Boolean.parseBoolean(clDelegate == null ? "true" : clDelegate) == false) {
            earLibCl.enableCurrentBeforeParentUnconditional();
        } else if (clDelegate != null) {
            // otherwise clDelegate == true
            earLibCl.disableCurrentBeforeParent();
        }
        if (System.getSecurityManager() != null) {
            addEEOrDeclaredPermissions(earLibCl, earDeclaredPC, false);
            if (_logger.isLoggable(Level.FINE))
                _logger.fine("added declaredPermissions to earlib: " + earDeclaredPC);
            addEEOrDeclaredPermissions(earLibCl, eeGarntsMap.get(SMGlobalPolicyUtil.CommponentType.ear), true);
            if (_logger.isLoggable(Level.FINE))
                _logger.fine("added all ee permissions to earlib: " + eeGarntsMap.get(SMGlobalPolicyUtil.CommponentType.ear));
        }
        embeddedConnCl = AccessController.doPrivileged(new PrivilegedAction<DelegatingClassLoader>() {

            @Override
            public DelegatingClassLoader run() {
                return new DelegatingClassLoader(earLibCl);
            }
        });
        cl = AccessController.doPrivileged(new PrivilegedAction<EarClassLoader>() {

            @Override
            public EarClassLoader run() {
                return new EarClassLoader(embeddedConnCl, holder.app);
            }
        });
        // add ear lib to module classloader list so we can
        // clean it up later
        cl.addModuleClassLoader(EAR_LIB, earLibCl);
        if (System.getSecurityManager() != null) {
            // push declared permissions to ear classloader
            addEEOrDeclaredPermissions(cl, earDeclaredPC, false);
            if (_logger.isLoggable(Level.FINE))
                _logger.fine("declaredPermissions added: " + earDeclaredPC);
            // push ejb permissions to ear classloader
            addEEOrDeclaredPermissions(cl, eeGarntsMap.get(SMGlobalPolicyUtil.CommponentType.ejb), true);
            if (_logger.isLoggable(Level.FINE))
                _logger.fine("ee permissions added: " + eeGarntsMap.get(SMGlobalPolicyUtil.CommponentType.ejb));
        }
    } catch (Exception e) {
        _logger.log(Level.SEVERE, strings.get("errAddLibs"), e);
        throw new RuntimeException(e);
    }
    for (ModuleDescriptor md : holder.app.getModules()) {
        ReadableArchive sub = null;
        String moduleUri = md.getArchiveUri();
        try {
            sub = archive.getSubArchive(moduleUri);
            if (sub instanceof InputJarArchive) {
                throw new IllegalArgumentException(strings.get("wrongArchType", moduleUri));
            }
        } catch (IOException e) {
            _logger.log(Level.FINE, "Sub archive " + moduleUri + " seems unreadable", e);
        }
        if (sub != null) {
            try {
                ArchiveHandler handler = context.getModuleArchiveHandlers().get(moduleUri);
                if (handler == null) {
                    handler = getArchiveHandlerFromModuleType(md.getModuleType());
                    if (handler == null) {
                        handler = deployment.getArchiveHandler(sub);
                    }
                    context.getModuleArchiveHandlers().put(moduleUri, handler);
                }
                if (handler != null) {
                    ActionReport subReport = context.getActionReport().addSubActionsReport();
                    // todo : this is a hack, once again,
                    // the handler is assuming a file:// url
                    ExtendedDeploymentContext subContext = new DeploymentContextImpl(subReport, sub, context.getCommandParameters(DeployCommandParameters.class), env) {

                        @Override
                        public File getScratchDir(String subDirName) {
                            String modulePortion = Util.getURIName(getSource().getURI());
                            return (new File(super.getScratchDir(subDirName), modulePortion));
                        }
                    };
                    // sub context will store the root archive handler also
                    // so we can figure out the enclosing archive type
                    subContext.setArchiveHandler(context.getArchiveHandler());
                    subContext.setParentContext((ExtendedDeploymentContext) context);
                    sub.setParentArchive(context.getSource());
                    ClassLoader subCl = handler.getClassLoader(cl, subContext);
                    if ((System.getSecurityManager() != null) && (subCl instanceof DDPermissionsLoader)) {
                        addEEOrDeclaredPermissions(subCl, earDeclaredPC, false);
                        if (_logger.isLoggable(Level.FINE))
                            _logger.fine("added declared permissions to sub module of " + subCl);
                    }
                    if (md.getModuleType().equals(DOLUtils.ejbType())) {
                        // for ejb module, we just add the ejb urls
                        // to EarClassLoader and use that to load
                        // ejb module
                        URL[] moduleURLs = ((URLClassLoader) subCl).getURLs();
                        for (URL moduleURL : moduleURLs) {
                            cl.addURL(moduleURL);
                        }
                        cl.addModuleClassLoader(moduleUri, cl);
                        PreDestroy.class.cast(subCl).preDestroy();
                    } else if (md.getModuleType().equals(DOLUtils.rarType())) {
                        embeddedConnCl.addDelegate((DelegatingClassLoader.ClassFinder) subCl);
                        cl.addModuleClassLoader(moduleUri, subCl);
                    } else {
                        Boolean isTempClassLoader = context.getTransientAppMetaData(ExtendedDeploymentContext.IS_TEMP_CLASSLOADER, Boolean.class);
                        if (subCl instanceof URLClassLoader && (isTempClassLoader != null) && isTempClassLoader) {
                            // for temp classloader, we add all the module
                            // urls to the top level EarClassLoader
                            URL[] moduleURLs = ((URLClassLoader) subCl).getURLs();
                            for (URL moduleURL : moduleURLs) {
                                cl.addURL(moduleURL);
                            }
                        }
                        cl.addModuleClassLoader(moduleUri, subCl);
                    }
                }
            } catch (IOException e) {
                _logger.log(Level.SEVERE, strings.get("noClassLoader", moduleUri), e);
            }
        }
    }
    return cl;
}
Also used : AbstractArchiveHandler(com.sun.enterprise.deploy.shared.AbstractArchiveHandler) ActionReport(org.glassfish.api.ActionReport) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) URL(java.net.URL) ApplicationHolder(org.glassfish.javaee.core.deployment.ApplicationHolder) PrivilegedAction(java.security.PrivilegedAction) DDPermissionsLoader(com.sun.enterprise.security.integration.DDPermissionsLoader) URLClassLoader(java.net.URLClassLoader) DelegatingClassLoader(org.glassfish.internal.api.DelegatingClassLoader) InputJarArchive(com.sun.enterprise.deployment.deploy.shared.InputJarArchive) DelegatingClassLoader(org.glassfish.internal.api.DelegatingClassLoader) XMLStreamException(javax.xml.stream.XMLStreamException) PrivilegedActionException(java.security.PrivilegedActionException) SAXParseException(org.xml.sax.SAXParseException) DeployCommandParameters(org.glassfish.api.deployment.DeployCommandParameters) URLClassLoader(java.net.URLClassLoader) PreDestroy(org.glassfish.hk2.api.PreDestroy)

Example 3 with ExtendedDeploymentContext

use of org.glassfish.internal.deployment.ExtendedDeploymentContext in project Payara by payara.

the class VirtualServer method addContext.

/**
 * Registers the given <tt>Context</tt> with this <tt>VirtualServer</tt>
 * at the given context root.
 *
 * <p>If this <tt>VirtualServer</tt> has already been started, the
 * given <tt>context</tt> will be started as well.
 * @throws org.glassfish.embeddable.GlassFishException
 */
@Override
public void addContext(Context context, String contextRoot) throws ConfigException, GlassFishException {
    if (_logger.isLoggable(Level.FINE)) {
        _logger.log(Level.FINE, LogFacade.VS_ADDED_CONTEXT);
    }
    if (!(context instanceof ContextFacade)) {
        // embedded context should always be created via ContextFacade
        return;
    }
    if (!contextRoot.startsWith("/")) {
        contextRoot = "/" + contextRoot;
    }
    ExtendedDeploymentContext deploymentContext = null;
    try {
        if (factory == null)
            factory = services.getService(ArchiveFactory.class);
        ContextFacade facade = (ContextFacade) context;
        File docRoot = facade.getDocRoot();
        ClassLoader classLoader = facade.getClassLoader();
        ReadableArchive archive = factory.openArchive(docRoot);
        if (report == null)
            report = new PlainTextActionReporter();
        ServerEnvironment env = services.getService(ServerEnvironment.class);
        DeployCommandParameters params = new DeployCommandParameters();
        params.contextroot = contextRoot;
        params.enabled = Boolean.FALSE;
        params.origin = OpsParams.Origin.deploy;
        params.virtualservers = getName();
        params.target = "server";
        ExtendedDeploymentContext initialContext = new DeploymentContextImpl(report, archive, params, env);
        if (deployment == null)
            deployment = services.getService(Deployment.class);
        ArchiveHandler archiveHandler = deployment.getArchiveHandler(archive);
        if (archiveHandler == null) {
            throw new RuntimeException("Cannot find archive handler for source archive");
        }
        params.name = archiveHandler.getDefaultApplicationName(archive, initialContext);
        Applications apps = domain.getApplications();
        ApplicationInfo appInfo = deployment.get(params.name);
        ApplicationRef appRef = domain.getApplicationRefInServer(params.target, params.name);
        if (appInfo != null && appRef != null) {
            if (appRef.getVirtualServers().contains(getName())) {
                throw new ConfigException("Context with name " + params.name + " is already registered on virtual server " + getName());
            } else {
                String virtualServers = appRef.getVirtualServers();
                virtualServers = virtualServers + "," + getName();
                params.virtualservers = virtualServers;
                params.force = Boolean.TRUE;
                if (_logger.isLoggable(Level.FINE)) {
                    _logger.log(Level.FINE, "Virtual server " + getName() + " added to context " + params.name);
                }
                return;
            }
        }
        deploymentContext = deployment.getBuilder(_logger, params, report).source(archive).archiveHandler(archiveHandler).build(initialContext);
        Properties properties = new Properties();
        deploymentContext.getAppProps().putAll(properties);
        if (classLoader != null) {
            ClassLoader parentCL = clh.createApplicationParentCL(classLoader, deploymentContext);
            ClassLoader cl = archiveHandler.getClassLoader(parentCL, deploymentContext);
            deploymentContext.setClassLoader(cl);
        }
        ApplicationConfigInfo savedAppConfig = new ApplicationConfigInfo(apps.getModule(com.sun.enterprise.config.serverbeans.Application.class, params.name));
        Properties appProps = deploymentContext.getAppProps();
        String appLocation = DeploymentUtils.relativizeWithinDomainIfPossible(deploymentContext.getSource().getURI());
        appProps.setProperty(ServerTags.LOCATION, appLocation);
        appProps.setProperty(ServerTags.OBJECT_TYPE, "user");
        appProps.setProperty(ServerTags.CONTEXT_ROOT, contextRoot);
        savedAppConfig.store(appProps);
        Transaction t = deployment.prepareAppConfigChanges(deploymentContext);
        appInfo = deployment.deploy(deploymentContext);
        if (appInfo != null) {
            facade.setAppName(appInfo.getName());
            if (_logger.isLoggable(Level.FINE)) {
                _logger.log(Level.FINE, LogFacade.VS_ADDED_CONTEXT, new Object[] { getName(), appInfo.getName() });
            }
            deployment.registerAppInDomainXML(appInfo, deploymentContext, t);
        } else {
            if (report.getActionExitCode().equals(ActionReport.ExitCode.FAILURE)) {
                throw new ConfigException(report.getMessage());
            }
        }
        // Update web.xml with programmatically added servlets, filters, and listeners
        File file = null;
        boolean delete = true;
        com.sun.enterprise.config.serverbeans.Application appBean = apps.getApplication(params.name);
        if (appBean != null) {
            file = new File(deploymentContext.getSource().getURI().getPath(), "/WEB-INF/web.xml");
            if (file.exists()) {
                delete = false;
            }
            updateWebXml(facade, file);
        } else {
            _logger.log(Level.SEVERE, LogFacade.APP_NOT_FOUND);
        }
        ReadableArchive source = appInfo.getSource();
        UndeployCommandParameters undeployParams = new UndeployCommandParameters(params.name);
        undeployParams.origin = UndeployCommandParameters.Origin.undeploy;
        undeployParams.target = "server";
        ExtendedDeploymentContext undeploymentContext = deployment.getBuilder(_logger, undeployParams, report).source(source).build();
        deployment.undeploy(params.name, undeploymentContext);
        params.origin = DeployCommandParameters.Origin.load;
        params.enabled = Boolean.TRUE;
        archive = factory.openArchive(docRoot);
        deploymentContext = deployment.getBuilder(_logger, params, report).source(archive).build();
        if (classLoader != null) {
            ClassLoader parentCL = clh.createApplicationParentCL(classLoader, deploymentContext);
            archiveHandler = deployment.getArchiveHandler(archive);
            ClassLoader cl = archiveHandler.getClassLoader(parentCL, deploymentContext);
            deploymentContext.setClassLoader(cl);
        }
        deployment.deploy(deploymentContext);
        // Enable the app using the modified web.xml
        // We can't use Deployment.enable since it doesn't take DeploymentContext with custom class loader
        deployment.updateAppEnabledAttributeInDomainXML(params.name, params.target, true);
        if (_logger.isLoggable(Level.FINE)) {
            _logger.log(Level.FINE, LogFacade.VS_ENABLED_CONTEXT, new Object[] { getName(), params.name() });
        }
        if (delete) {
            if (file != null) {
                if (file.exists() && !file.delete()) {
                    String path = file.toString();
                    _logger.log(Level.WARNING, LogFacade.UNABLE_TO_DELETE, path);
                }
            }
        }
        if (contextRoot.equals("/")) {
            contextRoot = "";
        }
        WebModule wm = (WebModule) findChild(contextRoot);
        if (wm != null) {
            facade.setUnwrappedContext(wm);
            wm.setEmbedded(true);
            if (config != null) {
                wm.setDefaultWebXml(config.getDefaultWebXml());
            }
        } else {
            throw new ConfigException("Deployed app not found " + contextRoot);
        }
        if (deploymentContext != null) {
            deploymentContext.postDeployClean(true);
        }
    } catch (Exception ex) {
        if (deployment != null && deploymentContext != null) {
            deploymentContext.clean();
        }
        throw new GlassFishException(ex);
    }
}
Also used : GlassFishException(org.glassfish.embeddable.GlassFishException) ArchiveHandler(org.glassfish.api.deployment.archive.ArchiveHandler) ApplicationInfo(org.glassfish.internal.data.ApplicationInfo) ConfigException(org.glassfish.embeddable.web.ConfigException) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) ApplicationRef(com.sun.enterprise.config.serverbeans.ApplicationRef) ServerEnvironment(org.glassfish.api.admin.ServerEnvironment) WebappClassLoader(org.glassfish.web.loader.WebappClassLoader) PlainTextActionReporter(com.sun.enterprise.v3.common.PlainTextActionReporter) Applications(com.sun.enterprise.config.serverbeans.Applications) ConfigException(org.glassfish.embeddable.web.ConfigException) IOException(java.io.IOException) GlassFishException(org.glassfish.embeddable.GlassFishException) DeploymentContextImpl(org.glassfish.deployment.common.DeploymentContextImpl) DeployCommandParameters(org.glassfish.api.deployment.DeployCommandParameters) UndeployCommandParameters(org.glassfish.api.deployment.UndeployCommandParameters) Transaction(org.jvnet.hk2.config.Transaction) ApplicationConfigInfo(org.glassfish.deployment.common.ApplicationConfigInfo) ReadableArchive(org.glassfish.api.deployment.archive.ReadableArchive) File(java.io.File) Application(com.sun.enterprise.deployment.Application)

Example 4 with ExtendedDeploymentContext

use of org.glassfish.internal.deployment.ExtendedDeploymentContext in project Payara by payara.

the class ClusteredCDIEventBusImpl method postConstruct.

@PostConstruct
void postConstruct() {
    ctxUtil = Globals.getDefaultHabitat().getService(JavaEEContextUtil.class);
    ExtendedDeploymentContext dc = Globals.getDefaultHabitat().getService(Deployment.class).getCurrentDeploymentContext();
    ctxUtil.setInstanceComponentId(DOLUtils.getComponentEnvId((JndiNameEnvironment) DOLUtils.getCurrentBundleForContext(dc)));
    try {
        InitialContext ctx = new InitialContext();
        managedExecutorService = (ManagedExecutorService) ctx.lookup("java:comp/DefaultManagedExecutorService");
    } catch (NamingException ex) {
        throw new RuntimeException(ex);
    }
    runtime.addCDIListener(this);
    if (runtime.isClustered()) {
        Logger.getLogger(ClusteredCDIEventBusImpl.class.getName()).log(Level.INFO, "Clustered CDI Event bus initialized");
    }
}
Also used : JndiNameEnvironment(com.sun.enterprise.deployment.JndiNameEnvironment) JavaEEContextUtil(org.glassfish.internal.api.JavaEEContextUtil) Deployment(org.glassfish.internal.deployment.Deployment) NamingException(javax.naming.NamingException) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) InitialContext(javax.naming.InitialContext) PostConstruct(javax.annotation.PostConstruct)

Example 5 with ExtendedDeploymentContext

use of org.glassfish.internal.deployment.ExtendedDeploymentContext in project Payara by payara.

the class StandaloneAppClientDeployerHelper method copyOriginalAppClientJAR.

protected void copyOriginalAppClientJAR(final DeploymentContext dc) throws IOException {
    ReadableArchive originalSource = ((ExtendedDeploymentContext) dc).getOriginalSource();
    originalSource.open(originalSource.getURI());
    OutputJarArchive target = new OutputJarArchive();
    target.create(appClientServerURI(dc));
    /*
         * Copy the manifest explicitly because ReadableArchive.entries()
         * excludes the manifest.
         */
    Manifest originalManifest = originalSource.getManifest();
    OutputStream os = target.putNextEntry(JarFile.MANIFEST_NAME);
    originalManifest.write(os);
    target.closeEntry();
    copyArchive(originalSource, target, Collections.EMPTY_SET);
    target.close();
    originalSource.close();
}
Also used : OutputJarArchive(com.sun.enterprise.deployment.deploy.shared.OutputJarArchive) OutputStream(java.io.OutputStream) ReadableArchive(org.glassfish.api.deployment.archive.ReadableArchive) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) Manifest(java.util.jar.Manifest)

Aggregations

ExtendedDeploymentContext (org.glassfish.internal.deployment.ExtendedDeploymentContext)39 ActionReport (org.glassfish.api.ActionReport)23 IOException (java.io.IOException)17 DeployCommandParameters (org.glassfish.api.deployment.DeployCommandParameters)17 File (java.io.File)16 Logger (java.util.logging.Logger)11 ReadableArchive (org.glassfish.api.deployment.archive.ReadableArchive)11 ApplicationInfo (org.glassfish.internal.data.ApplicationInfo)10 Properties (java.util.Properties)9 URI (java.net.URI)7 Deployment (org.glassfish.internal.deployment.Deployment)7 DeploymentContext (org.glassfish.api.deployment.DeploymentContext)6 UndeployCommandParameters (org.glassfish.api.deployment.UndeployCommandParameters)6 ArchiveHandler (org.glassfish.api.deployment.archive.ArchiveHandler)6 DeploymentContextImpl (org.glassfish.deployment.common.DeploymentContextImpl)6 TransactionFailure (org.jvnet.hk2.config.TransactionFailure)6 Application (com.sun.enterprise.deployment.Application)5 ArrayList (java.util.ArrayList)5 DeploymentProperties (org.glassfish.deployment.common.DeploymentProperties)5 VersioningException (org.glassfish.deployment.versioning.VersioningException)5