Search in sources :

Example 21 with org.jvnet.hk2.config

use of org.jvnet.hk2.config in project Payara by payara.

the class SetEnvironmentWarningConfigurationCommand method execute.

@Override
public void execute(AdminCommandContext acc) {
    Config config = targetUtil.getConfig(target);
    ActionReport actionReport = acc.getActionReport();
    EnvironmentWarningConfiguration environmentWarningConfiguration = config.getExtensionByType(EnvironmentWarningConfiguration.class);
    if (environmentWarningConfiguration != null) {
        try {
            ConfigSupport.apply(new SingleConfigCode<EnvironmentWarningConfiguration>() {

                @Override
                public Object run(EnvironmentWarningConfiguration config) throws PropertyVetoException {
                    if (enabled != null) {
                        config.setEnabled(enabled);
                    }
                    if (message != null) {
                        config.setMessage(message);
                    }
                    if (backgroundColour != null) {
                        if (backgroundColour.matches("^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$")) {
                            config.setBackgroundColour(backgroundColour);
                        } else {
                            throw new PropertyVetoException("Invalid data for background colour, must be a hex value.", new PropertyChangeEvent(config, "backgroundColour", config.getBackgroundColour(), backgroundColour));
                        }
                    }
                    if (textColour != null) {
                        if (textColour.matches("^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$")) {
                            config.setTextColour(textColour);
                        } else {
                            throw new PropertyVetoException("Invalid data for text colour, must be a hex value.", new PropertyChangeEvent(config, "textColour", config.getTextColour(), textColour));
                        }
                    }
                    return null;
                }
            }, environmentWarningConfiguration);
        } catch (TransactionFailure ex) {
            // Set failure
            actionReport.failure(Logger.getLogger(SetEnvironmentWarningConfigurationCommand.class.getName()), "Failed to update configuration", ex);
        }
    }
}
Also used : PropertyVetoException(java.beans.PropertyVetoException) TransactionFailure(org.jvnet.hk2.config.TransactionFailure) PropertyChangeEvent(java.beans.PropertyChangeEvent) Config(com.sun.enterprise.config.serverbeans.Config) ActionReport(org.glassfish.api.ActionReport) EnvironmentWarningConfiguration(fish.payara.appserver.environment.warning.config.EnvironmentWarningConfiguration)

Example 22 with org.jvnet.hk2.config

use of org.jvnet.hk2.config in project Payara by payara.

the class SetEjbInvokerConfigurationCommand method execute.

