Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * JBoss, Home of Professional Open Source.
   * Copyright 2011, Red Hat, Inc., and individual contributors
   * as indicated by the @author tags. See the copyright.txt file in the
   * distribution for a full listing of individual contributors.
   *
   * This is free software; you can redistribute it and/or modify it
   * under the terms of the GNU Lesser General Public License as
   * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
 
 package org.jboss.as.connector.subsystems.datasources;
 
 import static org.jboss.as.connector.ConnectorLogger.DS_DEPLOYER_LOGGER;
 import static org.jboss.as.connector.ConnectorMessages.MESSAGES;
 
 import java.net.URL;
 import java.util.List;
 import java.util.Map;
 
 
Base service for managing a data-source.

Author(s):
John Bailey
maeste
 
 public abstract class AbstractDataSourceService implements Service<DataSource> {
 
     public static final ServiceName SERVICE_NAME_BASE = ..append("data-source");
     private static final DeployersLogger DEPLOYERS_LOGGER = Logger.getMessageLogger(DeployersLogger.classAS7DataSourceDeployer.class.getName());
     private final InjectedValue<DriverdriverValue = new InjectedValue<Driver>();
 
     private final String jndiName;
 
    protected CommonDeployment deploymentMD;
    protected AbstractDataSourceService(final String jndiName) {
        this. = jndiName;
    }
    public synchronized void start(StartContext startContextthrows StartException {
        try {
            final ServiceContainer container = startContext.getController().getServiceContainer();
             = getDeployer().deploy(container);
            if (.getCfs().length != 1) {
                throw .cannotStartDs();
            }
             = (javax.sql.DataSource.getCfs()[0];
            .debugf("Adding datasource: %s".getCfJndiNames()[0]);
        } catch (Throwable t) {
            throw .deploymentError(t);
        }
    }
    protected abstract AS7DataSourceDeployer getDeployer() throws ValidateException ;
    public synchronized void stop(StopContext stopContext) {
        if ( != null) {
            if (.getDataSources() != null && .getValue() != null) {
                for (org.jboss.jca.core.api.management.DataSource mgtDs : .getDataSources()) {
                    .getValue().getDataSources().remove(mgtDs);
                }
            }
            if (.getConnectionManagers() != null) {
                for (ConnectionManager cm : .getConnectionManagers()) {
                    cm.shutdown();
                }
            }
        }
         = null;
    }
    public CommonDeployment getDeploymentMD() {
        return ;
    }
    public synchronized DataSource getValue() throws IllegalStateExceptionIllegalArgumentException {
        return ;
    }
        return ;
    }
    public Injector<DrivergetDriverInjector() {
        return ;
    }
        return ;
    }
        return ;
    }
        return ;
    }
        return ;
    }
    protected String buildConfigPropsString(Map<StringStringconfigProps) {
        final StringBuffer valueBuf = new StringBuffer();
        for (Map.Entry<StringStringconnProperty : configProps.entrySet()) {
            valueBuf.append(connProperty.getKey());
            valueBuf.append("=");
            valueBuf.append(connProperty.getValue());
            valueBuf.append(";");
        }
        return valueBuf.toString();
    }
        AccessController.doPrivileged(new SetContextLoaderAction(TransactionIntegration.class.getClassLoader()));
        try {
            return .getValue();
        } finally {
            AccessController.doPrivileged();
        }
    }
    private static final SetContextLoaderAction CLEAR_ACTION = new SetContextLoaderAction(null);
    private static class SetContextLoaderAction implements PrivilegedAction<Void> {
        private final ClassLoader classLoader;
        public SetContextLoaderAction(final ClassLoader classLoader) {
            this. = classLoader;
        }
        public Void run() {
            Thread.currentThread().setContextClassLoader();
            return null;
        }
    }
    protected class AS7DataSourceDeployer extends AbstractDsDeployer {
        private final org.jboss.jca.common.api.metadata.ds.DataSource dataSourceConfig;
        private final XaDataSource xaDataSourceConfig;
        private ServiceContainer serviceContainer;
        public AS7DataSourceDeployer(XaDataSource xaDataSourceConfig) {
            super();
            this. = xaDataSourceConfig;
            this. = null;
        }
        public AS7DataSourceDeployer(org.jboss.jca.common.api.metadata.ds.DataSource dataSourceConfig) {
            super();
            this. = dataSourceConfig;
            this. = null;
        }
        public CommonDeployment deploy(ServiceContainer serviceContainerthrows DeployException {
            try {
                if (serviceContainer == null) {
                    throw new DeployException(.nullVar("ServiceContainer"));
                }
                this. = serviceContainer;
                HashMap<Stringorg.jboss.jca.common.api.metadata.ds.Driverdrivers = new HashMap<Stringorg.jboss.jca.common.api.metadata.ds.Driver>(
                        1);
                DataSources dataSources = null;
                if ( != null) {
                    String driverName = .getDriver();
                    InstalledDriver installedDriver = .getValue().getInstalledDriver(driverName);
                    if (installedDriver != null) {
                        String moduleName = installedDriver.getModuleName() != null ? installedDriver.getModuleName().getName()
                                : null;
                        org.jboss.jca.common.api.metadata.ds.Driver driver = new DriverImpl(installedDriver.getDriverName(),
                                installedDriver.getMajorVersion(), installedDriver.getMinorVersion(),
                                moduleNameinstalledDriver.getDriverClassName(),
                                installedDriver.getDataSourceClassName(), installedDriver.getXaDataSourceClassName());
                        drivers.put(driverNamedriver);
                        dataSources = new DatasourcesImpl(Arrays.asList(), nulldrivers);
                    }
                } else if ( != null) {
                    String driverName = .getDriver();
                    InstalledDriver installedDriver = .getValue().getInstalledDriver(driverName);
                    if (installedDriver != null) {
                        String moduleName = installedDriver.getModuleName() != null ? installedDriver.getModuleName().getName()
                                : null;
                        org.jboss.jca.common.api.metadata.ds.Driver driver = new DriverImpl(installedDriver.getDriverName(),
                                installedDriver.getMajorVersion(), installedDriver.getMinorVersion(), moduleName,
                                installedDriver.getDriverClassName(),
                                installedDriver.getDataSourceClassName(), installedDriver.getXaDataSourceClassName());
                        drivers.put(driverNamedriver);
                        dataSources = new DatasourcesImpl(null, Arrays.asList(), drivers);
                    }
                }
                CommonDeployment c = createObjectsAndInjectValue(new URL("file://DataSourceDeployment"), ,
                        "uniqueJdbcLocalId""uniqueJdbcXAId"dataSourcesAbstractDataSourceService.class.getClassLoader());
                return c;
            } catch (MalformedURLException e) {
                throw .cannotDeploy(e);
            } catch (ValidateException e) {
                throw .cannotDeployAndValidate(e);
            }
        }
        @Override
        protected ClassLoader getDeploymentClassLoader(String uniqueId) {
            return .getValue().getClass().getClassLoader();
        }
        @Override
        protected String[] bindConnectionFactory(String deploymentfinal String jndiObject cfthrows Throwable {
            // AS7-2222: Just hack it
            if (cf instanceof javax.resource.Referenceable) {
                ((javax.resource.Referenceable)cf).setReference(new Reference(jndi));
            }
            // don't register because it's one during add operation
            return new String[] { jndi };
        }
        @Override
        protected Object initAndInject(String classNameList<? extends ConfigPropertyconfigsClassLoader cl)
                throws DeployException {
            try {
                Class clz = Class.forName(classNametruecl);
                Object o = clz.newInstance();
                if (configs != null) {
                    Injection injector = new Injection();
                    for (ConfigProperty cpmd : configs) {
                        if (cpmd.isValueSet()) {
                            boolean setValue = true;
                            if (cpmd instanceof org.jboss.jca.common.api.metadata.ra.ra16.ConfigProperty16) {
                                org.jboss.jca.common.api.metadata.ra.ra16.ConfigProperty16 cpmd16 = (org.jboss.jca.common.api.metadata.ra.ra16.ConfigProperty16cpmd;
                                if (cpmd16.getConfigPropertyIgnore() != null && cpmd16.getConfigPropertyIgnore().booleanValue())
                                    setValue = false;
                            }
                            if (setValue)
                                injector.inject(cpmd.getConfigPropertyType().getValue(), cpmd.getConfigPropertyName()
                                        .getValue(), cpmd.getConfigPropertyValue().getValue(), o);
                        }
                    }
                }
                return o;
            } catch (Throwable t) {
                throw .deploymentFailed(tclassName);
            }
        }
        @Override
        protected SubjectFactory getSubjectFactory(String securityDomainthrows DeployException {
            if (securityDomain == null || securityDomain.trim().equals("")) {
                return null;
            } else {
                return .getValue();
            }
        }
        @Override
            return .getValue();
        }
        @Override
        public ManagementRepository getManagementRepository() {
            return .getValue();
        }
        @Override
        protected void initAndInjectClassLoaderPlugin(ManagedConnectionFactory mcfCommonDataSource dsMetadata)
                throws DeployException {
                @Override
                public ClassLoader getClassLoader() {
                    return .getValue().getClass().getClassLoader();
                }
            });
        }
        @Override
            AccessController.doPrivileged(new SetContextLoaderAction(TransactionIntegration.class.getClassLoader()));
            try {
                return .getValue();
            } finally {
                AccessController.doPrivileged();
            }
        }
        @Override
        protected ManagedConnectionFactory createMcf(XaDataSource arg0String arg1ClassLoader arg2)
                throws NotFoundExceptionDeployException {
            final MyXaMCF xaManagedConnectionFactory = new MyXaMCF();
            if (.getUrlDelimiter() != null) {
                try {
                    xaManagedConnectionFactory.setURLDelimiter(.getUrlDelimiter());
                } catch (ResourceException e) {
                    throw .failedToGetUrlDelimiter(e);
                }
            }
            if (.getXaDataSourceClass() != null) {
                xaManagedConnectionFactory.setXADataSourceClass(.getXaDataSourceClass());
            }
            if (.getXaDataSourceProperty() != null) {
                xaManagedConnectionFactory.setXaProps(.getXaDataSourceProperty());
            }
            if (.getUrlSelectorStrategyClassName() != null) {
                xaManagedConnectionFactory
            }
            if (.getXaPool() != null && .getXaPool().isSameRmOverride() != null) {
                xaManagedConnectionFactory.setIsSameRMOverrideValue(.getXaPool().isSameRmOverride());
            }
            if (.getNewConnectionSql() != null) {
                xaManagedConnectionFactory.setNewConnectionSQL(.getNewConnectionSql());
            }
            if (.getUrlSelectorStrategyClassName() != null) {
                xaManagedConnectionFactory
            }
            setMcfProperties(xaManagedConnectionFactory.getStatement());
            xaManagedConnectionFactory.setUserTransactionJndiName("java:comp/UserTransaction");
            return xaManagedConnectionFactory;
        }
        @Override
                ClassLoader arg2throws NotFoundExceptionDeployException {
            final LocalManagedConnectionFactory managedConnectionFactory = new LocalManagedConnectionFactory();
            managedConnectionFactory.setUserTransactionJndiName("java:comp/UserTransaction");
            managedConnectionFactory.setDriverClass(.getDriverClass());
            if (.getDataSourceClass() != null) {
                managedConnectionFactory.setDataSourceClass(.getDataSourceClass());
            }
            if (.getConnectionProperties() != null) {
                managedConnectionFactory.setConnectionProperties(buildConfigPropsString(
                        .getConnectionProperties()));
            }
            if (.getConnectionUrl() != null) {
                managedConnectionFactory.setConnectionURL(.getConnectionUrl());
            }
            if (.getNewConnectionSql() != null) {
                managedConnectionFactory.setNewConnectionSQL(.getNewConnectionSql());
            }
            if (.getUrlSelectorStrategyClassName() != null) {
                managedConnectionFactory.setUrlSelectorStrategyClassName(.getUrlSelectorStrategyClassName());
            }
            setMcfProperties(managedConnectionFactory.getStatement());
            return managedConnectionFactory;
        }
        private void setMcfProperties(final BaseWrapperManagedConnectionFactory managedConnectionFactory,
                CommonDataSource dataSourceConfigfinal Statement statement) {
            if (dataSourceConfig.getTransactionIsolation() != null) {
                managedConnectionFactory.setTransactionIsolation(dataSourceConfig.getTransactionIsolation().name());
            }
            final DsSecurity security = dataSourceConfig.getSecurity();
            if (security != null) {
                if (security.getUserName() != null) {
                    managedConnectionFactory.setUserName(security.getUserName());
                }
                if (security.getPassword() != null) {
                    managedConnectionFactory.setPassword(security.getPassword());
                }
            }
            final TimeOut timeOut = dataSourceConfig.getTimeOut();
            if (timeOut != null) {
                if (timeOut.getUseTryLock() != null) {
                    managedConnectionFactory.setUseTryLock(timeOut.getUseTryLock().intValue());
                }
                if (timeOut.getQueryTimeout() != null) {
                    managedConnectionFactory.setQueryTimeout(timeOut.getQueryTimeout().intValue());
                }
            }
            if (statement != null) {
                if (statement.getTrackStatements() != null) {
                    managedConnectionFactory.setTrackStatements(statement.getTrackStatements().name());
                }
                if (statement.isSharePreparedStatements() != null) {
                    managedConnectionFactory.setSharePreparedStatements(statement.isSharePreparedStatements());
                }
                if (statement.getPreparedStatementsCacheSize() != null) {
                    managedConnectionFactory.setPreparedStatementCacheSize(statement.getPreparedStatementsCacheSize()
                            .intValue());
                }
            }
            final Validation validation = dataSourceConfig.getValidation();
            if (validation != null) {
                if (validation.isValidateOnMatch()) {
                    managedConnectionFactory.setValidateOnMatch(validation.isValidateOnMatch());
                }
                if (validation.getCheckValidConnectionSql() != null) {
                    managedConnectionFactory.setCheckValidConnectionSQL(validation.getCheckValidConnectionSql());
                }
                final Extension validConnectionChecker = validation.getValidConnectionChecker();
                if (validConnectionChecker != null) {
                    if (validConnectionChecker.getClassName() != null) {
                        managedConnectionFactory.setValidConnectionCheckerClassName(validConnectionChecker.getClassName());
                    }
                    if (validConnectionChecker.getConfigPropertiesMap() != null) {
                        managedConnectionFactory
                                .setValidConnectionCheckerProperties(buildConfigPropsString(validConnectionChecker
                                        .getConfigPropertiesMap()));
                    }
                }
                final Extension exceptionSorter = validation.getExceptionSorter();
                if (exceptionSorter != null) {
                    if (exceptionSorter.getClassName() != null) {
                        managedConnectionFactory.setExceptionSorterClassName(exceptionSorter.getClassName());
                    }
                    if (exceptionSorter.getConfigPropertiesMap() != null) {
                        managedConnectionFactory.setExceptionSorterProperties(buildConfigPropsString(exceptionSorter
                                .getConfigPropertiesMap()));
                    }
                }
                final Extension staleConnectionChecker = validation.getStaleConnectionChecker();
                if (staleConnectionChecker != null) {
                    if (staleConnectionChecker.getClassName() != null) {
                        managedConnectionFactory.setStaleConnectionCheckerClassName(staleConnectionChecker.getClassName());
                    }
                    if (staleConnectionChecker.getConfigPropertiesMap() != null) {
                        managedConnectionFactory
                                .setStaleConnectionCheckerProperties(buildConfigPropsString(staleConnectionChecker
                                        .getConfigPropertiesMap()));
                    }
                }
            }
        }
        // Override this method to change how jndiName is build in AS7
        @Override
        protected String buildJndiName(String rawJndiNameBoolean javaContext) {
            final String jndiName;
            if (!rawJndiName.startsWith("java:") && javaContext) {
                if (rawJndiName.startsWith("jboss/")) {
                    // Bind to java:jboss/ namespace
                    jndiName = "java:" + rawJndiName;
                } else {
                    // Bind to java:/ namespace
                    jndiName"java:/" + rawJndiName;
                }
            } else {
                jndiName = rawJndiName;
            }
            return jndiName;
        }
        @Override
        protected DeployersLogger getLogger() {
            return ;
        }
    }
    private class MyXaMCF extends XAManagedConnectionFactory {
        private static final long serialVersionUID = 4876371551002746953L;
        public void setXaProps(Map<StringStringinputProperties) {
            .putAll(inputProperties);
        }
    }
New to GrepCode? Check out our FAQ X