Package org.apache.geronimo.j2ee.deployment

Examples of org.apache.geronimo.j2ee.deployment.EARContext


        return path;
    }

    public void installModule(JarFile earFile, EARContext earContext, Module module, Collection configurationStores, ConfigurationStore targetConfigurationStore, Collection repositories) throws DeploymentException {
        EARContext moduleContext;
        if (module.isStandAlone()) {
            moduleContext = earContext;
        } else {
            Environment environment = module.getEnvironment();
            Artifact earConfigId = earContext.getConfigID();
            Artifact configId = new Artifact(earConfigId.getGroupId(), earConfigId.getArtifactId() + "_" + module.getTargetPath(), earConfigId.getVersion(), "car");
            environment.setConfigId(configId);
            environment.addDependency(earConfigId, ImportType.ALL);
            File configurationDir = new File(earContext.getBaseDir(), module.getTargetPath());
            configurationDir.mkdirs();

            // construct the web app deployment context... this is the same class used by the ear context
            try {
                File inPlaceConfigurationDir = null;
                if (null != earContext.getInPlaceConfigurationDir()) {
                    inPlaceConfigurationDir = new File(earContext.getInPlaceConfigurationDir(), module.getTargetPath());
                }
                moduleContext = new EARContext(configurationDir,
                        inPlaceConfigurationDir,
                        environment,
                        ConfigurationModuleType.WAR,
                        module.getModuleName(),
                        earContext);
            } catch (DeploymentException e) {
                cleanupConfigurationDir(configurationDir);
                throw e;
            }
        }
        module.setEarContext(moduleContext);
        module.setRootEarContext(earContext);

        try {
            // add the warfile's content to the configuration
            JarFile warFile = module.getModuleFile();
            Enumeration<JarEntry> entries = warFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                URI targetPath = new URI(null, entry.getName(), null);
                if (entry.getName().equals("WEB-INF/web.xml")) {
                    moduleContext.addFile(targetPath, module.getOriginalSpecDD());
                } else if (entry.getName().startsWith("WEB-INF/lib") && entry.getName().endsWith(".jar")) {
                    moduleContext.addInclude(targetPath, warFile, entry);
                } else {
                    moduleContext.addFile(targetPath, warFile, entry);
                }
            }

            //always add WEB-INF/classes to the classpath regardless of whether
            //any classes exist
            moduleContext.getConfiguration().addToClassPath("WEB-INF/classes/");

            // add the manifest classpath entries declared in the war to the class loader
            // we have to explicitly add these since we are unpacking the web module
            // and the url class loader will not pick up a manifest from an unpacked dir
            moduleContext.addManifestClassPath(warFile, RELATIVE_MODULE_BASE_URI);

        } catch (IOException e) {
            throw new DeploymentException("Problem deploying war", e);
        } catch (URISyntaxException e) {
            throw new DeploymentException("Could not construct URI for location of war entry", e);
        } finally {
            if (!module.isStandAlone()) {
                try {
                    moduleContext.flush();
                } catch (IOException e) {
                    throw new DeploymentException("Problem closing war context", e);
                }
            }
        }