@Override
public void execute(AdminCommandContext context) {
    ActionReport actionReport = context.getActionReport();
    Subject subject = context.getSubject();
    Config targetConfig = targetUtil.getConfig(target);
    EjbInvokerConfiguration config = targetConfig.getExtensionByType(EjbInvokerConfiguration.class);
    try {
        ConfigSupport.apply(configProxy -> {
            if (enabled != null) {
                configProxy.setEnabled(enabled.toString());
            }
            if (endpoint != null) {
                configProxy.setEndpoint(endpoint);
            }
            if (virtualServers != null) {
                configProxy.setVirtualServers(virtualServers);
            }
            if (securityEnabled != null) {
                configProxy.setSecurityEnabled(securityEnabled.toString());
            }
            if (realmName != null) {
                configProxy.setRealmName(realmName);
            }
            if (authType != null) {
                configProxy.setAuthType(authType);
            }
            if (authModule != null) {
                configProxy.setAuthModule(authModule);
            }
            if (authModuleClass != null) {
                if (StringUtils.ok(authModuleClass) && authModuleClass.indexOf('.') == -1) {
                    actionReport.failure(LOGGER, "authModuleClass parameter value must be fully qualified class name.");
                }
                configProxy.setAuthModuleClass(authModuleClass);
            }
            if (roles != null) {
                configProxy.setRoles(roles);
            }
            actionReport.setActionExitCode(ActionReport.ExitCode.SUCCESS);
            return configProxy;
        }, config);
    } catch (TransactionFailure ex) {
        actionReport.failure(LOGGER, "Failed to update EJB Invoker configuration", ex);
    }
    if (Boolean.parseBoolean(config.getSecurityEnabled())) {
        // If the required message security provider is not present, create it
        if (StringUtils.ok(config.getAuthModuleClass())) {
            String moduleClass = config.getAuthModuleClass();
            String moduleId = moduleClass.substring(moduleClass.lastIndexOf('.') + 1);
            ActionReport checkSecurityProviderReport = actionReport.addSubActionsReport();
            ActionReport createSecurityProviderReport = actionReport.addSubActionsReport();
            if (!messageSecurityProviderExists(moduleId, checkSecurityProviderReport, context.getSubject())) {
                createRequiredMessageSecurityProvider(moduleId, moduleClass, createSecurityProviderReport, subject);
            }
            if (checkSecurityProviderReport.hasFailures() || createSecurityProviderReport.hasFailures()) {
                actionReport.setActionExitCode(ActionReport.ExitCode.FAILURE);
                return;
            }
        }
        // Create the default user if it doesn't exist
        if (!StringUtils.ok(config.getRealmName()) || config.getRealmName().equals("file")) {
            ActionReport checkUserReport = actionReport.addSubActionsReport();
            ActionReport createUserReport = actionReport.addSubActionsReport();
            if (!defaultUserExists(config, checkUserReport, subject) && !checkUserReport.hasFailures()) {
                createDefaultUser(config, createUserReport, subject);
            }
            if (checkUserReport.hasFailures() || createUserReport.hasFailures()) {
                actionReport.setActionExitCode(ActionReport.ExitCode.FAILURE);
                return;
            }
        }
    }
    if (enabled != null) {
        if (enabled) {
            enableEjbInvoker(actionReport);
        } else {
            disableEjbInvoker(actionReport);
        }
    } else if (Boolean.parseBoolean(config.getEnabled())) {
        actionReport.setMessage("Restart server or re-enable the ejb-invoker service for the change to take effect.");
    }
    // If everything has passed, scrap the subaction reports as we don't want to print them out
    if (!actionReport.hasFailures() && !actionReport.hasWarnings()) {
        actionReport.getSubActionsReport().clear();
    }
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) Config(com.sun.enterprise.config.serverbeans.Config) ActionReport(org.glassfish.api.ActionReport) Subject(javax.security.auth.Subject)

Example 23 with org.jvnet.hk2.config

use of org.jvnet.hk2.config in project Payara by payara.

the class JdbcConnectionPoolDeployer method getMCFConfigProperties.

/**
 * Pull out the MCF configuration properties and return them as an array
 * of ConnectorConfigProperty
 *
 * @param adminPool   - The JdbcConnectionPool to pull out properties from
 * @param conConnPool - ConnectorConnectionPool which will be used by Resource Pool
 * @param connDesc    - The ConnectorDescriptor for this JDBC RA
 * @return ConnectorConfigProperty [] array of MCF Config properties specified
 *         in this JDBC RA
 */
