Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved.
   *
   * The contents of this file are subject to the terms of either the GNU
   * General Public License Version 2 only ("GPL") or the Common Development
   * and Distribution License("CDDL") (collectively, the "License").  You
   * may not use this file except in compliance with the License.  You can
  * obtain a copy of the License at
  * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
  * or packager/legal/LICENSE.txt.  See the License for the specific
  * language governing permissions and limitations under the License.
  *
  * When distributing the software, include this License Header Notice in each
  * file and include the License file at packager/legal/LICENSE.txt.
  *
  * GPL Classpath Exception:
  * Oracle designates this particular file as subject to the "Classpath"
  * exception as provided by Oracle in the GPL Version 2 section of the License
  * file that accompanied this code.
  *
  * Modifications:
  * If applicable, add the following below the License Header, with the fields
  * enclosed by brackets [] replaced by your own identifying information:
  * "Portions Copyright [year] [name of copyright owner]"
  *
  * Contributor(s):
  * If you wish your version of this file to be governed by only the CDDL or
  * only the GPL Version 2, indicate your decision by adding "[Contributor]
  * elects to include this software in this distribution under the [CDDL or GPL
  * Version 2] license."  If you don't indicate a single choice of license, a
  * recipient has the option to distribute your version of this file under
  * either the CDDL, the GPL Version 2 or to extend the choice of license to
  * its licensees as provided above.  However, if you add GPL Version 2 code
  * and therefore, elected the GPL Version 2 license, then the option applies
  * only if the new code is made subject to such option by the copyright
  * holder.
  */
 
 package com.sun.enterprise.connectors.module;
 
 
 import java.io.*;
 import java.util.*;
Deployer for a resource-adapter.