View Full Code Here


    public void installModule(JarFile earFile, EARContext earContext, Module module, Collection configurationStores, ConfigurationStore targetConfigurationStore, Collection repository) throws DeploymentException {
    }

    public void initContext(EARContext earContext, Module module, ClassLoader cl) throws DeploymentException {
        XmlObject container = module.getVendorDD();
        EARContext moduleContext = module.getEarContext();
        XmlObject[] raws = container.selectChildren(PERSISTENCE_QNAME);

        Map<String, PersistenceDocument.Persistence.PersistenceUnit> overrides = new HashMap<String, PersistenceDocument.Persistence.PersistenceUnit>();
        for (XmlObject raw : raws) {
            PersistenceDocument.Persistence persistence = (PersistenceDocument.Persistence) raw.copy().changeType(PersistenceDocument.Persistence.type);
            for (PersistenceDocument.Persistence.PersistenceUnit unit : persistence.getPersistenceUnitArray()) {
                overrides.put(unit.getName().trim(), unit);
            }
//            buildPersistenceUnits(persistence, module, module.getTargetPath());
        }
        try {
           
            File rootBaseFile;
            URI moduleBaseURI;
            if (module.getRootEarContext().getInPlaceConfigurationDir() == null) {
                rootBaseFile = module.getRootEarContext().getConfiguration().getConfigurationDir();
                moduleBaseURI = moduleContext.getBaseDir().toURI();
            } else {
                rootBaseFile = module.getRootEarContext().getInPlaceConfigurationDir();
                moduleBaseURI = moduleContext.getInPlaceConfigurationDir().toURI();
            }
            String rootBase = rootBaseFile.toURI().normalize().toString();

            Map rootGeneralData = module.getRootEarContext().getGeneralData();
            ClassPathList manifestcp = (ClassPathList) module.getEarContext().getGeneralData().get(ClassPathList.class);
            if (manifestcp == null) {
                manifestcp = new ClassPathList();
                manifestcp.add(module.getTargetPath());
            }
            URL[] urls = new URL[manifestcp.size()];
            int i = 0;
            for (String path : manifestcp) {
                path = path.replaceAll(" ", "%20");
                URL url = moduleBaseURI.resolve(path).toURL();
                urls[i++] = url;
            }
            ResourceFinder finder = new ResourceFinder("", null, urls);
            List<URL> knownPersistenceUrls = (List<URL>) rootGeneralData.get(PersistenceUnitBuilder.class.getName());
            if (knownPersistenceUrls == null) {
                knownPersistenceUrls = new ArrayList<URL>();
                rootGeneralData.put(PersistenceUnitBuilder.class.getName(), knownPersistenceUrls);
            }
            List<URL> persistenceUrls = finder.findAll("META-INF/persistence.xml");
            persistenceUrls.removeAll(knownPersistenceUrls);
            if (raws.length > 0 || persistenceUrls.size() > 0) {
                EnvironmentBuilder.mergeEnvironments(module.getEnvironment(), defaultEnvironment);
            }
            for (URL persistenceUrl : persistenceUrls) {
                String persistenceLocation;
                try {
                    persistenceLocation = persistenceUrl.toURI().toString();
                } catch (URISyntaxException e) {
                    //????
                    continue;
                }
                int pos = persistenceLocation.indexOf(rootBase);
                if (pos < 0) {
                    //not in the ear
                    continue;
                }
                int endPos = persistenceLocation.lastIndexOf("!/");
                if (endPos < 0) {
                    // if unable to find the '!/' marker, try to see if this is
                    // a war file with the persistence.xml directly embeded - no ejb-jar
                    endPos = persistenceLocation.lastIndexOf("META-INF");
                }
                if (endPos >= 0) {
                    //path relative to ear base uri
                    String relative = persistenceLocation.substring(pos + rootBase.length(), endPos);
                    //find path relative to module base uri
                    relative = module.getRelativePath(relative);
                    PersistenceDocument persistenceDocument;
                    try {
                        XmlObject xmlObject = XmlBeansUtil.parse(persistenceUrl, moduleContext.getClassLoader());
                        persistenceDocument = (PersistenceDocument) xmlObject.changeType(PersistenceDocument.type);
                    } catch (XmlException e) {
                        throw new DeploymentException("Could not parse persistence.xml file: " + persistenceUrl, e);
                    }
                    PersistenceDocument.Persistence persistence = persistenceDocument.getPersistence();
View Full Code Here

            respectExcludeUnlistedClasses(data);
        }
    }

    private GBeanData installPersistenceUnitGBean(PersistenceDocument.Persistence.PersistenceUnit persistenceUnit, Module module, String persistenceModulePath) throws DeploymentException {
        EARContext moduleContext = module.getEarContext();
        String persistenceUnitName = persistenceUnit.getName().trim();
        if (persistenceUnitName.length() == 0) {
            persistenceUnitName = ANON_PU_NAME;
        }
        AbstractName abstractName;
        if (persistenceModulePath == null || persistenceModulePath.length() == 0) {
            abstractName = moduleContext.getNaming().createChildName(module.getModuleName(), persistenceUnitName, PersistenceUnitGBean.GBEAN_INFO.getJ2eeType());
        } else {
            abstractName = moduleContext.getNaming().createChildName(module.getModuleName(), persistenceModulePath, NameFactory.PERSISTENCE_UNIT_MODULE);
            abstractName = moduleContext.getNaming().createChildName(abstractName, moduleContext.getConfigID(), persistenceUnitName, PersistenceUnitGBean.GBEAN_INFO.getJ2eeType());
        }
        GBeanData gbeanData = new GBeanData(abstractName, PersistenceUnitGBean.GBEAN_INFO);
        try {
            moduleContext.addGBean(gbeanData);
        } catch (GBeanAlreadyExistsException e) {
            throw new DeploymentException("Duplicate persistenceUnit name " + persistenceUnitName, e);
        }
        gbeanData.setAttribute("persistenceUnitName", persistenceUnitName);
        gbeanData.setAttribute("persistenceUnitRoot", persistenceModulePath);

        //set defaults:
        gbeanData.setAttribute("persistenceProviderClassName", defaultPersistenceProviderClassName);
        //spec 6.2.1.2 the default is JTA
        gbeanData.setAttribute("persistenceUnitTransactionType", "JTA");
        if (defaultJtaDataSourceName != null) {
            gbeanData.setReferencePattern("JtaDataSourceWrapper", defaultJtaDataSourceName);
        }
        if (defaultNonJtaDataSourceName != null) {
            gbeanData.setReferencePattern("NonJtaDataSourceWrapper", defaultNonJtaDataSourceName);
        }

        gbeanData.setAttribute("mappingFileNames", new ArrayList<String>());
        gbeanData.setAttribute("excludeUnlistedClasses", false);
        gbeanData.setAttribute("managedClassNames", new ArrayList<String>());
        gbeanData.setAttribute("jarFileUrls", new ArrayList<String>());
        Properties properties = new Properties();
        gbeanData.setAttribute("properties", properties);
        properties.putAll(defaultPersistenceUnitProperties);
        AbstractNameQuery transactionManagerName = moduleContext.getTransactionManagerName();
        gbeanData.setReferencePattern("TransactionManager", transactionManagerName);
        gbeanData.setReferencePattern("EntityManagerRegistry", extendedEntityManagerRegistryName);

        setOverrideableProperties(persistenceUnit, gbeanData);
        return gbeanData;
View Full Code Here

        } catch (ConfigurationAlreadyExistsException e) {
            throw new DeploymentException("Unable to create configuration directory for " + clientEnvironment.getConfigId(), e);
        }

        // construct the app client deployment context... this is the same class used by the ear context
        EARContext appClientDeploymentContext;
        try {

            appClientDeploymentContext = new EARContext(appClientDir,
                    null,
                    clientEnvironment,
                    ConfigurationModuleType.CAR,
                    earContext.getNaming(),
                    earContext.getConfigurationManager(),
                    null, //no server name needed on client
                    appClientModule.getAppClientName(),
                    transactionManagerObjectName,
                    connectionTrackerObjectName,
                    corbaGBeanObjectName,
                    earContext.getMessageDestinations());
            appClientModule.setEarContext(appClientDeploymentContext);
            appClientModule.setRootEarContext(appClientDeploymentContext);

            try {
                appClientDeploymentContext.addIncludeAsPackedJar(URI.create(module.getTargetPath()), moduleFile);
            } catch (IOException e) {
                throw new DeploymentException("Unable to copy app client module jar into configuration: " + moduleFile.getName(), e);
            }
            ClassPathList libClasspath = (ClassPathList) earContext.getGeneralData().get(ClassPathList.class);
            if (libClasspath != null) {
                for (String libEntryPath : libClasspath) {
                    try {
                        NestedJarFile library = new NestedJarFile(earFile, libEntryPath);
                        appClientDeploymentContext.addIncludeAsPackedJar(URI.create(libEntryPath), library);
                    } catch (IOException e) {
                        throw new DeploymentException("Could not add to app client library classpath: " + libEntryPath, e);
                    }
                }
            }
View Full Code Here

            earContext.addGBean(appClientModuleGBeanData);
        } catch (GBeanAlreadyExistsException e) {
            throw new DeploymentException("Could not add application client module gbean to configuration", e);
        }

        EARContext appClientDeploymentContext = appClientModule.getEarContext();
        //Share the ejb info with the ear.
        //TODO this might be too much, but I don't want to impose a dependency on geronimo-openejb to get
        //EjbModuleBuilder.EarData.class
        Map<Object, Object> generalData = earContext.getGeneralData();
        for (Map.Entry<Object, Object> entry : generalData.entrySet()) {
            Object key = entry.getKey();
            if (key instanceof Class && ((Class) key).getName().equals("org.apache.geronimo.openejb.deployment.EjbModuleBuilder$EarData")) {
                appClientDeploymentContext.getGeneralData().put(key, entry.getValue());
                break;
            }
        }

        // Create a Module ID Builder defaulting to similar settings to use for any children we create
        ModuleIDBuilder idBuilder = new ModuleIDBuilder();
        idBuilder.setDefaultGroup(appClientModule.getEnvironment().getConfigId().getGroupId());
        idBuilder.setDefaultVersion(appClientModule.getEnvironment().getConfigId().getVersion());
        try {
            try {

                //register the message destinations in the app client ear context.
                namingBuilders.initContext(appClient, geronimoAppClient, appClientModule);
                // extract the client Jar file into a standalone packed jar file and add the contents to the output
                URI moduleBase = new URI(appClientModule.getTargetPath());
                try {
                    appClientDeploymentContext.addIncludeAsPackedJar(moduleBase, moduleFile);
                } catch (IOException e) {
                    throw new DeploymentException("Unable to copy app client module jar into configuration: " + moduleFile.getName(), e);
                }

                // add manifest class path entries to the app client context
                addManifestClassPath(appClientDeploymentContext, appClientModule.getEarFile(), moduleFile, moduleBase);

                // get the classloader
                ClassLoader appClientClassLoader = appClientDeploymentContext.getClassLoader();

                // pop in all the gbeans declared in the geronimo app client file
                if (geronimoAppClient != null) {
                    serviceBuilder.build(geronimoAppClient, appClientDeploymentContext, appClientDeploymentContext);
                    //deploy the resource adapters specified in the geronimo-application.xml

                    for (ConnectorModule connectorModule : appClientModule.getResourceModules()) {
                        getConnectorModuleBuilder().addGBeans(appClientDeploymentContext, connectorModule, appClientClassLoader, repositories);
                    }
                }

                //Holder may be loaded in the "client" module classloader here, whereas
                //NamingBuilder.INJECTION_KEY.get(buildingContext) returns a Holder loaded in the j2ee-server classloader.
                Object holder;
                // add the app client static jndi provider
                //TODO track resource ref shared and app managed security
                AbstractName jndiContextName = earContext.getNaming().createChildName(appClientDeploymentContext.getModuleName(), "StaticJndiContext", "StaticJndiContext");
                GBeanData jndiContextGBeanData = new GBeanData(jndiContextName, StaticJndiContextPlugin.GBEAN_INFO);
                try {
                    Map<NamingBuilder.Key, Object> buildingContext = new HashMap<NamingBuilder.Key, Object>();
                    buildingContext.put(NamingBuilder.GBEAN_NAME_KEY, jndiContextName);
                    Configuration localConfiguration = appClientDeploymentContext.getConfiguration();
                    Configuration remoteConfiguration = earContext.getConfiguration();

                    if (!appClient.getMetadataComplete()) {
                        // Create a classfinder and populate it for the naming builder(s). The absence of a
                        // classFinder in the module will convey whether metadata-complete is set
                        // (or not)
                        appClientModule.setClassFinder(createAppClientClassFinder(appClient, appClientModule));
                    }

                    namingBuilders.buildNaming(appClient, geronimoAppClient, appClientModule, buildingContext);

                    if (!appClient.getMetadataComplete()) {
                        appClient.setMetadataComplete(true);
                        module.setOriginalSpecDD(module.getSpecDD().toString());
                    }

                    appClientModuleGBeanData.setAttribute("deploymentDescriptor", appClientModule.getOriginalSpecDD());
                    holder = NamingBuilder.INJECTION_KEY.get(buildingContext);
                    jndiContextGBeanData.setAttribute("context", NamingBuilder.JNDI_KEY.get(buildingContext));
                } catch (DeploymentException e) {
                    throw e;
                } catch (Exception e) {
                    throw new DeploymentException("Unable to construct jndi context for AppClientModule GBean " +
                            appClientModule.getName(), e);
                }
                appClientDeploymentContext.addGBean(jndiContextGBeanData);

                // finally add the app client container
                AbstractName appClientContainerName = appClientDeploymentContext.getModuleName();
                GBeanData appClientContainerGBeanData = new GBeanData(appClientContainerName, AppClientContainer.GBEAN_INFO);
                try {
                    appClientContainerGBeanData.setAttribute("mainClassName", appClientModule.getMainClassName());
                    appClientContainerGBeanData.setAttribute("appClientModuleName", appClientModuleName);
                    String callbackHandlerClassName = null;
                    if (appClient.isSetCallbackHandler()) {
                        callbackHandlerClassName = appClient.getCallbackHandler().getStringValue().trim();
                    }
                    if (geronimoAppClient.isSetCallbackHandler()) {
                        callbackHandlerClassName = geronimoAppClient.getCallbackHandler().trim();
                    }
                    String realmName = null;
                    if (geronimoAppClient.isSetRealmName()) {
                        realmName = geronimoAppClient.getRealmName().trim();
                    }
                    if (callbackHandlerClassName != null && realmName == null) {
                        throw new DeploymentException("You must specify a realm name with the callback handler");
                    }
                    if (realmName != null) {
                        appClientContainerGBeanData.setAttribute("realmName", realmName);
                        appClientContainerGBeanData.setAttribute("callbackHandlerClassName", callbackHandlerClassName);
                    } else if (geronimoAppClient.isSetDefaultSubject()) {
                        GerSubjectInfoType subjectInfoType = geronimoAppClient.getDefaultSubject();
                        SubjectInfo subjectInfo = buildSubjectInfo(subjectInfoType);
                        appClientContainerGBeanData.setAttribute("defaultSubject", subjectInfo);
                        appClientContainerGBeanData.setReferencePattern("CredentialStore", credentialStoreName);
                    } else if (earContext.getSecurityConfiguration() != null) {
                        log.warn("Configuration of app client default subject from ear security configuration no longer supported.");
                        //beware a linkage error if we cast this to SubjectInfo
//                        String realm = ((SecurityConfiguration) earContext.getSecurityConfiguration()).getDefaultSubjectRealm();
//                        String id = ((SecurityConfiguration) earContext.getSecurityConfiguration()).getDefaultSubjectId();
//                        if (realm != null) {
//                            SubjectInfo subjectInfo = new SubjectInfo(realm, id);
//                            appClientContainerGBeanData.setAttribute("defaultSubject", subjectInfo);
//                            appClientContainerGBeanData.setReferencePattern("CredentialStore", credentialStoreName);
//                        }
                    }
                    appClientContainerGBeanData.setReferencePattern("JNDIContext", jndiContextName);
                    appClientContainerGBeanData.setAttribute("holder", holder);

                } catch (Exception e) {
                    throw new DeploymentException("Unable to initialize AppClientModule GBean", e);
                }
                appClientDeploymentContext.addGBean(appClientContainerGBeanData);

                //TODO this may definitely not be the best place for this!
                for (ModuleBuilderExtension mbe : moduleBuilderExtensions) {
                    mbe.addGBeans(appClientDeploymentContext, appClientModule, appClientClassLoader, repositories);
                }

                // get the configuration data
                earContext.addAdditionalDeployment(appClientDeploymentContext.getConfigurationData());
            } finally {
                if (appClientDeploymentContext != null) {
                    try {
                        appClientDeploymentContext.close();
                    } catch (IOException e) {
                        //nothing we can do
                    }
                }
            }

        } catch (Throwable e) {
            File appClientDir = appClientDeploymentContext.getBaseDir();
            cleanupAppClientDir(appClientDir);
            if (e instanceof Error) {
                throw (Error) e;
            } else if (e instanceof DeploymentException) {
                throw (DeploymentException) e;
View Full Code Here

        return path;
    }

    public void installModule(JarFile earFile, EARContext earContext, Module module, Collection configurationStores, ConfigurationStore targetConfigurationStore, Collection repositories) throws DeploymentException {
        EARContext moduleContext;
        if (module.isStandAlone()) {
            moduleContext = earContext;
        } else {
            Environment environment = module.getEnvironment();
            Artifact earConfigId = earContext.getConfigID();
            Artifact configId = new Artifact(earConfigId.getGroupId(), earConfigId.getArtifactId() + "_" + module.getTargetPath(), earConfigId.getVersion(), "car");
            environment.setConfigId(configId);
            environment.addDependency(earConfigId, ImportType.ALL);
            File configurationDir = new File(earContext.getBaseDir(), module.getTargetPath());
            configurationDir.mkdirs();

            // construct the web app deployment context... this is the same class used by the ear context
            try {
                File inPlaceConfigurationDir = null;
                if (null != earContext.getInPlaceConfigurationDir()) {
                    inPlaceConfigurationDir = new File(earContext.getInPlaceConfigurationDir(), module.getTargetPath());
                }
                moduleContext = new EARContext(configurationDir,
                        inPlaceConfigurationDir,
                        environment,
                        ConfigurationModuleType.WAR,
                        module.getModuleName(),
                        earContext);
            } catch (DeploymentException e) {
                cleanupConfigurationDir(configurationDir);
                throw e;
            }
        }
        module.setEarContext(moduleContext);
        module.setRootEarContext(earContext);

        try {
            ClassPathList manifestcp = new ClassPathList();
            // add the warfile's content to the configuration
            JarFile warFile = module.getModuleFile();
            Enumeration<JarEntry> entries = warFile.entries();
            List<ZipEntry> libs = new ArrayList<ZipEntry>();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                URI targetPath = new URI(null, entry.getName(), null);
                if (entry.getName().equals("WEB-INF/web.xml")) {
                    moduleContext.addFile(targetPath, module.getOriginalSpecDD());
                } else if (entry.getName().startsWith("WEB-INF/lib") && entry.getName().endsWith(".jar")) {
                    // keep a collection of all libs in the war
                    // libs must be installed after WEB-INF/classes which must be installed after this copy phase
                    libs.add(entry);
                } else {
                    moduleContext.addFile(targetPath, warFile, entry);
                }
            }

            // always add WEB-INF/classes to the classpath regardless of whether
            // any classes exist.  This must be searched BEFORE the WEB-INF/lib jar files,
            // per the servlet specifications.
            moduleContext.getConfiguration().addToClassPath("WEB-INF/classes/");
            manifestcp.add("WEB-INF/classes/");

            // install the libs
            for (ZipEntry entry : libs) {
                URI targetPath = new URI(null, entry.getName(), null);
                moduleContext.addInclude(targetPath, warFile, entry);
                manifestcp.add(entry.getName());
            }

            // add the manifest classpath entries declared in the war to the class loader
            // we have to explicitly add these since we are unpacking the web module
            // and the url class loader will not pick up a manifest from an unpacked dir
            moduleContext.addManifestClassPath(warFile, RELATIVE_MODULE_BASE_URI);
            moduleContext.getGeneralData().put(ClassPathList.class, manifestcp);

        } catch (IOException e) {
            throw new DeploymentException("Problem deploying war", e);
        } catch (URISyntaxException e) {
            throw new DeploymentException("Could not construct URI for location of war entry", e);
        } finally {
            if (!module.isStandAlone()) {
                try {
                    moduleContext.flush();
                } catch (IOException e) {
                    throw new DeploymentException("Problem closing war context", e);
                }
            }
        }
View Full Code Here

        }
    }

    protected void basicInitContext(EARContext earContext, Module module, XmlObject gerWebApp, boolean hasSecurityRealmName) throws DeploymentException {
        //complete manifest classpath
        EARContext moduleContext = module.getEarContext();
        ClassPathList manifestcp = (ClassPathList) moduleContext.getGeneralData().get(ClassPathList.class);
        ModuleList moduleLocations = (ModuleList) module.getRootEarContext().getGeneralData().get(ModuleList.class);
        URI baseUri = URI.create(module.getTargetPath());
        URI resolutionUri = invertURI(baseUri);
        earContext.getCompleteManifestClassPath(module.getModuleFile(), baseUri, resolutionUri, manifestcp, moduleLocations);
View Full Code Here

        SpecSecurityBuilder builder = new SpecSecurityBuilder();
        return builder.buildSpecSecurityConfig(webApp);
    }

    protected void configureLocalJaspicProvider(AuthenticationWrapper authType, String contextPath, Module module, GBeanData securityFactoryData) throws DeploymentException, GBeanAlreadyExistsException {
        EARContext moduleContext = module.getEarContext();
        GBeanData authConfigProviderData = null;
        AbstractName providerName = moduleContext.getNaming().createChildName(module.getModuleName(), "authConfigProvider", GBeanInfoBuilder.DEFAULT_J2EE_TYPE);
        try {
            if (authType.isSetConfigProvider()) {
                authConfigProviderData = new GBeanData(providerName, AuthConfigProviderGBean.class);
                final XmlCursor xmlCursor = authType.getConfigProvider().newCursor();
                try {
                    XMLStreamReader reader = new InternWrapper(xmlCursor.newXMLStreamReader());
                    ConfigProviderType configProviderType = JaspiXmlUtil.loadConfigProvider(reader);
                    StringWriter out = new StringWriter();
                    JaspiXmlUtil.writeConfigProvider(configProviderType, out);
                    authConfigProviderData.setAttribute("config", out.toString());
                } finally {
                    xmlCursor.dispose();
                }
            } else if (authType.isSetServerAuthConfig()) {
                authConfigProviderData = new GBeanData(providerName, ServerAuthConfigGBean.class);
                final XmlCursor xmlCursor = authType.getServerAuthConfig().newCursor();
                try {
                    XMLStreamReader reader = new InternWrapper(xmlCursor.newXMLStreamReader());
                    ServerAuthConfigType serverAuthConfigType = JaspiXmlUtil.loadServerAuthConfig(reader);
                    StringWriter out = new StringWriter();
                    JaspiXmlUtil.writeServerAuthConfig(serverAuthConfigType, out);
                    authConfigProviderData.setAttribute("config", out.toString());
                } finally {
                    xmlCursor.dispose();
                }
            } else if (authType.isSetServerAuthContext()) {
                authConfigProviderData = new GBeanData(providerName, ServerAuthContextGBean.class);
                final XmlCursor xmlCursor = authType.getServerAuthContext().newCursor();
                try {
                    XMLStreamReader reader = new InternWrapper(xmlCursor.newXMLStreamReader());
                    ServerAuthContextType serverAuthContextType = JaspiXmlUtil.loadServerAuthContext(reader);
                    StringWriter out = new StringWriter();
                    JaspiXmlUtil.writeServerAuthContext(serverAuthContextType, out);
                    authConfigProviderData.setAttribute("config", out.toString());
                } finally {
                    xmlCursor.dispose();
                }
            } else if (authType.isSetServerAuthModule()) {
                authConfigProviderData = new GBeanData(providerName, ServerAuthModuleGBean.class);
                final XmlCursor xmlCursor = authType.getServerAuthModule().newCursor();
                try {
                    XMLStreamReader reader = new InternWrapper(xmlCursor.newXMLStreamReader());
                    AuthModuleType<ServerAuthModule> authModuleType = JaspiXmlUtil.loadServerAuthModule(reader);
                    StringWriter out = new StringWriter();
                    JaspiXmlUtil.writeServerAuthModule(authModuleType, out);
                    authConfigProviderData.setAttribute("config", out.toString());
                    authConfigProviderData.setAttribute("messageLayer", "Http");
                    authConfigProviderData.setAttribute("appContext", contextPath);
                    //TODO ??
                    authConfigProviderData.setAttribute("authenticationID", contextPath);
                } finally {
                    xmlCursor.dispose();
                }
            }
        } catch (ParserConfigurationException e) {
            throw new DeploymentException("Could not read auth config", e);
        } catch (IOException e) {
            throw new DeploymentException("Could not read auth config", e);
        } catch (SAXException e) {
            throw new DeploymentException("Could not read auth config", e);
        } catch (JAXBException e) {
            throw new DeploymentException("Could not read auth config", e);
        } catch (XMLStreamException e) {
            throw new DeploymentException("Could not read auth config", e);
        }
        if (authConfigProviderData != null) {
            moduleContext.addGBean(authConfigProviderData);
            securityFactoryData.addDependency(authConfigProviderData.getAbstractName());
        }
    }
View Full Code Here

            mbe.initContext(earContext, module, cl);
        }
    }

    public void addGBeans(EARContext earContext, Module module, ClassLoader cl, Collection repository) throws DeploymentException {
        EARContext moduleContext = module.getEarContext();
        AbstractName moduleName = moduleContext.getModuleName();
        WebModule webModule = (WebModule) module;

        WebAppType webApp = (WebAppType) webModule.getSpecDD();
        JettyWebAppType jettyWebApp = (JettyWebAppType) webModule.getVendorDD();
        GBeanData webModuleData = new GBeanData(moduleName, WebAppContextWrapper.class);

        configureBasicWebModuleAttributes(webApp, jettyWebApp, moduleContext, earContext, webModule, webModuleData);

        // unsharableResources, applicationManagedSecurityResources
        GBeanResourceEnvironmentBuilder rebuilder = new GBeanResourceEnvironmentBuilder(webModuleData);
        //N.B. use earContext not moduleContext
        //TODO fix this for javaee 5 !!!
        resourceEnvironmentSetter.setResourceEnvironment(rebuilder, webApp.getResourceRefArray(), jettyWebApp.getResourceRefArray());
        try {
            moduleContext.addGBean(webModuleData);

            // configure hosts and virtual-hosts
            configureHosts(earContext, jettyWebApp, webModuleData);


            String contextPath = webModule.getContextRoot();
            if (contextPath == null) {
                throw new DeploymentException("null contextPath");
            }
            if (!contextPath.startsWith("/")) {
                contextPath = "/" + contextPath;
            }
            webModuleData.setAttribute("contextPath", contextPath);

            if (jettyWebApp.isSetWorkDir()) {
                String workDir = jettyWebApp.getWorkDir();
                webModuleData.setAttribute("workDir", workDir);
            }

            if (jettyWebApp.isSetWebContainer()) {
                AbstractNameQuery webContainerName = ENCConfigBuilder.getGBeanQuery(GBeanInfoBuilder.DEFAULT_J2EE_TYPE, jettyWebApp.getWebContainer());
                webModuleData.setReferencePattern("JettyContainer", webContainerName);
            } else {
                webModuleData.setReferencePattern("JettyContainer", jettyContainerObjectName);
            }
            //stuff that jetty used to do
            if (webApp.getDisplayNameArray().length > 0) {
                webModuleData.setAttribute("displayName", webApp.getDisplayNameArray()[0].getStringValue());
            }

            // configure context parameters.
            configureContextParams(webApp, webModuleData);

            // configure listeners.
            configureListeners(webApp, webModuleData);

            webModuleData.setAttribute(WebAppContextWrapper.GBEAN_ATTR_SESSION_TIMEOUT,
                    (webApp.getSessionConfigArray().length == 1 && webApp.getSessionConfigArray(0).getSessionTimeout() != null) ?
                            webApp.getSessionConfigArray(0).getSessionTimeout().getBigIntegerValue().intValue() * 60 :
                            defaultSessionTimeoutSeconds);

            Boolean distributable = webApp.getDistributableArray().length == 1 ? TRUE : FALSE;
            webModuleData.setAttribute("distributable", distributable);
            if (TRUE == distributable) {
                clusteringBuilders.build(jettyWebApp, earContext, moduleContext);
                if (webModuleData.getReferencePatterns(WebAppContextWrapper.GBEAN_REF_SESSION_HANDLER_FACTORY) == null) {
                    log.warn("No clustering builders configured: app will not be clustered");
                    configureNoClustering(moduleContext, webModuleData);
                }
            } else {
                configureNoClustering(moduleContext, webModuleData);
            }

            // configure mime mappings.
            configureMimeMappings(webApp, webModuleData);

            // configure welcome file lists.
            configureWelcomeFileLists(webApp, webModuleData);

            // configure local encoding mapping lists.
            configureLocaleEncodingMappingLists(webApp, webModuleData);

            // configure error pages.
            configureErrorPages(webApp, webModuleData);

            // configure tag libs.
            Set<String> knownServletMappings = new HashSet<String>();
            Set<String> knownJspMappings = new HashSet<String>();
            Map<String, Set<String>> servletMappings = new HashMap<String, Set<String>>();
            if (jspServlet != null) {
                configureTagLibs(module, webApp, webModuleData, servletMappings, knownJspMappings, jspServlet.getServletName());
                GBeanData jspServletData = configureDefaultServlet(jspServlet, earContext, moduleName, knownJspMappings);
                knownServletMappings.addAll(knownJspMappings);
                module.getSharedContext().put(DEFAULT_JSP_SERVLET_KEY, jspServletData);
            }

            // configure login configs.
            configureAuthentication(module, webApp, jettyWebApp, webModuleData);

            // Make sure that servlet mappings point to available servlets and never add a duplicate pattern.

            buildServletMappings(module, webApp, servletMappings, knownServletMappings);

            //be careful that the jsp servlet defaults don't overrride anything configured in the app.
            if (jspServlet != null) {
                GBeanData jspServletData = (GBeanData) module.getSharedContext().get(DEFAULT_JSP_SERVLET_KEY);
                Set<String> jspMappings = (Set<String>) jspServletData.getAttribute("servletMappings");
                jspMappings.removeAll(knownServletMappings);
                jspMappings.addAll(knownJspMappings);
                jspServletData.setAttribute("servletMappings", jspMappings);
            }

            //"previous" filter mapping for linked list to keep dd's ordering.
            AbstractName previous = null;

            //add default filters
            if (defaultFilters != null) {
                previous = addDefaultFiltersGBeans(earContext, moduleContext, moduleName, previous);
            }

            //add default filtermappings
//            if (defaultFilterMappings != null) {
//                for (Iterator iterator = defaultFilterMappings.iterator(); iterator.hasNext();) {
//                    Object defaultFilterMapping = iterator.next();
//                    GBeanData filterMappingGBeanData = getGBeanData(kernel, defaultFilterMapping);
//                    String filterName = (String) filterMappingGBeanData.getAttribute("filterName");
//                    ObjectName defaultFilterMappingObjectName;
//                    if (filterMappingGBeanData.getAttribute("urlPattern") != null) {
//                        String urlPattern = (String) filterMappingGBeanData.getAttribute("urlPattern");
//                        defaultFilterMappingObjectName = NameFactory.getWebFilterMappingName(null, null, null, null, filterName, null, urlPattern, moduleName);
//                    } else {
//                        Set servletNames = filterMappingGBeanData.getReferencePatterns("Servlet");
//                        if (servletNames == null || servletNames.size() != 1) {
//                            throw new DeploymentException("Exactly one servlet name must be supplied");
//                        }
//                        ObjectName servletObjectName = (ObjectName) servletNames.iterator().next();
//                        String servletName = servletObjectName.getKeyProperty("name");
//                        defaultFilterMappingObjectName = NameFactory.getWebFilterMappingName(null, null, null, null, filterName, servletName, null, moduleName);
//                    }
//                    filterMappingGBeanData.setName(defaultFilterMappingObjectName);
//                    filterMappingGBeanData.setReferencePattern("JettyFilterMappingRegistration", webModuleName);
//                    moduleContext.addGBean(filterMappingGBeanData);
//                }
//            }

            // add filter mapping GBeans.
            addFilterMappingsGBeans(earContext, moduleContext, moduleName, webApp, previous);

            // add filter GBeans.
            addFiltersGBeans(earContext, moduleContext, moduleName, webApp);

            //add default servlets
            if (defaultServlets != null) {
                addDefaultServletsGBeans(earContext, moduleContext, moduleName, knownServletMappings);
            }

            //set up servlet gbeans.
            ServletType[] servletTypes = webApp.getServletArray();
            addServlets(moduleName, webModule, servletTypes, servletMappings, moduleContext);

            if (jettyWebApp.isSetSecurityRealmName()) {
                configureSecurityRealm(earContext, webApp, jettyWebApp, webModuleData);
            }

            //See Jetty-386, GERONIMO-3738
            if (jettyWebApp.getCompactPath()) {
                webModuleData.setAttribute("compactPath", Boolean.TRUE);
            }

            //TODO this may definitely not be the best place for this!
            for (ModuleBuilderExtension mbe : moduleBuilderExtensions) {
                mbe.addGBeans(earContext, module, cl, repository);
            }

            //not truly metadata complete until MBEs have run
            if (!webApp.getMetadataComplete()) {
                webApp.setMetadataComplete(true);
                module.setOriginalSpecDD(module.getSpecDD().toString());
            }
            webModuleData.setAttribute("deploymentDescriptor", module.getOriginalSpecDD());

            if (!module.isStandAlone()) {
                ConfigurationData moduleConfigurationData = moduleContext.getConfigurationData();
                earContext.addChildConfiguration(module.getTargetPath(), moduleConfigurationData);
            }
        } catch (DeploymentException de) {
            throw de;
        } catch (Exception e) {
View Full Code Here

            }
        }
    }

    private void configureAuthentication(Module module, WebAppType webApp, JettyWebAppType jettyWebApp, GBeanData webModuleData) throws DeploymentException, GBeanAlreadyExistsException {
        EARContext moduleContext = module.getEarContext();
        LoginConfigType[] loginConfigArray = webApp.getLoginConfigArray();
        if (loginConfigArray.length > 1) {
            throw new DeploymentException("Web app " + module.getName() + " cannot have more than one login-config element.  Currently has " + loginConfigArray.length + " login-config elements.");
        }
        JettyAuthenticationType authType = jettyWebApp.getAuthentication();
        if (loginConfigArray.length == 1 || authType != null || jettyWebApp.isSetSecurityRealmName()) {
            AbstractName factoryName = moduleContext.getNaming().createChildName(module.getModuleName(), "securityHandlerFactory", GBeanInfoBuilder.DEFAULT_J2EE_TYPE);
            webModuleData.setReferencePattern("SecurityHandlerFactory", factoryName);


            if (authType != null) {
                GBeanData securityFactoryData = new GBeanData(factoryName, AuthConfigProviderHandlerFactory.class);
                securityFactoryData.setAttribute("messageLayer", "HttpServlet");
                String contextPath = (String)webModuleData.getAttribute("contextPath");
                securityFactoryData.setAttribute("appContext", "server " + contextPath);
                configureConfigurationFactory(jettyWebApp, null, securityFactoryData);
                moduleContext.addGBean(securityFactoryData);
                configureLocalJaspicProvider(new JettyAuthenticationWrapper(authType), contextPath, module, securityFactoryData);
                //otherwise rely on pre-configured jaspi
            } else {
                LoginConfigType loginConfig = loginConfigArray.length == 1? loginConfigArray[0]: null;
                GBeanData securityFactoryData = new GBeanData(factoryName, JettySecurityHandlerFactory.class);
                configureConfigurationFactory(jettyWebApp, loginConfig, securityFactoryData);
                BuiltInAuthMethod auth = BuiltInAuthMethod.NONE;
                if (loginConfig != null) {
                    if (loginConfig.isSetAuthMethod()) {
                        String authMethod = loginConfig.getAuthMethod().getStringValue().trim();
                        auth = BuiltInAuthMethod.getValueOf(authMethod);

                        if (auth == BuiltInAuthMethod.BASIC) {
                            securityFactoryData.setAttribute("realmName", loginConfig.getRealmName().getStringValue().trim());
                        } else if (auth == BuiltInAuthMethod.DIGEST) {
                            securityFactoryData.setAttribute("realmName", loginConfig.getRealmName().getStringValue().trim());
                        } else if (auth == BuiltInAuthMethod.FORM) {
                            if (loginConfig.isSetFormLoginConfig()) {
                                FormLoginConfigType formLoginConfig = loginConfig.getFormLoginConfig();
                                securityFactoryData.setAttribute("loginPage", formLoginConfig.getFormLoginPage().getStringValue());
                                securityFactoryData.setAttribute("errorPage", formLoginConfig.getFormErrorPage().getStringValue());
                            }
                        } else if (auth == BuiltInAuthMethod.CLIENTCERT) {
                            //nothing to do
                        } else {
                            throw new DeploymentException("unrecognized auth method, use jaspi to configure: " + authMethod);
                        }

                    } else {
                        throw new DeploymentException("No auth method configured and no jaspi configured");
                    }
                    if (loginConfig.isSetRealmName()) {
                        webModuleData.setAttribute("realmName", loginConfig.getRealmName().getStringValue());
                    }
                }
                securityFactoryData.setAttribute("authMethod", auth);
                moduleContext.addGBean(securityFactoryData);
            }
        }
    }
View Full Code Here

TOP

Related Classes of org.apache.geronimo.j2ee.deployment.EARContext

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.