private ConnectorConfigProperty[] getMCFConfigProperties(JdbcConnectionPool adminPool, ConnectorConnectionPool conConnPool, ConnectorDescriptor connDesc) {
    ArrayList<ConnectorConfigProperty> propList = new ArrayList<>();
    if (adminPool.getResType() != null) {
        if (ConnectorConstants.JAVA_SQL_DRIVER.equals(adminPool.getResType())) {
            propList.add(new ConnectorConfigProperty("ClassName", adminPool.getDriverClassname() == null ? "" : adminPool.getDriverClassname(), "The driver class name", "java.lang.String"));
        } else {
            propList.add(new ConnectorConfigProperty("ClassName", adminPool.getDatasourceClassname() == null ? "" : adminPool.getDatasourceClassname(), "The datasource class name", "java.lang.String"));
        }
    } else {
        // When resType is null, one of these classnames would be specified
        if (adminPool.getDriverClassname() != null) {
            propList.add(new ConnectorConfigProperty("ClassName", adminPool.getDriverClassname() == null ? "" : adminPool.getDriverClassname(), "The driver class name", "java.lang.String"));
        } else if (adminPool.getDatasourceClassname() != null) {
            propList.add(new ConnectorConfigProperty("ClassName", adminPool.getDatasourceClassname() == null ? "" : adminPool.getDatasourceClassname(), "The datasource class name", "java.lang.String"));
        }
    }
    propList.add(new ConnectorConfigProperty("ConnectionValidationRequired", adminPool.getIsConnectionValidationRequired() + "", "Is connection validation required", "java.lang.String"));
    propList.add(new ConnectorConfigProperty("ValidationMethod", adminPool.getConnectionValidationMethod() == null ? "" : adminPool.getConnectionValidationMethod(), "How the connection is validated", "java.lang.String"));
    propList.add(new ConnectorConfigProperty("ValidationTableName", adminPool.getValidationTableName() == null ? "" : adminPool.getValidationTableName(), "Validation Table name", "java.lang.String"));
    propList.add(new ConnectorConfigProperty("ValidationClassName", adminPool.getValidationClassname() == null ? "" : adminPool.getValidationClassname(), "Validation Class name", "java.lang.String"));
    propList.add(new ConnectorConfigProperty("TransactionIsolation", adminPool.getTransactionIsolationLevel() == null ? "" : adminPool.getTransactionIsolationLevel(), "Transaction Isolatin Level", "java.lang.String"));
    propList.add(new ConnectorConfigProperty("GuaranteeIsolationLevel", adminPool.getIsIsolationLevelGuaranteed() + "", "Transaction Isolation Guarantee", "java.lang.String"));
    propList.add(new ConnectorConfigProperty("StatementWrapping", adminPool.getWrapJdbcObjects() + "", "Statement Wrapping", "java.lang.String"));
    propList.add(new ConnectorConfigProperty("LogJdbcCalls", adminPool.getLogJdbcCalls() + "", "Log JDBC Calls", "java.lang.String"));
    propList.add(new ConnectorConfigProperty("SlowQueryThresholdInSeconds", adminPool.getSlowQueryThresholdInSeconds() + "", "Slow Query Threshold In Seconds", "java.lang.String"));
    propList.add(new ConnectorConfigProperty("StatementTimeout", adminPool.getStatementTimeoutInSeconds() + "", "Statement Timeout", "java.lang.String"));
    PoolInfo poolInfo = conConnPool.getPoolInfo();
    propList.add(new ConnectorConfigProperty("PoolMonitoringSubTreeRoot", ConnectorsUtil.getPoolMonitoringSubTreeRoot(poolInfo, true) + "", "Pool Monitoring Sub Tree Root", "java.lang.String"));
    propList.add(new ConnectorConfigProperty("PoolName", poolInfo.getName() + "", "Pool Name", "java.lang.String"));
    if (poolInfo.getApplicationName() != null) {
        propList.add(new ConnectorConfigProperty("ApplicationName", poolInfo.getApplicationName() + "", "Application Name", "java.lang.String"));
    }
    if (poolInfo.getModuleName() != null) {
        propList.add(new ConnectorConfigProperty("ModuleName", poolInfo.getModuleName() + "", "Module name", "java.lang.String"));
    }
    propList.add(new ConnectorConfigProperty("StatementCacheSize", adminPool.getStatementCacheSize() + "", "Statement Cache Size", "java.lang.String"));
    propList.add(new ConnectorConfigProperty("StatementCacheType", adminPool.getStatementCacheType() + "", "Statement Cache Type", "java.lang.String"));
    propList.add(new ConnectorConfigProperty("InitSql", adminPool.getInitSql() + "", "InitSql", "java.lang.String"));
    propList.add(new ConnectorConfigProperty("SqlTraceListeners", adminPool.getSqlTraceListeners() + "", "Sql Trace Listeners", "java.lang.String"));
    propList.add(new ConnectorConfigProperty("StatementLeakTimeoutInSeconds", adminPool.getStatementLeakTimeoutInSeconds() + "", "Statement Leak Timeout in seconds", "java.lang.String"));
    propList.add(new ConnectorConfigProperty("StatementLeakReclaim", adminPool.getStatementLeakReclaim() + "", "Statement Leak Reclaim", "java.lang.String"));
    // dump user defined poperties into the list
    Set connDefDescSet = connDesc.getOutboundResourceAdapter().getConnectionDefs();
    // since this a 1.0 RAR, we will have only 1 connDefDesc
    if (connDefDescSet.size() != 1) {
        throw new MissingResourceException("Only one connDefDesc present", null, null);
    }
    Iterator iter = connDefDescSet.iterator();
    // Now get the set of MCF config properties associated with each
    // connection-definition . Each element here is an EnviromnentProperty
    Set mcfConfigProps = null;
    while (iter.hasNext()) {
        mcfConfigProps = ((ConnectionDefDescriptor) iter.next()).getConfigProperties();
    }
    if (mcfConfigProps != null) {
        Map mcfConPropKeys = new HashMap();
        Iterator mcfConfigPropsIter = mcfConfigProps.iterator();
        while (mcfConfigPropsIter.hasNext()) {
            String key = ((ConnectorConfigProperty) mcfConfigPropsIter.next()).getName();
            mcfConPropKeys.put(key.toUpperCase(locale), key);
        }
        String driverProperties = "";
        for (Property rp : adminPool.getProperty()) {
            if (rp == null) {
                continue;
            }
            String name = rp.getName();
            // making it easy to compare in the event of a reconfig
            if ("MATCHCONNECTIONS".equals(name.toUpperCase(locale))) {
                // JDBC - matchConnections if not set is decided by the ConnectionManager
                // so default is false
                conConnPool.setMatchConnections(toBoolean(rp.getValue(), false));
                logFine("MATCHCONNECTIONS");
            } else if ("ASSOCIATEWITHTHREAD".equals(name.toUpperCase(locale))) {
                conConnPool.setAssociateWithThread(toBoolean(rp.getValue(), false));
                logFine("ASSOCIATEWITHTHREAD");
            } else if ("LAZYCONNECTIONASSOCIATION".equals(name.toUpperCase(locale))) {
                ConnectionPoolObjectsUtils.setLazyEnlistAndLazyAssocProperties(rp.getValue(), adminPool.getProperty(), conConnPool);
                logFine("LAZYCONNECTIONASSOCIATION");
            } else if ("LAZYCONNECTIONENLISTMENT".equals(name.toUpperCase(Locale.getDefault()))) {
                conConnPool.setLazyConnectionEnlist(toBoolean(rp.getValue(), false));
                logFine("LAZYCONNECTIONENLISTMENT");
            } else if ("POOLDATASTRUCTURE".equals(name.toUpperCase(Locale.getDefault()))) {
                conConnPool.setPoolDataStructureType(rp.getValue());
                logFine("POOLDATASTRUCTURE");
            } else if (ConnectorConstants.DYNAMIC_RECONFIGURATION_FLAG.equals(name.toLowerCase(locale))) {
                String value = rp.getValue();
                try {
                    conConnPool.setDynamicReconfigWaitTimeout(Long.parseLong(rp.getValue()) * 1000L);
                    logFine(ConnectorConstants.DYNAMIC_RECONFIGURATION_FLAG);
                } catch (NumberFormatException nfe) {
                    _logger.log(Level.WARNING, "Invalid value for " + "'" + ConnectorConstants.DYNAMIC_RECONFIGURATION_FLAG + "' : " + value);
                }
            } else if ("POOLWAITQUEUE".equals(name.toUpperCase(locale))) {
                conConnPool.setPoolWaitQueue(rp.getValue());
                logFine("POOLWAITQUEUE");
            } else if ("DATASTRUCTUREPARAMETERS".equals(name.toUpperCase(locale))) {
                conConnPool.setDataStructureParameters(rp.getValue());
                logFine("DATASTRUCTUREPARAMETERS");
            } else if ("USERNAME".equals(name.toUpperCase(Locale.getDefault())) || "USER".equals(name.toUpperCase(locale))) {
                propList.add(new ConnectorConfigProperty("User", TranslatedConfigView.expandValue(rp.getValue()), "user name", "java.lang.String"));
            } else if ("PASSWORD".equals(name.toUpperCase(locale))) {
                propList.add(new ConnectorConfigProperty("Password", TranslatedConfigView.expandValue(rp.getValue()), "Password", "java.lang.String"));
            } else if ("JDBC30DATASOURCE".equals(name.toUpperCase(locale))) {
                propList.add(new ConnectorConfigProperty("JDBC30DataSource", rp.getValue(), "JDBC30DataSource", "java.lang.String"));
            } else if ("PREFER-VALIDATE-OVER-RECREATE".equals(name.toUpperCase(Locale.getDefault()))) {
                String value = rp.getValue();
                conConnPool.setPreferValidateOverRecreate(toBoolean(value, false));
                logFine("PREFER-VALIDATE-OVER-RECREATE : " + value);
            } else if ("STATEMENT-CACHE-TYPE".equals(name.toUpperCase(Locale.getDefault()))) {
                if (adminPool.getStatementCacheType() != null) {
                    propList.add(new ConnectorConfigProperty("StatementCacheType", rp.getValue(), "StatementCacheType", "java.lang.String"));
                }
            } else if ("NUMBER-OF-TOP-QUERIES-TO-REPORT".equals(name.toUpperCase(Locale.getDefault()))) {
                propList.add(new ConnectorConfigProperty("NumberOfTopQueriesToReport", rp.getValue(), "NumberOfTopQueriesToReport", "java.lang.String"));
            } else if ("TIME-TO-KEEP-QUERIES-IN-MINUTES".equals(name.toUpperCase(Locale.getDefault()))) {
                propList.add(new ConnectorConfigProperty("TimeToKeepQueriesInMinutes", rp.getValue(), "TimeToKeepQueriesInMinutes", "java.lang.String"));
            } else if ("MAXCACHESIZE".equals(name.toUpperCase(Locale.getDefault())) || "MAX-CACHE-SIZE".equals(name.toUpperCase(Locale.getDefault()))) {
                propList.add(new ConnectorConfigProperty("MaxCacheSize", rp.getValue(), "MaxCacheSize", "java.lang.String"));
            } else if (mcfConPropKeys.containsKey(name.toUpperCase(Locale.getDefault()))) {
                propList.add(new ConnectorConfigProperty((String) mcfConPropKeys.get(name.toUpperCase(Locale.getDefault())), rp.getValue() == null ? "" : TranslatedConfigView.expandValue(rp.getValue()), "Some property", "java.lang.String"));
            } else {
                driverProperties = driverProperties + "set" + escape(name) + "#" + escape(TranslatedConfigView.expandValue(rp.getValue())) + "##";
            }
        }
        if (!driverProperties.equals("")) {
            propList.add(new ConnectorConfigProperty("DriverProperties", driverProperties, "some proprietarty properties", "java.lang.String"));
        }
    }
    propList.add(new ConnectorConfigProperty("Delimiter", "#", "delim", "java.lang.String"));
    propList.add(new ConnectorConfigProperty("EscapeCharacter", "\\", "escapeCharacter", "java.lang.String"));
    // create an array of EnvironmentProperties from above list
    ConnectorConfigProperty[] eProps = new ConnectorConfigProperty[propList.size()];
    ListIterator propListIter = propList.listIterator();
    for (int i = 0; propListIter.hasNext(); i++) {
        eProps[i] = (ConnectorConfigProperty) propListIter.next();
    }
    return eProps;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) MissingResourceException(java.util.MissingResourceException) ArrayList(java.util.ArrayList) ListIterator(java.util.ListIterator) ConnectorConfigProperty(com.sun.enterprise.deployment.ConnectorConfigProperty) ListIterator(java.util.ListIterator) Iterator(java.util.Iterator) PoolInfo(org.glassfish.resourcebase.resources.api.PoolInfo) Map(java.util.Map) HashMap(java.util.HashMap) Property(org.jvnet.hk2.config.types.Property) ConnectorConfigProperty(com.sun.enterprise.deployment.ConnectorConfigProperty)