Author(s):
Jagadish Ramu
 
         implements PostConstructPreDestroyEventListener {
 
     @Inject
     private ConnectorRuntime runtime;
 
     @Inject
    private ClassLoaderHierarchy clh;
    @Inject
    @Inject
    @Inject
    private Domain domain;
    @Inject
    private ServerEnvironment env;
    private Resources resources;
    @Inject
    private Events events;
    
    @Inject
    private static Logger _logger = LogDomains.getLogger(ConnectorDeployer.class.);
    private static StringManager localStrings = StringManager.getManager(ConnectorRuntime.class);
    private static final String DOMAIN = "domain";
    private static final String EAR = "ear";
    public ConnectorDeployer() {
    }

    
Returns the meta data assocated with this Deployer

Returns:
the meta data for this Deployer
    public MetaData getMetaData() {
        return new MetaData(falsenull,
                new Class[]{Application.class});
    }

    
Loads the meta date associated with the application.

Parameters:
type type of metadata that this deployer has declared providing.
    public <T> T loadMetaData(Class<T> typeDeploymentContext context) {
        return null;
    }

    
Loads a previously prepared application in its execution environment and return a ContractProvider instance that will identify this environment in future communications with the application's container runtime.

Parameters:
container in which the application will reside
context of the deployment
Returns:
an ApplicationContainer instance identifying the running application
    @Override
    public ConnectorApplication load(ConnectorContainer containerDeploymentContext context) {
        super.load(containercontext);
        File sourceDir = context.getSourceDir();
        String sourcePath = sourceDir.getAbsolutePath();
        String moduleName = sourceDir.getName();
        ConnectorDescriptor connDesc = 
            context.getModuleMetaData(ConnectorDescriptor.class);
        if (connDesc != null) {
            connDesc.setClassLoader(context.getClassLoader());
        }
        if(.isLoggable(.)){
            .finest("connector-descriptor during load : " + connDesc);
        }
        boolean isEmbedded = ConnectorsUtil.isEmbedded(context);
        ConnectorClassFinder ccf = null;
        ClassLoader classLoader = null;
        //this check is not needed as system-rars are never deployed, just to be safe.
        if (!ConnectorsUtil.belongsToSystemRA(moduleName)) {
            try {
                //for a connector deployer, classloader will always be ConnectorClassFinder
                classLoader =  context.getClassLoader();
                //for embedded .rar, compute the embedded .rar name
                if (isEmbedded) {
                    moduleName = ConnectorsUtil.getEmbeddedRarModuleName(
                            ConnectorsUtil.getApplicationName(context), moduleName);
                }
                //don't add the class-finder to the chain if its embedded .rar
                if (!(isEmbedded)) {
                    ccf = (ConnectorClassFindercontext.getClassLoader();
                    .getConnectorClassLoader(null).addDelegate(ccf);
                }
                registerBeanValidator(moduleNamecontext.getSource(), classLoader);
                .createActiveResourceAdapter(connDescmoduleNamesourcePathclassLoader);
            } catch (Exception cre) {
                Object params[] = new Object[]{moduleNamecre};
                .log(."unable.to.load.ra"params);
                //since resource-adapter creation has failed, remove the class-loader for the RAR
                if (!(isEmbedded) && ccf != null) {
                    .getConnectorClassLoader(null).removeDelegate(ccf);
                }
                //since resource-adapter creation has failed, unregister bean validator of the RAR
                unregisterBeanValidator(moduleName);
                throw new RuntimeException(cre.getMessage(), cre);
            }
        }
        return new ConnectorApplication(moduleName, ConnectorsUtil.getApplicationName(context), ,
                classLoaderconnDesc);
    }



    
Unload or stop a previously running application identified with the ContractProvider instance. The container will be stop upon return from this method.

Parameters:
appContainer instance to be stopped
context of the undeployment
    public void unload(ConnectorApplication appContainerDeploymentContext context) {
        String moduleName = appContainer.getModuleName();
        try {
            .destroyActiveResourceAdapter(moduleName);
        } catch (ConnectorRuntimeException e) {
            Object params[] = new Object[]{moduleNamee};
            .log(."unable.to.unload.ra"params);
        } finally {
            //remove it only if it is not embedded
            if (!ConnectorsUtil.isEmbedded(context)) {
                //remove the class-finder (class-loader) from connector-class-loader chain
                DelegatingClassLoader dcl = .getConnectorClassLoader(null);
                for(DelegatingClassLoader.ClassFinder cf : dcl.getDelegates()){
                    ConnectorClassFinder ccf = (ConnectorClassFinder)cf;
                    if(ccf.getResourceAdapterName().equals(moduleName)){
                        dcl.removeDelegate(ccf);
                        break;
                    }
                }
            }
            unregisterBeanValidator(moduleName);
        }
    }

    
Clean any files and artifacts that were created during the execution of the prepare method.

Parameters:
dc deployment context
    public void clean(DeploymentContext dc) {
        super.clean(dc);
        //delete resource configuration
        if (dcp != null && dcp.origin == ..) {
            if (dcp.cascade != null && dcp.cascade) {
                File sourceDir = dc.getSourceDir();
                String moduleName = sourceDir.getName();
                if (ConnectorsUtil.isEmbedded(dc)) {
                    String applicationName = ConnectorsUtil.getApplicationName(dc);
                    moduleName = ConnectorsUtil.getEmbeddedRarModuleName(applicationNamemoduleName);
                }
                deleteAllResources(moduleNamedcp.target);
            }
        }
    }

    
deletes all resources (pool, resource, admin-object-resource, ra-config, work-security-map) of a resource-adapter)

Parameters:
moduleName resource-adapter name
targetServer target instance name
    private void deleteAllResources(String moduleNameString targetServer) {
        Collection<ConnectorConnectionPoolconPools = ConnectorsUtil.getAllPoolsOfModule(moduleName);
        Collection<StringpoolNames = ConnectorsUtil.getAllPoolNames(conPools);
        Collection<ResourceconnectorResources = ConnectorsUtil.getAllResources(poolNames);
        Collection<AdminObjectResourceadminObjectResources = ResourcesUtil.createInstance().
                getEnabledAdminObjectResources(moduleName);
        Collection<WorkSecurityMapsecurityMaps = ConnectorsUtil.getAllWorkSecurityMaps(moduleName);
        ResourceAdapterConfig rac = ConnectorsUtil.getRAConfig(moduleName);
        deleteConnectorResources(connectorResourcestargetServermoduleName);
        deleteConnectionPools(conPoolsmoduleName);
        deleteAdminObjectResources(adminObjectResourcestargetServermoduleName);
        deleteWorkSecurityMaps(securityMapsmoduleName);
        deleteRAConfig(rac);
    }
    private void deleteRAConfig(final ResourceAdapterConfig rac) {
        if (rac != null) {
            try {
                // delete resource-adapter-config
                if (ConfigSupport.apply(new SingleConfigCode<Resources>() {
                    public Object run(Resources paramthrows PropertyVetoExceptionTransactionFailure {
                        return param.getResources().remove(rac);
                    }
                }, ) == null) {
                    .log(."unable.to.delete.rac"rac.getResourceAdapterName());
                }
            } catch (TransactionFailure tfe) {
                Object params[] = new Object[]{rac.getResourceAdapterName(), tfe};
                .log(."unable.to.delete.rac.exception"params);
            }
        }
    }
    private void deleteWorkSecurityMaps(final Collection<WorkSecurityMapworkSecurityMapsString raName) {
        if (workSecurityMaps.size() > 0) {
            try {
                // delete work-security-maps
                if (ConfigSupport.apply(new SingleConfigCode<Resources>() {
                    public Object run(Resources paramthrows PropertyVetoException,
                            TransactionFailure {
                        for (WorkSecurityMap resource : workSecurityMaps) {
                            param.getResources().remove(resource);
                        }
                        return true// indicating that removal was successful
                    }
                }, ) == null) {
                    .log(."unable.to.delete.work.security.map"raName);
                }
            } catch (TransactionFailure tfe) {
                Object params[] = new Object[]{raNametfe};
                .log(."unable.to.delete.work.security.map.exception"params);
            }
        }
    }
    private void deleteAdminObjectResources(final Collection<AdminObjectResourceadminObjectResources,
                                            final String targetString raName) {
        if (adminObjectResources != null && adminObjectResources.size() > 0) {
            try {
                //delete resource-refs
                for (AdminObjectResource resource : adminObjectResources) {
                    String jndiName = resource.getJndiName();
                    deleteResourceRef(jndiNametarget);
                }
                // delete admin-object-resource
                if (ConfigSupport.apply(new SingleConfigCode<Resources>() {
                    public Object run(Resources paramthrows PropertyVetoExceptionTransactionFailure {
                        for (AdminObjectResource resource : adminObjectResources) {
                            param.getResources().remove(resource);
                        }
                        // not found
                        return true;
                    }
                }, ) == null) {
                    .log(."unable.to.delete.admin.object"raName);
                }
            } catch (TransactionFailure tfe) {
                Object params[] = new Object[]{raNametfe};
                .log(."unable.to.delete.admin.object.exception"params);
            }
        }
    }
    private void deleteConnectorResources(final Collection<ResourceconnectorResourcesfinal String target,
                                          String raName) {
        if (connectorResources.size() > 0) {
            try {
                //delete resource-refs
                for (Resource resource : connectorResources) {
                    String jndiName = ((ConnectorResourceresource).getJndiName();
                    deleteResourceRef(jndiNametarget);
                }
                // delete connector-resource
                if (ConfigSupport.apply(new SingleConfigCode<Resources>() {
                    public Object run(Resources paramthrows PropertyVetoExceptionTransactionFailure {
                        for (Resource resource : connectorResources) {
                            param.getResources().remove(resource);
                        }
                        // not found
                        return true;
                    }
                }, ) == null) {
                    .log(."unable.to.delete.connector.resource"raName);
                }
            } catch (TransactionFailure tfe) {
                Object params[] = new Object[]{raNametfe};
                .log(."unable.to.delete.connector.resource.exception"params);
            }
        }
    }
    private void deleteResourceRef(String jndiNameString targetthrows TransactionFailure {
        if (target.equals()) {
            return ;
        }
        if.getConfigNamed(target) != null){
            return ;
        }
        Server server = .getServerNamed(target);
        if (server != null) {
            if (server.isResourceRefExists(jndiName)) {
                // delete ResourceRef for Server
                server.deleteResourceRef(jndiName);
            }
        } else {
            Cluster cluster = .getClusterNamed(target);
            if(cluster != null){
                if (cluster.isResourceRefExists(jndiName)) {
                    // delete ResourceRef of Cluster
                    cluster.deleteResourceRef(jndiName);
                    // delete ResourceRef for all instances of Cluster
                    Target tgt = .getService(Target.class);
                    List<Serverinstances = tgt.getInstances(target);
                    for (Server svr : instances) {
                        if (svr.isResourceRefExists(jndiName)) {
                            svr.deleteResourceRef(jndiName);
                        }
                    }
                }
            }
        }
    }
    private void deleteConnectionPools(final Collection<ConnectorConnectionPoolconPoolsString raName) {
        if (conPools.size() > 0) {
            // delete connector connection pool
            try {
                if (ConfigSupport.apply(new SingleConfigCode<Resources>() {
                    public Object run(Resources paramthrows PropertyVetoExceptionTransactionFailure {
                        for (ConnectorConnectionPool cp : conPools) {
                            return param.getResources().remove(cp);
                        }
                        // not found
                        return null;
                    }
                }, ) == null) {
                    .log(."unable.to.delete.connector.connection.pool"raName);
                }
            } catch (TransactionFailure tfe) {
                Object params[] = new Object[]{raNametfe};
                .log(."unable.to.delete.connector.connection.pool.exception"params);
            }
        }
    }


    
The component has been injected with any dependency and will be placed into commission by the subsystem.
    public void postConstruct() {
         = .getResources();
        .register(this);
    }
    public void logFine(String message) {
        if(.isLoggable(.)) {
            .log(.message);
        }
    }
    private void registerBeanValidator(String rarNameReadableArchive archiveClassLoader classLoader) {
        ClassLoader contextCL = null;
        try {
            contextCL = Thread.currentThread().getContextClassLoader();
            Thread.currentThread().setContextClassLoader(classLoader);
            Validator beanValidator = null;
            ValidatorFactory validatorFactory = null;
            try {
                List<StringmappingsList = getValidationMappingDescriptors(archive);
                if (mappingsList.size() > 0) {
                    GenericBootstrap bootstrap = Validation.byDefaultProvider();
                    Configuration config = bootstrap.configure();
                    InputStream inputStream = null;
                    try {
                        for (String fileName : mappingsList) {
                            inputStream = archive.getEntry(fileName);
                            config.addMapping(inputStream);
                        }
                        validatorFactory = config.buildValidatorFactory();
                        ValidatorContext validatorContext = validatorFactory.usingContext();
                        beanValidator = validatorContext.getValidator();
                    } catch (IOException e) {
                        if(.isLoggable(.)) {
                            .log(."Exception while processing xml files for detecting " +
                                "bean-validation-mapping"e);
                        }
                    } finally {
                        try {
                            if (inputStream != null) {
                                inputStream.close();
                            }
                        } catch (Exception e) {
                            // ignore ?
                        }
                    }
                }
            } catch (Exception e) {
                Object params[] = new Object[]{rarNamee};
                .log(."error.processing.xml.for.bean.validation.mapping"params);
            }
            if (beanValidator == null) {
                validatorFactory = Validation.byDefaultProvider().configure().buildValidatorFactory();
                beanValidator = validatorFactory.getValidator();
            }
            ConnectorRegistry registry = ConnectorRegistry.getInstance();
            registry.addBeanValidator(rarNamebeanValidator);
        } finally {
            Thread.currentThread().setContextClassLoader(contextCL);
        }
    }
        String validationMappingNSName = "jboss.org/xml/ns/javax/validation/mapping";
        Enumeration entries = archive.entries();
        List<StringmappingList = new ArrayList<String>();
        while (entries.hasMoreElements()) {
            String fileName = (Stringentries.nextElement();
            if (fileName.toUpperCase(Locale.getDefault()).endsWith(".XML")) {
                BufferedReader reader = null;
                try {
                    InputStream is = archive.getEntry(fileName);
                    reader = new BufferedReader(new InputStreamReader(is));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        if (line.contains(validationMappingNSName)) {
                            mappingList.add(fileName);
                            break;
                        }
                    }
                } catch (IOException e) {
                    if(.isLoggable(.)) {
                        .log(."Exception while processing xml file [ " + fileName + " ] " +
                            "for detecting bean-validation-mapping"e);
                    }
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (Exception e) {
							//ignore ?
                        }
                    }
                }
            }
        }
        return mappingList;
    }
    private void unregisterBeanValidator(String rarName){
        ConnectorRegistry registry = ConnectorRegistry.getInstance();
        registry.removeBeanValidator(rarName);
    }
    public void event(Event event) {
        // added this pre-check so as to validate whether connector-resources referring
        // the application (that has rar or is an standalone rar) are present.
        // Though similar validation is done in 'ConnectorApplication', this is to
        // handle the case where the application is not enabled in DAS (no ConnectorApplication)
        if (/*env.isDas() && */ ..equals(event.type())) {
            //this is an application undeploy event
            DeploymentContext dc = (DeploymentContextevent.hook();
            String appName = dcp.name;
            Boolean cascade = dcp.cascade;
            Boolean ignoreCascade = dcp._ignoreCascade;
            if (cascade != null && ignoreCascade != null) {
                if (cascade || ignoreCascade) {
                    return;
                }
            }
            boolean isRAR = false;
            if (app != null && Boolean.valueOf(app.getEnabled())) {
                isRAR = app.containsSnifferType(.);
            }
            if (!isRAR) {
                return;
            }
            boolean isAppRefEnabled = false;
            Server server = .getServers().getServer(.getInstanceName());
            ApplicationRef appRef = server.getApplicationRef(appName);
            if (appRef != null && Boolean.valueOf(appRef.getEnabled())) {
                isAppRefEnabled = true;
            }
            if (isAppRefEnabled) {
                return;
            }
            boolean isEAR = app.containsSnifferType();
            String moduleName = appName;
            ResourcesUtil resourcesUtil = ResourcesUtil.createInstance();
            if (isEAR) {
                List<Modulemodules = app.getModule();
                for (Module module : modules) {
                    moduleName = module.getName();
                    if (module.getEngine(.) != null) {
                        moduleName = appName + . + moduleName;
                        if (moduleName.toLowerCase(Locale.getDefault()).endsWith(".rar")) {
                            int index = moduleName.lastIndexOf(".rar");
                            moduleName = moduleName.substring(0, index);
                            if (resourcesUtil.filterConnectorResources
                                    (.getAllResources(), moduleNametrue).size() > 0) {
                                setFailureStatus(dcmoduleName);
                                return;
                            }
                        }
                    }
                }
            } else {
                if (resourcesUtil.filterConnectorResources
                        (.getAllResources(), moduleNametrue).size() > 0) {
                    setFailureStatus(dcmoduleName);
                }
            }
        }
    }
    private void setFailureStatus(DeploymentContext dcString moduleName) {
        String message = .getString("con.deployer.resources.exist"moduleName);
        .log(."resources.of.rar.exist"moduleName);
        ActionReport report = dc.getActionReport();
        report.setMessage(message);
    }
    public void preDestroy() {
        .unregister(this);
    }
New to GrepCode? Check out our FAQ X