Search in sources :

Example 16 with ReadableArchive

use of org.glassfish.api.deployment.archive.ReadableArchive 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(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(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(COMPATIBILITY, compatProp);
            }
        }
        if (getSecurityManager() != null) {
            // Process declared permissions
            earDeclaredPC = getDeclaredPermissions(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(FINE)) {
                _logger.fine("added declaredPermissions to earlib: " + earDeclaredPC);
            }
            addEEOrDeclaredPermissions(earLibCl, eeGarntsMap.get(CommponentType.ear), true);
            if (_logger.isLoggable(Level.FINE)) {
                _logger.fine("added all ee permissions to earlib: " + eeGarntsMap.get(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(CommponentType.ejb), true);
            if (_logger.isLoggable(Level.FINE))
                _logger.fine("ee permissions added: " + eeGarntsMap.get(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 : ArchiveHandler(org.glassfish.api.deployment.archive.ArchiveHandler) 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) IOException(java.io.IOException) DelegatingClassLoader(org.glassfish.internal.api.DelegatingClassLoader) XMLStreamException(javax.xml.stream.XMLStreamException) FileNotFoundException(java.io.FileNotFoundException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) SAXParseException(org.xml.sax.SAXParseException) DeploymentContextImpl(org.glassfish.deployment.common.DeploymentContextImpl) DeployCommandParameters(org.glassfish.api.deployment.DeployCommandParameters) ModuleDescriptor(org.glassfish.deployment.common.ModuleDescriptor) URLClassLoader(java.net.URLClassLoader) PreDestroy(org.glassfish.hk2.api.PreDestroy) ReadableArchive(org.glassfish.api.deployment.archive.ReadableArchive) File(java.io.File)

Example 17 with ReadableArchive

use of org.glassfish.api.deployment.archive.ReadableArchive in project Payara by payara.

the class ResourcesDeployer method processArchive.

private void processArchive(DeploymentContext dc) {
    try {
        ReadableArchive archive = dc.getSource();
        if (ResourceUtil.hasGlassfishResourcesXML(archive, locator) || ResourceUtil.hasPayaraResourcesXML(archive, locator)) {
            Map<String, Map<String, List>> appScopedResources = new HashMap<>();
            Map<String, List<String>> jndiNames = new HashMap<>();
            List<Map.Entry<String, String>> raNames = new ArrayList<>();
            Map<String, String> fileNames = new HashMap<>();
            String appName = getAppNameFromDeployCmdParams(dc);
            // using appName as it is possible that "deploy --name=APPNAME" will
            // be different than the archive name.
            retrieveAllResourcesXMLs(fileNames, archive, appName);
            for (Map.Entry<String, String> entry : fileNames.entrySet()) {
                String moduleName = entry.getKey();
                String fileName = entry.getValue();
                debug("Sun Resources XML : " + fileName);
                moduleName = org.glassfish.resourcebase.resources.util.ResourceUtil.getActualModuleNameWithExtension(moduleName);
                String scope;
                if (appName.equals(moduleName)) {
                    scope = JAVA_APP_SCOPE_PREFIX;
                } else {
                    scope = JAVA_MODULE_SCOPE_PREFIX;
                }
                File file = new File(fileName);
                ResourcesXMLParser parser = new ResourcesXMLParser(file, scope);
                validateResourcesXML(file, parser);
                List list = parser.getResourcesList();
                Map<String, List> resourcesList = new HashMap<>();
                List<String> jndiNamesList = new ArrayList<>();
                List<org.glassfish.resources.api.Resource> nonConnectorResources = ResourcesXMLParser.getNonConnectorResourcesList(list, false, true);
                resourcesList.put(NON_CONNECTOR_RESOURCES, nonConnectorResources);
                for (org.glassfish.resources.api.Resource resource : nonConnectorResources) {
                    String jndiName = extractJNDIName(resource);
                    if (hasRAName(resource)) {
                        raNames.add(new AbstractMap.SimpleEntry<>(extractRAName(resource), resource.getType()));
                    }
                    if (jndiName != null) {
                        jndiNamesList.add(jndiName);
                    }
                }
                List<org.glassfish.resources.api.Resource> connectorResources = ResourcesXMLParser.getConnectorResourcesList(list, false, true);
                resourcesList.put(CONNECTOR_RESOURCES, connectorResources);
                for (org.glassfish.resources.api.Resource resource : connectorResources) {
                    String jndiName = extractJNDIName(resource);
                    if (hasRAName(resource)) {
                        raNames.add(new AbstractMap.SimpleEntry<>(extractRAName(resource), resource.getType()));
                    }
                    if (jndiName != null) {
                        jndiNamesList.add(jndiName);
                    }
                }
                jndiNames.put(moduleName, jndiNamesList);
                appScopedResources.put(moduleName, resourcesList);
            }
            dc.addTransientAppMetaData(APP_SCOPED_RESOURCES_JNDI_NAMES, jndiNames);
            dc.addTransientAppMetaData(APP_SCOPED_RESOURCES_RA_NAMES, raNames);
            dc.addTransientAppMetaData(APP_SCOPED_RESOURCES_MAP, appScopedResources);
            ApplicationInfo appInfo = appRegistry.get(appName);
            if (appInfo != null) {
                Application app = dc.getTransientAppMetaData(ServerTags.APPLICATION, Application.class);
                appInfo.addTransientAppMetaData(ServerTags.APPLICATION, app);
            }
        }
    } catch (Exception e) {
        // in the event notification infrastructure
        throw new DeploymentException("Failue while processing glassfish-resources.xml(s) in the archive ", e);
    }
}
Also used : ApplicationInfo(org.glassfish.internal.data.ApplicationInfo) org.glassfish.resources.api(org.glassfish.resources.api) ResourcesXMLParser(org.glassfish.resources.admin.cli.ResourcesXMLParser) Resource(com.sun.enterprise.config.serverbeans.Resource) Resource(org.glassfish.resources.api.Resource) ResourceException(javax.resource.ResourceException) IOException(java.io.IOException) DeploymentException(org.glassfish.deployment.common.DeploymentException) ResourceConflictException(org.glassfish.resourcebase.resources.api.ResourceConflictException) Resource(org.glassfish.resources.api.Resource) DeploymentException(org.glassfish.deployment.common.DeploymentException) ReadableArchive(org.glassfish.api.deployment.archive.ReadableArchive) File(java.io.File)

Example 18 with ReadableArchive

use of org.glassfish.api.deployment.archive.ReadableArchive in project Payara by payara.

the class ResourcesDeployer method retrieveAllResourcesXMLs.

/**
 * Puts all glassfish-resources.xml files of an archive into a map
 * <p>
 * If the archive is an ear all sub archives will be searched as well
 * @param fileNames Map of all glassfish-resources files.
 * All found glassfish-resource files will be added to it
 * @param archive The archive to search for glassfish-resources.xml files
 * @param actualArchiveName The path of the archive
 * @throws IOException
 */
public void retrieveAllResourcesXMLs(Map<String, String> fileNames, ReadableArchive archive, String actualArchiveName) throws IOException {
    if (DeploymentUtils.isArchiveOfType(archive, DOLUtils.earType(), locator)) {
        // Look for top-level META-INF/payara-resources.xml
        if (archive.exists(PAYARA_RESOURCES_XML_META_INF)) {
            String archivePath = archive.getURI().getPath();
            String fileName = archivePath + PAYARA_RESOURCES_XML_META_INF;
            if (_logger.isLoggable(Level.FINEST)) {
                _logger.log(Level.FINEST, "Payara-Resources Deployer - fileName : {0} - parent : {1}", new Object[] { fileName, archive.getName() });
            }
            fileNames.put(actualArchiveName, fileName);
        }
        // Look for top-level META-INF/glassfish-resources.xml
        if (archive.exists(RESOURCES_XML_META_INF)) {
            String archivePath = archive.getURI().getPath();
            String fileName = archivePath + RESOURCES_XML_META_INF;
            if (_logger.isLoggable(Level.FINEST)) {
                _logger.finest("GlassFish-Resources Deployer - fileName : " + fileName + " - parent : " + archive.getName());
            }
            fileNames.put(actualArchiveName, fileName);
        }
        // Look for sub-module level META-INF/glassfish-resources.xml and WEB-INF/glassfish-resources.xml
        // and also for payara-resources.xml
        Enumeration<String> entries = archive.entries();
        while (entries.hasMoreElements()) {
            String element = entries.nextElement();
            if (element.endsWith(".jar") || element.endsWith(".war") || element.endsWith(".rar") || element.endsWith("_jar") || element.endsWith("_war") || element.endsWith("_rar")) {
                ReadableArchive subArchive = archive.getSubArchive(element);
                if (subArchive != null) {
                    retrieveResourcesXMLFromArchive(fileNames, subArchive, subArchive.getName());
                }
            }
        }
    } else {
        // Look for standalone archive's META-INF/glassfish-resources.xml and WEB-INF/glassfish-resources.xml
        retrieveResourcesXMLFromArchive(fileNames, archive, actualArchiveName);
    }
}
Also used : ReadableArchive(org.glassfish.api.deployment.archive.ReadableArchive)

Example 19 with ReadableArchive

use of org.glassfish.api.deployment.archive.ReadableArchive 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 {
    _logger.fine(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 = classLoaderHierarchy.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 = classLoaderHierarchy.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) Deployment(org.glassfish.internal.deployment.Deployment) ConfigException(org.glassfish.embeddable.web.ConfigException) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) Properties(java.util.Properties) ApplicationRef(com.sun.enterprise.config.serverbeans.ApplicationRef) ServerEnvironment(org.glassfish.api.admin.ServerEnvironment) WebappClassLoader(org.glassfish.web.loader.WebappClassLoader) PlainTextActionReporter(com.sun.enterprise.admin.report.PlainTextActionReporter) ArchiveFactory(com.sun.enterprise.deploy.shared.ArchiveFactory) Applications(com.sun.enterprise.config.serverbeans.Applications) LifecycleException(org.apache.catalina.LifecycleException) 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 20 with ReadableArchive

use of org.glassfish.api.deployment.archive.ReadableArchive in project Payara by payara.

the class RootBeanDeploymentArchiveTest method testConstructor.

@Test
public void testConstructor() throws Exception {
    String archiveName = "an";
    String webInfLib1 = "WEB-INF/lib/lib1.jar";
    String webInfLib2 = "WEB-INF/lib/lib2.jar";
    String subArchive11Name = "sa1";
    String subArchive12Name = "sa2";
    URI webInfLib1URI = URI.create(webInfLib1);
    URI webInfLib2URI = URI.create(webInfLib2);
    ArrayList<String> lib1ClassNames = new ArrayList<>();
    lib1ClassNames.add(Lib1Class1.class.getName() + ".class");
    lib1ClassNames.add(Lib1Class2.class.getName() + ".class");
    ArrayList<String> lib2ClassNames = new ArrayList<>();
    lib2ClassNames.add(Lib2Class1.class.getName() + ".class");
    lib2ClassNames.add(Lib2Class2.class.getName() + ".class");
    WeldUtils.BDAType bdaType = WeldUtils.BDAType.WAR;
    ArrayList<String> webInfLibEntries = new ArrayList<>();
    webInfLibEntries.add(webInfLib1);
    webInfLibEntries.add(webInfLib2);
    EasyMockSupport mockSupport = new EasyMockSupport();
    BeansXml beansXML = mockSupport.createMock(BeansXml.class);
    WeldBootstrap wb = mockSupport.createMock(WeldBootstrap.class);
    ReadableArchive readableArchive = mockSupport.createMock(ReadableArchive.class);
    ReadableArchive subArchive1 = mockSupport.createMock(ReadableArchive.class);
    ReadableArchive subArchive2 = mockSupport.createMock(ReadableArchive.class);
    Collection<EjbDescriptor> ejbs = Collections.emptyList();
    DeploymentContext deploymentContext = mockSupport.createMock(DeploymentContext.class);
    expect(deploymentContext.getClassLoader()).andReturn(null).anyTimes();
    expect(readableArchive.getName()).andReturn(archiveName).anyTimes();
    expect(readableArchive.exists(WeldUtils.WEB_INF_BEANS_XML)).andReturn(true).anyTimes();
    expect(readableArchive.exists(WeldUtils.WEB_INF_CLASSES_META_INF_BEANS_XML)).andReturn(false).anyTimes();
    // in BeanDeploymentArchiveImpl.populate
    expect(deploymentContext.getTransientAppMetadata()).andReturn(null).anyTimes();
    expect(deploymentContext.getModuleMetaData(Application.class)).andReturn(null).anyTimes();
    expect(deploymentContext.getTransientAppMetaData(WeldDeployer.WELD_BOOTSTRAP, WeldBootstrap.class)).andReturn(wb).anyTimes();
    expect(wb.parse(anyObject(URL.class))).andReturn(beansXML).anyTimes();
    expect(readableArchive.getURI()).andReturn(URI.create("an.war")).anyTimes();
    expect(subArchive1.getURI()).andReturn(webInfLib1URI).anyTimes();
    expect(subArchive2.getURI()).andReturn(webInfLib2URI).anyTimes();
    expect(beansXML.getBeanDiscoveryMode()).andReturn(BeanDiscoveryMode.ALL).anyTimes();
    expect(readableArchive.entries()).andReturn(Collections.<String>emptyEnumeration());
    readableArchive.close();
    expect(readableArchive.exists(WeldUtils.WEB_INF_LIB)).andReturn(true).anyTimes();
    expect(readableArchive.entries(WeldUtils.WEB_INF_LIB)).andReturn(Collections.enumeration(webInfLibEntries));
    expect(readableArchive.getSubArchive(webInfLib1)).andReturn(subArchive1);
    expect(subArchive1.exists(WeldUtils.META_INF_BEANS_XML)).andReturn(true);
    expect(readableArchive.getSubArchive(webInfLib2)).andReturn(subArchive2);
    expect(subArchive2.exists(WeldUtils.META_INF_BEANS_XML)).andReturn(true);
    // build new BeanDeploymentArchiveImpl for lib1 and lib2
    setupMocksForWebInfLibBda(subArchive1, subArchive11Name, lib1ClassNames);
    setupMocksForWebInfLibBda(subArchive2, subArchive12Name, lib2ClassNames);
    readableArchive.close();
    mockSupport.replayAll();
    RootBeanDeploymentArchive rootBeanDeploymentArchive = new RootBeanDeploymentArchive(readableArchive, ejbs, deploymentContext);
    assertEquals("root_" + archiveName, rootBeanDeploymentArchive.getId());
    assertEquals(WeldUtils.BDAType.UNKNOWN, rootBeanDeploymentArchive.getBDAType());
    assertEquals(0, rootBeanDeploymentArchive.getBeanClasses().size());
    assertEquals(0, rootBeanDeploymentArchive.getBeanClassObjects().size());
    assertNull(rootBeanDeploymentArchive.getBeansXml());
    BeanDeploymentArchiveImpl moduleBda = (BeanDeploymentArchiveImpl) rootBeanDeploymentArchive.getModuleBda();
    assertNotNull(moduleBda);
    assertEquals(WeldUtils.BDAType.WAR, moduleBda.getBDAType());
    assertEquals(3, rootBeanDeploymentArchive.getBeanDeploymentArchives().size());
    assertTrue(rootBeanDeploymentArchive.getBeanDeploymentArchives().contains(moduleBda));
    assertEquals(3, moduleBda.getBeanDeploymentArchives().size());
    assertTrue(moduleBda.getBeanDeploymentArchives().contains(rootBeanDeploymentArchive));
    assertEquals(0, rootBeanDeploymentArchive.getModuleBeanClasses().size());
    assertEquals(0, rootBeanDeploymentArchive.getModuleBeanClassObjects().size());
    assertSame(rootBeanDeploymentArchive.getModuleClassLoaderForBDA(), moduleBda.getModuleClassLoaderForBDA());
    mockSupport.verifyAll();
    mockSupport.resetAll();
}
Also used : EasyMockSupport(org.easymock.EasyMockSupport) WeldBootstrap(org.jboss.weld.bootstrap.WeldBootstrap) WeldUtils(org.glassfish.weld.connector.WeldUtils) URI(java.net.URI) EjbDescriptor(com.sun.enterprise.deployment.EjbDescriptor) DeploymentContext(org.glassfish.api.deployment.DeploymentContext) BeansXml(org.jboss.weld.bootstrap.spi.BeansXml) ReadableArchive(org.glassfish.api.deployment.archive.ReadableArchive) Application(com.sun.enterprise.deployment.Application) Test(org.junit.Test)

Aggregations

ReadableArchive (org.glassfish.api.deployment.archive.ReadableArchive)97 IOException (java.io.IOException)46 File (java.io.File)28 URI (java.net.URI)18 ActionReport (org.glassfish.api.ActionReport)17 ExtendedDeploymentContext (org.glassfish.internal.deployment.ExtendedDeploymentContext)14 DeployCommandParameters (org.glassfish.api.deployment.DeployCommandParameters)12 WritableArchive (org.glassfish.api.deployment.archive.WritableArchive)12 Application (com.sun.enterprise.deployment.Application)10 JarFile (java.util.jar.JarFile)10 ArchiveHandler (org.glassfish.api.deployment.archive.ArchiveHandler)10 ApplicationInfo (org.glassfish.internal.data.ApplicationInfo)10 ArrayList (java.util.ArrayList)9 ModuleDescriptor (org.glassfish.deployment.common.ModuleDescriptor)9 ConfigurationDeploymentDescriptorFile (com.sun.enterprise.deployment.io.ConfigurationDeploymentDescriptorFile)8 Logger (java.util.logging.Logger)8 DeploymentDescriptorFile (com.sun.enterprise.deployment.io.DeploymentDescriptorFile)7 Manifest (java.util.jar.Manifest)7 HashSet (java.util.HashSet)6 HashMap (java.util.HashMap)5