Example 24 with org.jvnet.hk2.config

use of org.jvnet.hk2.config in project Payara by payara.

the class JdbcRecoveryResourceHandler method loadXAResourcesAndItsConnections.

/**
 * {@inheritDoc}
 */
@Override
public void loadXAResourcesAndItsConnections(List xaresList, List connList) {
    // Done so as to initialize connectors-runtime before loading jdbc-resources. need a better way ?
    ConnectorRuntime crt = connectorRuntimeProvider.get();
    Collection<JdbcResource> jdbcResources = getAllJdbcResources();
    if (jdbcResources == null || jdbcResources.size() == 0) {
        if (_logger.isLoggable(Level.FINEST)) {
            _logger.finest("loadXAResourcesAndItsConnections : no resources");
        }
        return;
    }
    List<JdbcConnectionPool> jdbcPools = new ArrayList<JdbcConnectionPool>();
    for (Resource resource : jdbcResources) {
        JdbcResource jdbcResource = (JdbcResource) resource;
        if (getResourcesUtil().isEnabled(jdbcResource)) {
            ResourceInfo resourceInfo = ConnectorsUtil.getResourceInfo(jdbcResource);
            JdbcConnectionPool pool = JdbcResourcesUtil.createInstance().getJdbcConnectionPoolOfResource(resourceInfo);
            if (pool != null && "javax.sql.XADataSource".equals(pool.getResType())) {
                jdbcPools.add(pool);
            }
            if (_logger.isLoggable(Level.FINE)) {
                _logger.fine("JdbcRecoveryResourceHandler:: loadXAResourcesAndItsConnections :: " + "adding : " + (jdbcResource.getPoolName()));
            }
        }
    }
    loadAllJdbcResources();
    // Read from the transaction-service , if the replacement of
    // Vendor XAResource class with our version required.
    // If yes, put the mapping in the xaresourcewrappers properties.
    Properties XAResourceWrappers = new Properties();
    XAResourceWrappers.put("oracle.jdbc.xa.client.OracleXADataSource", "com.sun.enterprise.transaction.jts.recovery.OracleXAResource");
    Config c = habitat.getService(Config.class, ServerEnvironment.DEFAULT_INSTANCE_NAME);
    txService = c.getExtensionByType(TransactionService.class);
    List<Property> properties = txService.getProperty();
    if (properties != null) {
        for (Property property : properties) {
            String name = property.getName();
            String value = property.getValue();
            if (name.equals("oracle-xa-recovery-workaround")) {
                if ("false".equals(value)) {
                    XAResourceWrappers.remove("oracle.jdbc.xa.client.OracleXADataSource");
                }
            } else if (name.equals("sybase-xa-recovery-workaround")) {
                if (value.equals("true")) {
                    XAResourceWrappers.put("com.sybase.jdbc2.jdbc.SybXADataSource", "com.sun.enterprise.transaction.jts.recovery.SybaseXAResource");
                }
            }
        }
    }
    for (JdbcConnectionPool jdbcConnectionPool : jdbcPools) {
        if (jdbcConnectionPool.getResType() == null || jdbcConnectionPool.getName() == null || !jdbcConnectionPool.getResType().equals("javax.sql.XADataSource")) {
            if (_logger.isLoggable(Level.FINEST)) {
                _logger.finest("skipping pool : " + jdbcConnectionPool.getName());
            }
            continue;
        }
        if (_logger.isLoggable(Level.FINEST)) {
            _logger.finest(" using pool : " + jdbcConnectionPool.getName());
        }
        PoolInfo poolInfo = ConnectorsUtil.getPoolInfo(jdbcConnectionPool);
        try {
            String[] dbUserPassword = getdbUserPasswordOfJdbcConnectionPool(jdbcConnectionPool);
            String dbUser = dbUserPassword[0];
            String dbPassword = dbUserPassword[1];
            if (dbPassword == null) {
                dbPassword = "";
                if (_logger.isLoggable(Level.FINEST)) {
                    _logger.log(Level.FINEST, "datasource.xadatasource_nullpassword_error", poolInfo);
                }
            }
            if (dbUser == null) {
                dbUser = "";
                if (_logger.isLoggable(Level.FINEST)) {
                    _logger.log(Level.FINEST, "datasource.xadatasource_nulluser_error", poolInfo);
                }
            }
            ManagedConnectionFactory fac = crt.obtainManagedConnectionFactory(poolInfo);
            Subject subject = new Subject();
            PasswordCredential pc = new PasswordCredential(dbUser, dbPassword.toCharArray());
            pc.setManagedConnectionFactory(fac);
            Principal prin = new ResourcePrincipal(dbUser, dbPassword);
            subject.getPrincipals().add(prin);
            subject.getPrivateCredentials().add(pc);
            ManagedConnection mc = fac.createManagedConnection(subject, null);
            connList.add(mc);
            try {
                XAResource xares = mc.getXAResource();
                if (xares != null) {
                    // See if a wrapper class for the vendor XADataSource is
                    // specified if yes, replace the XAResouce class of database
                    // vendor with our own version
                    String datasourceClassname = jdbcConnectionPool.getDatasourceClassname();
                    String wrapperclass = (String) XAResourceWrappers.get(datasourceClassname);
                    if (wrapperclass != null) {
                        // need to load wrapper class provided by "transactions" module.
                        // Using connector-class-loader so as to get access to "transaction" module.
                        XAResourceWrapper xaresWrapper = null;
                        xaresWrapper = (XAResourceWrapper) crt.getConnectorClassLoader().loadClass(wrapperclass).newInstance();
                        xaresWrapper.init(mc, subject);
                        if (_logger.isLoggable(Level.FINEST)) {
                            _logger.finest("adding resource " + poolInfo + " -- " + xaresWrapper);
                        }
                        xaresList.add(xaresWrapper);
                    } else {
                        if (_logger.isLoggable(Level.FINEST)) {
                            _logger.finest("adding resource " + poolInfo + " -- " + xares);
                        }
                        xaresList.add(xares);
                    }
                }
            } catch (ResourceException ex) {
                _logger.log(Level.WARNING, "datasource.xadatasource_error", poolInfo);
                if (_logger.isLoggable(Level.FINE)) {
                    _logger.log(Level.FINE, "datasource.xadatasource_error_excp", ex);
                }
            // ignored. Not at XA_TRANSACTION level
            }
        } catch (Exception ex) {
            _logger.log(Level.WARNING, "datasource.xadatasource_error", poolInfo);
            if (_logger.isLoggable(Level.FINE)) {
                _logger.log(Level.FINE, "datasource.xadatasource_error_excp", ex);
            }
        }
    }
}
Also used : JdbcResource(org.glassfish.jdbc.config.JdbcResource) Config(com.sun.enterprise.config.serverbeans.Config) ArrayList(java.util.ArrayList) PasswordCredential(javax.resource.spi.security.PasswordCredential) Properties(java.util.Properties) XAResourceWrapper(com.sun.enterprise.transaction.api.XAResourceWrapper) ManagedConnection(javax.resource.spi.ManagedConnection) ResourceException(javax.resource.ResourceException) Property(org.jvnet.hk2.config.types.Property) ResourceInfo(org.glassfish.resourcebase.resources.api.ResourceInfo) JdbcConnectionPool(org.glassfish.jdbc.config.JdbcConnectionPool) TransactionService(com.sun.enterprise.transaction.config.TransactionService) XAResource(javax.transaction.xa.XAResource) Resource(com.sun.enterprise.config.serverbeans.Resource) JdbcResource(org.glassfish.jdbc.config.JdbcResource) ResourcePrincipal(com.sun.enterprise.deployment.ResourcePrincipal) Subject(javax.security.auth.Subject) ResourceException(javax.resource.ResourceException) NamingException(javax.naming.NamingException) ManagedConnectionFactory(javax.resource.spi.ManagedConnectionFactory) XAResource(javax.transaction.xa.XAResource) PoolInfo(org.glassfish.resourcebase.resources.api.PoolInfo) ResourcePrincipal(com.sun.enterprise.deployment.ResourcePrincipal) Principal(java.security.Principal) ConnectorRuntime(com.sun.appserv.connectors.internal.api.ConnectorRuntime)

Example 25 with org.jvnet.hk2.config

use of org.jvnet.hk2.config in project Payara by payara.

the class CreateJMSHost method execute.

/**
 * Executes the command with the command parameters passed as Properties
 * where the keys are the paramter names and the values the parameter values
 *
 * @param context information
 */
public void execute(AdminCommandContext context) {
    final ActionReport report = context.getActionReport();
    Config targetConfig = domain.getConfigNamed(target);
    if (targetConfig != null)
        config = targetConfig;
    Server targetServer = domain.getServerNamed(target);
    // String configRef = targetServer.getConfigRef();
    if (targetServer != null) {
        config = domain.getConfigNamed(targetServer.getConfigRef());
    }
    com.sun.enterprise.config.serverbeans.Cluster cluster = domain.getClusterNamed(target);
    if (cluster != null) {
        config = domain.getConfigNamed(cluster.getConfigRef());
    }
    if (jmsHostName == null) {
        report.setMessage(localStrings.getLocalString("create.jms.host.noJmsHost", "No JMS Host name specified."));
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        return;
    }
    JmsService jmsservice = config.getExtensionByType(JmsService.class);
    // ensure we don't already have one of this name before creating it.
    for (JmsHost jmsHost : jmsservice.getJmsHost()) {
        if (jmsHostName.equals(jmsHost.getName())) {
            if (force) {
                ActionReport deleteReport = report.addSubActionsReport();
                ParameterMap parameters = new ParameterMap();
                parameters.set("DEFAULT", jmsHostName);
                parameters.set("target", target);
                commandRunner.getCommandInvocation("delete-jms-host", deleteReport, context.getSubject()).parameters(parameters).execute();
                if (ActionReport.ExitCode.FAILURE.equals(deleteReport.getActionExitCode())) {
                    report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                    return;
                }
                break;
            } else {
                report.setMessage(localStrings.getLocalString("create.jms.host.duplicate", "A JMS Host named {0} already exists.", jmsHostName));
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                return;
            }
        }
    }
    try {
        ConfigSupport.apply(new SingleConfigCode<JmsService>() {

            public Object run(JmsService param) throws PropertyVetoException, TransactionFailure {
                // TODO: need a way to create a JmsHost instance
                JmsHost jmsHost = param.createChild(JmsHost.class);
                jmsHost.setAdminPassword(mqpassword);
                jmsHost.setAdminUserName(mquser);
                jmsHost.setName(jmsHostName);
                jmsHost.setHost(mqhost);
                jmsHost.setPort(mqport);
                if (props != null) {
                    for (Map.Entry e : props.entrySet()) {
                        Property prop = jmsHost.createChild(Property.class);
                        prop.setName((String) e.getKey());
                        prop.setValue((String) e.getValue());
                        jmsHost.getProperty().add(prop);
                    }
                }
                param.getJmsHost().add(jmsHost);
                return jmsHost;
            }
        }, jmsservice);
    } catch (TransactionFailure tfe) {
        report.setMessage(localStrings.getLocalString("create.jms.host.fail", "Unable to create jms host {0}.", jmsHostName) + " " + tfe.getLocalizedMessage());
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        report.setFailureCause(tfe);
    }
    report.setMessage(localStrings.getLocalString("create.jms.host.success", "Jms Host {0} created.", jmsHostName));
    report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) JmsService(com.sun.enterprise.connectors.jms.config.JmsService) ParameterMap(org.glassfish.api.admin.ParameterMap) ActionReport(org.glassfish.api.ActionReport) com.sun.enterprise.config.serverbeans(com.sun.enterprise.config.serverbeans) PropertyVetoException(java.beans.PropertyVetoException) JmsHost(com.sun.enterprise.connectors.jms.config.JmsHost) Property(org.jvnet.hk2.config.types.Property)

Aggregations

TransactionFailure (org.jvnet.hk2.config.TransactionFailure)100 Config (com.sun.enterprise.config.serverbeans.Config)81 ActionReport (org.glassfish.api.ActionReport)79 PropertyVetoException (java.beans.PropertyVetoException)69 Property (org.jvnet.hk2.config.types.Property)53 Properties (java.util.Properties)24 CommandTarget (org.glassfish.config.support.CommandTarget)24 Target (org.glassfish.internal.api.Target)23 ArrayList (java.util.ArrayList)20 HashMap (java.util.HashMap)16 List (java.util.List)16 NetworkConfig (org.glassfish.grizzly.config.dom.NetworkConfig)16 ConfigBeanProxy (org.jvnet.hk2.config.ConfigBeanProxy)16 NetworkListener (org.glassfish.grizzly.config.dom.NetworkListener)15 Protocol (org.glassfish.grizzly.config.dom.Protocol)15 PropertyChangeEvent (java.beans.PropertyChangeEvent)14 Server (com.sun.enterprise.config.serverbeans.Server)13 IOException (java.io.IOException)12 Protocols (org.glassfish.grizzly.config.dom.Protocols)12 File (java.io.File)10