repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
null | wildfly-main/connector/src/test/java/org/jboss/as/connector/subsystems/jca/JcaSubsystemTestCase.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat Middleware LLC, 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.jca;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.jboss.as.connector.logging.ConnectorLogger;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.model.test.ModelTestControllerVersion;
import org.jboss.as.model.test.SingleClassFilter;
import org.jboss.as.naming.service.NamingService;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.as.subsystem.test.KernelServicesBuilder;
import org.jboss.as.subsystem.test.LegacyKernelServicesInitializer;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
import org.wildfly.clustering.server.service.ClusteringDefaultRequirement;
/**
* @author <a href="[email protected]">Kabir Khan</a>
* @author <a href="[email protected]>Stefano Maestri</a>
*/
public class JcaSubsystemTestCase extends AbstractSubsystemBaseTest {
public JcaSubsystemTestCase() {
super(JcaExtension.SUBSYSTEM_NAME, new JcaExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource("jca.xml");
}
@Override
protected String getSubsystemXsdPath() throws Exception {
return "schema/wildfly-jca_6_0.xsd";
}
@Override
protected AdditionalInitialization createAdditionalInitialization() {
return AdditionalInitialization.withCapabilities(
ClusteringDefaultRequirement.COMMAND_DISPATCHER_FACTORY.getName(),
ConnectorServices.LOCAL_TRANSACTION_PROVIDER_CAPABILITY,
ConnectorServices.TRANSACTION_XA_RESOURCE_RECOVERY_REGISTRY_CAPABILITY,
ConnectorServices.TRANSACTION_SYNCHRONIZATION_REGISTRY_CAPABILITY,
NamingService.CAPABILITY_NAME,
"org.wildfly.threads.thread-factory.string");
}
@Test
public void testFullConfig() throws Exception {
standardSubsystemTest("jca-full.xml");
}
@Test
public void testExpressionConfig() throws Exception {
standardSubsystemTest("jca-full-expression.xml", "jca-full.xml");
}
/** WFLY-2640 and WFLY-8141 */
@Test
public void testCCMHandling() throws Exception {
String xml = readResource("jca-minimal.xml");
final KernelServices services = createKernelServicesBuilder(createAdditionalInitialization()).setSubsystemXml(xml).build();
assertTrue("Subsystem boot failed!", services.isSuccessfulBoot());
//Get the model and the persisted xml from the first controller
final ModelNode model = services.readWholeModel();
// ccm is present despite not being in xml
ModelNode ccm = model.get("subsystem", "jca", "cached-connection-manager", "cached-connection-manager");
assertTrue(ccm.isDefined());
assertTrue(ccm.hasDefined("install")); // only true because readWholeModel reads defaults
// Because it exists we can do a write-attribute
PathAddress ccmAddress = PathAddress.pathAddress("subsystem", "jca").append("cached-connection-manager", "cached-connection-manager");
ModelNode writeOp = Util.getWriteAttributeOperation(ccmAddress, "install", true);
services.executeForResult(writeOp);
ModelNode readOp = Util.getReadAttributeOperation(ccmAddress, "install");
ModelNode result = services.executeForResult(readOp);
assertTrue(result.asBoolean());
ModelNode removeOp = Util.createRemoveOperation(ccmAddress);
services.executeForResult(removeOp);
// Read still works despite removal, but now the attributes are back to defaults
result = services.executeForResult(readOp);
assertFalse(result.asBoolean());
// Write attribute works despite removal
services.executeForResult(writeOp);
ModelNode addOp = Util.createAddOperation(ccmAddress);
addOp.get("debug").set(true);
services.executeForFailure(addOp); // already exists, with install=true
// Reset to default state and now we can add
ModelNode undefineOp = Util.createEmptyOperation("undefine-attribute", ccmAddress);
undefineOp.get("name").set("install");
services.executeForResult(undefineOp);
result = services.executeForResult(readOp);
assertFalse(result.asBoolean());
// Now add works
services.executeForResult(addOp);
ModelNode readOp2 = Util.getReadAttributeOperation(ccmAddress, "debug");
result = services.executeForResult(readOp2);
assertTrue(result.asBoolean());
// Cant' add again
services.executeForFailure(addOp);
// Remove and re-add
services.executeForResult(removeOp);
result = services.executeForResult(readOp2);
assertFalse(result.asBoolean());
services.executeForResult(addOp);
result = services.executeForResult(readOp2);
assertTrue(result.asBoolean());
}
/** WFLY-11104 */
@Test
public void testMultipleWorkManagers() throws Exception {
String xml = readResource("jca-minimal.xml");
final KernelServices services = createKernelServicesBuilder(createAdditionalInitialization()).setSubsystemXml(xml).build();
assertTrue("Subsystem boot failed!", services.isSuccessfulBoot());
//Get the model and the persisted xml from the first controller
final ModelNode model = services.readWholeModel();
PathAddress subystem = PathAddress.pathAddress("subsystem", "jca");
PathAddress dwm1 = subystem.append("distributed-workmanager", "dwm1");
PathAddress threads1 = dwm1.append("short-running-threads","dwm1");
PathAddress dwm2 = subystem.append("distributed-workmanager", "dwm2");
PathAddress threads2 = dwm2.append("short-running-threads","dwm2");
ModelNode composite = Util.createEmptyOperation("composite", PathAddress.EMPTY_ADDRESS);
ModelNode steps = composite.get("steps");
ModelNode addDwm1 = Util.createAddOperation(dwm1);
addDwm1.get("name").set("dwm1");
steps.add(addDwm1);
ModelNode addThreads1 = Util.createAddOperation(threads1);
addThreads1.get("max-threads").set(11);
addThreads1.get("queue-length").set(22);
steps.add(addThreads1);
ModelNode addDwm2 = Util.createAddOperation(dwm2);
addDwm2.get("name").set("dwm2");
steps.add(addDwm2);
ModelNode addThreads2 = Util.createAddOperation(threads2);
addThreads2.get("max-threads").set(11);
addThreads2.get("queue-length").set(22);
steps.add(addThreads2);
services.executeForResult(composite);
}
/** WFLY-16478. Test transformation of undefined elytron-enabled */
@Test
public void testEAP74Transformation() throws Exception {
ModelTestControllerVersion eap74ControllerVersion = ModelTestControllerVersion.EAP_7_4_0;
ModelVersion eap74ModelVersion = ModelVersion.create(5, 0, 0);
KernelServicesBuilder builder = createKernelServicesBuilder(createAdditionalInitialization())
.setSubsystemXmlResource("jca-default-elytron.xml");
KernelServices mainServices = initialKernelServices(builder, eap74ControllerVersion, eap74ModelVersion);
ModelNode legacyModel = checkSubsystemModelTransformation(mainServices, eap74ModelVersion);
assertTrue(legacyModel.toString(), legacyModel.get("subsystem", "jca", "workmanager", "default", "elytron-enabled").asBoolean(false));
assertTrue(legacyModel.toString(), legacyModel.get("subsystem", "jca", "workmanager", "anotherWm", "elytron-enabled").asBoolean(false));
assertTrue(legacyModel.toString(), legacyModel.get("subsystem", "jca", "distributed-workmanager", "MyDWM", "elytron-enabled").asBoolean(false));
mainServices.shutdown();
}
/** WFLY-16478 Test legacy parser sets old default value for elytron-enabled */
@Test
public void testLegacyDefaultElytronEnabled() throws Exception {
Set<ModelNode> required = new HashSet<>();
PathAddress subsystem = PathAddress.pathAddress("subsystem", "jca");
required.add(subsystem.append("workmanager", "default").toModelNode());
required.add(subsystem.append("workmanager", "anotherWm").toModelNode());
required.add(subsystem.append("distributed-workmanager", "MyDWM").toModelNode());
for (ModelNode op : parse(getSubsystemXml("jca_5_0.xml"))) {
if (ADD.equals(op.get(OP).asString()) && required.remove(op.get(ModelDescriptionConstants.OP_ADDR))) {
assertFalse(op.toString() + "\n did not correctly define elytron-enabled", op.get("elytron-enabled").asBoolean(true));
}
}
assertTrue("Not all expected ops were found\n" + required.toString(), required.isEmpty());
}
@Override
protected void compareXml(String configId, String original, String marshalled) throws Exception {
super.compareXml(configId, original, marshalled, true);
}
private KernelServices initialKernelServices(KernelServicesBuilder builder, ModelTestControllerVersion controllerVersion, final ModelVersion modelVersion) throws Exception {
LegacyKernelServicesInitializer initializer = builder.createLegacyKernelServicesBuilder(createAdditionalInitialization(), controllerVersion, modelVersion);
String mavenGroupId = controllerVersion.getMavenGroupId();
String artifactId = "wildfly-connector";
initializer.addMavenResourceURL(mavenGroupId + ":" + artifactId + ":" + controllerVersion.getMavenGavVersion())
.addMavenResourceURL(mavenGroupId + ":wildfly-clustering-api:" + controllerVersion.getMavenGavVersion())
.addMavenResourceURL(mavenGroupId + ":wildfly-clustering-spi:" + controllerVersion.getMavenGavVersion())
.addMavenResourceURL("org.wildfly.core:wildfly-threads:" + controllerVersion.getCoreVersion())
.setExtensionClassName("org.jboss.as.connector.subsystems.jca.JcaExtension")
.excludeFromParent(SingleClassFilter.createFilter(ConnectorLogger.class));
KernelServices mainServices = builder.build();
Assert.assertTrue(mainServices.isSuccessfulBoot());
KernelServices legacyServices = mainServices.getLegacyServices(modelVersion);
Assert.assertTrue(legacyServices.isSuccessfulBoot());
Assert.assertNotNull(legacyServices);
return mainServices;
}
}
| 12,131 | 46.76378 | 177 | java |
null | wildfly-main/connector/src/test/java/org/jboss/as/connector/subsystems/datasources/DatasourcesSubsystemTestCase.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat Middleware LLC, 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.subsystems.datasources.Constants.EXCEPTION_SORTER_MODULE;
import static org.jboss.as.connector.subsystems.datasources.Constants.STALE_CONNECTION_CHECKER_MODULE;
import static org.jboss.as.connector.subsystems.datasources.Constants.VALID_CONNECTION_CHECKER_MODULE;
import java.io.IOException;
import java.util.List;
import org.jboss.as.connector._private.Capabilities;
import org.jboss.as.connector.logging.ConnectorLogger;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.security.CredentialReference;
import org.jboss.as.model.test.FailedOperationTransformationConfig;
import org.jboss.as.model.test.ModelTestControllerVersion;
import org.jboss.as.model.test.ModelTestUtils;
import org.jboss.as.model.test.SingleClassFilter;
import org.jboss.as.naming.service.NamingService;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.as.subsystem.test.KernelServicesBuilder;
import org.jboss.as.subsystem.test.LegacyKernelServicesInitializer;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
/**
* @author <a href="[email protected]">Kabir Khan</a>
* @author <a href="[email protected]>Stefano Maestri</a>
*/
public class DatasourcesSubsystemTestCase extends AbstractSubsystemBaseTest {
public DatasourcesSubsystemTestCase() {
super(DataSourcesExtension.SUBSYSTEM_NAME, new DataSourcesExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
//test configuration put in standalone.xml
return readResource("datasources-minimal.xml");
}
@Override
protected String getSubsystemXsdPath() throws Exception {
return "schema/wildfly-datasources_7_0.xsd";
}
@Test
public void testFullConfig() throws Exception {
standardSubsystemTest("datasources-full.xml");
}
@Test
public void testElytronConfig() throws Exception {
standardSubsystemTest("datasources-elytron-enabled.xml");
}
@Test
public void testExpressionConfig() throws Exception {
standardSubsystemTest("datasources-full-expression.xml", "datasources-full.xml");
}
@Test
public void testElytronExpressionConfig() throws Exception {
standardSubsystemTest("datasources-elytron-enabled-expression.xml", "datasources-elytron-enabled.xml");
}
@Test
public void testRejectionsEAP74() throws Exception {
testTransformerEAP74Rejection("datasources-validation-custom-modules-reject.xml");
}
protected AdditionalInitialization createAdditionalInitialization() {
// Create a AdditionalInitialization.MANAGEMENT variant that has all the external
// capabilities used by the various configs used in this test class
return AdditionalInitialization.MANAGEMENT.withCapabilities(
Capabilities.AUTHENTICATION_CONTEXT_CAPABILITY + ".DsAuthCtxt",
Capabilities.AUTHENTICATION_CONTEXT_CAPABILITY + ".CredentialAuthCtxt",
CredentialReference.CREDENTIAL_STORE_CAPABILITY + ".test-store",
NamingService.CAPABILITY_NAME,
ConnectorServices.TRANSACTION_INTEGRATION_CAPABILITY_NAME
);
}
private void testTransformerEAP74Rejection(String subsystemXml) throws Exception {
ModelTestControllerVersion eap74ControllerVersion = ModelTestControllerVersion.EAP_7_4_0;
ModelVersion eap74ModelVersion = ModelVersion.create(6, 0, 0);
KernelServicesBuilder builder = createKernelServicesBuilder(createAdditionalInitialization());
KernelServices mainServices = initialKernelServices(builder, eap74ControllerVersion, eap74ModelVersion);
List<ModelNode> ops = builder.parseXmlResource(subsystemXml);
PathAddress subsystemAddress = PathAddress.pathAddress(DataSourcesSubsystemRootDefinition.PATH_SUBSYSTEM);
ModelTestUtils.checkFailedTransformedBootOperations(mainServices, eap74ModelVersion, ops, new FailedOperationTransformationConfig()
.addFailedAttribute(subsystemAddress.append(DataSourceDefinition.PATH_DATASOURCE),
new FailedOperationTransformationConfig.NewAttributesConfig(
EXCEPTION_SORTER_MODULE,
VALID_CONNECTION_CHECKER_MODULE,
STALE_CONNECTION_CHECKER_MODULE))
.addFailedAttribute(subsystemAddress.append(XaDataSourceDefinition.PATH_XA_DATASOURCE),
new FailedOperationTransformationConfig.NewAttributesConfig(
EXCEPTION_SORTER_MODULE,
VALID_CONNECTION_CHECKER_MODULE,
STALE_CONNECTION_CHECKER_MODULE))
);
}
private KernelServices initialKernelServices(KernelServicesBuilder builder, ModelTestControllerVersion controllerVersion, final ModelVersion modelVersion) throws Exception {
LegacyKernelServicesInitializer initializer = builder.createLegacyKernelServicesBuilder(createAdditionalInitialization(), controllerVersion, modelVersion);
String mavenGroupId = controllerVersion.getMavenGroupId();
String artifactId = "wildfly-connector";
if (controllerVersion.isEap() && controllerVersion.getMavenGavVersion().equals(controllerVersion.getCoreVersion())) { // EAP 6
artifactId = "jboss-as-connector";
}
initializer.addMavenResourceURL(mavenGroupId + ":" + artifactId + ":" + controllerVersion.getMavenGavVersion());
initializer.addMavenResourceURL("org.jboss.ironjacamar:ironjacamar-spec-api:1.0.28.Final")
.addMavenResourceURL("org.jboss.ironjacamar:ironjacamar-common-api:1.0.28.Final")
.setExtensionClassName("org.jboss.as.connector.subsystems.datasources.DataSourcesExtension")
.excludeFromParent(SingleClassFilter.createFilter(ConnectorLogger.class));
KernelServices mainServices = builder.build();
Assert.assertTrue(mainServices.isSuccessfulBoot());
KernelServices legacyServices = mainServices.getLegacyServices(modelVersion);
Assert.assertTrue(legacyServices.isSuccessfulBoot());
Assert.assertNotNull(legacyServices);
return mainServices;
}
}
| 7,628 | 48.538961 | 177 | java |
null | wildfly-main/connector/src/test/java/org/jboss/as/connector/subsystems/resourceadapters/ResourceAdaptersSubsystemTestCase.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat Middleware LLC, 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.resourceadapters;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.naming.service.NamingService;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
/**
* @author <a href="[email protected]">Kabir Khan</a>
*/
public class ResourceAdaptersSubsystemTestCase extends AbstractSubsystemBaseTest {
public ResourceAdaptersSubsystemTestCase() {
// FIXME ResourceAdaptersSubsystemTestCase constructor
super(ResourceAdaptersExtension.SUBSYSTEM_NAME, new ResourceAdaptersExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource("resource-adapters-full.xml");
}
@Override
protected String getSubsystemXsdPath() throws Exception {
return "schema/wildfly-resource-adapters_7_0.xsd";
}
@Override
protected Properties getResolvedProperties() {
Properties properties = new Properties();
properties.put("genericjms.cf.jndi-name", "genericjms");
properties.put("genericjms.cf.pool-name", "mypool");
properties.put("genericjms.cf.jndi.contextfactory", "foo");
properties.put("genericjms.cf.jndi.url", "bar");
properties.put("genericjms.cf.jndi.lookup", "baz");
return properties;
}
@Test
public void testFullConfig() throws Exception {
standardSubsystemTest("resource-adapters-pool.xml", null, true);
}
@Test
public void testFullConfigXa() throws Exception {
standardSubsystemTest("resource-adapters-xapool.xml", null, true);
}
@Test
public void testExpressionConfig() throws Exception {
standardSubsystemTest("resource-adapters-pool-expression.xml", "resource-adapters-pool.xml", true);
}
@Test
public void testExpressionConfigXa() throws Exception {
standardSubsystemTest("resource-adapters-xapool-expression.xml", "resource-adapters-xapool.xml", true);
}
@Test
public void testExpressionConfigElytron() throws Exception {
standardSubsystemTest("resource-adapters-pool-elytron-enabled.xml", "resource-adapters-pool-elytron-enabled-expression.xml", true);
}
protected AdditionalInitialization createAdditionalInitialization() {
return AdditionalInitialization.MANAGEMENT
.withCapabilities(ConnectorServices.TRANSACTION_INTEGRATION_CAPABILITY_NAME,
NamingService.CAPABILITY_NAME);
}
//TODO: remove this special method as soon as RA will have a unique name in DMR marshalled in xml
protected KernelServices standardSubsystemTest(final String configId, final String configIdResolvedModel, boolean compareXml) throws Exception {
final AdditionalInitialization additionalInit = createAdditionalInitialization();
// Parse the subsystem xml and install into the first controller
final String subsystemXml = configId == null ? getSubsystemXml() : getSubsystemXml(configId);
final KernelServices servicesA = super.createKernelServicesBuilder(additionalInit).setSubsystemXml(subsystemXml).build();
Assert.assertTrue("Subsystem boot failed!", servicesA.isSuccessfulBoot());
//Get the model and the persisted xml from the first controller
final ModelNode modelA = servicesA.readWholeModel();
validateModel(modelA);
// Test marshaling
final String marshalled = servicesA.getPersistedSubsystemXml();
servicesA.shutdown();
// validate the the normalized xmls
String normalizedSubsystem = normalizeXML(subsystemXml);
if (compareXml) {
compareXml(configId, normalizedSubsystem, normalizeXML(marshalled));
}
//Install the persisted xml from the first controller into a second controller
final KernelServices servicesB = super.createKernelServicesBuilder(additionalInit).setSubsystemXml(marshalled).build();
final ModelNode modelB = servicesB.readWholeModel();
//WE CANT DO THAT FOR RA BECAUSE THEIR NAME IS GENERATED ON THE FLY W/ archive/module concatenated to a counter.
//IT'S AN ISSUE WM_SECURITY_MAPPING_TO BE FIXED IN SUBSYSTEM
//Make sure the models from the two controllers are identical
//compare(modelA, modelB);
// Test the describe operation
final ModelNode operation = createDescribeOperation();
final ModelNode result = servicesB.executeOperation(operation);
Assert.assertTrue("the subsystem describe operation has to generate a list of operations to recreate the subsystem",
!result.hasDefined(ModelDescriptionConstants.FAILURE_DESCRIPTION));
final List<ModelNode> operations = result.get(ModelDescriptionConstants.RESULT).asList();
servicesB.shutdown();
final KernelServices servicesC = super.createKernelServicesBuilder(additionalInit).setBootOperations(operations).build();
final ModelNode modelC = servicesC.readWholeModel();
compare(modelB, modelC);
assertRemoveSubsystemResources(servicesC, getIgnoredChildResourcesForRemovalTest());
if (configIdResolvedModel != null) {
final String subsystemResolvedXml = getSubsystemXml(configIdResolvedModel);
final KernelServices servicesD = super.createKernelServicesBuilder(additionalInit).setSubsystemXml(subsystemResolvedXml).build();
Assert.assertTrue("Subsystem w/ reolved xml boot failed!", servicesD.isSuccessfulBoot());
final ModelNode modelD = servicesD.readWholeModel();
validateModel(modelD);
resolveandCompareModel(modelA, modelD);
}
return servicesA;
}
}
| 7,084 | 42.20122 | 148 | java |
null | wildfly-main/connector/src/test/java/org/jboss/as/connector/subsystems/resourceadapters/ResourceAdaptersTransformersTestCase.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2023, 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.resourceadapters;
import org.jboss.as.connector.logging.ConnectorLogger;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.model.test.FailedOperationTransformationConfig;
import org.jboss.as.model.test.ModelTestControllerVersion;
import org.jboss.as.model.test.ModelTestUtils;
import org.jboss.as.model.test.SingleClassFilter;
import org.jboss.as.naming.service.NamingService;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.as.subsystem.test.KernelServicesBuilder;
import org.jboss.as.subsystem.test.LegacyKernelServicesInitializer;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.RESOURCEADAPTER_NAME;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.WM_SECURITY;
import static org.jboss.as.connector.subsystems.resourceadapters.ResourceAdaptersExtension.SUBSYSTEM_PATH;
import static org.jboss.as.connector.subsystems.resourceadapters.ResourceAdaptersExtension.VERSION_6_0_0;
import static org.jboss.as.connector.subsystems.resourceadapters.ResourceAdaptersExtension.VERSION_6_1_0;
/**
* Class for testing the {@link ResourceAdaptersTransformers}.
*
* @author <a href="[email protected]">Petr Beran</a>
*/
public class ResourceAdaptersTransformersTestCase extends AbstractSubsystemBaseTest {
public ResourceAdaptersTransformersTestCase() {
super(ResourceAdaptersExtension.SUBSYSTEM_NAME, new ResourceAdaptersExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource("resource-adapters-transform_7_0.xml");
}
@Override
protected String getSubsystemXsdPath() {
return "schema/wildfly-resource-adapters_7_0.xsd";
}
/**
* Simple switch for returning the proper resource adapters subsystem version based on the EAP version.
*
* @param controllerVersion the EAP version based on which the subsystem version is decided.
* @return resource adapters subsystem version that specified EAP uses.
*/
private static ModelVersion getResourceAdapterModel(ModelTestControllerVersion controllerVersion) {
switch (controllerVersion) {
case EAP_7_4_0:
return VERSION_6_0_0; // EAP 7.4.0. uses the 6.0 version of resource adapters subsystem
default:
throw new IllegalArgumentException("Unsupported EAP version");
}
}
/**
* Test method for 7.0.0 to 6.0.0 resource adapters subsystem transformers for valid and rejecting configuration.
*
* @throws Exception if an error occurs during the kernel initialization or the subsystem transformation validation.
*/
@Test
public void test740transformers() throws Exception {
testTransformer(ModelTestControllerVersion.EAP_7_4_0);
testTransformerReject(ModelTestControllerVersion.EAP_7_4_0);
}
/**
* Tests valid transformation of resource adapters subsystem from 7.0.0 to 6.0.0
*
* @param controllerVersion version of the EAP running on the older resource adapters subsystem.
* @throws Exception if an error occurs during the kernel initialization or the subsystem transformation validation.
*/
private void testTransformer(final ModelTestControllerVersion controllerVersion) throws Exception {
String subsystemXml = "resource-adapters-transform_7_0.xml";
ModelVersion modelVersion = getResourceAdapterModel(controllerVersion);
KernelServicesBuilder builder = createKernelServicesBuilder(createAdditionalInitialization()).setSubsystemXmlResource(subsystemXml);
KernelServices mainServices = initialKernelServices(builder, controllerVersion);
KernelServices legacyServices = mainServices.getLegacyServices(modelVersion);
Assert.assertNotNull(legacyServices);
Assert.assertTrue(legacyServices.isSuccessfulBoot());
checkSubsystemModelTransformation(mainServices, modelVersion);
}
/**
* Tests valid transformation of resource adapters subsystem from 7.0.0 to 6.0.0
*
* @param controllerVersion version of the EAP running on the older resource adapters subsystem.
* @throws Exception if an error occurs during the kernel initialization or the subsystem transformation validation.
*/
private void testTransformerReject(final ModelTestControllerVersion controllerVersion) throws Exception {
// subsystemXml contains expression not understand by 6.0.0 version of the subsystem
String subsystemXml = "resource-adapters-transform-reject_7_0.xml";
ModelVersion modelVersion = getResourceAdapterModel(controllerVersion);
KernelServicesBuilder builder = createKernelServicesBuilder(createAdditionalInitialization());
KernelServices mainServices = initialKernelServices(builder, controllerVersion);
// the legacyServices are not able to boot successfully due to the rejected attribute in subsystemXml
KernelServices legacyServices = mainServices.getLegacyServices(modelVersion);
Assert.assertNotNull(legacyServices);
// Setting the subsystem based on the subsystemXml configuration
List<ModelNode> subsystem = builder.parseXmlResource(subsystemXml);
PathAddress subsystemAddress = PathAddress.pathAddress(SUBSYSTEM_PATH);
FailedOperationTransformationConfig config = new FailedOperationTransformationConfig();
// In case of resource adapters subsystem 6.0.0 or 6.1.0 the configuration should be rejected because
// the WM_SECURITY contains unsupported expression.
if (modelVersion.equals(VERSION_6_0_0) || modelVersion.equals(VERSION_6_1_0)) {
config.addFailedAttribute(subsystemAddress.append(RESOURCEADAPTER_NAME),
new FailedOperationTransformationConfig.NewAttributesConfig(WM_SECURITY));
}
ModelTestUtils.checkFailedTransformedBootOperations(mainServices, modelVersion, subsystem, config);
}
/**
* Builds the service container containing necessary capabilities and dependencies needed to run the tests.
*
* @param builder builder object for initializing the kernel services.
* @param controllerVersion version of EAP containing the old version of the subsystem.
* @return built kernel services based on the EAP version supplied.
* @throws Exception if it's not possible to add specified Maven dependencies.
*/
private KernelServices initialKernelServices(KernelServicesBuilder builder, ModelTestControllerVersion controllerVersion) throws Exception {
String mavenGroupId = controllerVersion.getMavenGroupId();
ModelVersion modelVersion = getResourceAdapterModel(controllerVersion);
String artifactId = "wildfly-connector";
LegacyKernelServicesInitializer initializer = builder.createLegacyKernelServicesBuilder(createAdditionalInitialization(), controllerVersion, modelVersion);
initializer.addMavenResourceURL(mavenGroupId + ":" + artifactId + ":" + controllerVersion.getMavenGavVersion()) // Adds the resource adapter subsystem package
.addMavenResourceURL("org.jboss.spec.javax.resource:jboss-connector-api_1.7_spec:2.0.0.Final-redhat-00001") // The 6.0.0 subsystem on EAP 7.4.0 uses the javax prefix
.setExtensionClassName("org.jboss.as.connector.subsystems.resourceadapters.ResourceAdaptersExtension") // Adds the transformer registration
.skipReverseControllerCheck()
.dontPersistXml()
.excludeFromParent(SingleClassFilter.createFilter(ConnectorLogger.class));
KernelServices mainServices = builder.build();
Assert.assertTrue(mainServices.isSuccessfulBoot());
return mainServices;
}
/**
* Provides additional capabilities for the model controller.
*
* @return additional capabilities for the model controller.
*/
protected AdditionalInitialization createAdditionalInitialization() {
// Adds additional capabilities, both TRANSACTION_INTEGRATION_CAPABILITY_NAME and CAPABILITY_NAME
// are needed for the testTransformerReject method.
return AdditionalInitialization.withCapabilities
(ConnectorServices.TRANSACTION_INTEGRATION_CAPABILITY_NAME,
NamingService.CAPABILITY_NAME);
}
}
| 9,773 | 50.172775 | 181 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/ConnectorServices.java | /*
* 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;
/**
* ConnectorServices contains some utility methods used internally and
* constants for all connector's subsystems service names.
* This class is @Deprecated us org.jboss.as.connector.util.ConnectorServices instead
*
* @author Stefano Maestri (c) 2011 Red Hat Inc.
*/
@Deprecated
public class ConnectorServices extends org.jboss.as.connector.util.ConnectorServices {
}
| 1,435 | 38.888889 | 86 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/security/ElytronSecurityContext.java | /*
* Copyright 2017 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.connector.security;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.HashSet;
import java.util.Set;
import javax.security.auth.Subject;
import org.jboss.jca.core.spi.security.SecurityContext;
import org.wildfly.security.auth.server.SecurityIdentity;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* An Elytron based {@link SecurityContext} implementation.
*
* @author Flavia Rainone
* @author <a href="mailto:[email protected]">Stefan Guilhen</a>
*/
public class ElytronSecurityContext implements SecurityContext {
private Subject authenticatedSubject;
@Override
public Subject getAuthenticatedSubject() {
return this.authenticatedSubject;
}
@Override
public void setAuthenticatedSubject(final Subject subject) {
this.authenticatedSubject = subject;
}
@Override
public String[] getRoles() {
if (this.authenticatedSubject != null) {
// check if the authenticated subject contains a SecurityIdentity in its private credentials.
Set<SecurityIdentity> authenticatedIdentities = this.getPrivateCredentials(SecurityIdentity.class);
// iterate through the identities adding all the roles found.
final Set<String> rolesSet = new HashSet<>();
for (SecurityIdentity identity : authenticatedIdentities) {
for (String role : identity.getRoles(ElytronSecurityIntegration.SECURITY_IDENTITY_ROLE)) {
rolesSet.add(role);
}
}
return rolesSet.toArray(new String[rolesSet.size()]);
}
return new String[0];
}
/**
* Runs the work contained in {@param runnable} as an authenticated Identity.
*
* @param work executes the work
*/
public void runWork(Runnable work) {
// if we have an authenticated subject we check if it contains a security identity and use the identity to run the work.
if (this.authenticatedSubject != null) {
Set<SecurityIdentity> authenticatedIdentities = this.getPrivateCredentials(SecurityIdentity.class);
if (!authenticatedIdentities.isEmpty()) {
SecurityIdentity identity = authenticatedIdentities.iterator().next();
identity.runAs(work);
return;
}
}
// no authenticated subject found or the subject didn't have a security identity - just run the work.
work.run();
}
protected<T> Set<T> getPrivateCredentials(Class<T> credentialClass) {
if (!WildFlySecurityManager.isChecking()) {
return this.authenticatedSubject.getPrivateCredentials(credentialClass);
} else {
return AccessController.doPrivileged((PrivilegedAction<Set<T>>) () -> this.authenticatedSubject.getPrivateCredentials(credentialClass));
}
}
}
| 3,533 | 36.595745 | 148 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/security/ElytronSubjectFactory.java | /*
* Copyright 2017 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.connector.security;
import org.ietf.jgss.GSSName;
import org.jboss.as.connector._private.Capabilities;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.server.CurrentServiceContainer;
import org.jboss.jca.core.spi.security.SubjectFactory;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceName;
import org.wildfly.security.auth.callback.CredentialCallback;
import org.wildfly.security.auth.client.AuthenticationConfiguration;
import org.wildfly.security.auth.client.AuthenticationContext;
import org.wildfly.security.auth.client.AuthenticationContextConfigurationClient;
import org.wildfly.security.auth.principal.NamePrincipal;
import org.wildfly.security.credential.GSSKerberosCredential;
import org.wildfly.security.manager.WildFlySecurityManager;
import jakarta.resource.spi.security.PasswordCredential;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.kerberos.KerberosPrincipal;
import static org.jboss.as.connector.logging.ConnectorLogger.ROOT_LOGGER;
import java.net.URI;
import java.security.AccessController;
import java.security.PrivilegedAction;
/**
* An Elytron based {@link SubjectFactory} implementation. It uses an {@link AuthenticationContext} to select a configuration
* that matches the resource {@link URI} to obtain the username and password pair that will be inserted into the constructed
* {@link Subject} instance.
*
* @author Flavia Rainone
* @author <a href="mailto:[email protected]">Stefan Guilhen</a>
*/
public class ElytronSubjectFactory implements SubjectFactory, Capabilities {
private static final RuntimeCapability<Void> AUTHENTICATION_CONTEXT_RUNTIME_CAPABILITY = RuntimeCapability
.Builder.of(AUTHENTICATION_CONTEXT_CAPABILITY, true, AuthenticationContext.class)
.build();
private static final AuthenticationContextConfigurationClient AUTH_CONFIG_CLIENT =
AccessController.doPrivileged(AuthenticationContextConfigurationClient.ACTION);
private final AuthenticationContext authenticationContext;
private URI targetURI;
/**
* Constructor
*/
public ElytronSubjectFactory() {
this(null, null);
}
/**
* Constructor.
*
* @param targetURI the {@link URI} of the target.
*/
public ElytronSubjectFactory(final AuthenticationContext authenticationContext, final URI targetURI) {
this.authenticationContext = authenticationContext;
this.targetURI = targetURI;
}
/**
* {@inheritDoc}
*/
public Subject createSubject() {
// If a authenticationContext was defined on the subsystem use that context, otherwise use capture the current
// configuration.
final Subject subject = this.createSubject(getAuthenticationContext());
if (ROOT_LOGGER.isTraceEnabled()) {
ROOT_LOGGER.subject(subject, Integer.toHexString(System.identityHashCode(subject)));
}
return subject;
}
/**
* {@inheritDoc}
*/
public Subject createSubject(final String authenticationContextName) {
AuthenticationContext context;
if (authenticationContextName != null && !authenticationContextName.isEmpty()) {
final ServiceContainer container = this.currentServiceContainer();
final ServiceName authContextServiceName = AUTHENTICATION_CONTEXT_RUNTIME_CAPABILITY.getCapabilityServiceName(authenticationContextName);
context = (AuthenticationContext) container.getRequiredService(authContextServiceName).getValue();
}
else {
context = getAuthenticationContext();
}
final Subject subject = this.createSubject(context);
if (ROOT_LOGGER.isTraceEnabled()) {
ROOT_LOGGER.subject(subject, Integer.toHexString(System.identityHashCode(subject)));
}
return subject;
}
/**
* Create a {@link Subject} with the principal and password credential obtained from the authentication configuration
* that matches the target {@link URI}.
*
* @param authenticationContext the {@link AuthenticationContext} used to select a configuration that matches the
* target {@link URI}.
* @return the constructed {@link Subject}. It contains a single principal and a {@link PasswordCredential}.
*/
private Subject createSubject(final AuthenticationContext authenticationContext) {
final AuthenticationConfiguration configuration = AUTH_CONFIG_CLIENT.getAuthenticationConfiguration(this.targetURI, authenticationContext);
final CallbackHandler handler = AUTH_CONFIG_CLIENT.getCallbackHandler(configuration);
final NameCallback nameCallback = new NameCallback("Username: ");
final PasswordCallback passwordCallback = new PasswordCallback("Password: ", false);
final CredentialCallback credentialCallback = new CredentialCallback(GSSKerberosCredential.class);
try {
handler.handle(new Callback[]{nameCallback, passwordCallback, credentialCallback});
Subject subject = new Subject();
// if a GSSKerberosCredential was found, add the enclosed GSSCredential and KerberosTicket to the private set in the Subject.
if (credentialCallback.getCredential() != null) {
GSSKerberosCredential kerberosCredential = GSSKerberosCredential.class.cast(credentialCallback.getCredential());
this.addPrivateCredential(subject, kerberosCredential.getKerberosTicket());
this.addPrivateCredential(subject, kerberosCredential.getGssCredential());
// use the GSSName to build a kerberos principal and set it in the Subject.
GSSName gssName = kerberosCredential.getGssCredential().getName();
subject.getPrincipals().add(new KerberosPrincipal(gssName.toString()));
}
// use the name from the callback, if available, to build a principal and set it in the Subject.
if (nameCallback.getName() != null) {
subject.getPrincipals().add(new NamePrincipal(nameCallback.getName()));
}
// use the password from the callback, if available, to build a credential and set it as a private credential in the Subject.
if (passwordCallback.getPassword() != null) {
this.addPrivateCredential(subject, new PasswordCredential(nameCallback.getName(), passwordCallback.getPassword()));
}
return subject;
} catch(Exception e) {
throw new SecurityException(e);
}
}
/**
* Get a reference to the current {@link ServiceContainer}.
*
* @return a reference to the current {@link ServiceContainer}.
*/
private ServiceContainer currentServiceContainer() {
if(WildFlySecurityManager.isChecking()) {
return AccessController.doPrivileged(CurrentServiceContainer.GET_ACTION);
}
return CurrentServiceContainer.getServiceContainer();
}
/**
* Add the specified credential to the subject's private credentials set.
*
* @param subject the {@link Subject} to add the credential to.
* @param credential a reference to the credential.
*/
private void addPrivateCredential(final Subject subject, final Object credential) {
if (!WildFlySecurityManager.isChecking()) {
subject.getPrivateCredentials().add(credential);
}
else {
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
subject.getPrivateCredentials().add(credential);
return null;
});
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ElytronSubjectFactory@").append(Integer.toHexString(System.identityHashCode(this)));
sb.append("]");
return sb.toString();
}
private AuthenticationContext getAuthenticationContext() {
return authenticationContext == null ? AuthenticationContext.captureCurrent() : authenticationContext;
}
}
| 9,029 | 43.264706 | 149 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/security/ElytronSecurityIntegration.java | /*
* Copyright 2017 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.connector.security;
import java.security.AccessController;
import javax.security.auth.callback.CallbackHandler;
import org.jboss.as.connector.logging.ConnectorLogger;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.server.CurrentServiceContainer;
import org.jboss.jca.core.spi.security.Callback;
import org.jboss.jca.core.spi.security.SecurityContext;
import org.jboss.jca.core.spi.security.SecurityIntegration;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceName;
import org.wildfly.security.auth.server.SecurityDomain;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* An Elytron based {@link SecurityIntegration} implementation.
*
* @author Flavia Rainone
* @author <a href="mailto:[email protected]">Stefan Guilhen</a>
*/
public class ElytronSecurityIntegration implements SecurityIntegration {
static final String SECURITY_IDENTITY_ROLE = "ejb";
private static final String SECURITY_DOMAIN_CAPABILITY = "org.wildfly.security.security-domain";
private static final RuntimeCapability<Void> SECURITY_DOMAIN_RUNTIME_CAPABILITY = RuntimeCapability
.Builder.of(SECURITY_DOMAIN_CAPABILITY, true, SecurityDomain.class)
.build();
private final ThreadLocal<SecurityContext> securityContext = new ThreadLocal<>();
@Override
public SecurityContext createSecurityContext(String sd) throws Exception {
return new ElytronSecurityContext();
}
@Override
public SecurityContext getSecurityContext() {
return this.securityContext.get();
}
@Override
public void setSecurityContext(SecurityContext context) {
this.securityContext.set(context);
}
@Override
public CallbackHandler createCallbackHandler() {
// we need a Callback to retrieve the Elytron security domain that will be used by the CallbackHandler.
throw ConnectorLogger.ROOT_LOGGER.unsupportedCreateCallbackHandlerMethod();
}
@Override
public CallbackHandler createCallbackHandler(final Callback callback) {
assert callback != null;
// TODO switch to use the elytron security domain once the callback has that info available.
final String securityDomainName = callback.getDomain();
// get domain reference from the service container and create the callback handler using the domain.
if (securityDomainName != null) {
final ServiceContainer container = this.currentServiceContainer();
final ServiceName securityDomainServiceName = SECURITY_DOMAIN_RUNTIME_CAPABILITY.getCapabilityServiceName(securityDomainName);
final SecurityDomain securityDomain = (SecurityDomain) container.getRequiredService(securityDomainServiceName).getValue();
return new ElytronCallbackHandler(securityDomain, callback);
}
// TODO use subsystem logger for the exception.
throw ConnectorLogger.ROOT_LOGGER.invalidCallbackSecurityDomain();
}
/**
* Get a reference to the current {@link ServiceContainer}.
*
* @return a reference to the current {@link ServiceContainer}.
*/
private ServiceContainer currentServiceContainer() {
if(WildFlySecurityManager.isChecking()) {
return AccessController.doPrivileged(CurrentServiceContainer.GET_ACTION);
}
return CurrentServiceContainer.getServiceContainer();
}
}
| 4,062 | 39.63 | 138 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/security/CallbackImpl.java | /*
* Copyright 2017 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.connector.security;
import java.util.Map;
/**
* Extension of CallbackImpl with added support for Elytron.
*
* @author Flavia Rainone
*/
public class CallbackImpl extends org.jboss.jca.core.security.CallbackImpl {
private boolean elytronEnabled;
public CallbackImpl(boolean mappingRequired, String domain, String defaultPrincipal, String[] defaultGroups,
Map<String, String> principals, Map<String, String> groups) {
super(mappingRequired, domain, defaultPrincipal, defaultGroups, principals, groups);
}
}
| 1,161 | 33.176471 | 112 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/security/ElytronCallbackHandler.java | /*
* Copyright 2017 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.connector.security;
import static org.jboss.as.connector.logging.ConnectorLogger.SUBSYSTEM_RA_LOGGER;
import java.io.IOException;
import java.io.Serializable;
import java.security.AccessController;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import jakarta.resource.spi.security.PasswordCredential;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import jakarta.security.auth.message.callback.CallerPrincipalCallback;
import jakarta.security.auth.message.callback.GroupPrincipalCallback;
import jakarta.security.auth.message.callback.PasswordValidationCallback;
import org.jboss.jca.core.spi.security.Callback;
import org.wildfly.security.auth.principal.NamePrincipal;
import org.wildfly.security.auth.server.RealmUnavailableException;
import org.wildfly.security.auth.server.SecurityDomain;
import org.wildfly.security.auth.server.SecurityIdentity;
import org.wildfly.security.auth.server.ServerAuthenticationContext;
import org.wildfly.security.authz.RoleMapper;
import org.wildfly.security.authz.Roles;
import org.wildfly.security.evidence.PasswordGuessEvidence;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* An Elytron based {@link CallbackHandler} implementation designed for the Jakarta Connectors security inflow. It uses the information
* obtained from the {@link javax.security.auth.callback.Callback}s to authenticate and authorize the identity supplied
* by the resource adapter and inserts the {@link SecurityIdentity} representing the authorized identity in the subject's
* private credentials set.
*
* @author Flavia Rainone
* @author <a href="mailto:[email protected]">Stefan Guilhen</a>
*/
public class ElytronCallbackHandler implements CallbackHandler, Serializable {
private final SecurityDomain securityDomain;
private final Callback mappings;
private Subject executionSubject;
/**
* Constructor
* @param securityDomain the Elytron security domain used to establish the caller principal.
* @param mappings The mappings.
*/
public ElytronCallbackHandler(final SecurityDomain securityDomain, final Callback mappings) {
this.securityDomain = securityDomain;
this.mappings = mappings;
}
/**
* {@inheritDoc}
*/
public void handle(javax.security.auth.callback.Callback[] callbacks) throws UnsupportedCallbackException, IOException {
if (SUBSYSTEM_RA_LOGGER.isTraceEnabled())
SUBSYSTEM_RA_LOGGER.elytronHandlerHandle(Arrays.toString(callbacks));
// work wrapper calls the callback handler a second time with default callback values after the handler was invoked
// by the RA. We must check if the execution subject already contains an identity and allow for replacement of the
// identity with values found in the default callbacks only if the subject has no identity yet or if the identity
// is the anonymous one.
if (this.executionSubject != null) {
final SecurityIdentity subjectIdentity = this.getPrivateCredential(this.executionSubject, SecurityIdentity.class);
if (subjectIdentity != null && !subjectIdentity.isAnonymous()) {
return;
}
}
if (callbacks != null && callbacks.length > 0)
{
if (this.mappings != null && this.mappings.isMappingRequired())
{
callbacks = this.mappings.mapCallbacks(callbacks);
}
GroupPrincipalCallback groupPrincipalCallback = null;
CallerPrincipalCallback callerPrincipalCallback = null;
PasswordValidationCallback passwordValidationCallback = null;
for (javax.security.auth.callback.Callback callback : callbacks) {
if (callback instanceof GroupPrincipalCallback) {
groupPrincipalCallback = (GroupPrincipalCallback) callback;
if (this.executionSubject == null) {
this.executionSubject = groupPrincipalCallback.getSubject();
} else if (!this.executionSubject.equals(groupPrincipalCallback.getSubject())) {
// TODO merge the contents of the subjects?
}
} else if (callback instanceof CallerPrincipalCallback) {
callerPrincipalCallback = (CallerPrincipalCallback) callback;
if (this.executionSubject == null) {
this.executionSubject = callerPrincipalCallback.getSubject();
} else if (!this.executionSubject.equals(callerPrincipalCallback.getSubject())) {
// TODO merge the contents of the subjects?
}
} else if (callback instanceof PasswordValidationCallback) {
passwordValidationCallback = (PasswordValidationCallback) callback;
if (this.executionSubject == null) {
this.executionSubject = passwordValidationCallback.getSubject();
} else if (!this.executionSubject.equals(passwordValidationCallback.getSubject())) {
// TODO merge the contents of the subjects?
}
} else {
throw new UnsupportedCallbackException(callback);
}
}
this.handleInternal(callerPrincipalCallback, groupPrincipalCallback, passwordValidationCallback);
}
}
protected void handleInternal(final CallerPrincipalCallback callerPrincipalCallback, final GroupPrincipalCallback groupPrincipalCallback,
final PasswordValidationCallback passwordValidationCallback) throws IOException {
if(this.executionSubject == null) {
throw SUBSYSTEM_RA_LOGGER.executionSubjectNotSetInHandler();
}
SecurityIdentity identity = this.securityDomain.getAnonymousSecurityIdentity();
// establish the caller principal using the info from the callback.
Principal callerPrincipal = null;
if (callerPrincipalCallback != null) {
Principal callbackPrincipal = callerPrincipalCallback.getPrincipal();
callerPrincipal = callbackPrincipal != null ? new NamePrincipal(callbackPrincipal.getName()) :
callerPrincipalCallback.getName() != null ? new NamePrincipal(callerPrincipalCallback.getName()) : null;
}
// a null principal is the ra contract for requiring the use of the unauthenticated identity - no point in attempting to authenticate.
if (callerPrincipal != null) {
// check if we have a username/password pair to authenticate - first try the password validation callback.
if (passwordValidationCallback != null) {
final String username = passwordValidationCallback.getUsername();
final char[] password = passwordValidationCallback.getPassword();
try {
identity = this.authenticate(username, password);
// add a password credential to the execution subject and set the successful result in the callback.
this.addPrivateCredential(this.executionSubject, new PasswordCredential(username, password));
passwordValidationCallback.setResult(true);
} catch (SecurityException e) {
passwordValidationCallback.setResult(false);
return;
}
} else {
// identity not established using the callback - check if the execution subject contains a password credential.
PasswordCredential passwordCredential = this.getPrivateCredential(this.executionSubject, PasswordCredential.class);
if (passwordCredential != null) {
try {
identity = this.authenticate(passwordCredential.getUserName(), passwordCredential.getPassword());
} catch (SecurityException e) {
return;
}
} else {
identity = securityDomain.createAdHocIdentity(callerPrincipal);
}
}
// at this point we either have an authenticated identity or an anonymous one. We must now check if the caller principal
// is different from the identity principal and switch to the caller principal identity if needed.
if (!callerPrincipal.equals(identity.getPrincipal())) {
identity = identity.createRunAsIdentity(callerPrincipal.getName());
}
// if we have new roles coming from the group callback, set a new mapper in the identity.
if (groupPrincipalCallback != null) {
String[] groups = groupPrincipalCallback.getGroups();
if (groups != null) {
Set<String> roles = new HashSet<>(Arrays.asList(groups));
// TODO what category should we use here?
identity = identity.withRoleMapper(ElytronSecurityIntegration.SECURITY_IDENTITY_ROLE, RoleMapper.constant(Roles.fromSet(roles)));
}
}
}
// set the authenticated identity as a private credential in the subject.
this.executionSubject.getPrincipals().add(identity.getPrincipal());
this.addPrivateCredential(executionSubject, identity);
}
/**
* Authenticate the user with the given credential against the configured Elytron security domain.
*
* @param username the user being authenticated.
* @param credential the credential used as evidence to verify the user's identity.
* @return the authenticated and authorized {@link SecurityIdentity}.
* @throws IOException if an error occurs while authenticating the user.
*/
private SecurityIdentity authenticate(final String username, final char[] credential) throws IOException {
final ServerAuthenticationContext context = this.securityDomain.createNewAuthenticationContext();
final PasswordGuessEvidence evidence = new PasswordGuessEvidence(credential != null ? credential : null);
try {
context.setAuthenticationName(username);
if (context.verifyEvidence(evidence)) {
if (context.authorize()) {
context.succeed();
return context.getAuthorizedIdentity();
} else {
context.fail();
throw new SecurityException("Authorization failed");
}
} else {
context.fail();
throw new SecurityException("Authentication failed");
}
} catch (IllegalArgumentException | IllegalStateException | RealmUnavailableException e) {
context.fail();
throw e;
} finally {
if (!context.isDone()) {
context.fail();
}
evidence.destroy();
}
}
protected<T> T getPrivateCredential(final Subject subject, final Class<T> credentialClass) {
T credential = null;
if (subject != null) {
Set<T> credentialSet;
if (!WildFlySecurityManager.isChecking()) {
credentialSet = subject.getPrivateCredentials(credentialClass);
} else {
credentialSet = AccessController.doPrivileged((PrivilegedAction<Set<T>>) () ->
subject.getPrivateCredentials(credentialClass));
}
if (!credentialSet.isEmpty()) {
credential = credentialSet.iterator().next();
}
}
return credential;
}
/**
* Add the specified credential to the subject's private credentials set.
*
* @param subject the {@link Subject} to add the credential to.
* @param credential a reference to the credential.
*/
protected void addPrivateCredential(final Subject subject, final Object credential) {
if (!WildFlySecurityManager.isChecking()) {
subject.getPrivateCredentials().add(credential);
}
else {
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
subject.getPrivateCredentials().add(credential);
return null;
});
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ElytronCallbackHandler@").append(Integer.toHexString(System.identityHashCode(this)));
sb.append("[mappings=").append(mappings);
sb.append("]");
return sb.toString();
}
}
| 13,565 | 46.433566 | 149 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/_private/Capabilities.java | /*
* Copyright 2017 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.connector._private;
import javax.sql.DataSource;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.naming.service.NamingService;
/**
* Capabilities for the connector subsystems.
* <p>
* <strong>This is not to be used outside of the various connector subsystems.</strong>
* </p>
*
* @author <a href="mailto:[email protected]">James R. Perkins</a>
*/
public interface Capabilities {
/**
* The name for the data-source capability
*/
String DATA_SOURCE_CAPABILITY_NAME = "org.wildfly.data-source";
/**
* The name of the authentication-context capability provided by Elytron.
*/
String AUTHENTICATION_CONTEXT_CAPABILITY = "org.wildfly.security.authentication-context";
String ELYTRON_SECURITY_DOMAIN_CAPABILITY = "org.wildfly.security.security-domain";
String RESOURCE_ADAPTER_CAPABILITY_NAME = "org.wildfly.resource-adapter";
String JCA_NAMING_CAPABILITY_NAME = "org.wildfly.jca.naming";
/**
* The data-source capability
*/
RuntimeCapability<Void> DATA_SOURCE_CAPABILITY = RuntimeCapability.Builder.of(DATA_SOURCE_CAPABILITY_NAME, true, DataSource.class)
.addRequirements(NamingService.CAPABILITY_NAME, ConnectorServices.TRANSACTION_INTEGRATION_CAPABILITY_NAME)
.build();
RuntimeCapability<Void> RESOURCE_ADAPTER_CAPABILITY = RuntimeCapability.Builder.of(RESOURCE_ADAPTER_CAPABILITY_NAME, true)
.addRequirements(ConnectorServices.TRANSACTION_INTEGRATION_CAPABILITY_NAME, NamingService.CAPABILITY_NAME)
.build();
RuntimeCapability<Void> JCA_NAMING_CAPABILITY = RuntimeCapability.Builder.of(JCA_NAMING_CAPABILITY_NAME)
.addRequirements(NamingService.CAPABILITY_NAME)
.build();
}
| 2,440 | 36.553846 | 134 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/annotations/repository/jandex/AnnotationImpl.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, 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.annotations.repository.jandex;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.jboss.as.connector.logging.ConnectorLogger;
import org.jboss.jca.common.spi.annotations.repository.Annotation;
/**
*
* An AnnotationImpl.
*
* @author <a href="mailto:[email protected]">Stefano Maestri</a>
*
*/
public class AnnotationImpl implements Annotation {
private final String className;
private final ClassLoader cl;
private final List<String> parameterTypes;
private final String memberName;
private final boolean onMethod;
private final boolean onField;
private final Class<? extends java.lang.annotation.Annotation> annotationClass;
/**
* Create a new AnnotationImpl.
*
* @param className className
* @param cl classloader
* @param parameterTypes parameterTypes
* @param memberName memberName
* @param onMethod onMethod
* @param onField onField
* @param annotationClass annotationClass
*/
@SuppressWarnings("unchecked")
public AnnotationImpl(String className, ClassLoader cl, List<String> parameterTypes, String memberName, boolean onMethod,
boolean onField, Class<?> annotationClass) {
super();
this.className = className;
this.cl = cl;
if (parameterTypes != null) {
this.parameterTypes = new ArrayList<String>(parameterTypes.size());
this.parameterTypes.addAll(parameterTypes);
} else {
this.parameterTypes = new ArrayList<String>(0);
}
this.memberName = memberName;
this.onMethod = onMethod;
this.onField = onField;
if (annotationClass.isAnnotation()) {
this.annotationClass = (Class<? extends java.lang.annotation.Annotation>) annotationClass;
} else {
throw ConnectorLogger.ROOT_LOGGER.notAnAnnotation(annotationClass);
}
}
/**
* Get the className.
*
* @return the className.
*/
@Override
public final String getClassName() {
return className;
}
/**
* Get the annotation.
*
* @return the annotation.
*/
@Override
public final Object getAnnotation() {
try {
if (isOnField()) {
Class<?> clazz = cl.loadClass(className);
while (!clazz.equals(Object.class)) {
try {
Field field = clazz.getDeclaredField(memberName);
return field.getAnnotation(annotationClass);
} catch (Throwable t) {
clazz = clazz.getSuperclass();
}
}
} else if (isOnMethod()) {
Class<?> clazz = cl.loadClass(className);
Class<?>[] params = new Class<?>[parameterTypes.size()];
int i = 0;
for (String paramClazz : parameterTypes) {
params[i] = cl.loadClass(paramClazz);
i++;
}
while (!clazz.equals(Object.class)) {
try {
Method method = clazz.getDeclaredMethod(memberName, params);
return method.getAnnotation(annotationClass);
} catch (Throwable t) {
clazz = clazz.getSuperclass();
}
}
} else { // onClass
Class<?> clazz = cl.loadClass(className);
return clazz.getAnnotation(annotationClass);
}
} catch (Exception e) {
ConnectorLogger.ROOT_LOGGER.debug(e.getMessage(), e);
}
return null;
}
/**
* Get the parameterTypes.
*
* @return the parameterTypes.
*/
@Override
public final List<String> getParameterTypes() {
return Collections.unmodifiableList(parameterTypes);
}
/**
* Get the memberName.
*
* @return the memberName.
*/
@Override
public final String getMemberName() {
return memberName;
}
/**
* Get the onMethod.
*
* @return the onMethod.
*/
@Override
public final boolean isOnMethod() {
return onMethod;
}
/**
* Get the onField.
*
* @return the onField.
*/
@Override
public final boolean isOnField() {
return onField;
}
}
| 5,602 | 29.123656 | 125 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/annotations/repository/jandex/JandexAnnotationRepositoryImpl.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, 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.annotations.repository.jandex;
import static org.wildfly.common.Assert.checkNotNullParam;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.FieldInfo;
import org.jboss.jandex.Index;
import org.jboss.jandex.MethodInfo;
import org.jboss.jandex.Type;
import org.jboss.jca.common.spi.annotations.repository.Annotation;
import org.jboss.jca.common.spi.annotations.repository.AnnotationRepository;
/**
*
* An AnnotationRepositoryImpl.
*
* @author <a href="mailto:[email protected]">Stefano Maestri</a>
*
*/
public class JandexAnnotationRepositoryImpl implements AnnotationRepository {
private final Index backingRepository;
private final ClassLoader cl;
/**
*
* Create a new AnnotationRepositoryImpl using papaki backend
*
* @param backingRepository the caking papaki repository
* @param cl classLoader
* @throws IllegalArgumentException in case pas sed repository is null
*/
public JandexAnnotationRepositoryImpl(Index backingRepository, ClassLoader cl) throws IllegalArgumentException {
this.backingRepository = checkNotNullParam("backingRepository", backingRepository);
this.cl = cl;
}
@Override
public Collection<Annotation> getAnnotation(Class<?> annotationClass) {
List<AnnotationInstance> instances = backingRepository.getAnnotations(DotName.createSimple(annotationClass
.getName()));
ArrayList<Annotation> annotations = new ArrayList<Annotation>(instances.size());
for (AnnotationInstance instance : instances) {
AnnotationTarget target = instance.target();
Annotation annotation = null;
if (target instanceof MethodInfo) {
MethodInfo m = (MethodInfo) target;
List<String> parameterTypes = new ArrayList<String>(m.args().length);
for (Type type : m.args()) {
parameterTypes.add(type.toString());
}
String declaringClass = m.declaringClass().name().toString();
annotation = new AnnotationImpl(declaringClass, cl, parameterTypes, m.name(), true, false, annotationClass);
}
if (target instanceof FieldInfo) {
FieldInfo f = (FieldInfo) target;
String declaringClass = f.declaringClass().name().toString();
annotation = new AnnotationImpl(declaringClass, cl, null, f.name(), false, true, annotationClass);
}
if (target instanceof ClassInfo) {
ClassInfo c = (ClassInfo) target;
annotation = new AnnotationImpl(c.name().toString(), cl, null, null, false, false, annotationClass);
}
if (annotation != null) {
annotations.add(annotation);
}
}
annotations.trimToSize();
if (annotations.isEmpty()) {
return null;
} else {
return Collections.unmodifiableList(annotations);
}
}
}
| 4,321 | 39.392523 | 124 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/logging/ConnectorLogger.java | /*
* 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.logging;
import static org.jboss.logging.Logger.Level.DEBUG;
import static org.jboss.logging.Logger.Level.ERROR;
import static org.jboss.logging.Logger.Level.INFO;
import static org.jboss.logging.Logger.Level.WARN;
import java.sql.Driver;
import java.util.Set;
import javax.security.auth.Subject;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.dmr.ModelNode;
import org.jboss.jca.deployers.common.DeployException;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
import org.jboss.modules.ModuleLoadException;
import org.jboss.msc.service.StartException;
import org.jboss.vfs.VirtualFile;
/**
* @author <a href="mailto:[email protected]">James R. Perkins</a>
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
@MessageLogger(projectCode = "WFLYJCA", length = 4)
public interface ConnectorLogger extends BasicLogger {
/**
* The root logger with a category of the default package.
*/
ConnectorLogger ROOT_LOGGER = Logger.getMessageLogger(ConnectorLogger.class, "org.jboss.as.connector");
/**
* A logger with the category {@code org.jboss.as.connector.deployers.jdbc}.
*/
ConnectorLogger DEPLOYER_JDBC_LOGGER = Logger.getMessageLogger(ConnectorLogger.class, "org.jboss.as.connector.deployers.jdbc");
/**
* A logger with the category {@code org.jboss.as.deployment.connector}.
*/
ConnectorLogger DEPLOYMENT_CONNECTOR_LOGGER = Logger.getMessageLogger(ConnectorLogger.class, "org.jboss.as.connector.deployment");
/**
* A logger with the category {@code org.jboss.as.deployment.connector.registry}.
*/
ConnectorLogger DEPLOYMENT_CONNECTOR_REGISTRY_LOGGER = Logger.getMessageLogger(ConnectorLogger.class, "org.jboss.as.connector.deployment.registry");
/**
* A logger with the category {@code org.jboss.as.connector.deployer.dsdeployer}.
*/
ConnectorLogger DS_DEPLOYER_LOGGER = Logger.getMessageLogger(ConnectorLogger.class, "org.jboss.as.connector.deployer.dsdeployer");
/**
* A logger with the category {@code org.jboss.as.connector.services.mdr}.
*/
ConnectorLogger MDR_LOGGER = Logger.getMessageLogger(ConnectorLogger.class, "org.jboss.as.connector.services.mdr");
/**
* A logger with the category {@code org.jboss.as.connector.subsystems.datasources}.
*/
ConnectorLogger SUBSYSTEM_DATASOURCES_LOGGER = Logger.getMessageLogger(ConnectorLogger.class, "org.jboss.as.connector.subsystems.datasources");
/**
* A logger with the category {@code org.jboss.as.connector.subsystems.resourceadapters}.
*/
ConnectorLogger SUBSYSTEM_RA_LOGGER = Logger.getMessageLogger(ConnectorLogger.class, "org.jboss.as.connector.subsystems.resourceadapters");
/**
* Logs an informational message indicating the data source has been bound.
*
* @param jndiName the JNDI name
*/
@LogMessage(level = INFO)
@Message(id = 1, value = "Bound data source [%s]")
void boundDataSource(String jndiName);
/**
* Logs an informational message indicating the Jakarta Connectors bound the object represented by the {@code description}
* parameter.
*
* @param description the description of what was bound.
* @param jndiName the JNDI name.
*/
@LogMessage(level = INFO)
@Message(id = 2, value = "Bound Jakarta Connectors %s [%s]")
void boundJca(String description, String jndiName);
/**
* Logs a warning message indicating inability to instantiate the driver class.
*
* @param driverClassName the driver class name.
* @param reason the reason the the driver could not be instantiated.
*/
@LogMessage(level = WARN)
@Message(id = 3, value = "Unable to instantiate driver class \"%s\": %s")
void cannotInstantiateDriverClass(String driverClassName, Throwable reason);
/**
* Logs an informational message indicating the JDBC driver is compliant.
*
* @param driver the JDBC driver class.
* @param majorVersion the major version of the driver.
* @param minorVersion the minor version of the driver.
*/
@LogMessage(level = INFO)
@Message(id = 4, value = "Deploying JDBC-compliant driver %s (version %d.%d)")
void deployingCompliantJdbcDriver(Class<? extends Driver> driver, int majorVersion, int minorVersion);
/**
* Logs an informational message indicating the JDBC driver is non-compliant.
*
* @param driver the non-compliant JDBC driver class.
* @param majorVersion the major version of the driver.
* @param minorVersion the minor version of the driver.
*/
@LogMessage(level = INFO)
@Message(id = 5, value = "Deploying non-JDBC-compliant driver %s (version %d.%d)")
void deployingNonCompliantJdbcDriver(Class<? extends Driver> driver, int majorVersion, int minorVersion);
/**
* Logs an informational message indicating an admin object was registered.
*
* @param jndiName the JNDI name.
*/
@LogMessage(level = INFO)
@Message(id = 6, value = "Registered admin object at %s")
void registeredAdminObject(String jndiName);
/**
* Logs an informational message indicating the JNDI connection factory was registered.
*
* @param jndiName the JNDI connection factory.
*/
@LogMessage(level = INFO)
@Message(id = 7, value = "Registered connection factory %s")
void registeredConnectionFactory(String jndiName);
// /**
// * Logs an informational message indicating the service, represented by the {@code serviceName} parameter, is
// * starting.
// *
// * @param serviceName the name of the service that is starting.
// */
// @LogMessage(level = INFO)
// @Message(id = 8, value = "Starting service %s")
// void startingService(ServiceName serviceName);
/**
* Logs an informational message indicating the subsystem, represented by the {@code subsystem} parameter, is
* starting.
*
* @param subsystem the subsystem that is starting.
* @param version the version of the subsystem.
*/
@LogMessage(level = INFO)
@Message(id = 9, value = "Starting %s Subsystem (%s)")
void startingSubsystem(String subsystem, String version);
/**
* Logs an informational message indicating the data source has been unbound.
*
* @param jndiName the JNDI name
*/
@LogMessage(level = INFO)
@Message(id = 10, value = "Unbound data source [%s]")
void unboundDataSource(String jndiName);
/**
* Logs an informational message indicating the Jakarta Connectors inbound the object represented by the {@code description}
* parameter.
*
* @param description the description of what was unbound.
* @param jndiName the JNDI name.
*/
@LogMessage(level = INFO)
@Message(id = 11, value = "Unbound Jakarta Connectors %s [%s]")
void unboundJca(String description, String jndiName);
@LogMessage(level = WARN)
@Message(id = 12, value = "<drivers/> in standalone -ds.xml deployments aren't supported: Ignoring %s")
void driversElementNotSupported(String deploymentName);
// @Message(id = 13, value = "the attribute class-name cannot be null for more than one connection-definition")
// OperationFailedException classNameNullForMoreCD();
//
// @Message(id = 14, value = "the attribute class-name cannot be null for more than one admin-object")
// OperationFailedException classNameNullForMoreAO();
//
@Message(id = 15, value = "the attribute driver-name (%s) cannot be different from driver resource name (%s)")
OperationFailedException driverNameAndResourceNameNotEquals(String driverName, String resourceName);
@LogMessage(level = WARN)
@Message(id = 16, value = "Method %s on DataSource class %s not found. Ignoring")
void methodNotFoundOnDataSource(final String method, final Class<?> clazz);
@LogMessage(level = DEBUG)
@Message(id = 17, value = "Forcing ironjacamar.xml descriptor to null")
void forceIJToNull();
@LogMessage(level = INFO)
@Message(id = 18, value = "Started Driver service with driver-name = %s")
void startedDriverService(String driverName);
@LogMessage(level = INFO)
@Message(id = 19, value = "Stopped Driver service with driver-name = %s")
void stoppedDriverService(String driverName);
@LogMessage(level = WARN)
@Message(id = 20, value = "Unsupported selector's option: %s")
void unsupportedSelectorOption(String name);
@LogMessage(level = WARN)
@Message(id = 21, value = "Unsupported policy's option: %s")
void unsupportedPolicyOption(String name);
/**
* Creates an exception indicating a failure to start JGroup channel for a Distributed Work Manager
*
* @param channelName the name of the channel
* @param wmName the name of the workmanager
* @return a {@link StartException} for the error.
*/
@Message(id = 22, value = "Failed to start JGroups channel %s for distributed workmanager %s")
StartException failedToStartJGroupsChannel(String channelName, String wmName);
@Message(id = 23, value = "Cannot find WorkManager %s or it isn't a distributed workmanager. Only DWM can override configurations")
OperationFailedException failedToFindDistributedWorkManager(String wmName);
@Message(id = 24, value = "Failed to start JGroups transport for distributed workmanager %s")
StartException failedToStartDWMTransport(String wmName);
@Message(id = 25, value = "Unsupported selector's option: %s")
OperationFailedException unsupportedSelector(String name);
@Message(id = 26, value = "Unsupported policy's option: %s")
OperationFailedException unsupportedPolicy(String name);
@LogMessage(level = WARN)
@Message(id = 27, value = "No ironjacamar.security defined for %s")
void noSecurityDefined(String jndiName);
@LogMessage(level = WARN)
@Message(id = 28, value = "@ConnectionFactoryDefinition will have limited management: %s")
void connectionFactoryAnnotation(String jndiName);
@LogMessage(level = WARN)
@Message(id = 29, value = "@AdministeredObjectDefinition will have limited management: %s")
void adminObjectAnnotation(String jndiName);
/**
* Creates an exception indicating the inability to complete the deployment.
*
* @param cause the cause of the error.
* @return a {@link DeployException} for the error.
*/
@Message(id = 30, value = "unable to deploy")
DeployException cannotDeploy(@Cause Throwable cause);
/**
* Creates an exception indicating the inability to deploy and validate a datasource or an XA datasource.
*
* @param cause the cause of the error.
* @return a {@link DeployException} for the error.
*/
@Message(id = 31, value = "unable to validate and deploy ds or xads")
DeployException cannotDeployAndValidate(@Cause Throwable cause);
// /**
// * Creates an exception indicating the data source was unable to start because it create more than one connection
// * factory.
// *
// * @return a {@link StartException} for the error.
// */
// @Message(id = 32, value = "Unable to start the ds because it generated more than one cf")
// StartException cannotStartDs();
/**
* Creates an exception indicating an error occurred during deployment.
*
* @param cause the cause of the error.
* @param name the name of the deployment in error.
* @return a {@link StartException} for the error.
*/
@Message(id = 33, value = "Error during the deployment of %s")
StartException deploymentError(@Cause Throwable cause, String name);
/**
* A message indicating inability to instantiate the driver class.
*
* @param driverClassName the driver class name.
* @return the message.
*/
@Message(id = 34, value = "Unable to instantiate driver class \"%s\". See log (WARN) for more details")
String cannotInstantiateDriverClass(String driverClassName);
/**
* Creates an exception indicating the specified driver version does not match the actual driver version.
*
* @return an {@link IllegalStateException} for the error.
*/
@Message(id = 35, value = "Specified driver version doesn't match with actual driver version")
IllegalStateException driverVersionMismatch();
/**
* A message indicating the type, represented by the {@code type} parameter, failed to be created for the operation
* represented by the {@code operation} message.
*
* @param type the type that failed to create.
* @param operation the operation.
* @param reasonMessage the reason.
* @return the message.
*/
@Message(id = 36, value = "Failed to create %s instance for [%s]%n reason: %s")
String failedToCreate(String type, ModelNode operation, String reasonMessage);
/**
* A message indicating a failure to get the metrics.
*
* @param message a message to append.
* @return the message.
*/
@Message(id = 37, value = "failed to get metrics: %s")
String failedToGetMetrics(String message);
// /**
// * Creates an exception indicating a failure to get the module attachment for the deployment unit represented by
// * the {@code deploymentUnit} parameter.
// *
// * @param deploymentUnit the deployment.
// * @return a {@link DeploymentUnitProcessingException} for the error.
// */
//@Message(id = 38, value = "Failed to get module attachment for %s")
//DeploymentUnitProcessingException failedToGetModuleAttachment(DeploymentUnit deploymentUnit);
/**
* Creates an exception indicating a failure to get the URL delimiter.
*
* @param cause the cause of the error.
* @return a {@link DeployException} for the error.
*/
@Message(id = 39, value = "failed to get url delimiter")
DeployException failedToGetUrlDelimiter(@Cause Throwable cause);
/**
* A message indicating a failure to invoke an operation.
*
* @param message the message to append.
* @return th message.
*/
@Message(id = 40, value = "failed to invoke operation: %s")
String failedToInvokeOperation(String message);
/**
* A message indicating a failure to load the module for a driver.
*
* @param moduleName the module name.
* @return the message.
*/
@Message(id = 41, value = "Failed to load module for driver [%s]")
String failedToLoadModuleDriver(String moduleName);
/**
* Creates an exception indicating a failure to match the pool.
*
* @param jndiName the JNDI name.
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 42, value = "failed to match pool. Check JndiName: %s")
IllegalArgumentException failedToMatchPool(String jndiName);
/**
* Creates an exception indicating a failure to parse the service XML.
*
* @param xmlFile the service XML file.
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 43, value = "Failed to parse service xml [%s]")
DeploymentUnitProcessingException failedToParseServiceXml(VirtualFile xmlFile);
/**
* Creates an exception indicating a failure to parse the service XML.
*
* @param cause the cause of the error.
* @param xmlFile the service XML file.
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
DeploymentUnitProcessingException failedToParseServiceXml(@Cause Throwable cause, VirtualFile xmlFile);
/**
* Creates an exception indicating a failure to process the resource adapter child archives for the deployment root
* represented by the {@code deploymentRoot} parameter.
*
* @param cause the cause of the error.
* @param deploymentRoot the deployment root.
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 44, value = "Failed to process RA child archives for [%s]")
DeploymentUnitProcessingException failedToProcessRaChild(@Cause Throwable cause, VirtualFile deploymentRoot);
/**
* A message indicating a failure to set an attribute.
*
* @param message the message to append.
* @return the message.
*/
@Message(id = 45, value = "failed to set attribute: %s")
String failedToSetAttribute(String message);
/**
* Creates an exception indicating the deployment, represented by the {@code deploymentName} parameter, failed to
* start.
*
* @param cause the cause of the error.
* @param deploymentName the deployment name.
* @return a {@link StartException} for the error.
*/
@Message(id = 46, value = "Failed to start RA deployment [%s]")
StartException failedToStartRaDeployment(@Cause Throwable cause, String deploymentName);
/**
* Creates an exception indicating the connection is not valid.
*
* @return an {@link IllegalStateException} for the error.
*/
@Message(id = 47, value = "Connection is not valid")
IllegalStateException invalidConnection(@Cause Exception e);
// /**
// * A message indicating the parameter name is invalid.
// *
// * @param parameterName the invalid parameter name.
// * @return the message.
// */
// @Message(id = 48, value = "Invalid parameter name: %s")
// String invalidParameterName(String parameterName);
/**
* Creates an exception indicating non-explicit JNDI bindings are not supported.
*
* @return an {@link IllegalStateException} for the error.
*/
@Message(id = 49, value = "Non-explicit JNDI bindings not supported")
IllegalStateException jndiBindingsNotSupported();
/**
* A message indicating there are no metrics available.
*
* @return the message.
*/
@Message(id = 50, value = "no metrics available")
String noMetricsAvailable();
/**
* Creates an exception indicating the class, represented by the {@code clazz} parameter, should be an annotation.
*
* @param clazz the invalid class.
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 51, value = "%s should be an annotation")
IllegalArgumentException notAnAnnotation(Class<?> clazz);
/**
* A message indicating the variable is {@code null}.
*
* @param name the name of the variable.
* @return the message
*/
@Message(id = 52, value = "%s is null")
String nullVar(String name);
/**
* A message indicating the service, represented by the {@code serviceType} parameter, is already started on the
* object represented by the {@code obj} parameter.
*
* @param serviceType the service type.
* @param obj the object.
* @return the message.
*/
@Message(id = 53, value = "%s service [%s] is already started")
String serviceAlreadyStarted(String serviceType, Object obj);
/**
* A message indicating the service, represented by the {@code serviceType} parameter, is not available on th object
* represented by the {@code obj} parameter.
*
* @param serviceType the service type.
* @param obj the object.
* @return the message.
*/
@Message(id = 54, value = "%s service [%s] is not available")
String serviceNotAvailable(String serviceType, Object obj);
// /**
// * A message indicating the service, represented by the {@code serviceType} parameter, is not enabled on th object
// * represented by the {@code obj} parameter.
// *
// * @param serviceType the service type.
// * @param obj the object.
// * @return the message.
// */
// @Message(id = 55, value = "%s service [%s] is not enabled")
// String serviceNotEnabled(String serviceType, Object obj);
/**
* Creates an exception indicating the service is not started.
*
* @return an {@link IllegalStateException} for the error.
*/
@Message(id = 56, value = "Service not started")
IllegalStateException serviceNotStarted();
// /**
// * Creates an exception indicating the property type is unknown.
// *
// * @param propertyType the unknown property type.
// * @param propertyName the name of the property.
// * @return an {@link IllegalArgumentException} for the error.
// */
// @Message(id = 57, value = "Unknown property type: %s for property %s")
// IllegalArgumentException unknownPropertyType(String propertyType, String propertyName);
/**
* Creates an exception indicating a variable is undefined.
*
* @param name the name of the variable.
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 58, value = "%s is undefined")
IllegalArgumentException undefinedVar(String name);
// /**
// * Creates an exception indicating that a service is already registered
// *
// * @param name the name of the service.
// * @return an {@link IllegalStateException} for the error.
// */
// @Message(id = 59, value = "Service '%s' already registered")
// IllegalStateException serviceAlreadyRegistered(String name);
// /**
// * Creates an exception indicating that a service isn't registered
// *
// * @param name the name of the service.
// * @return an {@link IllegalStateException} for the error.
// */
// @Message(id = 60, value = "Service '%s' isn't registered")
// IllegalStateException serviceIsntRegistered(String name);
/**
* Failed to load native libraries
*
* @param cause the exception.
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 61, value = "Failed to load native libraries")
DeploymentUnitProcessingException failedToLoadNativeLibraries(@Cause Throwable cause);
// /**
// * Creates an exception indicating that the ServiceName doesn't belong to a resource adapter service
// *
// * @param serviceName The service name
// * @return an {@link IllegalArgumentException} for the error.
// */
// @Message(id = 62, value = "%s isn't a resource adapter service")
// IllegalArgumentException notResourceAdapterService(ServiceName serviceName);
// /**
// * Creates and returns an exception indicating that the param named <code>paramName</code> cannot be null
// * or empty string.
// *
// * @param paramName The param name
// * @return an {@link IllegalArgumentException} for the exception
// */
// @Message(id = 63, value = "%s cannot be null or empty")
// IllegalArgumentException stringParamCannotBeNullOrEmpty(final String paramName);
@Message(id = 64, value = "Exception deploying datasource %s")
DeploymentUnitProcessingException exceptionDeployingDatasource(@Cause Throwable cause, String datasource);
/**
* No datasource exists at the deployment address
*/
@Message(id = 65, value = "No DataSource exists at address %s")
String noDataSourceRegisteredForAddress(PathAddress address);
/**
* Creates an exception indicating unknown attribute
*
* @return an {@link IllegalStateException} for the error.
*/
@Message(id = 66, value = "Unknown attribute %s")
IllegalStateException unknownAttribute(String attributeName);
/**
* Creates an exception indicating unknown operation
*
* @return an {@link IllegalStateException} for the error.
*/
@Message(id = 67, value = "Unknown operation %s")
IllegalStateException unknownOperation(String attributeName);
// /**
// * A message indicating the driver is not installed
// *
// * @param driverName the driver name.
// * @return the message.
// */
// @Message(id = 68, value = "Driver named \"%s\" is not installed.")
// String driverNotPresent(String driverName);
/**
* A message indicating that at least on xa-datasource-property is required
*
* @return the message.
*/
@Message(id = 69, value = "At least one xa-datasource-property is required for an xa-datasource")
OperationFailedException xaDataSourcePropertiesNotPresent();
// /**
// * A message indicating that jndi-name is missing and it's a required attribute
// *
// * @return the message.
// */
// @Message(id = 70, value = "Jndi name is required")
// OperationFailedException jndiNameRequired();
// /**
// * A message indicating that jndi-name has an invalid format
// *
// * @return the message.
// */
// @Message(id = 71, value = "Jndi name have to start with java:/ or java:jboss/")
// OperationFailedException jndiNameInvalidFormat();
/**
* Creates an exception indicating the deployment failed.
*
* @param cause the cause of the error.
* @param className the name of the class that failed.
* @return a {@link DeployException} for the error.
*/
@Message(id = 72, value = "Deployment %s failed")
DeployException deploymentFailed(@Cause Throwable cause, String className);
/**
* A message indicating a failure to load the module for a RA deployed as module.
*
* @param moduleName the module name.
* @return the message.
*/
@Message(id = 73, value = "Failed to load module for RA [%s] Cause: %s")
String failedToLoadModuleRA(String moduleName, String cause);
/**
* Creates an exception indicating a method is undefined.
*
* @param name the name of the method.
* @return an {@link NoSuchMethodException} for the error.
*/
@Message(id = 74, value = "Method %s not found")
NoSuchMethodException noSuchMethod(String name);
/**
* Creates an exception indicating a field is undefined.
*
* @param name the name of the field.
* @return an {@link NoSuchMethodException} for the error.
*/
@Message(id = 75, value = "Field %s not found")
NoSuchMethodException noSuchField(String name);
/**
* Creates an exception indicating a property can't be resolved
*
* @param name the name of the property.
* @return an {@link NoSuchMethodException} for the error.
*/
@Message(id = 76, value = "Unknown property resolution for property %s")
IllegalArgumentException noPropertyResolution(String name);
/**
* A message indicating that at least one of archive or module attributes
* gave to be defined
*
* @return the message.
*/
@Message(id = 77, value = "At least one of ARCHIVE or MODULE is required")
OperationFailedException archiveOrModuleRequired();
/**
* A message indicating a failure to load the module for a RA deployed as module.
* The cause of this failure ius the use of unsupported compressed form for the rar
*
* @param moduleName the module name.
* @return the message.
*/
@Message(id = 78, value = "Rar are supported only in uncompressed form. Failed to load module for RA [%s]")
String compressedRarNotSupportedInModuleRA(String moduleName);
/**
* Creates an exception indicating a failure to deploy the datasource because driver is not specified
*
* @param dsName the datasource to be deployed.
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 79, value = "Failed to deploy datasource %s because driver is not specified")
DeploymentUnitProcessingException FailedDeployDriverNotSpecified(String dsName);
/**
* Creates an exception indicating missing rar.
*
* @param raName - name.
* @return a {@link OperationFailedException} for the error.
*/
@Message(id = 80, value = "RAR '%s' not yet deployed.")
OperationFailedException RARNotYetDeployed(String raName);
// /**
// * MDR empty during deployment of deployment annotation
// *
// * @param jndiName The JNDI name
// * @return a {@link DeploymentUnitProcessingException} for the error.
// */
// @Message(id = 81, value = "Empty MDR while deploying %s")
// DeploymentUnitProcessingException emptyMdr(String jndiName);
// /**
// * Resource adapter not found during deployment of deployment annotation
// *
// * @param ra The resource adapter
// * @param jndiName The JNDI name
// * @return a {@link DeploymentUnitProcessingException} for the error.
// */
// @Message(id = 82, value = "Resource adapter (%s) not found while deploying %s")
// DeploymentUnitProcessingException raNotFound(String ra, String jndiName);
/**
* Invalid connection factory interface defined
*
* @param cf The connection factory
* @param ra The resource adapter
* @param jndiName The JNDI name
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 83, value = "Connection factory interface (%s) is incorrect for resource adapter '%s' while deploying %s")
DeploymentUnitProcessingException invalidConnectionFactory(String cf, String ra, String jndiName);
/**
* Admin object declared for JCA 1.0 archive
*
* @param ra The resource adapter
* @param jndiName The JNDI name
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 84, value = "Admin object declared for JCA 1.0 resource adapter '%s' while deploying %s")
DeploymentUnitProcessingException adminObjectForJCA10(String ra, String jndiName);
/**
* Invalid admin object class defined
*
* @param ao The admin object
* @param ra The resource adapter
* @param jndiName The JNDI name
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 85, value = "Admin object class (%s) is incorrect for resource adapter '%s' while deploying %s")
DeploymentUnitProcessingException invalidAdminObject(String ao, String ra, String jndiName);
/**
* Logs a warning message indicating can't find the driver class name.
*
* @param driverName the driver jar.
*/
@LogMessage(level = WARN)
@Message(id = 86, value = "Unable to find driver class name in \"%s\" jar")
void cannotFindDriverClassName(String driverName);
@LogMessage(level = ERROR)
@Message(id = 87, value = "Unable to register recovery: %s (%s)")
void unableToRegisterRecovery(String key, boolean isXa);
@Message(id = 88, value = "Attributes %s rejected. Must be true")
String rejectAttributesMustBeTrue(Set<String> key);
@LogMessage(level = WARN)
@Message(id = 89, value = "Exception during unregistering deployment")
void exceptionDuringUnregistering(@Cause org.jboss.jca.core.spi.rar.NotFoundException nfe);
@Message(id = 90, value = "Jndi name shouldn't include '//' or end with '/'")
OperationFailedException jndiNameShouldValidate();
@LogMessage(level = WARN)
@Message(id = 91, value = "-ds.xml file deployments are deprecated. Support may be removed in a future version.")
void deprecated();
@Message(id = 92, value = "Indexed child resources can only be registered if the parent resource supports ordered children. The parent of '%s' is not indexed")
IllegalStateException indexedChildResourceRegistrationNotAvailable(PathElement address);
@LogMessage(level = INFO)
@Message(id = 93, value = "The '%s' operation is deprecated. Use of the 'add' or 'remove' operations is preferred, or if required the 'write-attribute' operation can used to set the deprecated 'enabled' attribute")
void legacyDisableEnableOperation(String name);
// @Message(id = 94, value = "Driver %s should be defined in a profile named 'default' activated on server where deploying *-ds.xml")
// IllegalStateException driverNotDefinedInDefaultProfile(String driverName);
// @Message(id = 95, value = "At least one driver should be defined in a profile named 'default' activated on server where deploying *-ds.xml")
// IllegalStateException noDriverDefinedInDefaultProfile();
@LogMessage(level = ERROR)
@Message(id = 96, value = "Error during recovery shutdown")
void errorDuringRecoveryShutdown(@Cause Throwable cause);
@LogMessage(level = WARN)
@Message(id = 97, value = "Exception while stopping resource adapter")
void errorStoppingRA(@Cause Throwable cause);
@LogMessage(level = INFO)
@Message(id = 98, value = "Bound non-transactional data source: %s")
void boundNonJTADataSource(String jndiName);
@LogMessage(level = INFO)
@Message(id = 99, value = "Unbound non-transactional data source: %s")
void unBoundNonJTADataSource(String jndiName);
@Message(id = 100, value = "Operation %s is not supported")
UnsupportedOperationException noSupportedOperation(String operation);
@Message(id = 101, value = "Thread pool: %s(type: %s) can not be added for workmanager: %s, only one thread pool is allowed for each type.")
OperationFailedException oneThreadPoolWorkManager(String threadPoolName, String threadPoolType, String workManagerName);
/**
* A message indicating that an attribute can only be set if another attribute is set as {@code true}.
*
* @param attribute attribute that is invalid: it is defined but requires another attribute to be set as {@code true}
* @param requiredAttribute attribute that is required to be defined as {@code true}
* @return the message.
*/
@Message(id = 102, value = "Attribute %s can only be defined if %s is true")
OperationFailedException attributeRequiresTrueAttribute(String attribute, String requiredAttribute);
/**
* A message indicating that an attribute can only be set if another attribute is undefined or set as {@code false}.
*
* @param attribute attribute that is invalid: it is defined but requires another attribute to be set as {@code false} or to be undefined
* @param requiredFalseAttribute attribute that is required to be undefined or defined as {@code false}
* @return the message.
*/
@Message(id = 103, value = "Attribute %s can only be defined if %s is undefined or false")
OperationFailedException attributeRequiresFalseOrUndefinedAttribute(String attribute, String requiredFalseAttribute);
@Message(id = 104, value = "Subject=%s\nSubject identity=%s")
String subject(Subject subject, String identity);
@LogMessage(level = INFO)
@Message(id = 106, value = "Elytron handler handle: %s")
void elytronHandlerHandle(String callbacks);
@Message(id = 107, value = "Execution subject was not provided to the callback handler")
SecurityException executionSubjectNotSetInHandler();
@Message(id = 108, value = "Supplied callback doesn't contain a security domain reference")
IllegalArgumentException invalidCallbackSecurityDomain();
@Message(id = 109, value = "Callback with security domain is required - use createCallbackHandler(Callback callback) instead")
UnsupportedOperationException unsupportedCreateCallbackHandlerMethod();
@Message(id = 110, value = "CredentialSourceSupplier is invalid for DSSecurity")
IllegalStateException invalidCredentialSourceSupplier(@Cause Throwable cause);
@Message(id = 111, value = "WorkManager hasn't elytron-enabled flag set accordingly with RA one")
IllegalStateException invalidElytronWorkManagerSetting();
@Message(id = 112, value = "Datasource %s is disabled")
IllegalArgumentException datasourceIsDisabled(String jndiName);
@LogMessage(level = ERROR)
@Message(id =113, value = "Unexcepted error during worker execution : %s")
void unexceptedWorkerCompletionError(String errorMessage, @Cause Throwable t);
@Message(id = 114, value = "Failed to load datasource class: %s")
OperationFailedException failedToLoadDataSourceClass(String clsName, @Cause Throwable t);
@Message(id = 115, value = "Module for driver [%s] or one of it dependencies is missing: [%s]")
String missingDependencyInModuleDriver(String moduleName, String missingModule);
@Message(id = 116, value = "Failed to load module for RA [%s] - the module or one of its dependencies is missing [%s]")
String raModuleNotFound(String moduleName, String missingModule);
@Message(id = 117, value = "%s is not a valid %s implementation")
OperationFailedException notAValidDataSourceClass(String clz, String dsClz);
@LogMessage(level = INFO)
@Message(id = 118, value = "Binding connection factory named %s to alias %s")
void bindingAlias(String jndiName, String alias);
@LogMessage(level = INFO)
@Message(id = 119, value = "Unbinding connection factory named %s to alias %s")
void unbindingAlias(String jndiName, String alias);
/**
* Creates an exception indicating the data source was unable to start because it create more than one connection
* factory.
* @param dataSourceJNDIName
*
* @return a {@link StartException} for the error.
*/
@Message(id = 120, value = "Unable to start the data source '%s' because there are no connection factories, either not defined or failed, please check log.")
StartException cannotStartDSNoConnectionFactory(String dataSourceJNDIName);
/**
* Creates an exception indicating the data source was unable to start because it create more than one connection
* factory.
* @param dataSourceJNDIName
* @param factoriesCount
*
* @return a {@link StartException} for the error.
*/
@Message(id = 121, value = "Unable to start the data source '%s' because there is more than one(%s) connection factory defined.")
StartException cannotStartDSTooManyConnectionFactories(String dataSourceJNDIName, int factoriesCount);
@Message(id = 122, value = "Thread pool name %s(type: %s) must match the workmanager name %s.")
OperationFailedException threadPoolNameMustMatchWorkManagerName(String threadPoolName, String threadPoolType, String workManagerName);
@Message(id = 123, value = "Connection definition %s from resource adapter %s is configured to require the legacy security subsystem, which is not present")
OperationFailedException legacySecurityNotAvailable(String connectionDef, String ra);
@Message(id = 124, value = "Datasource %s is configured to require the legacy security subsystem, which is not present")
OperationFailedException legacySecurityNotAvailable(String datasourceName);
@Message(id = 125, value = "Datasource %s is configured to require the legacy security subsystem, which is not present")
DeploymentUnitProcessingException legacySecurityNotAvailableForDsXml(String datasourceName);
@Message(id = 126, value = "Connection definition for %s is configured to require the legacy security subsystem, which is not present")
DeploymentUnitProcessingException legacySecurityNotAvailableForRa(String deploymentName);
@Message(id = 127, value = "Connection factory %s is configured to require the legacy security subsystem, which is not present")
IllegalStateException legacySecurityNotAvailableForConnectionFactory(String jndiName);
@Message(id = 128, value = "Legacy security is not available")
IllegalStateException legacySecurityNotAvailable();
@Message(id = 129, value = "Wrong module name %s")
OperationFailedException wrongModuleName(@Cause ModuleLoadException exception, String moduleName);
@Message(id = 130, value = "Report directory %s does not exist")
OperationFailedException reportDirectoryDoesNotExist(String reportDirectory);
@Message(id = 131, value = "Legacy security attribute %s is no longer supported. Please use Elytron configuration instead")
OperationFailedException legacySecurityAttributeNotSupported(String attribute);
@Message(id = 132, value = "Legacy security is no longer supported. Please use Elytron configuration instead")
String legacySecurityNotSupported();
}
| 41,609 | 41.158055 | 218 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/driver/DriverService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, 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.services.driver;
import static org.jboss.as.connector.logging.ConnectorLogger.DEPLOYER_JDBC_LOGGER;
import java.sql.Driver;
import org.jboss.as.connector.logging.ConnectorLogger;
import org.jboss.as.connector.services.driver.registry.DriverRegistry;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
/**
* Service wrapper for a {@link Driver}.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class DriverService implements Service<Driver> {
private final InjectedValue<DriverRegistry> injectedDriverRegistry = new InjectedValue<DriverRegistry>();
private final InstalledDriver driverMetaData;
private final Driver driver;
public DriverService(InstalledDriver driverMetaData, Driver driver) {
assert driverMetaData != null : ConnectorLogger.ROOT_LOGGER.nullVar("driverMetaData");
assert driver != null : ConnectorLogger.ROOT_LOGGER.nullVar("driver");
this.driverMetaData = driverMetaData;
this.driver = driver;
}
@Override
public Driver getValue() throws IllegalStateException, IllegalArgumentException {
return driver;
}
@Override
public void start(StartContext context) throws StartException {
injectedDriverRegistry.getValue().registerInstalledDriver(driverMetaData);
DEPLOYER_JDBC_LOGGER.startedDriverService(driverMetaData.getDriverName());
}
@Override
public void stop(StopContext context) {
injectedDriverRegistry.getValue().unregisterInstalledDriver(driverMetaData);
DEPLOYER_JDBC_LOGGER.stoppedDriverService(driverMetaData.getDriverName());
}
public Injector<DriverRegistry> getDriverRegistryServiceInjector() {
return injectedDriverRegistry;
}
}
| 2,993 | 35.072289 | 109 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/driver/InstalledDriver.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.services.driver;
import org.jboss.modules.ModuleIdentifier;
/**
* Metadata describing a JDBC driver that has been installed as a service in the
* runtime.
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public final class InstalledDriver {
private final String driverName;
private final ModuleIdentifier moduleName;
private final String deploymentUnitName;
private final String driverClassName;
private final String dataSourceClassName;
private final String xaDataSourceClassName;
private final int majorVersion;
private final int minorVersion;
private final boolean jdbcCompliant;
/**
* Creates a new InstalledDriver for a driver that was loaded from the
* module path.
* @param driverName the symbolic name of the driver was loaded
* @param moduleName the name of the module from which the driver was loaded
* @param driverClassName the name of the {@link java.sql.Driver}
* implementation class
* @param dataSourceClassName the name of the {@link javax.sql.DataSource}
* implementation class
* @param xaDataSourceClassName the name of the {@link javax.sql.XADataSource}
* implementation class
* @param majorVersion the driver major version
* @param minorVersion the driver minor version
* @param jdbcCompliant whether the driver is JDBC compliant
*/
public InstalledDriver(final String driverName, final ModuleIdentifier moduleName, final String driverClassName,
final String dataSourceClassName, final String xaDataSourceClassName,
final int majorVersion, final int minorVersion, final boolean jdbcCompliant) {
this.deploymentUnitName = null;
this.moduleName = moduleName;
this.driverName = driverName;
this.driverClassName = driverClassName;
this.dataSourceClassName = dataSourceClassName;
this.xaDataSourceClassName = xaDataSourceClassName;
this.majorVersion = majorVersion;
this.minorVersion = minorVersion;
this.jdbcCompliant = jdbcCompliant;
}
/**
* Creates a new InstalledDriver for a driver that was installed from a
* deployment.
* @param deploymentUnitName the name of the deployment unit from which the
* driver was installed
* @param driverClassName the name of the {@link java.sql.Driver}
* implementation class
* @param dataSourceClassName the name of the {@link javax.sql.DataSource}
* implementation class
* @param xaDataSourceClassName the name of the {@link javax.sql.XADataSource}
* implementation class
* @param majorVersion the driver major version
* @param minorVersion the driver minor version
* @param jdbcCompliant whether the driver is JDBC compliant
*/
public InstalledDriver(final String deploymentUnitName, final String driverClassName,
final String dataSourceClassName, final String xaDataSourceClassName,
final int majorVersion, final int minorVersion, final boolean jdbcCompliant) {
this.deploymentUnitName = deploymentUnitName;
this.moduleName = null;
this.driverName = deploymentUnitName;
this.driverClassName = driverClassName;
this.dataSourceClassName = dataSourceClassName;
this.xaDataSourceClassName = xaDataSourceClassName;
this.majorVersion = majorVersion;
this.minorVersion = minorVersion;
this.jdbcCompliant = jdbcCompliant;
}
/**
* Gets the name of the module from which the driver was loaded, if it was
* loaded from the module path.
* @return the module name, or {@code null} if {@link #isFromDeployment()}
* returns {@code true}
*/
public ModuleIdentifier getModuleName() {
return moduleName;
}
/**
* Gets the name of the deployment unit from which the driver was loaded, if
* it was loaded from a deployment.
* @return the deployment unit name, or {@code null} if
* {@link #isFromDeployment()} returns {@code false}
*/
public String getDeploymentUnitName() {
return deploymentUnitName;
}
/**
* Gets the fully qualified class name of the driver's implementation of
* {@link java.sql.Driver}
* @return the class name. Will not be {@code null}
*/
public String getDriverClassName() {
return driverClassName;
}
/**
* Gets the driver's major version number.
* @return the major version number
*/
public int getMajorVersion() {
return majorVersion;
}
/**
* Gets the driver's minor version number.
* @return the minor version number
*/
public int getMinorVersion() {
return minorVersion;
}
/**
* Gets whether the driver is JDBC compliant.
* @return {@code true} if the driver is JDBC compliant; {@code false} if
* not
*/
public boolean isJdbcCompliant() {
return jdbcCompliant;
}
/**
* Gets whether the driver was loaded from a deployment unit.
* @return {@code true} if the driver was loaded from a deployment unit;
* {@code false} if it was loaded from a module on the module path
*/
public boolean isFromDeployment() {
return deploymentUnitName != null;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
InstalledDriver that = (InstalledDriver) o;
if (jdbcCompliant != that.jdbcCompliant) return false;
if (majorVersion != that.majorVersion) return false;
if (minorVersion != that.minorVersion) return false;
if (dataSourceClassName != null ? !dataSourceClassName.equals(that.dataSourceClassName) : that.dataSourceClassName != null)
return false;
if (deploymentUnitName != null ? !deploymentUnitName.equals(that.deploymentUnitName) : that.deploymentUnitName != null)
return false;
if (driverClassName != null ? !driverClassName.equals(that.driverClassName) : that.driverClassName != null)
return false;
if (driverName != null ? !driverName.equals(that.driverName) : that.driverName != null) return false;
if (moduleName != null ? !moduleName.equals(that.moduleName) : that.moduleName != null) return false;
if (xaDataSourceClassName != null ? !xaDataSourceClassName.equals(that.xaDataSourceClassName) : that.xaDataSourceClassName != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = driverName != null ? driverName.hashCode() : 0;
result = 31 * result + (moduleName != null ? moduleName.hashCode() : 0);
result = 31 * result + (deploymentUnitName != null ? deploymentUnitName.hashCode() : 0);
result = 31 * result + (driverClassName != null ? driverClassName.hashCode() : 0);
result = 31 * result + (dataSourceClassName != null ? dataSourceClassName.hashCode() : 0);
result = 31 * result + (xaDataSourceClassName != null ? xaDataSourceClassName.hashCode() : 0);
result = 31 * result + majorVersion;
result = 31 * result + minorVersion;
result = 31 * result + (jdbcCompliant ? 1 : 0);
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (moduleName != null) {
sb.append(moduleName);
} else {
sb.append(deploymentUnitName);
}
sb.append(':');
sb.append(driverClassName);
sb.append('#');
sb.append(majorVersion);
sb.append('#');
sb.append(minorVersion);
return sb.toString();
}
public String getDriverName() {
return driverName;
}
public String getDataSourceClassName() {
return dataSourceClassName;
}
public String getXaDataSourceClassName() {
return xaDataSourceClassName;
}
}
| 9,208 | 38.354701 | 139 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/driver/registry/DriverRegistry.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.services.driver.registry;
import java.util.Set;
import org.jboss.as.connector.services.driver.InstalledDriver;
/**
* A registry for JDBC drivers installed in the system.
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public interface DriverRegistry {
/**
* Register an installed JDBC driver
* @param driver the driver
*/
void registerInstalledDriver(InstalledDriver driver) throws IllegalArgumentException;
/**
* Unregister an installed JDBC driver
* @param driver the driver
*/
void unregisterInstalledDriver(InstalledDriver driver);
/**
* Get the installed drivers
* @return The set of drivers
*/
Set<InstalledDriver> getInstalledDrivers();
InstalledDriver getInstalledDriver(String name);
}
| 1,836 | 33.018519 | 89 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/driver/registry/DriverRegistryService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.services.driver.registry;
import static org.jboss.as.connector.logging.ConnectorLogger.DEPLOYMENT_CONNECTOR_REGISTRY_LOGGER;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* The JDBC driver registry service
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public final class DriverRegistryService implements Service<DriverRegistry> {
private final DriverRegistry value;
/**
* Create an instance
*/
public DriverRegistryService() {
this.value = new DriverRegistryImpl();
}
@Override
public DriverRegistry getValue() throws IllegalStateException {
return ConnectorServices.notNull(value);
}
@Override
public void start(StartContext context) throws StartException {
DEPLOYMENT_CONNECTOR_REGISTRY_LOGGER.debugf("Starting service %s", ConnectorServices.JDBC_DRIVER_REGISTRY_SERVICE);
}
@Override
public void stop(StopContext context) {
DEPLOYMENT_CONNECTOR_REGISTRY_LOGGER.debugf("Stopping service %s", ConnectorServices.JDBC_DRIVER_REGISTRY_SERVICE);
}
}
| 2,296 | 34.890625 | 123 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/driver/registry/DriverRegistryImpl.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.services.driver.registry;
import static org.jboss.as.connector.logging.ConnectorLogger.DEPLOYMENT_CONNECTOR_REGISTRY_LOGGER;
import static org.wildfly.common.Assert.checkNotNullParam;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.jboss.as.connector.services.driver.InstalledDriver;
/**
* Standard {@link DriverRegistry} implementation.
* @author Brian Stansberry (c) 2011 Red Hat Inc.
* @author <a href="mailto:[email protected]">James R. Perkins</a>
*/
public class DriverRegistryImpl implements DriverRegistry {
private final Map<String, InstalledDriver> drivers = Collections.synchronizedMap(new HashMap<>());
@Override
public void registerInstalledDriver(InstalledDriver driver) throws IllegalArgumentException {
checkNotNullParam("driver", driver);
DEPLOYMENT_CONNECTOR_REGISTRY_LOGGER.tracef("Adding driver: %s", driver);
drivers.put(driver.getDriverName(), driver);
}
@Override
public void unregisterInstalledDriver(InstalledDriver driver) {
checkNotNullParam("driver", driver);
DEPLOYMENT_CONNECTOR_REGISTRY_LOGGER.tracef("Removing deployment: %s", driver);
drivers.remove(driver.getDriverName());
}
@Override
public Set<InstalledDriver> getInstalledDrivers() {
synchronized (drivers) {
return Collections.unmodifiableSet(new HashSet<>(drivers.values()));
}
}
@Override
public InstalledDriver getInstalledDriver(String name) throws IllegalStateException {
return drivers.get(name);
}
}
| 2,693 | 35.90411 | 102 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/jca/CachedConnectionManagerService.java | /*
* 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.services.jca;
import static org.jboss.as.connector.logging.ConnectorLogger.ROOT_LOGGER;
import org.jboss.jca.core.api.connectionmanager.ccm.CachedConnectionManager;
import org.jboss.jca.core.connectionmanager.ccm.CachedConnectionManagerImpl;
import org.jboss.jca.core.spi.transaction.TransactionIntegration;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
/**
* Cached connection manager service
*/
public class CachedConnectionManagerService implements Service<CachedConnectionManager> {
public static final ServiceName SERVICE_NAME_BASE = ServiceName.JBOSS.append("connector", "ccm");
private final InjectedValue<TransactionIntegration> transactionIntegration = new InjectedValue<TransactionIntegration>();
private volatile CachedConnectionManager value;
private final boolean debug;
private final boolean error;
private final boolean ignoreUnknownConnections;
/** create an instance **/
public CachedConnectionManagerService(final boolean debug, final boolean error, boolean ignoreUnknownConnections) {
super();
this.debug = debug;
this.error = error;
this.ignoreUnknownConnections = ignoreUnknownConnections;
}
@Override
public CachedConnectionManager getValue() throws IllegalStateException, IllegalArgumentException {
return value;
}
@Override
public void start(StartContext context) throws StartException {
value = new CachedConnectionManagerImpl(transactionIntegration.getValue());
value.setDebug(debug);
value.setError(error);
value.setIgnoreUnknownConnections(ignoreUnknownConnections);
value.start();
ROOT_LOGGER.debugf("Started CcmService %s", context.getController().getName());
}
@Override
public void stop(StopContext context) {
value.stop();
ROOT_LOGGER.debugf("Stopped CcmService %s", context.getController().getName());
}
public Injector<TransactionIntegration> getTransactionIntegrationInjector() {
return transactionIntegration;
}
}
| 3,357 | 37.597701 | 125 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/jca/NonTxCachedConnectionManagerService.java | /*
* 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.services.jca;
import static org.jboss.as.connector.logging.ConnectorLogger.ROOT_LOGGER;
import jakarta.resource.spi.ActivationSpec;
import jakarta.resource.spi.ManagedConnection;
import jakarta.resource.spi.ManagedConnectionFactory;
import jakarta.resource.spi.ResourceAdapter;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import jakarta.transaction.TransactionSynchronizationRegistry;
import javax.transaction.xa.XAResource;
import org.jboss.jca.core.api.connectionmanager.ConnectionManager;
import org.jboss.jca.core.api.connectionmanager.ccm.CachedConnectionManager;
import org.jboss.jca.core.connectionmanager.ccm.CachedConnectionManagerImpl;
import org.jboss.jca.core.spi.recovery.RecoveryPlugin;
import org.jboss.jca.core.spi.security.SubjectFactory;
import org.jboss.jca.core.spi.transaction.ConnectableResource;
import org.jboss.jca.core.spi.transaction.TransactionIntegration;
import org.jboss.jca.core.spi.transaction.XAResourceStatistics;
import org.jboss.jca.core.spi.transaction.local.LocalXAResource;
import org.jboss.jca.core.spi.transaction.recovery.XAResourceRecovery;
import org.jboss.jca.core.spi.transaction.recovery.XAResourceRecoveryRegistry;
import org.jboss.jca.core.spi.transaction.usertx.UserTransactionRegistry;
import org.jboss.jca.core.spi.transaction.xa.XAResourceWrapper;
import org.jboss.jca.core.spi.transaction.xa.XATerminator;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* Cached connection manager service
*/
public class NonTxCachedConnectionManagerService implements Service<CachedConnectionManager> {
private volatile CachedConnectionManager value;
private final boolean debug;
private final boolean error;
private final boolean ignoreUnknownConnections;
/** create an instance **/
public NonTxCachedConnectionManagerService(final boolean debug, final boolean error, boolean ignoreUnknownConnections) {
super();
this.debug = debug;
this.error = error;
this.ignoreUnknownConnections = ignoreUnknownConnections;
}
@Override
public CachedConnectionManager getValue() throws IllegalStateException, IllegalArgumentException {
return value;
}
@Override
public void start(StartContext context) throws StartException {
value = new CachedConnectionManagerImpl(new NoopTransactionIntegration());
value.setDebug(debug);
value.setError(error);
value.setIgnoreUnknownConnections(ignoreUnknownConnections);
value.start();
ROOT_LOGGER.debugf("Started CcmService %s", context.getController().getName());
}
@Override
public void stop(StopContext context) {
value.stop();
ROOT_LOGGER.debugf("Stopped CcmService %s", context.getController().getName());
}
/** No operation transaction integration */
private static class NoopTransactionIntegration implements TransactionIntegration {
@Override
public TransactionManager getTransactionManager() {
return null;
}
@Override
public TransactionSynchronizationRegistry getTransactionSynchronizationRegistry() {
return null;
}
@Override
public UserTransactionRegistry getUserTransactionRegistry() {
return null;
}
@Override
public XAResourceRecoveryRegistry getRecoveryRegistry() {
return null;
}
@Override
public XATerminator getXATerminator() {
return null;
}
@Override
public XAResourceRecovery createXAResourceRecovery(ResourceAdapter rar, ActivationSpec as, String productName,
String productVersion) {
throw ROOT_LOGGER.noSupportedOperation("createXAResourceRecovery");
}
@Override
public XAResourceRecovery createXAResourceRecovery(ManagedConnectionFactory mcf, Boolean pad, Boolean override,
Boolean wrapXAResource, String recoverUserName, String recoverPassword, String recoverSecurityDomain,
SubjectFactory subjectFactory, RecoveryPlugin plugin, XAResourceStatistics xastat) {
throw ROOT_LOGGER.noSupportedOperation("createXAResourceRecovery-Security");
}
@Override
public LocalXAResource createLocalXAResource(ConnectionManager cm, String productName, String productVersion,
String jndiName, XAResourceStatistics xastat) {
throw ROOT_LOGGER.noSupportedOperation("createLocalXAResource");
}
@Override
public LocalXAResource createConnectableLocalXAResource(ConnectionManager cm, String productName,
String productVersion, String jndiName, ConnectableResource cr, XAResourceStatistics xastat) {
throw ROOT_LOGGER.noSupportedOperation("createConnectableLocalXAResource");
}
@Override
public LocalXAResource createConnectableLocalXAResource(ConnectionManager cm, String productName,
String productVersion, String jndiName, ManagedConnection mc, XAResourceStatistics xastat) {
return null;
}
@Override
public XAResourceWrapper createXAResourceWrapper(XAResource xares, boolean pad, Boolean override, String productName,
String productVersion, String jndiName, boolean firstResource, XAResourceStatistics xastat) {
throw ROOT_LOGGER.noSupportedOperation("createXAResourceWrapper");
}
@Override
public XAResourceWrapper createConnectableXAResourceWrapper(XAResource xares, boolean pad, Boolean override,
String productName, String productVersion, String jndiName, ConnectableResource cr, XAResourceStatistics xastat) {
throw ROOT_LOGGER.noSupportedOperation("createConnectableXAResourceWrapper");
}
@Override
public XAResourceWrapper createConnectableXAResourceWrapper(XAResource xares, boolean pad, Boolean override,
String productName, String productVersion, String jndiName, ManagedConnection mc, XAResourceStatistics xastat) {
throw ROOT_LOGGER.noSupportedOperation("createConnectableXAResourceWrapper");
}
@Override
public boolean isFirstResource(ManagedConnection mc) {
throw ROOT_LOGGER.noSupportedOperation("isFirstResource");
}
@Override
public boolean isConnectableResource(ManagedConnection mc) {
throw ROOT_LOGGER.noSupportedOperation("isConnectableResource");
}
@Override
public Object getIdentifier(Transaction tx) {
throw ROOT_LOGGER.noSupportedOperation("getIdentifier");
}
}
}
| 7,916 | 40.668421 | 130 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/datasources/statistics/DataSourceStatisticsService.java | /*
* 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.services.datasources.statistics;
import static org.jboss.as.connector.logging.ConnectorLogger.ROOT_LOGGER;
import org.jboss.as.connector.dynamicresource.StatisticsResourceDefinition;
import org.jboss.as.connector.subsystems.datasources.DataSourcesSubsystemProviders;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.PlaceholderResource;
import org.jboss.as.controller.registry.Resource;
import org.jboss.jca.core.spi.statistics.StatisticsPlugin;
import org.jboss.jca.deployers.common.CommonDeployment;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
public class DataSourceStatisticsService implements Service<ManagementResourceRegistration> {
private static final PathElement JDBC_STATISTICS = PathElement.pathElement("statistics", "jdbc");
private static final PathElement POOL_STATISTICS = PathElement.pathElement("statistics", "pool");
private final ManagementResourceRegistration registration;
private final boolean statsEnabled;
protected final InjectedValue<CommonDeployment> injectedDeploymentMD = new InjectedValue<>();
/**
* create an instance *
*/
public DataSourceStatisticsService(final ManagementResourceRegistration registration,
final boolean statsEnabled) {
super();
this.registration = registration;
this.statsEnabled = statsEnabled;
}
@Override
public void start(StartContext context) throws StartException {
ROOT_LOGGER.debugf("Starting DataSourceStatisticsService");
synchronized (JDBC_STATISTICS) {
CommonDeployment deploymentMD = injectedDeploymentMD.getValue();
StatisticsPlugin jdbcStats = deploymentMD.getDataSources()[0].getStatistics();
StatisticsPlugin poolStats = deploymentMD.getDataSources()[0].getPool().getStatistics();
jdbcStats.setEnabled(statsEnabled);
poolStats.setEnabled(statsEnabled);
int jdbcStatsSize = jdbcStats.getNames().size();
int poolStatsSize = poolStats.getNames().size();
if ((jdbcStatsSize > 0 || poolStatsSize > 0) && registration != null) {
if (jdbcStatsSize > 0 && registration.getSubModel(PathAddress.pathAddress(JDBC_STATISTICS)) == null) {
ManagementResourceRegistration jdbcRegistration = registration
.registerSubModel(new StatisticsResourceDefinition(JDBC_STATISTICS,
DataSourcesSubsystemProviders.RESOURCE_NAME, jdbcStats));
}
if (poolStatsSize > 0 && registration.getSubModel(PathAddress.pathAddress(POOL_STATISTICS)) == null) {
ManagementResourceRegistration poolRegistration = registration
.registerSubModel(new StatisticsResourceDefinition(POOL_STATISTICS,
DataSourcesSubsystemProviders.RESOURCE_NAME, poolStats));
}
}
}
}
@Override
public void stop(StopContext context) {
synchronized (JDBC_STATISTICS) {
if (registration != null) {
registration.unregisterSubModel(JDBC_STATISTICS);
registration.unregisterSubModel(POOL_STATISTICS);
}
}
}
@Override
public ManagementResourceRegistration getValue() throws IllegalStateException, IllegalArgumentException {
return registration;
}
public Injector<CommonDeployment> getCommonDeploymentInjector() {
return injectedDeploymentMD;
}
public static void registerStatisticsResources(Resource datasourceResource) {
synchronized (JDBC_STATISTICS) {
if (!datasourceResource.hasChild(JDBC_STATISTICS)) {
datasourceResource.registerChild(JDBC_STATISTICS, new PlaceholderResource.PlaceholderResourceEntry(JDBC_STATISTICS));
}
if (!datasourceResource.hasChild(POOL_STATISTICS)) {
datasourceResource.registerChild(POOL_STATISTICS, new PlaceholderResource.PlaceholderResourceEntry(POOL_STATISTICS));
}
}
}
public static void removeStatisticsResources(Resource datasourceResource) {
synchronized (JDBC_STATISTICS) {
if (datasourceResource.hasChild(JDBC_STATISTICS)) {
datasourceResource.removeChild(JDBC_STATISTICS);
}
if (datasourceResource.hasChild(POOL_STATISTICS)) {
datasourceResource.removeChild(POOL_STATISTICS);
}
}
}
}
| 5,965 | 41.014085 | 133 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/dwm/PolicyService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.services.dwm;
import org.jboss.jca.core.spi.workmanager.policy.Policy;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* Connection validator service
* @author <a href="mailto:[email protected]">Jesper Pedersen</a>
*/
final class PolicyService implements Service<Policy> {
private final Policy policy;
/**
* Constructor
*/
public PolicyService(Policy policy) {
this.policy = policy;
}
@Override
public Policy getValue() throws IllegalStateException {
return policy;
}
@Override
public void start(StartContext context) throws StartException {
}
@Override
public void stop(StopContext context) {
}
}
| 1,875 | 30.266667 | 73 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/rarepository/NonJTADataSourceRaRepositoryService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.services.rarepository;
import static org.jboss.as.connector.logging.ConnectorLogger.MDR_LOGGER;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.jca.core.rar.SimpleResourceAdapterRepository;
import org.jboss.jca.core.spi.mdr.MetadataRepository;
import org.jboss.jca.core.spi.rar.ResourceAdapterRepository;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
/**
* A MdrService. it provide access to IronJacamar's metadata repository
* @author <a href="mailto:[email protected]">Stefano Maestri</a>
*/
public final class NonJTADataSourceRaRepositoryService implements Service<ResourceAdapterRepository> {
private final ResourceAdapterRepository value;
private final InjectedValue<MetadataRepository> mdrValue = new InjectedValue<MetadataRepository>();
/**
* Create instance
*/
public NonJTADataSourceRaRepositoryService() {
this.value = new SimpleResourceAdapterRepository();
}
@Override
public ResourceAdapterRepository getValue() {
return ConnectorServices.notNull(value);
}
@Override
public void start(StartContext context) throws StartException {
((SimpleResourceAdapterRepository) value).setMetadataRepository(mdrValue.getValue());
MDR_LOGGER.debugf("Starting service NonJTADataSourceRaRepositoryService");
}
@Override
public void stop(StopContext context) {
}
public Injector<MetadataRepository> getMdrInjector() {
return mdrValue;
}
}
| 2,753 | 34.766234 | 103 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/rarepository/RaRepositoryService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.services.rarepository;
import static org.jboss.as.connector.logging.ConnectorLogger.MDR_LOGGER;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.jca.core.rar.SimpleResourceAdapterRepository;
import org.jboss.jca.core.spi.mdr.MetadataRepository;
import org.jboss.jca.core.spi.rar.ResourceAdapterRepository;
import org.jboss.jca.core.spi.transaction.TransactionIntegration;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
/**
* A MdrService. it provide access to IronJacamar's metadata repository
* @author <a href="mailto:[email protected]">Stefano Maestri</a>
*/
public final class RaRepositoryService implements Service<ResourceAdapterRepository> {
private final ResourceAdapterRepository value;
private final InjectedValue<MetadataRepository> mdrValue = new InjectedValue<MetadataRepository>();
private final InjectedValue<TransactionIntegration> tiValue = new InjectedValue<TransactionIntegration>();
/**
* Create instance
*/
public RaRepositoryService() {
this.value = new SimpleResourceAdapterRepository();
}
@Override
public ResourceAdapterRepository getValue() {
return ConnectorServices.notNull(value);
}
@Override
public void start(StartContext context) throws StartException {
((SimpleResourceAdapterRepository) value).setMetadataRepository(mdrValue.getValue());
((SimpleResourceAdapterRepository) value).setTransactionIntegration(tiValue.getValue());
MDR_LOGGER.debugf("Starting service RaRepositoryService");
}
@Override
public void stop(StopContext context) {
}
public Injector<MetadataRepository> getMdrInjector() {
return mdrValue;
}
public Injector<TransactionIntegration> getTransactionIntegrationInjector() {
return tiValue;
}
}
| 3,092 | 35.821429 | 110 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/mdr/AS7MetadataRepository.java | /*
* 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.services.mdr;
import java.util.Set;
import org.jboss.jca.common.api.metadata.resourceadapter.Activation;
import org.jboss.jca.core.spi.mdr.MetadataRepository;
/**
* AS7's extension of MetadataRepository
*
* @author Stefano Maestri (c) 2011 Red Hat Inc.
*/
public interface AS7MetadataRepository extends MetadataRepository {
Activation getIronJacamarMetaData(String uniqueId);
Set<String> getResourceAdaptersWithIronJacamarMetadata();
}
| 1,509 | 34.952381 | 70 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/mdr/MdrService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.services.mdr;
import static org.jboss.as.connector.logging.ConnectorLogger.MDR_LOGGER;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* A MdrService. it provide access to IronJacamar's metadata repository
* @author <a href="mailto:[email protected]">Stefano Maestri</a>
*/
public final class MdrService implements Service<AS7MetadataRepository> {
private final AS7MetadataRepository value;
/**
* Create instance
*/
public MdrService() {
this.value = new AS7MetadataRepositoryImpl();
}
@Override
public AS7MetadataRepository getValue() throws IllegalStateException {
return ConnectorServices.notNull(value);
}
@Override
public void start(StartContext context) throws StartException {
MDR_LOGGER.debugf("Starting service MDR");
}
@Override
public void stop(StopContext context) {
}
}
| 2,124 | 32.203125 | 74 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/mdr/AS7MetadataRepositoryImpl.java | /*
* 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.services.mdr;
import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.jboss.jca.common.api.metadata.resourceadapter.Activation;
import org.jboss.jca.common.api.metadata.spec.Connector;
import org.jboss.jca.core.mdr.SimpleMetadataRepository;
import org.jboss.jca.core.spi.mdr.AlreadyExistsException;
import org.jboss.jca.core.spi.mdr.NotFoundException;
/**
* An AS7' implementation of MetadataRepository
*
* @author Stefano Maestri (c) 2011 Red Hat Inc.
*/
public class AS7MetadataRepositoryImpl extends SimpleMetadataRepository implements AS7MetadataRepository {
private final ConcurrentMap<String, Activation> ironJacamarMetaData = new ConcurrentHashMap<>();
/**
* Constructor
*/
public AS7MetadataRepositoryImpl() {
}
@Override
public synchronized void registerResourceAdapter(String uniqueId, File root, Connector md, Activation activation)
throws AlreadyExistsException {
super.registerResourceAdapter(uniqueId, root, md, activation);
if (activation != null) {
ironJacamarMetaData.put(uniqueId, activation);
}
}
@Override
public synchronized void unregisterResourceAdapter(String uniqueId) throws NotFoundException {
super.unregisterResourceAdapter(uniqueId);
ironJacamarMetaData.remove(uniqueId);
}
@Override
public synchronized boolean hasResourceAdapter(String uniqueId) {
return super.hasResourceAdapter(uniqueId);
}
@Override
public synchronized Connector getResourceAdapter(String uniqueId) throws NotFoundException {
return super.getResourceAdapter(uniqueId);
}
@Override
public synchronized Set<String> getResourceAdapters() {
return super.getResourceAdapters();
}
@Override
public synchronized File getRoot(String uniqueId) throws NotFoundException {
return super.getRoot(uniqueId);
}
@Override
public synchronized Activation getActivation(String uniqueId) throws NotFoundException {
return super.getActivation(uniqueId);
}
@Override
public synchronized void registerJndiMapping(String uniqueId, String clz, String jndi) {
super.registerJndiMapping(uniqueId, clz, jndi);
}
@Override
public synchronized void unregisterJndiMapping(String uniqueId, String clz, String jndi) throws NotFoundException {
super.unregisterJndiMapping(uniqueId, clz, jndi);
}
@Override
public synchronized boolean hasJndiMappings(String uniqueId) {
return super.hasJndiMappings(uniqueId);
}
@Override
public synchronized Map<String, List<String>> getJndiMappings(String uniqueId) throws NotFoundException {
return super.getJndiMappings(uniqueId);
}
@Override
public synchronized Activation getIronJacamarMetaData(String uniqueId) {
return ironJacamarMetaData.get(uniqueId);
}
@Override
public synchronized Set<String> getResourceAdaptersWithIronJacamarMetadata() {
return Collections.unmodifiableSet(ironJacamarMetaData.keySet());
}
}
| 4,293 | 33.629032 | 119 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/WorkManagerService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.services.workmanager;
import static org.jboss.as.connector.logging.ConnectorLogger.ROOT_LOGGER;
import static org.jboss.as.connector.subsystems.jca.Constants.DEFAULT_NAME;
import java.util.concurrent.Executor;
import org.jboss.as.connector.security.ElytronSecurityIntegration;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.as.txn.integration.JBossContextXATerminator;
import org.jboss.jca.core.tx.jbossts.XATerminatorImpl;
import org.jboss.jca.core.workmanager.WorkManagerCoordinator;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.jboss.threads.BlockingExecutor;
/**
* A WorkManager Service.
*
* @author <a href="mailto:[email protected]">Stefano Maestri</a>
* @author <a href="mailto:[email protected]">Jesper Pedersen</a>
*/
public final class WorkManagerService implements Service<NamedWorkManager> {
private final NamedWorkManager value;
private final InjectedValue<Executor> executorShort = new InjectedValue<Executor>();
private final InjectedValue<Executor> executorLong = new InjectedValue<Executor>();
private final InjectedValue<JBossContextXATerminator> xaTerminator = new InjectedValue<JBossContextXATerminator>();
/**
* create an instance
*
* @param value the work manager
*/
public WorkManagerService(NamedWorkManager value) {
super();
ROOT_LOGGER.debugf("Building WorkManager");
this.value = value;
}
@Override
public NamedWorkManager getValue() throws IllegalStateException {
return ConnectorServices.notNull(value);
}
@Override
public void start(StartContext context) throws StartException {
ROOT_LOGGER.debugf("Starting Jakarta Connectors WorkManager: ", value.getName());
BlockingExecutor longRunning = (BlockingExecutor) executorLong.getOptionalValue();
if (longRunning != null) {
this.value.setLongRunningThreadPool(longRunning);
this.value.setShortRunningThreadPool(new StatisticsExecutorImpl((BlockingExecutor) executorShort.getValue()));
} else {
this.value.setLongRunningThreadPool(new StatisticsExecutorImpl((BlockingExecutor) executorShort.getValue()));
this.value.setShortRunningThreadPool(new StatisticsExecutorImpl((BlockingExecutor) executorShort.getValue()));
}
this.value.setXATerminator(new XATerminatorImpl(xaTerminator.getValue()));
if (value.getName().equals(DEFAULT_NAME)) {
WorkManagerCoordinator.getInstance().setDefaultWorkManager(value);
} else {
WorkManagerCoordinator.getInstance().registerWorkManager(value);
}
//this is a value.restart() equivalent
if (value.isShutdown())
value.cancelShutdown();
this.value.setSecurityIntegration(new ElytronSecurityIntegration());
ROOT_LOGGER.debugf("Started Jakarta Connectors WorkManager: ", value.getName());
}
@Override
public void stop(StopContext context) {
ROOT_LOGGER.debugf("Stopping Jakarta Connectors WorkManager: ", value.getName());
//shutting down immediately (synchronous method) the workmanager and release all works
value.shutdown();
if (value.getName().equals(DEFAULT_NAME)) {
WorkManagerCoordinator.getInstance().setDefaultWorkManager(null);
} else {
WorkManagerCoordinator.getInstance().unregisterWorkManager(value);
}
ROOT_LOGGER.debugf("Stopped Jakarta Connectors WorkManager: ", value.getName());
}
public Injector<Executor> getExecutorShortInjector() {
return executorShort;
}
public Injector<Executor> getExecutorLongInjector() {
return executorLong;
}
public Injector<JBossContextXATerminator> getXaTerminatorInjector() {
return xaTerminator;
}
}
| 5,126 | 37.261194 | 122 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/DistributedWorkManagerService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.services.workmanager;
import static org.jboss.as.connector.logging.ConnectorLogger.ROOT_LOGGER;
import java.util.concurrent.Executor;
import org.jboss.as.connector.security.ElytronSecurityIntegration;
import org.jboss.as.connector.services.workmanager.transport.CommandDispatcherTransport;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.as.txn.integration.JBossContextXATerminator;
import org.jboss.jca.core.spi.workmanager.Address;
import org.jboss.jca.core.tx.jbossts.XATerminatorImpl;
import org.jboss.jca.core.workmanager.WorkManagerCoordinator;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.jboss.threads.BlockingExecutor;
import org.wildfly.clustering.server.dispatcher.CommandDispatcherFactory;
/**
* A WorkManager Service.
*
* @author <a href="mailto:[email protected]">Stefano Maestri</a>
* @author <a href="mailto:[email protected]">Jesper Pedersen</a>
*/
public final class DistributedWorkManagerService implements Service<NamedDistributedWorkManager> {
private final NamedDistributedWorkManager value;
private final InjectedValue<Executor> executorShort = new InjectedValue<Executor>();
private final InjectedValue<Executor> executorLong = new InjectedValue<Executor>();
private final InjectedValue<JBossContextXATerminator> xaTerminator = new InjectedValue<JBossContextXATerminator>();
private final InjectedValue<CommandDispatcherFactory> dispatcherFactory = new InjectedValue<>();
/**
* create an instance
*
* @param value the work manager
*/
public DistributedWorkManagerService(NamedDistributedWorkManager value) {
super();
ROOT_LOGGER.debugf("Building DistributedWorkManager");
this.value = value;
}
@Override
public NamedDistributedWorkManager getValue() throws IllegalStateException {
return ConnectorServices.notNull(value);
}
@Override
public void start(StartContext context) throws StartException {
ROOT_LOGGER.debugf("Starting Jakarta Connectors DistributedWorkManager: ", value.getName());
CommandDispatcherTransport transport = new CommandDispatcherTransport(this.dispatcherFactory.getValue(), this.value.getName());
this.value.setTransport(transport);
BlockingExecutor longRunning = (BlockingExecutor) executorLong.getOptionalValue();
if (longRunning != null) {
this.value.setLongRunningThreadPool(longRunning);
this.value.setShortRunningThreadPool(new StatisticsExecutorImpl((BlockingExecutor) executorShort.getValue()));
} else {
this.value.setLongRunningThreadPool(new StatisticsExecutorImpl((BlockingExecutor) executorShort.getValue()));
this.value.setShortRunningThreadPool(new StatisticsExecutorImpl((BlockingExecutor) executorShort.getValue()));
}
this.value.setXATerminator(new XATerminatorImpl(xaTerminator.getValue()));
this.value.setSecurityIntegration(new ElytronSecurityIntegration());
try {
transport.startup();
} catch (Throwable throwable) {
ROOT_LOGGER.trace("failed to start DWM transport:", throwable);
throw ROOT_LOGGER.failedToStartDWMTransport(this.value.getName());
}
transport.register(new Address(value.getId(), value.getName(), transport.getId()));
WorkManagerCoordinator.getInstance().registerWorkManager(value);
ROOT_LOGGER.debugf("Started Jakarta Connectors DistributedWorkManager: ", value.getName());
}
@Override
public void stop(StopContext context) {
ROOT_LOGGER.debugf("Stopping Jakarta Connectors DistributedWorkManager: ", value.getName());
value.prepareShutdown();
try {
value.getTransport().shutdown();
} catch (Throwable throwable) {
ROOT_LOGGER.trace("failed to stop DWM transport:", throwable);
}
value.shutdown();
WorkManagerCoordinator.getInstance().unregisterWorkManager(value);
ROOT_LOGGER.debugf("Stopped Jakarta Connectors DistributedWorkManager: ", value.getName());
}
public Injector<Executor> getExecutorShortInjector() {
return executorShort;
}
public Injector<Executor> getExecutorLongInjector() {
return executorLong;
}
public Injector<JBossContextXATerminator> getXaTerminatorInjector() {
return xaTerminator;
}
public Injector<CommandDispatcherFactory> getCommandDispatcherFactoryInjector() {
return this.dispatcherFactory;
}
}
| 5,833 | 37.635762 | 135 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/WildflyWorkWrapper.java | /*
* Copyright 2017 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.connector.services.workmanager;
import java.util.concurrent.CountDownLatch;
import jakarta.resource.spi.work.ExecutionContext;
import jakarta.resource.spi.work.Work;
import jakarta.resource.spi.work.WorkCompletedException;
import jakarta.resource.spi.work.WorkListener;
import org.jboss.as.connector.security.ElytronSecurityContext;
import org.jboss.as.connector.logging.ConnectorLogger;
import org.jboss.jca.core.spi.security.SecurityIntegration;
import org.jboss.jca.core.workmanager.WorkManagerImpl;
/**
* Extension of WildflyWorkWrapper with added Elytron support.
*
* @author Flavia Rainone
*/
public class WildflyWorkWrapper extends org.jboss.jca.core.workmanager.WorkWrapper {
/**
* Create a new WildflyWorkWrapper
*
* @param workManager the work manager
* @param si The security integration
* @param work the work
* @param executionContext the execution context
* @param workListener the WorkListener
* @param startedLatch The latch for when work has started
* @param completedLatch The latch for when work has completed
* @param startTime The start time
* @throws IllegalArgumentException for null work, execution context or a negative start timeout
*/
WildflyWorkWrapper(WorkManagerImpl workManager, SecurityIntegration si, Work work, ExecutionContext executionContext,
WorkListener workListener, CountDownLatch startedLatch, CountDownLatch completedLatch, long startTime) {
super(workManager, si, work, executionContext, workListener, startedLatch, completedLatch, startTime);
}
@Override
protected void runWork() throws WorkCompletedException {
if (securityIntegration.getSecurityContext() != null)
((ElytronSecurityContext) securityIntegration.getSecurityContext()).runWork(() -> {
try {
WildflyWorkWrapper.super.runWork();
} catch (WorkCompletedException e) {
ConnectorLogger.ROOT_LOGGER.unexceptedWorkerCompletionError(e.getLocalizedMessage(),e);
}
});
else super.runWork();
}
}
| 2,799 | 40.791045 | 121 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/NamedWorkManager.java | /*
* 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.services.workmanager;
import jakarta.resource.spi.work.ExecutionContext;
import jakarta.resource.spi.work.Work;
import jakarta.resource.spi.work.WorkListener;
import java.util.concurrent.CountDownLatch;
import org.jboss.jca.core.spi.security.SecurityIntegration;
import org.jboss.jca.core.workmanager.WorkManagerImpl;
/**
* A named WorkManager.
* @author <a href="mailto:[email protected]">Jesper Pedersen</a>
* @author Flavia Rainone
*/
public class NamedWorkManager extends WorkManagerImpl {
/** Default WorkManager name */
public static final String DEFAULT_NAME = "default";
/**
* Constructor
* @param name The name of the WorkManager
*/
public NamedWorkManager(String name) {
super();
setName(name);
}
@Override
protected WildflyWorkWrapper createWorkWrapper(SecurityIntegration securityIntegration, Work work,
ExecutionContext executionContext, WorkListener workListener, CountDownLatch startedLatch,
CountDownLatch completedLatch) {
return new WildflyWorkWrapper(this, securityIntegration, work, executionContext, workListener,
startedLatch, completedLatch, System.currentTimeMillis());
}
}
| 2,346 | 38.116667 | 134 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/StatisticsExecutorImpl.java | /*
* IronJacamar, a Jakarta EE Connector Architecture implementation
* Copyright 2010, 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.services.workmanager;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import org.jboss.as.threads.ManagedJBossThreadPoolExecutorService;
import org.jboss.as.threads.ManagedQueueExecutorService;
import org.jboss.as.threads.ManagedQueuelessExecutorService;
import org.jboss.as.threads.ManagedScheduledExecutorService;
import org.jboss.jca.core.CoreLogger;
import org.jboss.jca.core.api.workmanager.StatisticsExecutor;
import org.jboss.logging.Logger;
import org.jboss.threads.BlockingExecutor;
import org.jboss.threads.JBossThreadPoolExecutor;
import org.jboss.threads.management.ThreadPoolExecutorMBean;
/**
* A StatisticsExecutor implementation keeping track of numberOfFreeThreads
*
* @author Stefano Maestri
*/
public class StatisticsExecutorImpl implements StatisticsExecutor {
/**
* The logger
*/
private static CoreLogger log = Logger.getMessageLogger(CoreLogger.class,
org.jboss.jca.core.workmanager.StatisticsExecutorImpl.class.getName());
private final BlockingExecutor realExecutor;
/**
* StatisticsExecutorImpl constructor
*
* @param realExecutor the real executor we are delegating
*/
public StatisticsExecutorImpl(BlockingExecutor realExecutor) {
this.realExecutor = realExecutor;
}
@Override
public void execute(Runnable runnable) {
realExecutor.execute(runnable);
}
@Override
public void executeBlocking(Runnable runnable) throws RejectedExecutionException, InterruptedException {
realExecutor.executeBlocking(runnable);
}
@Override
public void executeBlocking(Runnable runnable, long l, TimeUnit timeUnit) throws RejectedExecutionException,
InterruptedException {
realExecutor.executeBlocking(runnable, l, timeUnit);
}
@Override
public void executeNonBlocking(Runnable runnable) throws RejectedExecutionException {
realExecutor.executeNonBlocking(runnable);
}
@Override
public long getNumberOfFreeThreads() {
if (realExecutor instanceof JBossThreadPoolExecutor) {
return (long) ((JBossThreadPoolExecutor) realExecutor).getMaximumPoolSize()
- ((JBossThreadPoolExecutor) realExecutor).getActiveCount();
}
if (realExecutor instanceof ThreadPoolExecutorMBean) {
return (long) ((ThreadPoolExecutorMBean) realExecutor).getMaxThreads()
- ((ThreadPoolExecutorMBean) realExecutor).getCurrentThreadCount();
}
if (realExecutor instanceof ManagedQueueExecutorService) {
return (long) ((ManagedQueueExecutorService) realExecutor).getMaxThreads()
- ((ManagedQueueExecutorService) realExecutor).getCurrentThreadCount();
}
if (realExecutor instanceof ManagedJBossThreadPoolExecutorService) {
return (long) ((ManagedJBossThreadPoolExecutorService) realExecutor).getMaxThreads()
- ((ManagedJBossThreadPoolExecutorService) realExecutor).getCurrentThreadCount();
}
if (realExecutor instanceof ManagedQueuelessExecutorService) {
return (long) ((ManagedQueuelessExecutorService) realExecutor).getMaxThreads()
- ((ManagedQueuelessExecutorService) realExecutor).getCurrentThreadCount();
}
if (realExecutor instanceof ManagedScheduledExecutorService) {
return (long) ((ManagedScheduledExecutorService) realExecutor).getLargestPoolSize()
- ((ManagedScheduledExecutorService) realExecutor).getActiveCount();
}
return 0L;
}
}
| 4,725 | 40.45614 | 112 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/NamedDistributedWorkManager.java | /*
* 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.services.workmanager;
import jakarta.resource.spi.work.ExecutionContext;
import jakarta.resource.spi.work.Work;
import jakarta.resource.spi.work.WorkListener;
import java.util.concurrent.CountDownLatch;
import org.jboss.jca.core.spi.security.SecurityIntegration;
import org.jboss.jca.core.workmanager.DistributedWorkManagerImpl;
/**
* A named WorkManager.
* @author <a href="mailto:[email protected]">Jesper Pedersen</a>
*/
public class NamedDistributedWorkManager extends DistributedWorkManagerImpl {
private final boolean elytronEnabled;
/**
* Constructor
* @param name The name of the WorkManager
*/
public NamedDistributedWorkManager(String name, final boolean elytronEnabled) {
super();
setName(name);
this.elytronEnabled = elytronEnabled;
}
protected WildflyWorkWrapper createWorKWrapper(SecurityIntegration securityIntegration, Work work,
ExecutionContext executionContext, WorkListener workListener, CountDownLatch startedLatch,
CountDownLatch completedLatch) {
return new WildflyWorkWrapper(this, securityIntegration, work, executionContext, workListener,
startedLatch, completedLatch, System.currentTimeMillis());
}
public boolean isElytronEnabled() {
return elytronEnabled;
}
}
| 2,466 | 39.442623 | 141 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/statistics/DistributedWorkManagerStatisticsService.java | /*
* 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.services.workmanager.statistics;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import org.jboss.as.connector.dynamicresource.ClearWorkManagerStatisticsHandler;
import org.jboss.as.connector.subsystems.resourceadapters.CommonAttributes;
import org.jboss.as.connector.subsystems.resourceadapters.Constants;
import org.jboss.as.connector.subsystems.resourceadapters.WorkManagerRuntimeAttributeReadHandler;
import org.jboss.as.connector.subsystems.resourceadapters.WorkManagerRuntimeAttributeWriteHandler;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.ResourceBuilder;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.descriptions.OverrideDescriptionProvider;
import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.jca.core.api.workmanager.DistributedWorkManager;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
public class DistributedWorkManagerStatisticsService implements Service<ManagementResourceRegistration> {
private final ManagementResourceRegistration overrideRegistration;
private final boolean statsEnabled;
protected final InjectedValue<DistributedWorkManager> distributedWorkManager = new InjectedValue<>();
/**
* create an instance *
*/
public DistributedWorkManagerStatisticsService(final ManagementResourceRegistration registration,
final String name,
final boolean statsEnabled) {
super();
if (registration.isAllowsOverride()) {
overrideRegistration = registration.registerOverrideModel(name, new OverrideDescriptionProvider() {
@Override
public Map<String, ModelNode> getAttributeOverrideDescriptions(Locale locale) {
return Collections.emptyMap();
}
@Override
public Map<String, ModelNode> getChildTypeOverrideDescriptions(Locale locale) {
return Collections.emptyMap();
}
});
} else {
overrideRegistration = registration;
}
this.statsEnabled = statsEnabled;
}
@Override
public void start(StartContext context) throws StartException {
synchronized (this) {
DistributedWorkManager dwm = distributedWorkManager.getValue();
dwm.setDistributedStatisticsEnabled(statsEnabled);
if (dwm.getDistributedStatistics() != null) {
PathElement peDistributedWm = PathElement.pathElement(Constants.STATISTICS_NAME, "distributed");
ResourceBuilder resourceBuilder = ResourceBuilder.Factory.create(peDistributedWm,
new StandardResourceDescriptionResolver(Constants.STATISTICS_NAME + "." + Constants.WORKMANAGER_NAME, CommonAttributes.RESOURCE_NAME, CommonAttributes.class.getClassLoader()));
ManagementResourceRegistration dwmSubRegistration = overrideRegistration.registerSubModel(resourceBuilder.build());
OperationStepHandler metricHandler = new WorkManagerRuntimeAttributeReadHandler(dwm, dwm.getDistributedStatistics(), false);
for (SimpleAttributeDefinition metric : Constants.WORKMANAGER_METRICS) {
dwmSubRegistration.registerMetric(metric, metricHandler);
}
OperationStepHandler readHandler = new WorkManagerRuntimeAttributeReadHandler(dwm, dwm.getDistributedStatistics(), false);
OperationStepHandler writeHandler = new WorkManagerRuntimeAttributeWriteHandler(dwm, false, Constants.DISTRIBUTED_WORKMANAGER_RW_ATTRIBUTES);
for (SimpleAttributeDefinition attribute : Constants.DISTRIBUTED_WORKMANAGER_RW_ATTRIBUTES) {
dwmSubRegistration.registerReadWriteAttribute(attribute, readHandler, writeHandler);
}
dwmSubRegistration.registerOperationHandler(ClearWorkManagerStatisticsHandler.DEFINITION, new ClearWorkManagerStatisticsHandler(dwm));
}
}
}
@Override
public void stop(StopContext context) {
PathElement peDistributedWm = PathElement.pathElement(Constants.STATISTICS_NAME, "distributed");
if (overrideRegistration.getSubModel(PathAddress.pathAddress(peDistributedWm)) != null)
overrideRegistration.unregisterSubModel(peDistributedWm);
}
@Override
public ManagementResourceRegistration getValue() throws IllegalStateException, IllegalArgumentException {
return overrideRegistration;
}
public Injector<DistributedWorkManager> getDistributedWorkManagerInjector() {
return distributedWorkManager;
}
}
| 6,275 | 43.510638 | 200 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/statistics/WorkManagerStatisticsService.java | /*
* 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.services.workmanager.statistics;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import org.jboss.as.connector.dynamicresource.ClearWorkManagerStatisticsHandler;
import org.jboss.as.connector.subsystems.resourceadapters.CommonAttributes;
import org.jboss.as.connector.subsystems.resourceadapters.Constants;
import org.jboss.as.connector.subsystems.resourceadapters.WorkManagerRuntimeAttributeReadHandler;
import org.jboss.as.connector.subsystems.resourceadapters.WorkManagerRuntimeAttributeWriteHandler;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.ResourceBuilder;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.descriptions.OverrideDescriptionProvider;
import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.jca.core.api.workmanager.WorkManager;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
public class WorkManagerStatisticsService implements Service<ManagementResourceRegistration> {
private final ManagementResourceRegistration overrideRegistration;
private final boolean statsEnabled;
protected final InjectedValue<WorkManager> workManager = new InjectedValue<>();
/**
* create an instance *
*/
public WorkManagerStatisticsService(final ManagementResourceRegistration registration,
final String name,
final boolean statsEnabled) {
super();
if (registration.isAllowsOverride()) {
overrideRegistration = registration.registerOverrideModel(name, new OverrideDescriptionProvider() {
@Override
public Map<String, ModelNode> getAttributeOverrideDescriptions(Locale locale) {
return Collections.emptyMap();
}
@Override
public Map<String, ModelNode> getChildTypeOverrideDescriptions(Locale locale) {
return Collections.emptyMap();
}
});
} else {
overrideRegistration = registration;
}
this.statsEnabled = statsEnabled;
}
@Override
public void start(StartContext context) throws StartException {
synchronized (this) {
WorkManager wm = workManager.getValue();
wm.setStatisticsEnabled(statsEnabled);
if (wm.getStatistics() != null) {
PathElement peLocaldWm = PathElement.pathElement(Constants.STATISTICS_NAME, "local");
ResourceBuilder resourceBuilder = ResourceBuilder.Factory.create(peLocaldWm,
new StandardResourceDescriptionResolver(Constants.STATISTICS_NAME + "." + Constants.WORKMANAGER_NAME, CommonAttributes.RESOURCE_NAME, CommonAttributes.class.getClassLoader()));
ManagementResourceRegistration wmSubRegistration = overrideRegistration.registerSubModel(resourceBuilder.build());
OperationStepHandler metricHandler = new WorkManagerRuntimeAttributeReadHandler(wm, wm.getStatistics(), false);
for (SimpleAttributeDefinition metric : Constants.WORKMANAGER_METRICS) {
wmSubRegistration.registerMetric(metric, metricHandler);
}
OperationStepHandler readHandler = new WorkManagerRuntimeAttributeReadHandler(wm, wm.getStatistics(), false);
OperationStepHandler writeHandler = new WorkManagerRuntimeAttributeWriteHandler(wm, false, Constants.WORKMANAGER_RW_ATTRIBUTES);
for (SimpleAttributeDefinition attribute : Constants.WORKMANAGER_RW_ATTRIBUTES) {
wmSubRegistration.registerReadWriteAttribute(attribute, readHandler, writeHandler);
}
wmSubRegistration.registerOperationHandler(ClearWorkManagerStatisticsHandler.DEFINITION, new ClearWorkManagerStatisticsHandler(wm));
}
}
}
@Override
public void stop(StopContext context) {
PathElement peLocaldWm = PathElement.pathElement(Constants.STATISTICS_NAME, "local");
if (overrideRegistration.getSubModel(PathAddress.pathAddress(peLocaldWm)) != null)
overrideRegistration.unregisterSubModel(peLocaldWm);
}
@Override
public ManagementResourceRegistration getValue() throws IllegalStateException, IllegalArgumentException {
return overrideRegistration;
}
public Injector<WorkManager> getWorkManagerInjector() {
return workManager;
}
}
| 6,024 | 42.035714 | 200 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/ClearDistributedStatisticsCommand.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import org.jboss.jca.core.spi.workmanager.Address;
import org.wildfly.clustering.dispatcher.Command;
/**
* Equivalent to {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport#clearDistributedStatistics(java.util.Map)}.
* @author Paul Ferraro
*/
public class ClearDistributedStatisticsCommand implements Command<Void, CommandDispatcherTransport> {
private static final long serialVersionUID = -1590205163985739077L;
private final Address address;
public ClearDistributedStatisticsCommand(Address address) {
this.address = address;
}
@Override
public Void execute(CommandDispatcherTransport transport) {
transport.localClearDistributedStatistics(this.address);
return null;
}
}
| 1,849 | 38.361702 | 140 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/LeaveCommand.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import org.wildfly.clustering.dispatcher.Command;
import org.wildfly.clustering.group.Node;
/**
* Equivalent to {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport#viewAccepted(org.jgroups.View)}.
* @author Paul Ferraro
*/
public class LeaveCommand implements Command<Void, CommandDispatcherTransport> {
private static final long serialVersionUID = -3857530778548976078L;
private final Node member;
public LeaveCommand(Node member) {
this.member = member;
}
@Override
public Void execute(CommandDispatcherTransport transport) {
transport.leave(this.member);
return null;
}
}
| 1,750 | 36.255319 | 129 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/ShortRunningFreeCommand.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import org.jboss.jca.core.spi.workmanager.Address;
import org.wildfly.clustering.dispatcher.Command;
/**
* Equivalent to {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport#getShortRunningFree(java.util.Map)}.
* @author Paul Ferraro
*/
public class ShortRunningFreeCommand implements Command<Long, CommandDispatcherTransport> {
private static final long serialVersionUID = 2200993132804378135L;
private final Address address;
public ShortRunningFreeCommand(Address address) {
this.address = address;
}
@Override
public Long execute(CommandDispatcherTransport transport) {
return transport.localGetShortRunningFree(this.address);
}
}
| 1,800 | 38.152174 | 133 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/DeltaWorkFailedCommand.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import org.jboss.jca.core.spi.workmanager.Address;
import org.wildfly.clustering.dispatcher.Command;
/**
* Equivalent to {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport#deltaWorkFailed(java.util.Map)}.
* @author Paul Ferraro
*/
public class DeltaWorkFailedCommand implements Command<Void, CommandDispatcherTransport> {
private static final long serialVersionUID = 8092302980939329432L;
private final Address address;
public DeltaWorkFailedCommand(Address address) {
this.address = address;
}
@Override
public Void execute(CommandDispatcherTransport transport) {
transport.localDeltaWorkFailed(this.address);
return null;
}
}
| 1,804 | 37.404255 | 129 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/LongRunningFreeCommand.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import org.jboss.jca.core.spi.workmanager.Address;
import org.wildfly.clustering.dispatcher.Command;
/**
* Equivalent to {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport#getLongRunningFree(java.util.Map)}.
* @author Paul Ferraro
*/
public class LongRunningFreeCommand implements Command<Long, CommandDispatcherTransport> {
private static final long serialVersionUID = -3552549556601333089L;
private final Address address;
public LongRunningFreeCommand(Address address) {
this.address = address;
}
@Override
public Long execute(CommandDispatcherTransport transport) {
return transport.localGetLongRunningFree(this.address);
}
}
| 1,797 | 38.086957 | 132 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/CommandDispatcherTransport.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import jakarta.resource.spi.work.DistributableWork;
import jakarta.resource.spi.work.WorkException;
import org.jboss.as.connector.logging.ConnectorLogger;
import org.jboss.jca.core.api.workmanager.DistributedWorkManager;
import org.jboss.jca.core.spi.workmanager.Address;
import org.jboss.jca.core.workmanager.transport.remote.AbstractRemoteTransport;
import org.jboss.jca.core.workmanager.transport.remote.ProtocolMessages.Request;
import org.wildfly.clustering.Registration;
import org.wildfly.clustering.dispatcher.Command;
import org.wildfly.clustering.dispatcher.CommandDispatcher;
import org.wildfly.clustering.dispatcher.CommandDispatcherException;
import org.wildfly.clustering.ee.cache.concurrent.StampedLockServiceExecutor;
import org.wildfly.clustering.ee.concurrent.ServiceExecutor;
import org.wildfly.clustering.group.GroupListener;
import org.wildfly.clustering.group.Membership;
import org.wildfly.clustering.group.Node;
import org.wildfly.clustering.server.dispatcher.CommandDispatcherFactory;
import org.wildfly.common.function.ExceptionRunnable;
import org.wildfly.common.function.ExceptionSupplier;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* {@link DistributedWorkManager}-specific transport based on a {@link CommandDispatcher}.
* The current implementation is a direct translation of {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport}.
* @author Paul Ferraro
*/
public class CommandDispatcherTransport extends AbstractRemoteTransport<Node> implements GroupListener {
private final ServiceExecutor executor = new StampedLockServiceExecutor();
private final CommandDispatcherFactory dispatcherFactory;
private final String name;
private volatile CommandDispatcher<CommandDispatcherTransport> dispatcher;
private volatile Registration groupListenerRegistration;
private volatile boolean initialized = false;
public CommandDispatcherTransport(CommandDispatcherFactory dispatcherFactory, String name) {
this.dispatcherFactory = dispatcherFactory;
this.name = name;
}
@Override
public String getId() {
return this.getOwnAddress().getName();
}
@Override
public void startup() throws Exception {
this.dispatcher = this.dispatcherFactory.createCommandDispatcher(this.name, this, WildFlySecurityManager.getClassLoaderPrivileged(this.getClass()));
this.groupListenerRegistration = this.dispatcherFactory.getGroup().register(this);
this.broadcast(new JoinCommand());
}
@Override
public void shutdown() {
this.executor.close(() -> {
try {
this.broadcast(new LeaveCommand(this.getOwnAddress()));
} catch (WorkException e) {
ConnectorLogger.ROOT_LOGGER.warn(e.getLocalizedMessage(), e);
} finally {
this.groupListenerRegistration.close();
this.dispatcher.close();
}
});
}
@Override
public void initialize() throws Exception {
this.initialized = true;
}
@Override
public boolean isInitialized() {
return this.initialized;
}
@Override
protected Node getOwnAddress() {
return this.dispatcherFactory.getGroup().getLocalMember();
}
@Override
protected Serializable sendMessage(Node physicalAddress, Request request, Serializable... parameters) throws WorkException {
Command<?, CommandDispatcherTransport> command = createCommand(request, parameters);
CommandDispatcher<CommandDispatcherTransport> dispatcher = this.dispatcher;
ExceptionSupplier<Optional<Serializable>, WorkException> task = new ExceptionSupplier<>() {
@Override
public Optional<Serializable> get() throws WorkException {
try {
CompletionStage<?> response = dispatcher.executeOnMember(command, physicalAddress);
return Optional.ofNullable((Serializable) response.toCompletableFuture().join());
} catch (CancellationException e) {
return Optional.empty();
} catch (CommandDispatcherException | CompletionException e) {
throw new WorkException(e);
}
}
};
Optional<Serializable> val = this.executor.execute(task).orElse(null);
return val != null ? val.orElse(null) : null;
}
private void broadcast(Command<Void, CommandDispatcherTransport> command) throws WorkException {
CommandDispatcher<CommandDispatcherTransport> dispatcher = this.dispatcher;
ExceptionRunnable<WorkException> task = new ExceptionRunnable<>() {
@Override
public void run() throws WorkException {
try {
for (Map.Entry<Node, CompletionStage<Void>> entry : dispatcher.executeOnGroup(command).entrySet()) {
// Verify that command executed successfully on all nodes
try {
entry.getValue().toCompletableFuture().join();
} catch (CancellationException e) {
// Ignore
} catch (CompletionException e) {
throw new WorkException(e);
}
}
} catch (CommandDispatcherException e) {
throw new WorkException(e);
}
}
};
this.executor.execute(task);
}
private static Command<?, CommandDispatcherTransport> createCommand(Request request, Serializable... parameters) {
Address address = (parameters.length > 0) ? (Address) parameters[0] : null;
switch (request) {
case CLEAR_DISTRIBUTED_STATISTICS: {
return new ClearDistributedStatisticsCommand(address);
}
case DELTA_DOWORK_ACCEPTED: {
return new DeltaDoWorkAcceptedCommand(address);
}
case DELTA_DOWORK_REJECTED: {
return new DeltaDoWorkRejectedCommand(address);
}
case DELTA_SCHEDULEWORK_ACCEPTED: {
return new DeltaScheduleWorkAcceptedCommand(address);
}
case DELTA_SCHEDULEWORK_REJECTED: {
return new DeltaScheduleWorkRejectedCommand(address);
}
case DELTA_STARTWORK_ACCEPTED: {
return new DeltaStartWorkAcceptedCommand(address);
}
case DELTA_STARTWORK_REJECTED: {
return new DeltaStartWorkRejectedCommand(address);
}
case DELTA_WORK_FAILED: {
return new DeltaWorkFailedCommand(address);
}
case DELTA_WORK_SUCCESSFUL: {
return new DeltaWorkSuccessfulCommand(address);
}
case DO_WORK: {
return new DoWorkCommand(address, (DistributableWork) parameters[2]);
}
case GET_DISTRIBUTED_STATISTICS: {
return new DistributedStatisticsCommand(address);
}
case GET_LONGRUNNING_FREE: {
return new LongRunningFreeCommand(address);
}
case GET_SHORTRUNNING_FREE: {
return new ShortRunningFreeCommand(address);
}
case PING: {
return new PingCommand();
}
case SCHEDULE_WORK: {
return new ScheduleWorkCommand(address, (DistributableWork) parameters[2]);
}
case START_WORK: {
return new StartWorkCommand(address, (DistributableWork) parameters[2]);
}
case UPDATE_LONGRUNNING_FREE: {
return new UpdateLongRunningFreeCommand(address, (Long) parameters[1]);
}
case UPDATE_SHORTRUNNING_FREE: {
return new UpdateShortRunningFreeCommand(address, (Long) parameters[1]);
}
case WORKMANAGER_ADD: {
return new AddWorkManagerCommand(address, (Node) parameters[1]);
}
case WORKMANAGER_REMOVE: {
return new RemoveWorkManagerCommand(address);
}
default: {
throw new IllegalStateException(request.name());
}
}
}
@Override
public void membershipChanged(Membership previousMembership, Membership membership, boolean merged) {
Runnable task = () -> {
Set<Node> leavers = new HashSet<>(previousMembership.getMembers());
leavers.removeAll(membership.getMembers());
// Handle abrupt leavers
for (Node leaver : leavers) {
this.leave(leaver);
}
if (merged) {
this.join(membership);
}
};
this.executor.execute(task);
}
public void join() {
this.join(this.dispatcherFactory.getGroup().getMembership());
}
private void join(Membership membership) {
Map<Node, CompletionStage<Set<Address>>> futures = new HashMap<>();
for (Node member : membership.getMembers()) {
if (!this.getOwnAddress().equals(member) && !this.nodes.containsValue(member)) {
try {
futures.put(member, this.dispatcher.executeOnMember(new GetWorkManagersCommand(), member));
} catch (CommandDispatcherException e) {
ConnectorLogger.ROOT_LOGGER.warn(e.getLocalizedMessage(), e);
}
}
}
for (Map.Entry<Node, CompletionStage<Set<Address>>> entry : futures.entrySet()) {
Node member = entry.getKey();
try {
Set<Address> addresses = entry.getValue().toCompletableFuture().join();
for (Address address : addresses) {
this.join(address, member);
this.localUpdateLongRunningFree(address, this.getShortRunningFree(address));
this.localUpdateShortRunningFree(address, this.getShortRunningFree(address));
}
} catch (CancellationException e) {
// Ignore
} catch (CompletionException e) {
ConnectorLogger.ROOT_LOGGER.warn(e.getLocalizedMessage(), e);
}
}
}
}
| 11,832 | 40.960993 | 156 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/DeltaScheduleWorkRejectedCommand.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import org.jboss.jca.core.spi.workmanager.Address;
import org.wildfly.clustering.dispatcher.Command;
/**
* Equivalent to {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport#deltaScheduleWorkRejected(java.util.Map)}.
* @author Paul Ferraro
*/
public class DeltaScheduleWorkRejectedCommand implements Command<Void, CommandDispatcherTransport> {
private static final long serialVersionUID = 5726410485723041645L;
private final Address address;
public DeltaScheduleWorkRejectedCommand(Address address) {
this.address = address;
}
@Override
public Void execute(CommandDispatcherTransport transport) {
transport.localDeltaScheduleWorkRejected(this.address);
return null;
}
}
| 1,844 | 38.255319 | 139 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/DistributedStatisticsCommand.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import org.jboss.jca.core.api.workmanager.DistributedWorkManagerStatisticsValues;
import org.jboss.jca.core.spi.workmanager.Address;
import org.wildfly.clustering.dispatcher.Command;
/**
* Equivalent to {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport#getDistributedStatistics(java.util.Map)}.
* @author Paul Ferraro
*/
public class DistributedStatisticsCommand implements Command<DistributedWorkManagerStatisticsValues, CommandDispatcherTransport> {
private static final long serialVersionUID = -8884303103746998259L;
private final Address address;
public DistributedStatisticsCommand(Address address) {
this.address = address;
}
@Override
public DistributedWorkManagerStatisticsValues execute(CommandDispatcherTransport transport) {
return transport.localGetDistributedStatistics(this.address);
}
}
| 1,971 | 40.957447 | 138 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/GetWorkManagersCommand.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import java.util.Set;
import org.jboss.jca.core.spi.workmanager.Address;
import org.wildfly.clustering.dispatcher.Command;
/**
* Equivalent to {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport#getAddresses(org.jgroups.Address)}.
* @author Paul Ferraro
*/
public class GetWorkManagersCommand implements Command<Set<Address>, CommandDispatcherTransport> {
private static final long serialVersionUID = 8595995018539997003L;
@Override
public Set<Address> execute(CommandDispatcherTransport transport) {
return transport.getAddresses(transport.getOwnAddress());
}
}
| 1,709 | 39.714286 | 132 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/DeltaScheduleWorkAcceptedCommand.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import org.jboss.jca.core.spi.workmanager.Address;
import org.wildfly.clustering.dispatcher.Command;
/**
* Equivalent to {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport#deltaScheduleWorkAccepted(java.util.Map)}.
* @author Paul Ferraro
*/
public class DeltaScheduleWorkAcceptedCommand implements Command<Void, CommandDispatcherTransport> {
private static final long serialVersionUID = -3878717003141874003L;
private final Address address;
public DeltaScheduleWorkAcceptedCommand(Address address) {
this.address = address;
}
@Override
public Void execute(CommandDispatcherTransport transport) {
transport.localDeltaScheduleWorkAccepted(this.address);
return null;
}
}
| 1,845 | 38.276596 | 139 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/StartWorkCommand.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import jakarta.resource.spi.work.DistributableWork;
import jakarta.resource.spi.work.WorkException;
import org.jboss.jca.core.spi.workmanager.Address;
import org.wildfly.clustering.dispatcher.Command;
/**
* Equivalent to {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport#startWork(Address, DistributableWork)}.
* @author Paul Ferraro
*/
public class StartWorkCommand implements Command<Long, CommandDispatcherTransport> {
private static final long serialVersionUID = -661447249010320508L;
private final Address address;
private final DistributableWork work;
public StartWorkCommand(Address address, DistributableWork work) {
this.address = address;
this.work = work;
}
@Override
public Long execute(CommandDispatcherTransport transport) throws WorkException {
return transport.localStartWork(this.address, this.work);
}
}
| 2,004 | 38.313725 | 136 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/DeltaWorkSuccessfulCommand.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import org.jboss.jca.core.spi.workmanager.Address;
import org.wildfly.clustering.dispatcher.Command;
/**
* Equivalent to {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport#deltaWorkSuccessful(java.util.Map)}.
* @author Paul Ferraro
*/
public class DeltaWorkSuccessfulCommand implements Command<Void, CommandDispatcherTransport> {
private static final long serialVersionUID = -3397082802806176447L;
private final Address address;
public DeltaWorkSuccessfulCommand(Address address) {
this.address = address;
}
@Override
public Void execute(CommandDispatcherTransport transport) {
transport.localDeltaWorkSuccessful(this.address);
return null;
}
}
| 1,821 | 37.765957 | 133 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/ScheduleWorkCommand.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import jakarta.resource.spi.work.DistributableWork;
import jakarta.resource.spi.work.WorkException;
import org.jboss.jca.core.spi.workmanager.Address;
import org.wildfly.clustering.dispatcher.Command;
/**
* Equivalent to {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport#scheduleWork(Address, DistributableWork)}.
* @author Paul Ferraro
*/
public class ScheduleWorkCommand implements Command<Void, CommandDispatcherTransport> {
private static final long serialVersionUID = -661447249010320508L;
private final Address address;
private final DistributableWork work;
public ScheduleWorkCommand(Address address, DistributableWork work) {
this.address = address;
this.work = work;
}
@Override
public Void execute(CommandDispatcherTransport transport) throws WorkException {
transport.localScheduleWork(this.address, this.work);
return null;
}
}
| 2,030 | 38.057692 | 139 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/DeltaDoWorkRejectedCommand.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import org.jboss.jca.core.spi.workmanager.Address;
import org.wildfly.clustering.dispatcher.Command;
/**
* Equivalent to {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport#deltaDoWorkRejected(java.util.Map)}.
* @author Paul Ferraro
*/
public class DeltaDoWorkRejectedCommand implements Command<Void, CommandDispatcherTransport> {
private static final long serialVersionUID = 7864134087221121821L;
private final Address address;
public DeltaDoWorkRejectedCommand(Address address) {
this.address = address;
}
@Override
public Void execute(CommandDispatcherTransport transport) {
transport.localDeltaDoWorkRejected(this.address);
return null;
}
}
| 1,820 | 37.744681 | 133 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/UpdateLongRunningFreeCommand.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import org.jboss.jca.core.spi.workmanager.Address;
import org.wildfly.clustering.dispatcher.Command;
/**
* Equivalent to {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport#updateLongRunningFree(java.util.Map, Long)}.
* @author Paul Ferraro
*/
public class UpdateLongRunningFreeCommand implements Command<Void, CommandDispatcherTransport> {
private static final long serialVersionUID = -3887902059566674034L;
private final Address address;
private final long free;
public UpdateLongRunningFreeCommand(Address address, long free) {
this.address = address;
this.free = free;
}
@Override
public Void execute(CommandDispatcherTransport transport) {
transport.localUpdateLongRunningFree(this.address, this.free);
return null;
}
}
| 1,912 | 38.040816 | 141 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/DeltaStartWorkRejectedCommand.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import org.jboss.jca.core.spi.workmanager.Address;
import org.wildfly.clustering.dispatcher.Command;
/**
* Equivalent to {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport#deltaStartWorkRejected(java.util.Map)}.
* @author Paul Ferraro
*/
public class DeltaStartWorkRejectedCommand implements Command<Void, CommandDispatcherTransport> {
private static final long serialVersionUID = -1980521523518562227L;
private final Address address;
public DeltaStartWorkRejectedCommand(Address address) {
this.address = address;
}
@Override
public Void execute(CommandDispatcherTransport transport) {
transport.localDeltaStartWorkRejected(this.address);
return null;
}
}
| 1,833 | 38.021277 | 136 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/RemoveWorkManagerCommand.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import org.jboss.jca.core.spi.workmanager.Address;
import org.wildfly.clustering.dispatcher.Command;
/**
* Equivalent to {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport#workManagerRemove(java.util.Map)}.
* @author Paul Ferraro
*/
public class RemoveWorkManagerCommand implements Command<Void, CommandDispatcherTransport> {
private static final long serialVersionUID = 2582985650458275860L;
private final Address address;
public RemoveWorkManagerCommand(Address address) {
this.address = address;
}
@Override
public Void execute(CommandDispatcherTransport transport) {
transport.localWorkManagerRemove(this.address);
return null;
}
}
| 1,812 | 37.574468 | 131 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/AddWorkManagerCommand.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import org.jboss.jca.core.spi.workmanager.Address;
import org.wildfly.clustering.dispatcher.Command;
import org.wildfly.clustering.group.Node;
/**
* Equivalent to {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport#addWorkManager(java.util.Map, org.jgroups.Address)}.
* @author Paul Ferraro
*/
public class AddWorkManagerCommand implements Command<Void, CommandDispatcherTransport> {
private static final long serialVersionUID = -6747024371979702527L;
private final Address address;
private final Node member;
public AddWorkManagerCommand(Address address, Node member) {
this.address = address;
this.member = member;
}
@Override
public Void execute(CommandDispatcherTransport transport) {
transport.localWorkManagerAdd(this.address, this.member);
transport.localUpdateShortRunningFree(this.address, transport.getShortRunningFree(this.address));
transport.localUpdateLongRunningFree(this.address, transport.getLongRunningFree(this.address));
return null;
}
}
| 2,162 | 39.811321 | 149 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/JoinCommand.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import org.wildfly.clustering.dispatcher.Command;
/**
* Equivalent to {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport#viewAccepted(org.jgroups.View)}.
* @author Paul Ferraro
*/
public class JoinCommand implements Command<Void, CommandDispatcherTransport> {
private static final long serialVersionUID = 2120774292518363374L;
@Override
public Void execute(CommandDispatcherTransport transport) throws Exception {
transport.join();
return null;
}
}
| 1,604 | 38.146341 | 129 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/CommandDispatcherTransportClassTableContributor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import java.util.Arrays;
import java.util.List;
import jakarta.resource.spi.work.DistributableWork;
import jakarta.resource.spi.work.Work;
import org.jboss.jca.core.api.workmanager.DistributedWorkManagerStatisticsValues;
import org.jboss.jca.core.spi.workmanager.Address;
import org.kohsuke.MetaInfServices;
import org.wildfly.clustering.marshalling.jboss.ClassTableContributor;
/**
* {@link ClassTableContributor} for a {@link CommandDispatcherTransport}.
* @author Paul Ferraro
*/
@MetaInfServices(ClassTableContributor.class)
public class CommandDispatcherTransportClassTableContributor implements ClassTableContributor {
@Override
public List<Class<?>> getKnownClasses() {
return Arrays.asList(Address.class, DistributedWorkManagerStatisticsValues.class,
DistributableWork.class, Work.class, GetWorkManagersCommand.class,
DeltaDoWorkAcceptedCommand.class, DeltaDoWorkRejectedCommand.class,
DeltaScheduleWorkAcceptedCommand.class, DeltaScheduleWorkRejectedCommand.class,
DeltaStartWorkAcceptedCommand.class, DeltaStartWorkRejectedCommand.class,
DeltaWorkFailedCommand.class, DeltaWorkSuccessfulCommand.class,
ClearDistributedStatisticsCommand.class, DistributedStatisticsCommand.class,
PingCommand.class, LongRunningFreeCommand.class, ShortRunningFreeCommand.class,
DoWorkCommand.class, StartWorkCommand.class, ScheduleWorkCommand.class,
UpdateLongRunningFreeCommand.class, UpdateShortRunningFreeCommand.class,
JoinCommand.class, LeaveCommand.class);
}
}
| 2,733 | 46.137931 | 95 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/DeltaDoWorkAcceptedCommand.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import org.jboss.jca.core.spi.workmanager.Address;
import org.wildfly.clustering.dispatcher.Command;
/**
* Equivalent to {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport#deltaDoWorkAccepted(java.util.Map)}.
* @author Paul Ferraro
*/
public class DeltaDoWorkAcceptedCommand implements Command<Void, CommandDispatcherTransport> {
private static final long serialVersionUID = -2256088009794548082L;
private final Address address;
public DeltaDoWorkAcceptedCommand(Address address) {
this.address = address;
}
@Override
public Void execute(CommandDispatcherTransport transport) {
transport.localDeltaDoWorkAccepted(this.address);
return null;
}
}
| 1,821 | 37.765957 | 133 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/DeltaStartWorkAcceptedCommand.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import org.jboss.jca.core.spi.workmanager.Address;
import org.wildfly.clustering.dispatcher.Command;
/**
* Equivalent to {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport#deltaStartWorkAccepted(java.util.Map)}.
* @author Paul Ferraro
*/
public class DeltaStartWorkAcceptedCommand implements Command<Void, CommandDispatcherTransport> {
private static final long serialVersionUID = -2940831151921131815L;
private final Address address;
public DeltaStartWorkAcceptedCommand(Address address) {
this.address = address;
}
@Override
public Void execute(CommandDispatcherTransport transport) {
transport.localDeltaStartWorkAccepted(this.address);
return null;
}
}
| 1,833 | 38.021277 | 136 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/PingCommand.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import org.wildfly.clustering.dispatcher.Command;
/**
* Equivalent to {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport#localPing()}.
* @author Paul Ferraro
*/
public class PingCommand implements Command<Long, CommandDispatcherTransport> {
private static final long serialVersionUID = 7747022347047976535L;
@Override
public Long execute(CommandDispatcherTransport transport) {
return transport.localPing();
}
}
| 1,558 | 38.974359 | 110 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/DoWorkCommand.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import jakarta.resource.spi.work.DistributableWork;
import jakarta.resource.spi.work.WorkException;
import org.jboss.jca.core.spi.workmanager.Address;
import org.wildfly.clustering.dispatcher.Command;
/**
* Equivalent to {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport#doWork(Address, DistributableWork)}.
* @author Paul Ferraro
*/
public class DoWorkCommand implements Command<Void, CommandDispatcherTransport> {
private static final long serialVersionUID = -661447249010320508L;
private final Address address;
private final DistributableWork work;
public DoWorkCommand(Address address, DistributableWork work) {
this.address = address;
this.work = work;
}
@Override
public Void execute(CommandDispatcherTransport transport) throws WorkException {
transport.localDoWork(this.address, this.work);
return null;
}
}
| 2,006 | 37.596154 | 133 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/workmanager/transport/UpdateShortRunningFreeCommand.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.services.workmanager.transport;
import org.jboss.jca.core.spi.workmanager.Address;
import org.wildfly.clustering.dispatcher.Command;
/**
* Equivalent to {@link org.jboss.jca.core.workmanager.transport.remote.jgroups.JGroupsTransport#updateShortRunningFree(java.util.Map, Long)}.
* @author Paul Ferraro
*/
public class UpdateShortRunningFreeCommand implements Command<Void, CommandDispatcherTransport> {
private static final long serialVersionUID = -3887902059566674034L;
private final Address address;
private final long free;
public UpdateShortRunningFreeCommand(Address address, long free) {
this.address = address;
this.free = free;
}
@Override
public Void execute(CommandDispatcherTransport transport) {
transport.localUpdateShortRunningFree(this.address, this.free);
return null;
}
}
| 1,916 | 38.122449 | 142 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/bootstrap/BootStrapContextService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.services.bootstrap;
import static org.jboss.as.connector.logging.ConnectorLogger.ROOT_LOGGER;
import org.jboss.as.connector.subsystems.jca.JcaSubsystemConfiguration;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.as.txn.integration.JBossContextXATerminator;
import org.jboss.jca.core.api.bootstrap.CloneableBootstrapContext;
import org.jboss.jca.core.api.workmanager.WorkManager;
import org.jboss.jca.core.bootstrapcontext.BootstrapContextCoordinator;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.jboss.msc.value.Value;
/**
* A DefaultBootStrapContextService Service
* @author <a href="mailto:[email protected]">Stefano Maestri</a>
*/
public final class BootStrapContextService implements Service<CloneableBootstrapContext> {
private final CloneableBootstrapContext value;
private final String name;
private final boolean usingDefaultWm;
private final InjectedValue<WorkManager> workManagerValue = new InjectedValue<WorkManager>();
private final InjectedValue<com.arjuna.ats.jbossatx.jta.TransactionManagerService> txManager = new InjectedValue<com.arjuna.ats.jbossatx.jta.TransactionManagerService>();
private final InjectedValue<JBossContextXATerminator> xaTerminator = new InjectedValue<JBossContextXATerminator>();
private final InjectedValue<JcaSubsystemConfiguration> jcaConfig = new InjectedValue<JcaSubsystemConfiguration>();
public Value<WorkManager> getWorkManagerValue() {
return workManagerValue;
}
/** create an instance **/
public BootStrapContextService(CloneableBootstrapContext value, String name, boolean usingDefaultWm) {
super();
ROOT_LOGGER.debugf("Building DefaultBootstrapContext");
this.value = value;
this.name = name;
this.usingDefaultWm = usingDefaultWm;
}
@Override
public CloneableBootstrapContext getValue() throws IllegalStateException {
return ConnectorServices.notNull(value);
}
@Override
public void start(StartContext context) throws StartException {
this.value.setWorkManager(workManagerValue.getValue());
this.value.setTransactionSynchronizationRegistry(txManager.getValue().getTransactionSynchronizationRegistry());
this.value.setXATerminator(xaTerminator.getValue());
jcaConfig.getValue().getBootstrapContexts().put(name, value);
if(usingDefaultWm) {
jcaConfig.getValue().setDefaultBootstrapContext(value);
BootstrapContextCoordinator.getInstance().setDefaultBootstrapContext(value);
} else {
BootstrapContextCoordinator.getInstance().registerBootstrapContext(value);
}
ROOT_LOGGER.debugf("Starting JCA DefaultBootstrapContext");
}
@Override
public void stop(StopContext context) {
jcaConfig.getValue().getBootstrapContexts().remove(name);
if (usingDefaultWm) {
jcaConfig.getValue().setDefaultBootstrapContext(null);
BootstrapContextCoordinator.getInstance().setDefaultBootstrapContext(null);
} else {
BootstrapContextCoordinator.getInstance().unregisterBootstrapContext(value);
}
}
public Injector<com.arjuna.ats.jbossatx.jta.TransactionManagerService> getTxManagerInjector() {
return txManager;
}
public Injector<JBossContextXATerminator> getXaTerminatorInjector() {
return xaTerminator;
}
public Injector<WorkManager> getWorkManagerValueInjector() {
return workManagerValue;
}
public Injector<JcaSubsystemConfiguration> getJcaConfigInjector() {
return jcaConfig;
}
}
| 4,909 | 38.28 | 174 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/bootstrap/NamedBootstrapContext.java | /*
* 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.services.bootstrap;
import org.jboss.jca.core.api.bootstrap.CloneableBootstrapContext;
import org.jboss.jca.core.bootstrapcontext.BaseCloneableBootstrapContext;
/**
* A named bootstrap context.
* @author <a href="mailto:[email protected]">Jesper Pedersen</a>
*/
public class NamedBootstrapContext extends BaseCloneableBootstrapContext {
/** Default BootstrapContext name */
public static final String DEFAULT_NAME = "default";
/** The name of the BootstrapContext - unique container wide */
private String name;
/**
* Constructor
* @param name The name of the WorkManager
*/
public NamedBootstrapContext(final String name) {
super();
setName(name);
}
public NamedBootstrapContext(final String name, final String workManagerName) {
this(name);
this.setWorkManagerName(workManagerName);
}
/**
* Get the name
* @return The value
*/
public String getName() {
return name;
}
/**
* Set the name
* @param v The value
*/
public void setName(String v) {
name = v;
}
@Override
public CloneableBootstrapContext clone() throws CloneNotSupportedException {
NamedBootstrapContext nbc = (NamedBootstrapContext)super.clone();
nbc.setName(getName());
nbc.setWorkManagerName(getWorkManagerName());
return nbc;
}
}
| 2,468 | 30.653846 | 83 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/transactionintegration/TransactionIntegrationService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.services.transactionintegration;
import static org.jboss.as.connector.logging.ConnectorLogger.ROOT_LOGGER;
import java.util.function.Consumer;
import java.util.function.Supplier;
import jakarta.transaction.TransactionSynchronizationRegistry;
import org.jboss.as.txn.integration.JBossContextXATerminator;
import org.jboss.jca.core.spi.transaction.TransactionIntegration;
import org.jboss.jca.core.tx.jbossts.TransactionIntegrationImpl;
import org.jboss.msc.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.tm.XAResourceRecoveryRegistry;
import org.jboss.tm.usertx.UserTransactionRegistry;
import org.wildfly.transaction.client.ContextTransactionManager;
/**
* A WorkManager Service.
* @author <a href="mailto:[email protected]">Stefano Maestri</a>
*/
public final class TransactionIntegrationService implements Service {
private final Consumer<TransactionIntegration> tiConsumer;
private final Supplier<TransactionSynchronizationRegistry> tsrSupplier;
private final Supplier<UserTransactionRegistry> utrSupplier;
private final Supplier<JBossContextXATerminator> terminatorSupplier;
private final Supplier<XAResourceRecoveryRegistry> rrSupplier;
/** create an instance **/
public TransactionIntegrationService(final Consumer<TransactionIntegration> tiConsumer,
final Supplier<TransactionSynchronizationRegistry> tsrSupplier,
final Supplier<UserTransactionRegistry> utrSupplier,
final Supplier<JBossContextXATerminator> terminatorSupplier,
final Supplier<XAResourceRecoveryRegistry> rrSupplier) {
this.tiConsumer = tiConsumer;
this.tsrSupplier = tsrSupplier;
this.utrSupplier = utrSupplier;
this.terminatorSupplier = terminatorSupplier;
this.rrSupplier = rrSupplier;
}
@Override
public void start(final StartContext context) throws StartException {
tiConsumer.accept(new TransactionIntegrationImpl(ContextTransactionManager.getInstance(),
tsrSupplier.get(), utrSupplier.get(), terminatorSupplier.get(), rrSupplier.get()));
ROOT_LOGGER.debugf("Starting Jakarta Connectors TransactionIntegrationService");
}
@Override
public void stop(final StopContext context) {
tiConsumer.accept(null);
}
}
| 3,575 | 41.571429 | 104 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/AdminObjectService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, 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.services.resourceadapters;
import static org.jboss.as.connector.logging.ConnectorLogger.ROOT_LOGGER;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
public class AdminObjectService implements Service<Object> {
public static final ServiceName SERVICE_NAME_BASE = ServiceName.JBOSS.append("connector", "admin-object");
private final Object value;
/** create an instance **/
public AdminObjectService(Object value) {
super();
this.value = value;
}
@Override
public Object getValue() throws IllegalStateException, IllegalArgumentException {
return value;
}
@Override
public void start(StartContext context) throws StartException {
ROOT_LOGGER.debugf("started AdminObjectService %s", context.getController().getName());
}
@Override
public void stop(StopContext context) {
ROOT_LOGGER.debugf("stopped AdminObjectService %s", context.getController().getName());
}
}
| 2,185 | 33.15625 | 110 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/DirectAdminObjectActivatorService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, 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.services.resourceadapters;
import static org.jboss.as.connector.logging.ConnectorLogger.ROOT_LOGGER;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.jboss.as.connector.logging.ConnectorLogger;
import org.jboss.as.connector.services.mdr.AS7MetadataRepository;
import org.jboss.as.connector.services.resourceadapters.deployment.registry.ResourceAdapterDeploymentRegistry;
import org.jboss.as.connector.subsystems.jca.JcaSubsystemConfiguration;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.service.NamingService;
import org.jboss.jca.common.api.metadata.common.TransactionSupportEnum;
import org.jboss.jca.common.api.metadata.resourceadapter.Activation;
import org.jboss.jca.common.api.metadata.resourceadapter.ConnectionDefinition;
import org.jboss.jca.common.api.metadata.spec.AdminObject;
import org.jboss.jca.common.api.metadata.spec.Connector;
import org.jboss.jca.common.api.metadata.spec.ResourceAdapter;
import org.jboss.jca.common.metadata.resourceadapter.ActivationImpl;
import org.jboss.jca.common.metadata.resourceadapter.AdminObjectImpl;
import org.jboss.jca.core.api.connectionmanager.ccm.CachedConnectionManager;
import org.jboss.jca.core.api.management.ManagementRepository;
import org.jboss.jca.core.spi.rar.ResourceAdapterRepository;
import org.jboss.jca.core.spi.transaction.TransactionIntegration;
import org.jboss.modules.Module;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
public class DirectAdminObjectActivatorService implements Service<ContextNames.BindInfo> {
public static final ServiceName SERVICE_NAME_BASE =
ServiceName.JBOSS.append("connector").append("direct-connection-factory-activator");
protected final InjectedValue<AS7MetadataRepository> mdr = new InjectedValue<AS7MetadataRepository>();
private final String jndiName;
private final String className;
private final String resourceAdapter;
private final String raId;
private final Map<String, String> properties;
private final Module module;
private final ContextNames.BindInfo bindInfo;
/**
* create an instance *
*/
public DirectAdminObjectActivatorService(String jndiName, String className, String resourceAdapter,
String raId, Map<String, String> properties, Module module, ContextNames.BindInfo bindInfo) {
this.jndiName = jndiName;
this.className = className;
this.resourceAdapter = resourceAdapter;
this.raId = raId;
this.properties = properties;
this.module = module;
this.bindInfo = bindInfo;
}
@Override
public ContextNames.BindInfo getValue() throws IllegalStateException, IllegalArgumentException {
return bindInfo;
}
@Override
public void start(StartContext context) throws StartException {
ROOT_LOGGER.debugf("started DirectConnectionFactoryActivatorService %s", context.getController().getName());
String aoClass = null;
try {
Connector cmd = mdr.getValue().getResourceAdapter(raId);
if (cmd.getVersion() == Connector.Version.V_10) {
throw ConnectorLogger.ROOT_LOGGER.adminObjectForJCA10(resourceAdapter, jndiName);
} else {
ResourceAdapter ra1516 = (ResourceAdapter) cmd.getResourceadapter();
if (ra1516.getAdminObjects() != null) {
for (AdminObject ao : ra1516.getAdminObjects()) {
if (ao.getAdminobjectClass().getValue().equals(className))
aoClass = ao.getAdminobjectClass().getValue();
}
}
}
if (aoClass == null || !aoClass.equals(className)) {
throw ConnectorLogger.ROOT_LOGGER.invalidAdminObject(aoClass, resourceAdapter, jndiName);
}
Map<String, String> aoConfigProperties = new HashMap<String, String>();
if (properties != null) {
for (Map.Entry<String,String> prop : properties.entrySet()) {
String key = prop.getKey();
String value = prop.getValue();
if (key.startsWith("ao.")) {
aoConfigProperties.put(key.substring(3), value);
} else if (!key.startsWith("ra.")) {
aoConfigProperties.put(key, value);
}
}
}
org.jboss.jca.common.api.metadata.resourceadapter.AdminObject ao = new AdminObjectImpl(aoConfigProperties, aoClass, jndiName, poolName(aoClass, className), Boolean.TRUE, Boolean.TRUE);
Activation activation = new ActivationImpl(null, null, TransactionSupportEnum.LocalTransaction, Collections.<ConnectionDefinition>emptyList(), Collections.singletonList(ao),
null, Collections.<String>emptyList(), null, null);
String serviceName = jndiName;
serviceName = serviceName.replace(':', '_');
serviceName = serviceName.replace('/', '_');
ResourceAdapterActivatorService activator = new ResourceAdapterActivatorService(cmd, activation, module.getClassLoader(), serviceName);
activator.setCreateBinderService(false);
activator.setBindInfo(bindInfo);
ServiceTarget serviceTarget = context.getChildTarget();
ServiceBuilder adminObjectServiceBuilder = serviceTarget
.addService(ConnectorServices.RESOURCE_ADAPTER_ACTIVATOR_SERVICE.append(serviceName), activator)
.addDependency(ConnectorServices.IRONJACAMAR_MDR, AS7MetadataRepository.class,
activator.getMdrInjector())
.addDependency(ConnectorServices.RA_REPOSITORY_SERVICE, ResourceAdapterRepository.class,
activator.getRaRepositoryInjector())
.addDependency(ConnectorServices.MANAGEMENT_REPOSITORY_SERVICE, ManagementRepository.class,
activator.getManagementRepositoryInjector())
.addDependency(ConnectorServices.RESOURCE_ADAPTER_REGISTRY_SERVICE,
ResourceAdapterDeploymentRegistry.class, activator.getRegistryInjector())
.addDependency(ConnectorServices.getCachedCapabilityServiceName(ConnectorServices.TRANSACTION_INTEGRATION_CAPABILITY_NAME), TransactionIntegration.class,
activator.getTxIntegrationInjector())
.addDependency(ConnectorServices.CONNECTOR_CONFIG_SERVICE,
JcaSubsystemConfiguration.class, activator.getConfigInjector())
// No legacy security services needed as this activation has no connection definitions
// or work manager, so nothing configures a legacy security domain
/*
.addDependency(SubjectFactoryService.SERVICE_NAME, SubjectFactory.class,
activator.getSubjectFactoryInjector())
.addDependency(SimpleSecurityManagerService.SERVICE_NAME,
ServerSecurityManager.class, activator.getServerSecurityManager())
*/
.addDependency(ConnectorServices.CCM_SERVICE, CachedConnectionManager.class,
activator.getCcmInjector());
adminObjectServiceBuilder.requires(ConnectorServices.getCachedCapabilityServiceName(NamingService.CAPABILITY_NAME));
adminObjectServiceBuilder.requires(ConnectorServices.getCachedCapabilityServiceName(ConnectorServices.LOCAL_TRANSACTION_PROVIDER_CAPABILITY));
adminObjectServiceBuilder.requires(ConnectorServices.BOOTSTRAP_CONTEXT_SERVICE.append("default"));
adminObjectServiceBuilder.setInitialMode(ServiceController.Mode.ACTIVE).install();
} catch (Exception e) {
throw new StartException(e);
}
}
public Injector<AS7MetadataRepository> getMdrInjector() {
return mdr;
}
@Override
public void stop(StopContext context) {
ROOT_LOGGER.debugf("stopped DirectConnectionFactoryActivatorService %s", context.getController().getName());
}
private String poolName(final String aoClass, final String aoInterface) {
if (aoInterface != null) {
if (aoInterface.indexOf(".") != -1) {
return aoInterface.substring(aoInterface.lastIndexOf(".") + 1);
} else {
return aoInterface;
}
}
if (aoClass.indexOf(".") != -1) {
return aoClass.substring(aoClass.lastIndexOf(".") + 1);
} else {
return aoClass;
}
}
}
| 10,296 | 47.570755 | 196 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/AdminObjectReferenceFactoryService.java | /*
* 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.services.resourceadapters;
import org.jboss.as.naming.ContextListAndJndiViewManagedReferenceFactory;
import org.jboss.as.naming.ContextListManagedReferenceFactory;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.naming.ValueManagedReference;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
/**
* Service responsible for exposing a {@link ManagedReferenceFactory} for an admin object
* @author @author <a href="mailto:[email protected]">Stefano Maestri</a>
*/
public class AdminObjectReferenceFactoryService implements Service<ManagedReferenceFactory>, ContextListAndJndiViewManagedReferenceFactory {
public static final ServiceName SERVICE_NAME_BASE =
ServiceName.JBOSS.append("connector").append("admin-object").append("reference-factory");
private final InjectedValue<Object> adminObjectValue = new InjectedValue<Object>();
private ManagedReference reference;
public synchronized void start(StartContext startContext) throws StartException {
reference = new ValueManagedReference(adminObjectValue.getValue());
}
public synchronized void stop(StopContext stopContext) {
reference = null;
}
public synchronized ManagedReferenceFactory getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
public synchronized ManagedReference getReference() {
return reference;
}
public Injector<Object> getAdminObjectInjector() {
return adminObjectValue;
}
@Override
public String getInstanceClassName() {
final Object value = reference != null ? reference.getInstance() : null;
return value != null ? value.getClass().getName() : ContextListManagedReferenceFactory.DEFAULT_INSTANCE_CLASS_NAME;
}
@Override
public String getJndiViewInstanceValue() {
final Object value = reference != null ? reference.getInstance() : null;
return String.valueOf(value);
}
}
| 3,314 | 39.925926 | 140 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/DirectConnectionFactoryActivatorService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, 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.services.resourceadapters;
import static org.jboss.as.connector.logging.ConnectorLogger.ROOT_LOGGER;
import static org.jboss.as.connector.logging.ConnectorLogger.SUBSYSTEM_RA_LOGGER;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import jakarta.resource.spi.TransactionSupport;
import org.jboss.as.connector.logging.ConnectorLogger;
import org.jboss.as.connector.metadata.api.common.Security;
import org.jboss.as.connector.metadata.common.SecurityImpl;
import org.jboss.as.connector.services.mdr.AS7MetadataRepository;
import org.jboss.as.connector.services.resourceadapters.deployment.registry.ResourceAdapterDeploymentRegistry;
import org.jboss.as.connector.subsystems.jca.JcaSubsystemConfiguration;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.service.NamingService;
import org.jboss.jca.common.api.metadata.Defaults;
import org.jboss.jca.common.api.metadata.common.Pool;
import org.jboss.jca.common.api.metadata.common.TransactionSupportEnum;
import org.jboss.jca.common.api.metadata.resourceadapter.Activation;
import org.jboss.jca.common.api.metadata.resourceadapter.AdminObject;
import org.jboss.jca.common.api.metadata.spec.ConnectionDefinition;
import org.jboss.jca.common.api.metadata.spec.Connector;
import org.jboss.jca.common.api.metadata.spec.ResourceAdapter;
import org.jboss.jca.common.metadata.common.PoolImpl;
import org.jboss.jca.common.metadata.common.XaPoolImpl;
import org.jboss.jca.common.metadata.resourceadapter.ActivationImpl;
import org.jboss.jca.core.api.connectionmanager.ccm.CachedConnectionManager;
import org.jboss.jca.core.api.management.ManagementRepository;
import org.jboss.jca.core.spi.rar.ResourceAdapterRepository;
import org.jboss.jca.core.spi.transaction.TransactionIntegration;
import org.jboss.modules.Module;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartException;
import org.jboss.msc.value.InjectedValue;
public class DirectConnectionFactoryActivatorService implements org.jboss.msc.service.Service<ContextNames.BindInfo> {
private static final ServiceName SECURITY_MANAGER_SERVICE = ServiceName.JBOSS.append("security", "simple-security-manager");
private static final ServiceName SUBJECT_FACTORY_SERVICE = ServiceName.JBOSS.append("security", "subject-factory");
public static final ServiceName SERVICE_NAME_BASE =
ServiceName.JBOSS.append("connector").append("direct-connection-factory-activator");
protected final InjectedValue<AS7MetadataRepository> mdr = new InjectedValue<AS7MetadataRepository>();
private final String jndiName;
private final String interfaceName;
private final String resourceAdapter;
private final String raId;
private final int maxPoolSize;
private final int minPoolSize;
private final Map<String, String> properties;
private final TransactionSupport.TransactionSupportLevel transactionSupport;
private final Module module;
private final ContextNames.BindInfo bindInfo;
private boolean legacySecurityAvailable;
/**
* create an instance *
*/
public DirectConnectionFactoryActivatorService(String jndiName, String interfaceName, String resourceAdapter,
String raId, int maxPoolSize, int minPoolSize,
Map<String, String> properties, TransactionSupport.TransactionSupportLevel transactionSupport,
Module module, ContextNames.BindInfo bindInfo, boolean legacySecurityAvailable) {
this.jndiName = jndiName;
this.interfaceName = interfaceName;
this.resourceAdapter = resourceAdapter;
this.raId = raId;
this.maxPoolSize = maxPoolSize;
this.minPoolSize = minPoolSize;
this.properties = properties;
if (transactionSupport == null)
transactionSupport = TransactionSupport.TransactionSupportLevel.NoTransaction;
this.transactionSupport = transactionSupport;
this.module = module;
this.bindInfo = bindInfo;
this.legacySecurityAvailable = legacySecurityAvailable;
}
@Override
public ContextNames.BindInfo getValue() throws IllegalStateException, IllegalArgumentException {
return bindInfo;
}
@Override
public void start(org.jboss.msc.service.StartContext context) throws org.jboss.msc.service.StartException {
ROOT_LOGGER.debugf("started DirectConnectionFactoryActivatorService %s", context.getController().getName());
String cfInterface = null;
try {
Connector cmd = mdr.getValue().getResourceAdapter(raId);
ResourceAdapter ra = cmd.getResourceadapter();
if (ra.getOutboundResourceadapter() != null) {
for (ConnectionDefinition cd : ra.getOutboundResourceadapter().getConnectionDefinitions()) {
if (cd.getConnectionFactoryInterface().getValue().equals(interfaceName))
cfInterface = cd.getConnectionFactoryInterface().getValue();
}
}
if (cfInterface == null || !cfInterface.equals(interfaceName)) {
throw ConnectorLogger.ROOT_LOGGER.invalidConnectionFactory(cfInterface, resourceAdapter, jndiName);
}
Map<String, String> raConfigProperties = new HashMap<String, String>();
Map<String, String> mcfConfigProperties = new HashMap<String, String>();
String securitySetting = null;
String securitySettingDomain = null;
if (properties != null) {
for (Map.Entry<String,String> prop : properties.entrySet()) {
String key = prop.getKey();
String value = prop.getValue();
if (key.equals("ironjacamar.security")) {
securitySetting = value;
} else if (key.equals("ironjacamar.security.elytron-authentication-context")) {
securitySettingDomain = value;
} else if (key.equals("ironjacamar.security.domain")) {
throw new StartException(SUBSYSTEM_RA_LOGGER.legacySecurityNotSupported());
} else {
if (key.startsWith("ra.")) {
raConfigProperties.put(key.substring(3), value);
} else if (key.startsWith("mcf.")) {
mcfConfigProperties.put(key.substring(4), value);
} else {
mcfConfigProperties.put(key, value);
}
}
}
}
String mcfClass = null;
if (ra.getOutboundResourceadapter() != null) {
for (ConnectionDefinition cd :
ra.getOutboundResourceadapter().getConnectionDefinitions()) {
if (cd.getConnectionFactoryInterface().getValue().equals(cfInterface))
mcfClass = cd.getManagedConnectionFactoryClass().getValue();
}
}
Security security = null;
if (securitySetting != null) {
if ("".equals(securitySetting) || ("application".equals(securitySetting))) {
throw new StartException(SUBSYSTEM_RA_LOGGER.legacySecurityNotSupported());
} else if ("domain".equals(securitySetting) && securitySettingDomain != null) {
security = new SecurityImpl(securitySettingDomain, null, false);
} else if ("domain-and-application".equals(securitySetting) && securitySettingDomain != null) {
security = new SecurityImpl(null, securitySettingDomain, false);
}
}
if (security == null) {
SUBSYSTEM_RA_LOGGER.noSecurityDefined(jndiName);
}
Pool pool = null;
Boolean isXA = Boolean.FALSE;
if (transactionSupport == TransactionSupport.TransactionSupportLevel.XATransaction) {
pool = new XaPoolImpl(minPoolSize < 0 ? Defaults.MIN_POOL_SIZE : minPoolSize, Defaults.INITIAL_POOL_SIZE, maxPoolSize < 0 ? Defaults.MAX_POOL_SIZE : maxPoolSize,
Defaults.PREFILL, Defaults.USE_STRICT_MIN, Defaults.FLUSH_STRATEGY,
null, Defaults.FAIR, Defaults.IS_SAME_RM_OVERRIDE, Defaults.INTERLEAVING, Defaults.PAD_XID, Defaults.WRAP_XA_RESOURCE, Defaults.NO_TX_SEPARATE_POOL);
isXA = Boolean.TRUE;
} else {
pool = new PoolImpl(minPoolSize < 0 ? Defaults.MIN_POOL_SIZE : minPoolSize, Defaults.INITIAL_POOL_SIZE, maxPoolSize < 0 ? Defaults.MAX_POOL_SIZE : maxPoolSize,
Defaults.PREFILL, Defaults.USE_STRICT_MIN, Defaults.FLUSH_STRATEGY, null, Defaults.FAIR);
}
TransactionSupportEnum transactionSupportValue = TransactionSupportEnum.NoTransaction;
if (transactionSupport == TransactionSupport.TransactionSupportLevel.XATransaction) {
transactionSupportValue = TransactionSupportEnum.XATransaction;
} else if (transactionSupport == TransactionSupport.TransactionSupportLevel.LocalTransaction) {
transactionSupportValue = TransactionSupportEnum.LocalTransaction;
}
org.jboss.jca.common.api.metadata.resourceadapter.ConnectionDefinition cd = new org.jboss.jca.common.metadata.resourceadapter.ConnectionDefinitionImpl(mcfConfigProperties, mcfClass, jndiName, poolName(cfInterface),
Boolean.TRUE, Boolean.TRUE, Boolean.TRUE, Boolean.TRUE, Boolean.TRUE, Defaults.CONNECTABLE, Defaults.TRACKING,
Defaults.MCP, Defaults.ENLISTMENT_TRACE, pool, null, null, security, null, isXA);
Activation activation = new ActivationImpl(null, null, transactionSupportValue, Collections.singletonList(cd), Collections.<AdminObject>emptyList(), raConfigProperties, Collections.<String>emptyList(), null, null);
String serviceName = jndiName;
serviceName = serviceName.replace(':', '_');
serviceName = serviceName.replace('/', '_');
ResourceAdapterActivatorService activator = new ResourceAdapterActivatorService(cmd, activation, module.getClassLoader(), serviceName);
activator.setCreateBinderService(false);
activator.setBindInfo(bindInfo);
org.jboss.msc.service.ServiceTarget serviceTarget = context.getChildTarget();
ServiceName activatorServiceName = ConnectorServices.RESOURCE_ADAPTER_ACTIVATOR_SERVICE.append(serviceName);
org.jboss.msc.service.ServiceBuilder connectionFactoryServiceBuilder = serviceTarget
.addService(activatorServiceName, activator)
.addDependency(ConnectorServices.IRONJACAMAR_MDR, AS7MetadataRepository.class,
activator.getMdrInjector())
.addDependency(ConnectorServices.RA_REPOSITORY_SERVICE, ResourceAdapterRepository.class,
activator.getRaRepositoryInjector())
.addDependency(ConnectorServices.MANAGEMENT_REPOSITORY_SERVICE, ManagementRepository.class,
activator.getManagementRepositoryInjector())
.addDependency(ConnectorServices.RESOURCE_ADAPTER_REGISTRY_SERVICE,
ResourceAdapterDeploymentRegistry.class, activator.getRegistryInjector())
.addDependency(ConnectorServices.CONNECTOR_CONFIG_SERVICE,
JcaSubsystemConfiguration.class, activator.getConfigInjector())
.addDependency(ConnectorServices.CCM_SERVICE, CachedConnectionManager.class,
activator.getCcmInjector())
.addDependency(ConnectorServices.getCachedCapabilityServiceName(ConnectorServices.TRANSACTION_INTEGRATION_CAPABILITY_NAME), TransactionIntegration.class,
activator.getTxIntegrationInjector());
connectionFactoryServiceBuilder.requires(ConnectorServices.getCachedCapabilityServiceName(NamingService.CAPABILITY_NAME));
connectionFactoryServiceBuilder.requires(ConnectorServices.getCachedCapabilityServiceName(ConnectorServices.LOCAL_TRANSACTION_PROVIDER_CAPABILITY));
connectionFactoryServiceBuilder.requires(ConnectorServices.BOOTSTRAP_CONTEXT_SERVICE.append("default"));
connectionFactoryServiceBuilder.setInitialMode(org.jboss.msc.service.ServiceController.Mode.ACTIVE).install();
} catch (Exception e) {
throw new org.jboss.msc.service.StartException(e);
}
}
public Injector<AS7MetadataRepository> getMdrInjector() {
return mdr;
}
@Override
public void stop(org.jboss.msc.service.StopContext context) {
ROOT_LOGGER.debugf("stopped DirectConnectionFactoryActivatorService %s", context.getController().getName());
}
private String poolName(final String cfInterface) {
if (cfInterface.indexOf(".") != -1) {
return cfInterface.substring(cfInterface.lastIndexOf(".") + 1);
} else {
return cfInterface;
}
}
}
| 14,522 | 50.867857 | 226 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/ResourceAdapterActivatorService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.services.resourceadapters;
import static org.jboss.as.connector.logging.ConnectorLogger.DEPLOYMENT_CONNECTOR_LOGGER;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.jboss.as.connector.metadata.deployment.ResourceAdapterDeployment;
import org.jboss.as.connector.services.resourceadapters.deployment.AbstractResourceAdapterDeploymentService;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.jca.common.api.metadata.resourceadapter.Activation;
import org.jboss.jca.common.api.metadata.resourceadapter.AdminObject;
import org.jboss.jca.common.api.metadata.resourceadapter.ConnectionDefinition;
import org.jboss.jca.common.api.metadata.spec.Connector;
import org.jboss.jca.common.api.metadata.spec.ResourceAdapter;
import org.jboss.jca.deployers.DeployersLogger;
import org.jboss.jca.deployers.common.CommonDeployment;
import org.jboss.logging.Logger;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceController.Mode;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* A ResourceAdapterDeploymentService.
* @author <a href="mailto:[email protected]">Stefano Maestri</a>
* @author <a href="mailto:[email protected]">Jesper Pedersen</a>
*/
public final class ResourceAdapterActivatorService extends AbstractResourceAdapterDeploymentService implements
Service<ResourceAdapterDeployment> {
private static final DeployersLogger DEPLOYERS_LOGGER = Logger.getMessageLogger(DeployersLogger.class, ResourceAdapterActivator.class.getName());
private final ClassLoader cl;
private final Connector cmd;
private final Activation activation;
private final String deploymentName;
private CommonDeployment deploymentMD;
private ContextNames.BindInfo bindInfo;
private final List<String> jndiAliases = new ArrayList<>();
private boolean createBinderService = true;
public ResourceAdapterActivatorService(final Connector cmd, final Activation activation, ClassLoader cl,
final String deploymentName) {
this.cmd = cmd;
this.activation = activation;
this.cl = cl;
this.deploymentName = deploymentName;
this.connectorServicesRegistrationName = deploymentName;
this.bindInfo = null;
}
public ContextNames.BindInfo getBindInfo(String jndi) {
if (bindInfo != null) {
return bindInfo;
}
return ContextNames.bindInfoFor(jndi);
}
public void setBindInfo(ContextNames.BindInfo bindInfo) {
this.bindInfo = bindInfo;
}
public void addJndiAlias(String alias) {
this.jndiAliases.add(alias);
}
public void addJndiAliases(Collection<String> aliases) {
this.jndiAliases.addAll(aliases);
}
@Override
public Collection<String> getJndiAliases() {
return Collections.unmodifiableList(this.jndiAliases);
}
@Override
public boolean isCreateBinderService() {
return createBinderService;
}
public void setCreateBinderService(boolean createBinderService) {
this.createBinderService = createBinderService;
}
@Override
public void start(StartContext context) throws StartException {
String pathname = "file://RaActivator" + deploymentName;
try {
ResourceAdapterActivator activator = new ResourceAdapterActivator(context.getChildTarget(), new URL(pathname), deploymentName,
new File(pathname), cl, cmd, activation);
activator.setConfiguration(getConfig().getValue());
// FIXME!!, this should probably be done by IJ and not the service
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(cl);
deploymentMD = activator.doDeploy();
} finally {
Thread.currentThread().setContextClassLoader(old);
}
String raName = deploymentMD.getDeploymentName();
ServiceName raServiceName = ConnectorServices.getResourceAdapterServiceName(raName);
value = new ResourceAdapterDeployment(deploymentMD, raName, raServiceName);
registry.getValue().registerResourceAdapterDeployment(value);
managementRepository.getValue().getConnectors().add(value.getDeployment().getConnector());
context.getChildTarget()
.addService(raServiceName,
new ResourceAdapterService(raServiceName, value.getDeployment().getResourceAdapter())).setInitialMode(Mode.ACTIVE)
.install();
DEPLOYMENT_CONNECTOR_LOGGER.debugf("Started service %s", ConnectorServices.RESOURCE_ADAPTER_ACTIVATOR_SERVICE);
} catch (Throwable t) {
// To clean up we need to invoke blocking behavior, so do that in another thread
// and let this MSC thread return
String raName = deploymentName;
ServiceName raServiceName = ConnectorServices.getResourceAdapterServiceName(raName);
cleanupStartAsync(context, deploymentName, raServiceName, t);
}
}
/**
* Stop
*/
@Override
public void stop(final StopContext context) {
stopAsync(context, deploymentName, ConnectorServices.RESOURCE_ADAPTER_ACTIVATOR_SERVICE);
}
public CommonDeployment getDeploymentMD() {
return deploymentMD;
}
private class ResourceAdapterActivator extends AbstractWildFlyRaDeployer {
private final Activation activation;
public ResourceAdapterActivator(ServiceTarget serviceTarget, URL url, String deploymentName, File root,
ClassLoader cl, Connector cmd, Activation activation) {
super(serviceTarget, url, deploymentName, root, cl, cmd, null);
this.activation = activation;
}
@Override
public CommonDeployment doDeploy() throws Throwable {
this.setConfiguration(getConfig().getValue());
//never validate bean for services activated in this way (Jakarta Messaging)
this.getConfiguration().setBeanValidation(false);
this.start();
CommonDeployment dep = this.createObjectsAndInjectValue(url, deploymentName, root, cl, cmd, activation);
return dep;
}
@Override
protected boolean checkActivation(Connector cmd, Activation activation) {
if (cmd != null) {
Set<String> raMcfClasses = new HashSet<String>();
Set<String> raAoClasses = new HashSet<String>();
ResourceAdapter ra = (ResourceAdapter) cmd.getResourceadapter();
if (ra != null && ra.getOutboundResourceadapter() != null
&& ra.getOutboundResourceadapter().getConnectionDefinitions() != null) {
List<org.jboss.jca.common.api.metadata.spec.ConnectionDefinition> cdMetas = ra.getOutboundResourceadapter().getConnectionDefinitions();
if (!cdMetas.isEmpty()) {
for (org.jboss.jca.common.api.metadata.spec.ConnectionDefinition cdMeta : cdMetas) {
raMcfClasses.add(cdMeta.getManagedConnectionFactoryClass().getValue());
}
}
}
if (ra != null && ra.getAdminObjects() != null) {
List<org.jboss.jca.common.api.metadata.spec.AdminObject> aoMetas = ra.getAdminObjects();
if (!aoMetas.isEmpty()) {
for (org.jboss.jca.common.api.metadata.spec.AdminObject aoMeta : aoMetas) {
raAoClasses.add(aoMeta.getAdminobjectClass().getValue());
}
}
}
// Pure inflow
if (raMcfClasses.isEmpty() && raAoClasses.isEmpty())
return true;
if (activation != null) {
Set<String> ijMcfClasses = new HashSet<String>();
Set<String> ijAoClasses = new HashSet<String>();
boolean mcfSingle = raMcfClasses.size() == 1;
boolean aoSingle = raAoClasses.size() == 1;
boolean mcfOk = true;
boolean aoOk = true;
if (activation.getConnectionDefinitions() != null) {
for (ConnectionDefinition def : activation.getConnectionDefinitions()) {
String clz = def.getClassName();
if (clz != null) {
ijMcfClasses.add(clz);
}
}
}
if (!mcfSingle) {
Iterator<String> it = ijMcfClasses.iterator();
while (mcfOk && it.hasNext()) {
String clz = it.next();
if (!raMcfClasses.contains(clz))
mcfOk = false;
}
}
if (activation.getAdminObjects() != null) {
for (AdminObject def : activation.getAdminObjects()) {
String clz = def.getClassName();
if (clz != null) {
ijAoClasses.add(clz);
}
}
}
if (!aoSingle) {
Iterator<String> it = ijAoClasses.iterator();
while (aoOk && it.hasNext()) {
String clz = it.next();
if (!raAoClasses.contains(clz))
aoOk = false;
}
}
return mcfOk || aoOk;
}
}
return false;
}
@Override
protected DeployersLogger getLogger() {
return DEPLOYERS_LOGGER;
}
@Override
protected void setRecoveryForResourceAdapterInResourceAdapterRepository(String key, boolean isXA) {
try {
raRepository.getValue().setRecoveryForResourceAdapter(key, isXA);
} catch (Throwable t) {
DEPLOYMENT_CONNECTOR_LOGGER.unableToRegisterRecovery(key, isXA);
}
}
}
}
| 11,939 | 39.474576 | 155 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/IronJacamarActivationResourceService.java | /*
* 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.services.resourceadapters;
import static org.jboss.as.connector.logging.ConnectorLogger.ROOT_LOGGER;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.jboss.as.connector.dynamicresource.ClearStatisticsHandler;
import org.jboss.as.connector.dynamicresource.StatisticsResourceDefinition;
import org.jboss.as.connector.metadata.deployment.ResourceAdapterDeployment;
import org.jboss.as.connector.services.mdr.AS7MetadataRepository;
import org.jboss.as.connector.subsystems.common.pool.PoolMetrics;
import org.jboss.as.connector.subsystems.resourceadapters.CommonAttributes;
import org.jboss.as.connector.subsystems.resourceadapters.Constants;
import org.jboss.as.connector.subsystems.resourceadapters.IronJacamarResource;
import org.jboss.as.connector.subsystems.resourceadapters.IronJacamarResourceCreator;
import org.jboss.as.connector.subsystems.resourceadapters.ResourceAdaptersExtension;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.ResourceBuilder;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.descriptions.OverrideDescriptionProvider;
import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
import org.jboss.jca.core.api.management.AdminObject;
import org.jboss.jca.core.api.management.ConnectionFactory;
import org.jboss.jca.core.api.management.Connector;
import org.jboss.jca.core.api.management.ManagedConnectionFactory;
import org.jboss.jca.core.connectionmanager.ConnectionManager;
import org.jboss.jca.core.spi.statistics.StatisticsPlugin;
import org.jboss.jca.deployers.common.CommonDeployment;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
/**
* Registers the {@link ManagementResourceRegistration} and {@link Resource} for displaying various
* statistics reported by a {@link ResourceAdapterDeployment}. The available statistics depend on
* the deployment implementation, so they cannot be known/registered before the deployment is processed.
*/
public final class IronJacamarActivationResourceService implements Service<ManagementResourceRegistration> {
private static PathElement SUBSYSTEM_PATH_ELEMENT = PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, ResourceAdaptersExtension.SUBSYSTEM_NAME);
private static PathAddress RA_ADDRESS = PathAddress.pathAddress(SUBSYSTEM_PATH_ELEMENT,
PathElement.pathElement(Constants.IRONJACAMAR_NAME, Constants.IRONJACAMAR_NAME),
PathElement.pathElement(Constants.RESOURCEADAPTER_NAME));
private final ManagementResourceRegistration registration;
private final Resource deploymentResource;
private final boolean statsEnabled;
private final InjectedValue<ResourceAdapterDeployment> deployment = new InjectedValue<>();
private final InjectedValue<AS7MetadataRepository> mdr = new InjectedValue<>();
/**
* create an instance *
*/
public IronJacamarActivationResourceService(final ManagementResourceRegistration registration, final Resource deploymentResource,
final boolean statsEnabled) {
this.registration = registration;
this.deploymentResource = deploymentResource;
this.statsEnabled = statsEnabled;
}
@Override
public void start(StartContext context) throws StartException {
final CommonDeployment deploymentMD = deployment.getValue().getDeployment();
final String deploymentName = deploymentMD.getDeploymentName();
ROOT_LOGGER.debugf("Starting IronJacamarActivationResourceService %s", deploymentName);
try {
Connector connector = deploymentMD.getConnector();
if (connector != null && connector.getResourceAdapter() != null) {
final OverrideDescriptionProvider OD_PROVIDER = new OverrideDescriptionProvider() {
@Override
public Map<String, ModelNode> getAttributeOverrideDescriptions(Locale locale) {
return Collections.emptyMap();
}
@Override
public Map<String, ModelNode> getChildTypeOverrideDescriptions(Locale locale) {
return Collections.emptyMap();
}
};
final PathElement EXTENDED_STATS = PathElement.pathElement(Constants.STATISTICS_NAME, "extended");
final PathAddress EXTENDED_STATS_ADDR = PathAddress.pathAddress(EXTENDED_STATS);
final PathAddress CON_DEF_ADDR = PathAddress.EMPTY_ADDRESS.append(Constants.CONNECTIONDEFINITIONS_NAME);
ManagementResourceRegistration raRegistration =
registration.getSubModel(RA_ADDRESS).registerOverrideModel(deploymentName, OD_PROVIDER);
ResourceBuilder resourceBuilder = ResourceBuilder.Factory.create(EXTENDED_STATS,
new StandardResourceDescriptionResolver(Constants.STATISTICS_NAME + "." + Constants.WORKMANAGER_NAME, CommonAttributes.RESOURCE_NAME, CommonAttributes.class.getClassLoader()));
ManagementResourceRegistration raStatsSubRegistration = raRegistration.registerSubModel(resourceBuilder.build());
StatisticsPlugin raStats = connector.getResourceAdapter().getStatistics();
if (raStats != null) {
raStats.setEnabled(statsEnabled);
PoolMetrics.ParametrizedPoolMetricsHandler handler = new PoolMetrics.ParametrizedPoolMetricsHandler(raStats);
for (AttributeDefinition attribute : StatisticsResourceDefinition.getAttributesFromPlugin(raStats)) {
raStatsSubRegistration.registerMetric(attribute, handler);
}
raStatsSubRegistration.registerOperationHandler(ClearStatisticsHandler.DEFINITION, new ClearStatisticsHandler(raStats));
}
List<ConnectionFactory> connectionFactories = connector.getConnectionFactories();
if (connectionFactories != null) {
for (ConnectionFactory cf : connectionFactories) {
ManagedConnectionFactory mcf = cf.getManagedConnectionFactory();
StatisticsPlugin extendStats = mcf == null ? null : mcf.getStatistics();
if (extendStats != null) {
extendStats.setEnabled(statsEnabled);
if (!extendStats.getNames().isEmpty()) {
ManagementResourceRegistration cdRegistration = raRegistration.getSubModel(CON_DEF_ADDR);
ManagementResourceRegistration overrideCdRegistration =
cdRegistration.registerOverrideModel(cf.getJndiName(), OD_PROVIDER);
if (overrideCdRegistration.getSubModel(EXTENDED_STATS_ADDR) == null) {
overrideCdRegistration.registerSubModel(new StatisticsResourceDefinition(EXTENDED_STATS, CommonAttributes.RESOURCE_NAME, extendStats));
}
}
}
}
}
ConnectionManager[] connectionManagers = deploymentMD.getConnectionManagers();
if (connectionManagers != null) {
PathElement POOL_STATS = PathElement.pathElement(Constants.STATISTICS_NAME, "pool");
PathAddress POOL_STATS_ADDR = PathAddress.pathAddress(POOL_STATS);
for (ConnectionManager cm : connectionManagers) {
if (cm.getPool() != null) {
StatisticsPlugin poolStats = cm.getPool().getStatistics();
poolStats.setEnabled(statsEnabled);
if (!poolStats.getNames().isEmpty()) {
ManagementResourceRegistration cdRegistration = raRegistration.getSubModel(CON_DEF_ADDR);
ManagementResourceRegistration overrideCdRegistration =
cdRegistration.registerOverrideModel(cm.getJndiName(), OD_PROVIDER);
if (overrideCdRegistration.getSubModel(POOL_STATS_ADDR) == null) {
overrideCdRegistration.registerSubModel(new StatisticsResourceDefinition(POOL_STATS, CommonAttributes.RESOURCE_NAME, poolStats));
}
}
}
}
}
List<AdminObject> adminObjects = connector.getAdminObjects();
if (adminObjects != null) {
PathAddress AO_ADDR = PathAddress.EMPTY_ADDRESS.append(Constants.ADMIN_OBJECTS_NAME);
for (AdminObject ao : adminObjects) {
StatisticsPlugin extendStats = ao.getStatistics();
if (extendStats != null) {
extendStats.setEnabled(statsEnabled);
if (!extendStats.getNames().isEmpty()) {
ManagementResourceRegistration cdRegistration = raRegistration.getSubModel(AO_ADDR);
ManagementResourceRegistration overrideCdRegistration =
cdRegistration.registerOverrideModel(ao.getJndiName(), OD_PROVIDER);
if (overrideCdRegistration.getSubModel(EXTENDED_STATS_ADDR) == null) {
overrideCdRegistration.registerSubModel(new StatisticsResourceDefinition(EXTENDED_STATS, CommonAttributes.RESOURCE_NAME, extendStats));
}
}
}
}
}
}
} catch (IllegalArgumentException e) {
//ignore it, already restered
}
Resource subsystemResource;
if (!deploymentResource.hasChild(SUBSYSTEM_PATH_ELEMENT)) {
subsystemResource = new IronJacamarResource.IronJacamarRuntimeResource();
deploymentResource.registerChild(SUBSYSTEM_PATH_ELEMENT, subsystemResource);
} else {
subsystemResource = deploymentResource.getChild(SUBSYSTEM_PATH_ELEMENT);
}
IronJacamarResourceCreator.INSTANCE.execute(subsystemResource, mdr.getValue(), deployment.getValue().getRaName());
}
@Override
public void stop(StopContext context) {
final CommonDeployment deploymentMD = deployment.getValue().getDeployment();
final String deploymentName = deploymentMD.getDeploymentName();
ROOT_LOGGER.debugf("Stopping IronJacamarActivationResourceService %s", deploymentName);
Connector connector = deploymentMD.getConnector();
if (connector != null && connector.getResourceAdapter() != null) {
// We may have registered override resource registrations so we need to remove those
ManagementResourceRegistration raReg = registration.getSubModel(RA_ADDRESS.getParent().append(Constants.RESOURCEADAPTER_NAME, deploymentName));
ManagementResourceRegistration cdefReg = raReg.getSubModel(PathAddress.pathAddress(PathElement.pathElement(Constants.CONNECTIONDEFINITIONS_NAME)));
List<ConnectionFactory> connectionFactories = connector.getConnectionFactories();
if (connectionFactories != null) { // code reads that it won't be null but it's not documented, so...
for (ConnectionFactory cf : connectionFactories) {
// We might not have registered an override for this one but it's no harm to remove
// and simpler to just do it vs analyzing to see if we did
cdefReg.unregisterOverrideModel(cf.getJndiName());
}
}
ConnectionManager[] connectionManagers = deploymentMD.getConnectionManagers();
if (connectionManagers != null) {
for (ConnectionManager cm : connectionManagers) {
// We might not have registered an override for this one but it's no harm to remove
// and simpler to just do it vs analyzing to see if we did
cdefReg.unregisterOverrideModel(cm.getJndiName());
}
}
List<AdminObject> adminObjects = connector.getAdminObjects();
if (adminObjects != null) { // code reads that it won't be null but it's not documented, so...
ManagementResourceRegistration aoReg = raReg.getSubModel(PathAddress.pathAddress(PathElement.pathElement(Constants.ADMIN_OBJECTS_NAME)));
for (AdminObject ao : adminObjects) {
// We might not have registered an override for this one but it's no harm to remove
// and simpler to just do it vs analyzing to see if we did
aoReg.unregisterOverrideModel(ao.getJndiName());
}
}
ManagementResourceRegistration raBaseReg = registration.getSubModel(RA_ADDRESS);
raBaseReg.unregisterOverrideModel(deploymentName);
}
deploymentResource.removeChild(SUBSYSTEM_PATH_ELEMENT);
}
@Override
public ManagementResourceRegistration getValue() throws IllegalStateException, IllegalArgumentException {
return registration;
}
public Injector<AS7MetadataRepository> getMdrInjector() {
return mdr;
}
public Injector<ResourceAdapterDeployment> getResourceAdapterDeploymentInjector() {
return deployment;
}
}
| 15,297 | 52.48951 | 200 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/ConnectionFactoryReferenceFactoryService.java | /*
* 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.services.resourceadapters;
import org.jboss.as.naming.ContextListAndJndiViewManagedReferenceFactory;
import org.jboss.as.naming.ContextListManagedReferenceFactory;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.naming.ValueManagedReference;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
/**
* Service responsible for exposing a {@link ManagedReferenceFactory} for a connection factory
* @author @author <a href="mailto:[email protected]">Stefano Maestri</a>
*/
public class ConnectionFactoryReferenceFactoryService implements Service<ManagedReferenceFactory>, ContextListAndJndiViewManagedReferenceFactory {
public static final ServiceName SERVICE_NAME_BASE = ServiceName.JBOSS.append("connection-factory").append(
"reference-factory");
private final InjectedValue<Object> connectionFactoryValue = new InjectedValue<Object>();
private ManagedReference reference;
private final String name;
public ConnectionFactoryReferenceFactoryService(String name) {
this.name = name;
}
public String getName() {
return name;
}
public synchronized void start(StartContext startContext) throws StartException {
reference = new ValueManagedReference(connectionFactoryValue.getValue());
}
public synchronized void stop(StopContext stopContext) {
reference = null;
}
public synchronized ManagedReferenceFactory getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
public synchronized ManagedReference getReference() {
return reference;
}
public Injector<Object> getConnectionFactoryInjector() {
return connectionFactoryValue;
}
@Override
public String getInstanceClassName() {
final Object value = reference != null ? reference.getInstance() : null;
return value != null ? value.getClass().getName() : ContextListManagedReferenceFactory.DEFAULT_INSTANCE_CLASS_NAME;
}
@Override
public String getJndiViewInstanceValue() {
final Object value = reference != null ? reference.getInstance() : null;
return String.valueOf(value);
}
}
| 3,529 | 38.222222 | 146 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/ConnectionFactoryService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, 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.services.resourceadapters;
import static org.jboss.as.connector.logging.ConnectorLogger.ROOT_LOGGER;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
public class ConnectionFactoryService implements Service<Object> {
public static final ServiceName SERVICE_NAME_BASE =
ServiceName.JBOSS.append("connector").append("connection-factory").append("reference-factory");
private final Object value;
/** create an instance **/
public ConnectionFactoryService(Object value) {
super();
this.value = value;
}
@Override
public Object getValue() throws IllegalStateException, IllegalArgumentException {
return value;
}
@Override
public void start(StartContext context) throws StartException {
ROOT_LOGGER.debugf("started ConnectionFactoryService %s", context.getController().getName());
}
@Override
public void stop(StopContext context) {
ROOT_LOGGER.debugf("stopped ConnectionFactoryService %s", context.getController().getName());
}
}
| 2,257 | 34.28125 | 103 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/ResourceAdapterService.java | /*
* 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.services.resourceadapters;
import static org.jboss.as.connector.logging.ConnectorLogger.ROOT_LOGGER;
import jakarta.resource.spi.ResourceAdapter;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
public class ResourceAdapterService implements Service<ResourceAdapter> {
private ServiceName serviceName;
private final ResourceAdapter value;
/** create an instance **/
public ResourceAdapterService(ServiceName serviceName, ResourceAdapter value) {
super();
this.serviceName = serviceName;
this.value = value;
}
@Override
public ResourceAdapter getValue() throws IllegalStateException, IllegalArgumentException {
return value;
}
@Override
public void start(StartContext context) throws StartException {
ROOT_LOGGER.debugf("Started ResourceAdapterService %s", serviceName);
}
@Override
public void stop(StopContext context) {
ROOT_LOGGER.debugf("Stopped ResourceAdapterService %s", serviceName);
}
}
| 2,226 | 34.349206 | 94 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/deployment/ResourceAdapterDeploymentService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.services.resourceadapters.deployment;
import static org.jboss.as.connector.logging.ConnectorLogger.DEPLOYMENT_CONNECTOR_LOGGER;
import java.io.File;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import org.jboss.as.connector.logging.ConnectorLogger;
import org.jboss.as.connector.metadata.deployment.ResourceAdapterDeployment;
import org.jboss.as.connector.metadata.xmldescriptors.ConnectorXmlDescriptor;
import org.jboss.as.connector.services.mdr.AS7MetadataRepository;
import org.jboss.as.connector.services.resourceadapters.IronJacamarActivationResourceService;
import org.jboss.as.connector.services.resourceadapters.ResourceAdapterService;
import org.jboss.as.connector.subsystems.resourceadapters.RaOperationUtil;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.naming.WritableServiceBasedNamingStore;
import org.jboss.jca.common.api.metadata.resourceadapter.Activation;
import org.jboss.jca.common.api.metadata.spec.AdminObject;
import org.jboss.jca.common.api.metadata.spec.ConnectionDefinition;
import org.jboss.jca.common.api.metadata.spec.Connector;
import org.jboss.jca.common.api.metadata.spec.ResourceAdapter;
import org.jboss.jca.deployers.DeployersLogger;
import org.jboss.jca.deployers.common.CommonDeployment;
import org.jboss.logging.Logger;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceController.Mode;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* A ResourceAdapterDeploymentService.
*
* @author <a href="mailto:[email protected]">Stefano Maestri</a>
* @author <a href="mailto:[email protected]">Jesper Pedersen</a>
*/
public final class ResourceAdapterDeploymentService extends AbstractResourceAdapterDeploymentService implements
Service<ResourceAdapterDeployment> {
private static final DeployersLogger DEPLOYERS_LOGGER = Logger.getMessageLogger(DeployersLogger.class, "org.jboss.as.connector.deployers.RADeployer");
private final ClassLoader classLoader;
private final ConnectorXmlDescriptor connectorXmlDescriptor;
private final Connector cmd;
private final Activation activation;
private final ManagementResourceRegistration registration;
private final Resource deploymentResource;
private CommonDeployment raDeployment = null;
private String deploymentName;
private ServiceName deploymentServiceName;
private final ServiceName duServiceName;
/**
* @param connectorXmlDescriptor
* @param cmd
* @param classLoader
* @param deploymentServiceName
* @param duServiceName the deployment unit's service name
* @activationm activation
*/
public ResourceAdapterDeploymentService(final ConnectorXmlDescriptor connectorXmlDescriptor, final Connector cmd,
final Activation activation, final ClassLoader classLoader, final ServiceName deploymentServiceName, final ServiceName duServiceName,
final ManagementResourceRegistration registration, final Resource deploymentResource) {
this.connectorXmlDescriptor = connectorXmlDescriptor;
this.cmd = cmd;
this.activation = activation;
this.classLoader = classLoader;
this.deploymentServiceName = deploymentServiceName;
this.duServiceName = duServiceName;
this.registration = registration;
this.deploymentResource = deploymentResource;
}
@Override
public void start(StartContext context) throws StartException {
final URL url = connectorXmlDescriptor == null ? null : connectorXmlDescriptor.getUrl();
deploymentName = connectorXmlDescriptor == null ? null : connectorXmlDescriptor.getDeploymentName();
connectorServicesRegistrationName = deploymentName;
final File root = connectorXmlDescriptor == null ? null : connectorXmlDescriptor.getRoot();
DEPLOYMENT_CONNECTOR_LOGGER.debugf("DEPLOYMENT name = %s", deploymentName);
final boolean fromModule = duServiceName.getParent().equals(RaOperationUtil.RAR_MODULE);
final WildFLyRaDeployer raDeployer =
new WildFLyRaDeployer(context.getChildTarget(), url, deploymentName, root, classLoader, cmd, activation, deploymentServiceName, fromModule);
raDeployer.setConfiguration(config.getValue());
ClassLoader old = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
try {
WritableServiceBasedNamingStore.pushOwner(duServiceName);
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader);
raDeployment = raDeployer.doDeploy();
deploymentName = raDeployment.getDeploymentName();
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(old);
WritableServiceBasedNamingStore.popOwner();
}
if (raDeployer.checkActivation(cmd, activation)) {
DEPLOYMENT_CONNECTOR_LOGGER.debugf("Activating: %s", deploymentName);
ServiceName raServiceName = ConnectorServices.getResourceAdapterServiceName(deploymentName);
value = new ResourceAdapterDeployment(raDeployment, deploymentName, raServiceName);
managementRepository.getValue().getConnectors().add(value.getDeployment().getConnector());
registry.getValue().registerResourceAdapterDeployment(value);
ServiceTarget serviceTarget = context.getChildTarget();
serviceTarget
.addService(raServiceName,
new ResourceAdapterService(raServiceName, value.getDeployment().getResourceAdapter())).setInitialMode(Mode.ACTIVE)
.install();
final ServiceName deployerServiceName = ConnectorServices.RESOURCE_ADAPTER_DEPLOYER_SERVICE_PREFIX.append(deploymentName);
IronJacamarActivationResourceService ijResourceService = new IronJacamarActivationResourceService(registration, deploymentResource, false);
serviceTarget.addService(deployerServiceName.append(ConnectorServices.IRONJACAMAR_RESOURCE), ijResourceService)
.addDependency(ConnectorServices.IRONJACAMAR_MDR, AS7MetadataRepository.class, ijResourceService.getMdrInjector())
.addDependency(deployerServiceName, ResourceAdapterDeployment.class, ijResourceService.getResourceAdapterDeploymentInjector())
.setInitialMode(Mode.PASSIVE)
.install();
} else {
DEPLOYMENT_CONNECTOR_LOGGER.debugf("Not activating: %s", deploymentName);
}
} catch (Throwable t) {
cleanupStartAsync(context, deploymentName, t, duServiceName, classLoader);
}
}
// TODO this could be replaced by the superclass method if there is no need for the TCCL change and push/pop owner
// The stop() call doesn't do that so it's probably not needed
private void cleanupStartAsync(final StartContext context, final String deploymentName, final Throwable cause,
final ServiceName duServiceName, final ClassLoader toUse) {
ExecutorService executorService = getLifecycleExecutorService();
Runnable r = new Runnable() {
@Override
public void run() {
ClassLoader old = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WritableServiceBasedNamingStore.pushOwner(duServiceName);
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(toUse);
unregisterAll(deploymentName);
} finally {
try {
context.failed(ConnectorLogger.ROOT_LOGGER.failedToStartRaDeployment(cause, deploymentName));
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(old);
WritableServiceBasedNamingStore.popOwner();
}
}
}
};
try {
executorService.execute(r);
} catch (RejectedExecutionException e) {
r.run();
} finally {
context.asynchronous();
}
}
@Override
public Collection<String> getJndiAliases() {
return Collections.emptyList();
}
/**
* Stop
*/
@Override
public void stop(StopContext context) {
stopAsync(context, deploymentName, deploymentServiceName);
}
public CommonDeployment getRaDeployment() {
return raDeployment;
}
public AS7MetadataRepository getMdr() {
return mdr.getValue();
}
private class WildFLyRaDeployer extends AbstractWildFlyRaDeployer {
private final Activation activation;
private final boolean fromModule;
public WildFLyRaDeployer(ServiceTarget serviceContainer, URL url, String deploymentName, File root, ClassLoader cl,
Connector cmd, Activation activation, final ServiceName deploymentServiceName, final boolean fromModule) {
super(serviceContainer, url, deploymentName, root, cl, cmd, deploymentServiceName);
this.activation = activation;
this.fromModule = fromModule;
}
@Override
public CommonDeployment doDeploy() throws Throwable {
this.setConfiguration(getConfig().getValue());
this.start();
CommonDeployment dep = this.createObjectsAndInjectValue(url, deploymentName, root, cl, cmd, activation);
return dep;
}
@Override
protected boolean checkActivation(Connector cmd, Activation activation) {
if (cmd != null) {
Set<String> raMcfClasses = new HashSet<String>();
Set<String> raAoClasses = new HashSet<String>();
ResourceAdapter ra = cmd.getResourceadapter();
if (ra != null && ra.getOutboundResourceadapter() != null &&
ra.getOutboundResourceadapter().getConnectionDefinitions() != null) {
List<ConnectionDefinition> cdMetas = ra.getOutboundResourceadapter().getConnectionDefinitions();
if (!cdMetas.isEmpty()) {
for (ConnectionDefinition cdMeta : cdMetas) {
raMcfClasses.add(cdMeta.getManagedConnectionFactoryClass().getValue());
}
}
}
if (ra != null && ra.getAdminObjects() != null) {
List<AdminObject> aoMetas = ra.getAdminObjects();
if (!aoMetas.isEmpty()) {
for (AdminObject aoMeta : aoMetas) {
raAoClasses.add(aoMeta.getAdminobjectClass().getValue());
}
}
}
// Pure inflow always active except in case it is deployed as module
if (raMcfClasses.isEmpty() && raAoClasses.isEmpty() && !fromModule)
return true;
if (activation != null) {
if (activation.getConnectionDefinitions() != null) {
for (org.jboss.jca.common.api.metadata.resourceadapter.ConnectionDefinition def : activation.getConnectionDefinitions()) {
String clz = def.getClassName();
if (raMcfClasses.contains(clz))
return true;
}
}
if (activation.getAdminObjects() != null) {
for (org.jboss.jca.common.api.metadata.resourceadapter.AdminObject def : activation.getAdminObjects()) {
String clz = def.getClassName();
if (raAoClasses.contains(clz))
return true;
}
}
}
}
return false;
}
@Override
protected DeployersLogger getLogger() {
return DEPLOYERS_LOGGER;
}
@Override
protected void setRecoveryForResourceAdapterInResourceAdapterRepository(String key, boolean isXA) {
try {
raRepository.getValue().setRecoveryForResourceAdapter(key, isXA);
} catch (Throwable t) {
DEPLOYMENT_CONNECTOR_LOGGER.unableToRegisterRecovery(key, isXA);
}
}
}
}
| 14,328 | 45.372168 | 177 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/deployment/InactiveResourceAdapterDeploymentService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.services.resourceadapters.deployment;
import static org.jboss.as.connector.logging.ConnectorLogger.ROOT_LOGGER;
import org.jboss.as.connector.metadata.xmldescriptors.ConnectorXmlDescriptor;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.modules.Module;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* A ResourceAdapterXmlDeploymentService.
* @author <a href="mailto:[email protected]">Stefano Maestri</a>
* @author <a href="mailto:[email protected]">Jesper Pedersen</a>
*/
public final class InactiveResourceAdapterDeploymentService implements
Service<InactiveResourceAdapterDeploymentService.InactiveResourceAdapterDeployment> {
private final InactiveResourceAdapterDeployment value;
public InactiveResourceAdapterDeploymentService(ConnectorXmlDescriptor connectorXmlDescriptor,
Module module, final String deployment, final String deploymentUnitName, final ServiceName deploymentUnitServiceName,
final ManagementResourceRegistration registration, final ServiceTarget serviceTarget, final Resource resource) {
this.value = new InactiveResourceAdapterDeployment(connectorXmlDescriptor, module, deployment, deploymentUnitName, deploymentUnitServiceName, registration, serviceTarget, resource);
}
public InactiveResourceAdapterDeployment getValue() {
return value;
}
/**
* Start
*/
@Override
public void start(StartContext context) throws StartException {
ROOT_LOGGER.debugf("starting Inactive:" + value.toString());
}
/**
* Stop
*/
@Override
public void stop(StopContext context) {
}
public static class InactiveResourceAdapterDeployment {
private final Module module;
private final ConnectorXmlDescriptor connectorXmlDescriptor;
private final String deployment;
private final String deploymentUnitName;
private final ServiceName deploymentUnitServiceName;
private final ManagementResourceRegistration registration;
private final ServiceTarget serviceTarget;
private final Resource resource;
public InactiveResourceAdapterDeployment(final ConnectorXmlDescriptor connectorXmlDescriptor, final Module module, final String deployment,
final String deploymentUnitName, final ServiceName deploymentUnitServiceName, final ManagementResourceRegistration registration,
final ServiceTarget serviceTarget, final Resource resource) {
this.connectorXmlDescriptor = connectorXmlDescriptor;
this.module = module;
this.deployment = deployment;
this.deploymentUnitName = deploymentUnitName;
this.deploymentUnitServiceName = deploymentUnitServiceName;
this.registration = registration;
this.serviceTarget = serviceTarget;
this.resource = resource;
}
public Resource getResource() {
return resource;
}
public Module getModule() {
return module;
}
public ConnectorXmlDescriptor getConnectorXmlDescriptor() {
return connectorXmlDescriptor;
}
public String getDeployment() {
return deployment;
}
public String getDeploymentUnitName() {
return deploymentUnitName;
}
public ServiceName getDeploymentUnitServiceName() {
return deploymentUnitServiceName;
}
public ManagementResourceRegistration getRegistration() {
return registration;
}
public ServiceTarget getServiceTarget() {
return serviceTarget;
}
@Override
public String toString() {
return "InactiveResourceAdapterDeployment{" +
"module=" + module +
", connectorXmlDescriptor=" + connectorXmlDescriptor +
", deployment='" + deployment + '\'' +
", deploymentUnitName='" + deploymentUnitName + '\'' +
", registration=" + registration +
", serviceTarget=" + serviceTarget +
'}';
}
}
}
| 5,723 | 38.75 | 189 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/deployment/ResourceAdapterXmlDeploymentService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.services.resourceadapters.deployment;
import static org.jboss.as.connector.logging.ConnectorLogger.DEPLOYMENT_CONNECTOR_LOGGER;
import java.io.File;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import org.jboss.as.connector.metadata.deployment.ResourceAdapterDeployment;
import org.jboss.as.connector.metadata.xmldescriptors.ConnectorXmlDescriptor;
import org.jboss.as.connector.services.resourceadapters.ResourceAdapterService;
import org.jboss.as.connector.subsystems.resourceadapters.ModifiableResourceAdapter;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.as.naming.WritableServiceBasedNamingStore;
import org.jboss.jca.common.api.metadata.resourceadapter.Activation;
import org.jboss.jca.common.api.metadata.spec.Connector;
import org.jboss.jca.common.metadata.merge.Merger;
import org.jboss.jca.deployers.DeployersLogger;
import org.jboss.jca.deployers.common.CommonDeployment;
import org.jboss.logging.Logger;
import org.jboss.modules.Module;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* A ResourceAdapterXmlDeploymentService.
* @author <a href="mailto:[email protected]">Stefano Maestri</a>
* @author <a href="mailto:[email protected]">Jesper Pedersen</a>
*/
public final class ResourceAdapterXmlDeploymentService extends AbstractResourceAdapterDeploymentService implements
Service<ResourceAdapterDeployment> {
private static final DeployersLogger DEPLOYERS_LOGGER = Logger.getMessageLogger(DeployersLogger.class, "org.jboss.as.connector.deployers.RaXmlDeployer");
private final Module module;
private final ConnectorXmlDescriptor connectorXmlDescriptor;
private Activation raxml;
private final String deployment;
private String raName;
private ServiceName deploymentServiceName;
private CommonDeployment raxmlDeployment = null;
private final ServiceName duServiceName;
public ResourceAdapterXmlDeploymentService(ConnectorXmlDescriptor connectorXmlDescriptor, Activation raxml,
Module module, final String deployment, final ServiceName deploymentServiceName, final ServiceName duServiceName) {
this.connectorXmlDescriptor = connectorXmlDescriptor;
synchronized (this) {
this.raxml = raxml;
}
this.module = module;
this.deployment = deployment;
this.raName = deployment;
this.deploymentServiceName = deploymentServiceName;
this.duServiceName = duServiceName;
}
/**
* Start
*/
@Override
public void start(StartContext context) throws StartException {
try {
Connector cmd = mdr.getValue().getResourceAdapter(deployment);
File root = mdr.getValue().getRoot(deployment);
Activation localRaXml = getRaxml();
cmd = (new Merger()).mergeConnectorWithCommonIronJacamar(localRaXml, cmd);
String id = ((ModifiableResourceAdapter) raxml).getId();
final ServiceName raServiceName;
if (id == null || id.trim().isEmpty()) {
raServiceName = ConnectorServices.getResourceAdapterServiceName(raName);
this.connectorServicesRegistrationName = raName;
} else {
raServiceName = ConnectorServices.getResourceAdapterServiceName(id);
this.connectorServicesRegistrationName = id;
}
final WildFlyRaXmlDeployer raDeployer = new WildFlyRaXmlDeployer(context.getChildTarget(), connectorXmlDescriptor.getUrl(),
raName, root, module.getClassLoader(), cmd, localRaXml, deploymentServiceName);
raDeployer.setConfiguration(config.getValue());
WritableServiceBasedNamingStore.pushOwner(duServiceName);
ClassLoader old = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(module.getClassLoader());
raxmlDeployment = raDeployer.doDeploy();
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(old);
WritableServiceBasedNamingStore.popOwner();
}
value = new ResourceAdapterDeployment(raxmlDeployment, raName, raServiceName);
managementRepository.getValue().getConnectors().add(value.getDeployment().getConnector());
registry.getValue().registerResourceAdapterDeployment(value);
final ServiceBuilder raServiceSB = context.getChildTarget()
.addService(raServiceName,
new ResourceAdapterService(raServiceName, value.getDeployment().getResourceAdapter()));
raServiceSB.requires(deploymentServiceName);
raServiceSB.setInitialMode(ServiceController.Mode.ACTIVE).install();
} catch (Throwable t) {
cleanupStartAsync(context, raName, deploymentServiceName, t);
}
}
/**
* Stop
*/
@Override
public void stop(StopContext context) {
stopAsync(context, raName, deploymentServiceName);
}
@Override
public Collection<String> getJndiAliases() {
return Collections.emptyList();
}
public CommonDeployment getRaxmlDeployment() {
return raxmlDeployment;
}
public synchronized void setRaxml(Activation raxml) {
this.raxml = raxml;
}
public synchronized Activation getRaxml() {
return raxml;
}
private class WildFlyRaXmlDeployer extends AbstractWildFlyRaDeployer {
private final Activation activation;
public WildFlyRaXmlDeployer(ServiceTarget serviceTarget, URL url, String deploymentName, File root, ClassLoader cl,
Connector cmd, Activation activation, final ServiceName deploymentServiceName) {
super(serviceTarget, url, deploymentName, root, cl, cmd, deploymentServiceName);
this.activation = activation;
}
@Override
public CommonDeployment doDeploy() throws Throwable {
this.setConfiguration(getConfig().getValue());
this.start();
CommonDeployment dep = this.createObjectsAndInjectValue(url, deploymentName, root, cl, cmd, activation);
return dep;
}
@Override
protected boolean checkActivation(Connector cmd, Activation activation) {
return true;
}
@Override
protected DeployersLogger getLogger() {
return DEPLOYERS_LOGGER;
}
@Override
protected void setRecoveryForResourceAdapterInResourceAdapterRepository(String key, boolean isXA) {
try {
raRepository.getValue().setRecoveryForResourceAdapter(key, isXA);
} catch (Throwable t) {
DEPLOYMENT_CONNECTOR_LOGGER.unableToRegisterRecovery(key, isXA);
}
}
}
}
| 8,419 | 39.873786 | 162 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/deployment/JBossLogPrintWriter.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2014, 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.services.resourceadapters.deployment;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Formatter;
import java.util.Locale;
/**
* JBossLogPrintWriter PrintWriter for JBossLogging
*
* @author <a href="mailto:[email protected]">Jeff Zhang</a>
*/
public final class JBossLogPrintWriter extends PrintWriter {
private final String deploymentName;
private final BasicLogger logger;
private final Logger.Level level = Logger.Level.INFO;
private StringBuilder buffer = new StringBuilder();
private Formatter formatter;
public JBossLogPrintWriter(String deploymentName, BasicLogger logger) {
super(new OutputStream() {
@Override
public void write(final int b) throws IOException {
// do nothing
}
@Override
public void write(final byte[] b) throws IOException {
// do nothing
}
@Override
public void write(final byte[] b, final int off, final int len) throws IOException {
// do nothing
}
});
this.deploymentName = deploymentName;
this.logger = logger;
}
@Override
public void write(int c) {
synchronized (lock) {
if (c == '\n') {
outputLogger();
} else {
buffer.append((char) c);
}
}
}
@Override
public void write(char[] cbuf, int off, int len) {
synchronized (lock) {
int mark = 0;
int i;
for (i = 0; i < len; i++) {
final char c = cbuf[off + i];
if (c == '\n') {
buffer.append(cbuf, mark + off, i - mark);
outputLogger();
mark = i + 1;
}
}
buffer.append(cbuf, mark + off, i - mark);
}
}
@Override
public void write(char[] buf) {
write(buf, 0, buf.length);
}
@Override
public void write(String str, int off, int len) {
synchronized (lock) {
int mark = 0;
int i;
for (i = 0; i < len; i++) {
final char c = str.charAt(off + i);
if (c == '\n') {
buffer.append(str, mark + off, off + i);
outputLogger();
mark = i + 1;
}
}
buffer.append(str, mark + off, off + i);
}
}
@Override
public void write(String s) {
write(s, 0, s.length());
}
private void outputLogger() {
if (buffer.length() > 0) {
logger.log(level, deploymentName + ": " + buffer.toString());
buffer.setLength(0);
}
}
@Override
public void flush() {
synchronized (lock) {
outputLogger();
}
}
@Override
public void close() {
flush();
}
@Override
public boolean checkError() {
flush();
return false;
}
@Override
protected void setError() {
}
@Override
protected void clearError() {
}
@Override
public void print(boolean b) {
write(String.valueOf(b) );
}
@Override
public void print(char c) {
write(c);
}
@Override
public void print(int i) {
write(String.valueOf(i));
}
@Override
public void print(long l) {
write(String.valueOf(l));
}
@Override
public void print(float f) {
write(String.valueOf(f));
}
@Override
public void print(double d) {
write(String.valueOf(d));
}
@Override
public void print(char[] s) {
write(s);
}
@Override
public void print(String s) {
if (s != null) {
write(s);
}
}
@Override
public void print(Object obj) {
if (obj != null) {
write(String.valueOf(obj));
}
}
private void newLine() {
outputLogger();
}
@Override
public void println() {
newLine();
}
@Override
public void println(boolean x) {
synchronized (lock) {
print(x);
println();
}
}
@Override
public void println(char x) {
synchronized (lock) {
print(x);
println();
}
}
@Override
public void println(int x) {
synchronized (lock) {
print(x);
println();
}
}
@Override
public void println(long x) {
synchronized (lock) {
print(x);
println();
}
}
@Override
public void println(float x) {
synchronized (lock) {
print(x);
println();
}
}
@Override
public void println(double x) {
synchronized (lock) {
print(x);
println();
}
}
@Override
public void println(char[] x) {
synchronized (lock) {
print(x);
println();
}
}
@Override
public void println(String x) {
synchronized (lock) {
print(x);
println();
}
}
@Override
public void println(Object x) {
String s = String.valueOf(x);
synchronized (lock) {
print(s);
println();
}
}
@Override
public JBossLogPrintWriter printf(String format, Object ... args) {
return format(format, args);
}
@Override
public JBossLogPrintWriter printf(Locale l, String format, Object ... args) {
return format(l, format, args);
}
public JBossLogPrintWriter format(String format, Object ... args) {
synchronized (lock) {
if ((formatter == null)
|| (formatter.locale() != Locale.getDefault()))
formatter = new Formatter(this);
formatter.format(Locale.getDefault(), format, args);
}
return this;
}
public JBossLogPrintWriter format(Locale l, String format, Object ... args) {
synchronized (lock) {
if ((formatter == null) || (formatter.locale() != l))
formatter = new Formatter(this, l);
formatter.format(l, format, args);
}
return this;
}
@Override
public JBossLogPrintWriter append(CharSequence csq) {
if (csq != null)
write(csq.toString());
return this;
}
@Override
public JBossLogPrintWriter append(CharSequence csq, int start, int end) {
if (csq != null)
write(csq.subSequence(start, end).toString());
return this;
}
@Override
public JBossLogPrintWriter append(char c) {
write(c);
return this;
}
}
| 8,021 | 22.804154 | 96 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/deployment/AbstractResourceAdapterDeploymentService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.services.resourceadapters.deployment;
import static java.lang.Thread.currentThread;
import static java.security.AccessController.doPrivileged;
import static org.jboss.as.connector.logging.ConnectorLogger.DEPLOYMENT_CONNECTOR_LOGGER;
import java.io.File;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.PrivilegedAction;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadFactory;
import javax.naming.InitialContext;
import javax.naming.Reference;
import jakarta.resource.spi.ResourceAdapter;
import jakarta.transaction.TransactionManager;
import org.jboss.as.connector.logging.ConnectorLogger;
import org.jboss.as.connector.metadata.api.resourceadapter.WorkManagerSecurity;
import org.jboss.as.connector.metadata.deployment.ResourceAdapterDeployment;
import org.jboss.as.connector.security.CallbackImpl;
import org.jboss.as.connector.security.ElytronSubjectFactory;
import org.jboss.as.connector.services.mdr.AS7MetadataRepository;
import org.jboss.as.connector.services.resourceadapters.AdminObjectReferenceFactoryService;
import org.jboss.as.connector.services.resourceadapters.AdminObjectService;
import org.jboss.as.connector.services.resourceadapters.ConnectionFactoryReferenceFactoryService;
import org.jboss.as.connector.services.resourceadapters.ConnectionFactoryService;
import org.jboss.as.connector.services.resourceadapters.deployment.registry.ResourceAdapterDeploymentRegistry;
import org.jboss.as.connector.subsystems.common.jndi.Util;
import org.jboss.as.connector.subsystems.jca.JcaSubsystemConfiguration;
import org.jboss.as.connector.subsystems.resourceadapters.ResourceAdaptersSubsystemService;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.as.connector.util.Injection;
import org.jboss.as.connector.util.JCAValidatorFactory;
import org.jboss.as.naming.ContextListAndJndiViewManagedReferenceFactory;
import org.jboss.as.naming.ContextListManagedReferenceFactory;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.naming.ServiceBasedNamingStore;
import org.jboss.as.naming.ValueManagedReference;
import org.jboss.as.naming.WritableServiceBasedNamingStore;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.service.BinderService;
import org.jboss.jca.common.api.metadata.common.SecurityMetadata;
import org.jboss.jca.common.api.metadata.resourceadapter.Activation;
import org.jboss.jca.common.api.metadata.spec.ConfigProperty;
import org.jboss.jca.common.api.metadata.spec.Connector;
import org.jboss.jca.common.api.metadata.spec.XsdString;
import org.jboss.jca.core.api.connectionmanager.ccm.CachedConnectionManager;
import org.jboss.jca.core.api.management.ManagementRepository;
import org.jboss.jca.core.bootstrapcontext.BootstrapContextCoordinator;
import org.jboss.jca.core.connectionmanager.ConnectionManager;
import org.jboss.jca.core.spi.mdr.AlreadyExistsException;
import org.jboss.jca.core.spi.rar.ResourceAdapterRepository;
import org.jboss.jca.core.spi.security.Callback;
import org.jboss.jca.core.spi.transaction.TransactionIntegration;
import org.jboss.jca.core.spi.transaction.recovery.XAResourceRecovery;
import org.jboss.jca.core.spi.transaction.recovery.XAResourceRecoveryRegistry;
import org.jboss.jca.deployers.common.AbstractResourceAdapterDeployer;
import org.jboss.jca.deployers.common.BeanValidation;
import org.jboss.jca.deployers.common.CommonDeployment;
import org.jboss.jca.deployers.common.DeployException;
import org.jboss.logging.BasicLogger;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.LifecycleEvent;
import org.jboss.msc.service.LifecycleListener;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.jboss.threads.JBossThreadFactory;
import org.wildfly.security.manager.WildFlySecurityManager;
import org.wildfly.security.manager.action.ClearContextClassLoaderAction;
import org.wildfly.security.manager.action.SetContextClassLoaderFromClassAction;
/**
* A ResourceAdapterDeploymentService.
* @author <a href="mailto:[email protected]">Stefano Maestri</a>
* @author <a href="mailto:[email protected]">Jesper Pedersen</a>
*/
public abstract class AbstractResourceAdapterDeploymentService {
// Must be set by the start method
protected ResourceAdapterDeployment value;
protected final InjectedValue<AS7MetadataRepository> mdr = new InjectedValue<AS7MetadataRepository>();
protected final InjectedValue<ResourceAdapterRepository> raRepository = new InjectedValue<ResourceAdapterRepository>();
protected final InjectedValue<ResourceAdapterDeploymentRegistry> registry = new InjectedValue<ResourceAdapterDeploymentRegistry>();
protected final InjectedValue<ManagementRepository> managementRepository = new InjectedValue<ManagementRepository>();
protected final InjectedValue<JcaSubsystemConfiguration> config = new InjectedValue<JcaSubsystemConfiguration>();
protected final InjectedValue<TransactionIntegration> txInt = new InjectedValue<TransactionIntegration>();
protected final InjectedValue<CachedConnectionManager> ccmValue = new InjectedValue<CachedConnectionManager>();
protected final InjectedValue<ExecutorService> executorServiceInjector = new InjectedValue<ExecutorService>();
protected final InjectedValue<ResourceAdaptersSubsystemService> resourceAdaptersSubsystem = new InjectedValue<>();
protected String raRepositoryRegistrationId;
protected String connectorServicesRegistrationName;
protected String mdrRegistrationName;
public ResourceAdapterDeployment getValue() {
return ConnectorServices.notNull(value);
}
public void unregisterAll(String deploymentName) {
if (value != null) {
DEPLOYMENT_CONNECTOR_LOGGER.debugf("Unregistering: %s", deploymentName);
if (registry != null && registry.getValue() != null) {
registry.getValue().unregisterResourceAdapterDeployment(value);
}
if (managementRepository != null && managementRepository.getValue() != null &&
value.getDeployment() != null && value.getDeployment().getConnector() != null) {
managementRepository.getValue().getConnectors().remove(value.getDeployment().getConnector());
}
if (mdr != null && mdr.getValue() != null && value.getDeployment() != null
&& value.getDeployment().getCfs() != null && value.getDeployment().getCfJndiNames() != null) {
for (int i = 0; i < value.getDeployment().getCfs().length; i++) {
try {
String cf = value.getDeployment().getCfs()[i].getClass().getName();
String jndi = value.getDeployment().getCfJndiNames()[i];
mdr.getValue().unregisterJndiMapping(value.getDeployment().getURL().toExternalForm(), cf, jndi);
} catch (Throwable nfe) {
DEPLOYMENT_CONNECTOR_LOGGER.debug("Exception during JNDI unbinding", nfe);
}
}
}
if (mdr != null && mdr.getValue() != null && value.getDeployment().getAos() != null
&& value.getDeployment().getAoJndiNames() != null) {
for (int i = 0; i < value.getDeployment().getAos().length; i++) {
try {
String ao = value.getDeployment().getAos()[i].getClass().getName();
String jndi = value.getDeployment().getAoJndiNames()[i];
mdr.getValue().unregisterJndiMapping(value.getDeployment().getURL().toExternalForm(), ao, jndi);
} catch (Throwable nfe) {
DEPLOYMENT_CONNECTOR_LOGGER.debug("Exception during JNDI unbinding", nfe);
}
}
}
if (value!= null && value.getDeployment() != null && value.getDeployment().getRecovery() != null && txInt !=null && txInt.getValue() != null) {
XAResourceRecoveryRegistry rr = txInt.getValue().getRecoveryRegistry();
if (rr != null) {
for (XAResourceRecovery recovery : value.getDeployment().getRecovery()) {
if (recovery!= null) {
try {
recovery.shutdown();
} catch (Exception e) {
DEPLOYMENT_CONNECTOR_LOGGER.errorDuringRecoveryShutdown(e);
} finally {
rr.removeXAResourceRecovery(recovery);
}
}
}
}
}
if (value.getDeployment() != null && value.getDeployment().getConnectionManagers() != null) {
for (ConnectionManager cm : value.getDeployment().getConnectionManagers()) {
cm.shutdown();
}
}
if (value.getDeployment() != null && value.getDeployment().getResourceAdapter() != null) {
ClassLoader old = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(value.getDeployment().getResourceAdapter().getClass().getClassLoader());
value.getDeployment().getResourceAdapter().stop();
} catch (Throwable nfe) {
DEPLOYMENT_CONNECTOR_LOGGER.errorStoppingRA(nfe);
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(old);
}
}
if (value.getDeployment() != null && value.getDeployment().getBootstrapContextIdentifier() != null) {
BootstrapContextCoordinator.getInstance().removeBootstrapContext(value.getDeployment().getBootstrapContextIdentifier());
}
}
if (raRepositoryRegistrationId != null && raRepository != null && raRepository.getValue() != null) {
try {
raRepository.getValue().unregisterResourceAdapter(raRepositoryRegistrationId);
} catch (Throwable e) {
DEPLOYMENT_CONNECTOR_LOGGER.debug("Failed to unregister RA from RA Repository", e);
}
}
if (connectorServicesRegistrationName != null) {
try {
ConnectorServices.unregisterResourceAdapterIdentifier(connectorServicesRegistrationName);
} catch (Throwable e) {
DEPLOYMENT_CONNECTOR_LOGGER.debug("Failed to unregister RA from ConnectorServices", e);
}
}
if (mdrRegistrationName != null && mdr != null && mdr.getValue() != null) {
try {
mdr.getValue().unregisterResourceAdapter(mdrRegistrationName);
} catch (Throwable e) {
DEPLOYMENT_CONNECTOR_LOGGER.debug("Failed to unregister RA from MDR", e);
}
}
}
public Injector<AS7MetadataRepository> getMdrInjector() {
return mdr;
}
public Injector<ResourceAdapterRepository> getRaRepositoryInjector() {
return raRepository;
}
public Injector<ManagementRepository> getManagementRepositoryInjector() {
return managementRepository;
}
public Injector<ResourceAdapterDeploymentRegistry> getRegistryInjector() {
return registry;
}
public InjectedValue<JcaSubsystemConfiguration> getConfig() {
return config;
}
public InjectedValue<TransactionIntegration> getTxIntegration() {
return txInt;
}
public Injector<TransactionIntegration> getTxIntegrationInjector() {
return txInt;
}
public Injector<JcaSubsystemConfiguration> getConfigInjector() {
return config;
}
public Injector<CachedConnectionManager> getCcmInjector() {
return ccmValue;
}
public Injector<ExecutorService> getExecutorServiceInjector() {
return executorServiceInjector;
}
public Injector<ResourceAdaptersSubsystemService> getResourceAdaptersSubsystem() {
return resourceAdaptersSubsystem;
}
protected final ExecutorService getLifecycleExecutorService() {
ExecutorService result = executorServiceInjector.getOptionalValue();
if (result == null) {
// We added injection of the server executor late in WF 8, so in case some
// add-on projects don't know to inject it....
final ThreadGroup threadGroup = new ThreadGroup("ResourceAdapterDeploymentService ThreadGroup");
final String namePattern = "ResourceAdapterDeploymentService Thread Pool -- %t";
final ThreadFactory threadFactory = doPrivileged(new PrivilegedAction<JBossThreadFactory>() {
public JBossThreadFactory run() {
return new JBossThreadFactory(threadGroup, Boolean.FALSE, null, namePattern, null, null);
}
});
result = Executors.newSingleThreadExecutor(threadFactory);
}
return result;
}
public ContextNames.BindInfo getBindInfo(String jndi) {
return ContextNames.bindInfoFor(jndi);
}
public abstract Collection<String> getJndiAliases();
/**
* @return {@code true} if the binder service must be created to bind the connection factory
*/
public boolean isCreateBinderService() {
return true;
}
protected final void cleanupStartAsync(final StartContext context, final String deploymentName,
final ServiceName serviceName, final Throwable cause) {
ExecutorService executorService = getLifecycleExecutorService();
Runnable r = new Runnable() {
@Override
public void run() {
try {
// TODO -- one of the 3 previous synchronous calls to this method don't had the TCCL set,
// but the other two don't. I (BES 2013/10/21) intepret from that that setting the TCCL
// was not necessary and in caller that had it set it was an artifact of
WritableServiceBasedNamingStore.pushOwner(serviceName);
unregisterAll(deploymentName);
} finally {
WritableServiceBasedNamingStore.popOwner();
context.failed(ConnectorLogger.ROOT_LOGGER.failedToStartRaDeployment(cause, deploymentName));
}
}
};
try {
executorService.execute(r);
} catch (RejectedExecutionException e) {
r.run();
} finally {
context.asynchronous();
}
}
protected void stopAsync(final StopContext context, final String deploymentName, final ServiceName serviceName) {
ExecutorService executorService = getLifecycleExecutorService();
Runnable r = new Runnable() {
@Override
public void run() {
try {
DEPLOYMENT_CONNECTOR_LOGGER.debugf("Stopping service %s", serviceName);
WritableServiceBasedNamingStore.pushOwner(serviceName);
unregisterAll(deploymentName);
} finally {
WritableServiceBasedNamingStore.popOwner();
context.complete();
}
}
};
try {
executorService.execute(r);
} catch (RejectedExecutionException e) {
r.run();
} finally {
context.asynchronous();
}
}
protected abstract class AbstractWildFlyRaDeployer extends AbstractResourceAdapterDeployer {
protected final ServiceTarget serviceTarget;
protected final URL url;
protected final String deploymentName;
protected final File root;
protected final ClassLoader cl;
protected final Connector cmd;
protected final ServiceName deploymentServiceName;
protected AbstractWildFlyRaDeployer(ServiceTarget serviceTarget, URL url, String deploymentName, File root, ClassLoader cl,
Connector cmd, final ServiceName deploymentServiceName) {
super(true);
this.serviceTarget = serviceTarget;
this.url = url;
this.deploymentName = deploymentName;
this.root = root;
this.cl = cl;
this.cmd = cmd;
this.deploymentServiceName = deploymentServiceName;
}
public abstract CommonDeployment doDeploy() throws Throwable;
@Override
public String[] bindConnectionFactory(URL url, String deployment, Object cf) throws Throwable {
throw ConnectorLogger.ROOT_LOGGER.jndiBindingsNotSupported();
}
@Override
public String[] bindConnectionFactory(URL url, String deployment, Object cf, final String jndi) throws Throwable {
mdr.getValue().registerJndiMapping(url.toExternalForm(), cf.getClass().getName(), jndi);
DEPLOYMENT_CONNECTOR_LOGGER.registeredConnectionFactory(jndi);
final ConnectionFactoryService connectionFactoryService = new ConnectionFactoryService(cf);
final ServiceName connectionFactoryServiceName = ConnectionFactoryService.SERVICE_NAME_BASE.append(jndi);
ServiceBuilder connectionFactoryBuilder = serviceTarget.addService(connectionFactoryServiceName, connectionFactoryService);
if (deploymentServiceName != null)
connectionFactoryBuilder.requires(deploymentServiceName);
connectionFactoryBuilder.setInitialMode(ServiceController.Mode.ACTIVE).install();
// use a BindInfo to build the referenceFactoryService's service name.
// if the CF is in a java:app/ or java:module/ namespace, we need the whole bindInfo's binder service name
// to distinguish CFs with same name in different application (or module).
final ContextNames.BindInfo bindInfo = getBindInfo(jndi);
final ConnectionFactoryReferenceFactoryService referenceFactoryService = new ConnectionFactoryReferenceFactoryService(deployment);
final ServiceName referenceFactoryServiceName = ConnectionFactoryReferenceFactoryService.SERVICE_NAME_BASE
.append(bindInfo.getBinderServiceName());
serviceTarget.addService(referenceFactoryServiceName, referenceFactoryService)
.addDependency(connectionFactoryServiceName, Object.class, referenceFactoryService.getConnectionFactoryInjector())
.setInitialMode(ServiceController.Mode.ACTIVE).install();
if (isCreateBinderService()) {
final BinderService binderService = new BinderService(bindInfo.getBindName());
serviceTarget
.addService(bindInfo.getBinderServiceName(), binderService)
.addDependency(referenceFactoryServiceName, ManagedReferenceFactory.class,
binderService.getManagedObjectInjector())
.addDependency(bindInfo.getParentContextServiceName(), ServiceBasedNamingStore.class,
binderService.getNamingStoreInjector())
.addListener(new LifecycleListener() {
private volatile boolean bound;
public void handleEvent(final ServiceController<? extends Object> controller, final LifecycleEvent event) {
switch (event) {
case UP: {
DEPLOYMENT_CONNECTOR_LOGGER.boundJca("ConnectionFactory", jndi);
bound = true;
break;
}
case DOWN: {
if (bound) {
DEPLOYMENT_CONNECTOR_LOGGER.unboundJca("ConnectionFactory", jndi);
}
break;
}
case REMOVED: {
DEPLOYMENT_CONNECTOR_LOGGER.debugf("Removed Jakarta Connectors ConnectionFactory [%s]", jndi);
}
}
}
})
.setInitialMode(ServiceController.Mode.ACTIVE)
.install();
}
installJNDIAliases(bindInfo, serviceTarget);
// AS7-2222: Just hack it
if (cf instanceof jakarta.resource.Referenceable) {
((jakarta.resource.Referenceable)cf).setReference(new Reference(jndi));
}
return new String[] { jndi };
}
private void installJNDIAliases(final ContextNames.BindInfo bindInfo, final ServiceTarget serviceTarget) {
for (String alias : getJndiAliases()) {
final ContextNames.BindInfo aliasBindInfo = ContextNames.bindInfoFor(alias);
final BinderService aliasBinderService = new BinderService(alias);
aliasBinderService.getManagedObjectInjector().inject(new AliasManagedReferenceFactory(bindInfo.getAbsoluteJndiName()));
final ServiceBuilder sb = serviceTarget.addService(aliasBindInfo.getBinderServiceName(), aliasBinderService);
sb.addDependency(bindInfo.getParentContextServiceName(), ServiceBasedNamingStore.class, aliasBinderService.getNamingStoreInjector());
sb.requires(bindInfo.getBinderServiceName());
sb.addListener(new LifecycleListener() {
private volatile boolean bound;
@Override
public void handleEvent(ServiceController<?> controller, LifecycleEvent event) {
switch (event) {
case UP: {
DEPLOYMENT_CONNECTOR_LOGGER.bindingAlias(bindInfo.getAbsoluteJndiName(), alias);
bound = true;
break;
}
case DOWN: {
if (bound) {
DEPLOYMENT_CONNECTOR_LOGGER.unbindingAlias(bindInfo.getAbsoluteJndiName(), alias);
}
break;
}
case REMOVED: {
DEPLOYMENT_CONNECTOR_LOGGER.debugf("Removed messaging object [%s]", alias);
break;
}
}
}
});
sb.install();
}
}
@Override
public String[] bindAdminObject(URL url, String deployment, Object ao) throws Throwable {
throw ConnectorLogger.ROOT_LOGGER.jndiBindingsNotSupported();
}
@Override
public String[] bindAdminObject(URL url, String deployment, Object ao, final String jndi) throws Throwable {
mdr.getValue().registerJndiMapping(url.toExternalForm(), ao.getClass().getName(), jndi);
DEPLOYMENT_CONNECTOR_LOGGER.registeredAdminObject(jndi);
final AdminObjectService adminObjectService = new AdminObjectService(ao);
final ServiceName adminObjectServiceName = AdminObjectService.SERVICE_NAME_BASE.append(jndi);
serviceTarget.addService(adminObjectServiceName, adminObjectService).setInitialMode(ServiceController.Mode.ACTIVE)
.install();
// use a BindInfo to build the referenceFactoryService's service name.
// if the CF is in a java:app/ or java:module/ namespace, we need the whole bindInfo's binder service name
// to distinguish CFs with same name in different application (or module).
final ContextNames.BindInfo bindInfo = getBindInfo(jndi);
final AdminObjectReferenceFactoryService referenceFactoryService = new AdminObjectReferenceFactoryService();
final ServiceName referenceFactoryServiceName = AdminObjectReferenceFactoryService.SERVICE_NAME_BASE.append(bindInfo.getBinderServiceName());
serviceTarget.addService(referenceFactoryServiceName, referenceFactoryService)
.addDependency(adminObjectServiceName, Object.class, referenceFactoryService.getAdminObjectInjector())
.setInitialMode(ServiceController.Mode.ACTIVE).install();
if (isCreateBinderService()) {
final BinderService binderService = new BinderService(bindInfo.getBindName());
final ServiceName binderServiceName = bindInfo.getBinderServiceName();
serviceTarget
.addService(binderServiceName, binderService)
.addDependency(referenceFactoryServiceName, ManagedReferenceFactory.class,
binderService.getManagedObjectInjector())
.addDependency(bindInfo.getParentContextServiceName(), ServiceBasedNamingStore.class,
binderService.getNamingStoreInjector()).addListener(new LifecycleListener() {
private volatile boolean bound;
public void handleEvent(final ServiceController<?> controller, final LifecycleEvent event) {
switch (event) {
case UP: {
DEPLOYMENT_CONNECTOR_LOGGER.boundJca("AdminObject", jndi);
bound = true;
break;
}
case DOWN: {
if (bound) {
DEPLOYMENT_CONNECTOR_LOGGER.unboundJca("AdminObject", jndi);
}
break;
}
case REMOVED: {
DEPLOYMENT_CONNECTOR_LOGGER.debugf("Removed Jakarta Connectors AdminObject [%s]", jndi);
}
}
}
}).setInitialMode(ServiceController.Mode.ACTIVE).install();
}
// AS7-2222: Just hack it
if (ao instanceof jakarta.resource.Referenceable) {
((jakarta.resource.Referenceable)ao).setReference(new Reference(jndi));
}
return new String[] { jndi };
}
@Override
protected abstract boolean checkActivation(Connector cmd, Activation activation);
@Override
protected boolean checkConfigurationIsValid() {
return this.getConfiguration() != null;
}
@Override
protected PrintWriter getLogPrintWriter() {
return new JBossLogPrintWriter(deploymentName, (BasicLogger)this.log);
}
@Override
protected File getReportDirectory() {
if (resourceAdaptersSubsystem.getOptionalValue() != null) {
return resourceAdaptersSubsystem.getValue().getReportDirectory();
} else {
return null;
}
}
@Override
protected TransactionManager getTransactionManager() {
if (! WildFlySecurityManager.isChecking()) {
currentThread().setContextClassLoader(TransactionIntegration.class.getClassLoader());
} else {
doPrivileged(new SetContextClassLoaderFromClassAction(TransactionIntegration.class));
}
try {
return getTxIntegration().getValue().getTransactionManager();
} finally {
if (! WildFlySecurityManager.isChecking()) {
currentThread().setContextClassLoader(null);
} else {
doPrivileged(ClearContextClassLoaderAction.getInstance());
}
}
}
@Override
public Object initAndInject(String className, List<? extends ConfigProperty> configs, ClassLoader cl)
throws DeployException {
try {
Class clz = Class.forName(className, true, cl);
Object o = clz.newInstance();
if (configs != null) {
Injection injector = new Injection();
for (ConfigProperty cpmd : configs) {
if (cpmd.isValueSet()) {
if (XsdString.isNull(cpmd.getConfigPropertyType())) {
injector.inject(o,
cpmd.getConfigPropertyName().getValue(),
cpmd.getConfigPropertyValue().getValue());
} else {
injector.inject(o,
cpmd.getConfigPropertyName().getValue(),
cpmd.getConfigPropertyValue().getValue(),
cpmd.getConfigPropertyType().getValue());
}
}
}
}
return o;
} catch (Throwable t) {
throw ConnectorLogger.ROOT_LOGGER.deploymentFailed(t, className);
}
}
@Override
protected void registerResourceAdapterToMDR(URL url, File file, Connector connector, Activation ij)
throws AlreadyExistsException {
DEPLOYMENT_CONNECTOR_LOGGER.debugf("Registering ResourceAdapter %s", deploymentName);
mdr.getValue().registerResourceAdapter(deploymentName, file, connector, ij);
mdrRegistrationName = deploymentName;
}
@Override
protected String registerResourceAdapterToResourceAdapterRepository(ResourceAdapter instance) {
raRepositoryRegistrationId = raRepository.getValue().registerResourceAdapter(instance);
// make a note of this identifier for future use
if (connectorServicesRegistrationName != null) {
ConnectorServices.registerResourceAdapterIdentifier(connectorServicesRegistrationName, raRepositoryRegistrationId);
}
return raRepositoryRegistrationId;
}
@Override
protected org.jboss.jca.core.spi.security.SubjectFactory getSubjectFactory(
SecurityMetadata securityMetadata, final String jndiName) throws DeployException {
if (securityMetadata == null)
return null;
final String securityDomain = securityMetadata.resolveSecurityDomain();
if (securityDomain == null || securityDomain.trim().equals("")) {
return null;
} else {
try {
return new ElytronSubjectFactory(null, new URI(jndiName));
} catch (URISyntaxException e) {
throw ConnectorLogger.ROOT_LOGGER.cannotDeploy(e);
}
}
}
@Override
protected Callback createCallback(org.jboss.jca.common.api.metadata.resourceadapter.WorkManagerSecurity workManagerSecurity) {
if (workManagerSecurity != null) {
if (workManagerSecurity instanceof WorkManagerSecurity){
WorkManagerSecurity wms = (WorkManagerSecurity) workManagerSecurity;
String[] defaultGroups = wms.getDefaultGroups() != null ?
wms.getDefaultGroups().toArray(new String[workManagerSecurity.getDefaultGroups().size()]) : null;
return new CallbackImpl(wms.isMappingRequired(), wms.getDomain(),
wms.getDefaultPrincipal(), defaultGroups, wms.getUserMappings(), wms.getGroupMappings());
} else {
return super.createCallback(workManagerSecurity);
}
}
return null;
}
@Override
protected void setCallbackSecurity(org.jboss.jca.core.api.workmanager.WorkManager workManager, Callback cb) {
if (cb instanceof CallbackImpl) {
workManager.setCallbackSecurity(cb);
} else {
super.setCallbackSecurity(workManager, cb);
}
}
@Override
protected TransactionIntegration getTransactionIntegration() {
return getTxIntegration().getValue();
}
@Override
protected CachedConnectionManager getCachedConnectionManager() {
return ccmValue.getValue();
}
// Override this method to change how jndiName is build in AS7
@Override
protected String buildJndiName(String rawJndiName, Boolean javaContext) {
return Util.cleanJndiName(rawJndiName, javaContext);
}
@Override
protected BeanValidation getBeanValidation() {
return new BeanValidation(new JCAValidatorFactory(cl));
}
}
private static final class AliasManagedReferenceFactory implements ContextListAndJndiViewManagedReferenceFactory {
private final String name;
/**
* @param name original JNDI name
*/
public AliasManagedReferenceFactory(String name) {
this.name = name;
}
@Override
public ManagedReference getReference() {
try {
final Object value = new InitialContext().lookup(name);
return new ValueManagedReference(value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public String getInstanceClassName() {
final Object value = getReference().getInstance();
return value != null ? value.getClass().getName() : ContextListManagedReferenceFactory.DEFAULT_INSTANCE_CLASS_NAME;
}
@Override
public String getJndiViewInstanceValue() {
return String.valueOf(getReference().getInstance());
}
}
}
| 36,292 | 46.503927 | 155 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/deployment/registry/ResourceAdapterDeploymentRegistryService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.services.resourceadapters.deployment.registry;
import static org.jboss.as.connector.logging.ConnectorLogger.DEPLOYMENT_CONNECTOR_REGISTRY_LOGGER;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* The resource adapter deployment registry service
* @author <a href="mailto:[email protected]">Jesper Pedersen</a>
*/
public final class ResourceAdapterDeploymentRegistryService implements Service<ResourceAdapterDeploymentRegistry> {
private final ResourceAdapterDeploymentRegistry value;
/**
* Create an instance
*/
public ResourceAdapterDeploymentRegistryService() {
this.value = new ResourceAdapterDeploymentRegistryImpl();
}
@Override
public ResourceAdapterDeploymentRegistry getValue() throws IllegalStateException {
return ConnectorServices.notNull(value);
}
@Override
public void start(StartContext context) throws StartException {
DEPLOYMENT_CONNECTOR_REGISTRY_LOGGER.debugf("Starting service %s", ConnectorServices.RESOURCE_ADAPTER_REGISTRY_SERVICE);
}
/**
* Stop
*/
@Override
public void stop(StopContext context) {
DEPLOYMENT_CONNECTOR_REGISTRY_LOGGER.debugf("Stopping service %s", ConnectorServices.RESOURCE_ADAPTER_REGISTRY_SERVICE);
}
}
| 2,506 | 36.984848 | 128 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/deployment/registry/ResourceAdapterDeploymentRegistryImpl.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.services.resourceadapters.deployment.registry;
import static org.jboss.as.connector.logging.ConnectorLogger.DEPLOYMENT_CONNECTOR_REGISTRY_LOGGER;
import static org.wildfly.common.Assert.checkNotNullParam;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.jboss.as.connector.metadata.deployment.ResourceAdapterDeployment;
/**
* The interface for the resource adapter deployment registry
* @author <a href="mailto:[email protected]">Jesper Pedersen</a>
*/
public final class ResourceAdapterDeploymentRegistryImpl implements ResourceAdapterDeploymentRegistry {
private Set<ResourceAdapterDeployment> deployments;
/**
* Constructor
*/
public ResourceAdapterDeploymentRegistryImpl() {
this.deployments = new HashSet<ResourceAdapterDeployment>();
}
/**
* Register a resource adapter deployment
* @param deployment The deployment
*/
public void registerResourceAdapterDeployment(ResourceAdapterDeployment deployment) {
checkNotNullParam("deployment", deployment);
DEPLOYMENT_CONNECTOR_REGISTRY_LOGGER.tracef("Adding deployment: %s", deployment);
deployments.add(deployment);
}
/**
* Unregister a resource adapter deployment
* @param deployment The deployment
*/
public void unregisterResourceAdapterDeployment(ResourceAdapterDeployment deployment) {
checkNotNullParam("deployment", deployment);
DEPLOYMENT_CONNECTOR_REGISTRY_LOGGER.tracef("Removing deployment: %s", deployment);
deployments.remove(deployment);
}
/**
* Get the resource adapter deployments
* @return The set of deployments
*/
public Set<ResourceAdapterDeployment> getResourceAdapterDeployments() {
return Collections.unmodifiableSet(deployments);
}
}
| 2,900 | 34.378049 | 103 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/deployment/registry/ResourceAdapterDeploymentRegistry.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.services.resourceadapters.deployment.registry;
import java.util.Set;
import org.jboss.as.connector.metadata.deployment.ResourceAdapterDeployment;
/**
* The interface for the resource adapter deployment registry
* @author <a href="mailto:[email protected]">Jesper Pedersen</a>
*/
public interface ResourceAdapterDeploymentRegistry {
/**
* Register a resource adapter deployment
* @param deployment The deployment
*/
void registerResourceAdapterDeployment(ResourceAdapterDeployment deployment);
/**
* Unregister a resource adapter deployment
* @param deployment The deployment
*/
void unregisterResourceAdapterDeployment(ResourceAdapterDeployment deployment);
/**
* Get the resource adapter deployments
* @return The set of deployments
*/
Set<ResourceAdapterDeployment> getResourceAdapterDeployments();
}
| 1,944 | 35.698113 | 83 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/statistics/ResourceAdapterStatisticsService.java | /*
* 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.services.resourceadapters.statistics;
import static org.jboss.as.connector.logging.ConnectorLogger.ROOT_LOGGER;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import org.jboss.as.connector.dynamicresource.StatisticsResourceDefinition;
import org.jboss.as.connector.metadata.deployment.ResourceAdapterDeployment;
import org.jboss.as.connector.subsystems.resourceadapters.CommonAttributes;
import org.jboss.as.connector.subsystems.resourceadapters.Constants;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.descriptions.OverrideDescriptionProvider;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.jca.core.api.bootstrap.CloneableBootstrapContext;
import org.jboss.jca.core.spi.statistics.StatisticsPlugin;
import org.jboss.jca.deployers.common.CommonDeployment;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
public class ResourceAdapterStatisticsService implements Service<ManagementResourceRegistration> {
private final ManagementResourceRegistration overrideRegistration;
private final boolean statsEnabled;
protected final InjectedValue<ResourceAdapterDeployment> deployment = new InjectedValue<>();
protected final InjectedValue<CloneableBootstrapContext> bootstrapContext = new InjectedValue<>();
/**
* create an instance *
*/
public ResourceAdapterStatisticsService(final ManagementResourceRegistration registration,
final String jndiName,
final boolean statsEnabled) {
super();
if (registration.isAllowsOverride()) {
overrideRegistration = registration.registerOverrideModel(jndiName, new OverrideDescriptionProvider() {
@Override
public Map<String, ModelNode> getAttributeOverrideDescriptions(Locale locale) {
return Collections.emptyMap();
}
@Override
public Map<String, ModelNode> getChildTypeOverrideDescriptions(Locale locale) {
return Collections.emptyMap();
}
});
} else {
overrideRegistration = registration;
}
this.statsEnabled = statsEnabled;
}
@Override
public void start(StartContext context) throws StartException {
ROOT_LOGGER.debugf("Starting ResourceAdapterStatusicService");
synchronized (this) {
PathElement peExtendedStats = PathElement.pathElement(Constants.STATISTICS_NAME, "extended");
final CommonDeployment deploymentMD = deployment.getValue().getDeployment();
if (deploymentMD.getConnector() != null && deploymentMD.getConnector().getResourceAdapter() != null && deploymentMD.getConnector().getResourceAdapter().getStatistics() != null) {
StatisticsPlugin raStats = deploymentMD.getConnector().getResourceAdapter().getStatistics();
raStats.setEnabled(statsEnabled);
overrideRegistration.registerSubModel(new StatisticsResourceDefinition(peExtendedStats, CommonAttributes.RESOURCE_NAME, raStats));
}
}
}
@Override
public void stop(StopContext context) {
PathElement peLocaldWm = PathElement.pathElement(Constants.STATISTICS_NAME, "extended");
if (overrideRegistration.getSubModel(PathAddress.pathAddress(peLocaldWm)) != null)
overrideRegistration.unregisterSubModel(peLocaldWm);
}
@Override
public ManagementResourceRegistration getValue() throws IllegalStateException, IllegalArgumentException {
//TODO implement getValue
throw new UnsupportedOperationException();
}
public Injector<ResourceAdapterDeployment> getResourceAdapterDeploymentInjector() {
return deployment;
}
public Injector<CloneableBootstrapContext> getBootstrapContextInjector() {
return bootstrapContext;
}
}
| 5,331 | 40.333333 | 190 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/statistics/AdminObjectStatisticsService.java | /*
* 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.services.resourceadapters.statistics;
import static org.jboss.as.connector.logging.ConnectorLogger.ROOT_LOGGER;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import org.jboss.as.connector.dynamicresource.StatisticsResourceDefinition;
import org.jboss.as.connector.metadata.deployment.ResourceAdapterDeployment;
import org.jboss.as.connector.subsystems.resourceadapters.CommonAttributes;
import org.jboss.as.connector.subsystems.resourceadapters.Constants;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.descriptions.OverrideDescriptionProvider;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.jca.core.api.bootstrap.CloneableBootstrapContext;
import org.jboss.jca.core.api.management.AdminObject;
import org.jboss.jca.core.spi.statistics.StatisticsPlugin;
import org.jboss.jca.deployers.common.CommonDeployment;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
public class AdminObjectStatisticsService implements Service<ManagementResourceRegistration> {
private final ManagementResourceRegistration overrideRegistration;
private final boolean statsEnabled;
protected final InjectedValue<ResourceAdapterDeployment> deployment = new InjectedValue<>();
protected final InjectedValue<CloneableBootstrapContext> bootstrapContext = new InjectedValue<>();
/**
* create an instance *
*/
public AdminObjectStatisticsService(final ManagementResourceRegistration registration,
final String jndiName,
final boolean statsEnabled) {
super();
if (registration.isAllowsOverride()) {
overrideRegistration = registration.registerOverrideModel(jndiName, new OverrideDescriptionProvider() {
@Override
public Map<String, ModelNode> getAttributeOverrideDescriptions(Locale locale) {
return Collections.emptyMap();
}
@Override
public Map<String, ModelNode> getChildTypeOverrideDescriptions(Locale locale) {
return Collections.emptyMap();
}
});
} else {
overrideRegistration = registration;
}
this.statsEnabled = statsEnabled;
}
@Override
public void start(StartContext context) throws StartException {
ROOT_LOGGER.debugf("Starting ResourceAdapterStatusicService");
synchronized (this) {
final CommonDeployment deploymentMD = deployment.getValue().getDeployment();
PathElement peExtendedStats = PathElement.pathElement(Constants.STATISTICS_NAME, "extended");
if (deploymentMD.getConnector() != null && deploymentMD.getConnector().getAdminObjects() != null) {
for (AdminObject ao : deploymentMD.getConnector().getAdminObjects()) {
if (ao.getStatistics() != null) {
StatisticsPlugin extendStats = ao.getStatistics();
extendStats.setEnabled(statsEnabled);
if (!extendStats.getNames().isEmpty()
&& overrideRegistration.getSubModel(PathAddress.pathAddress(peExtendedStats)) == null) {
overrideRegistration.registerSubModel(new StatisticsResourceDefinition(peExtendedStats,
CommonAttributes.RESOURCE_NAME, extendStats));
}
}
}
}
}
}
@Override
public void stop(StopContext context) {
PathElement peLocaldWm = PathElement.pathElement(Constants.STATISTICS_NAME, "extended");
if (overrideRegistration.getSubModel(PathAddress.pathAddress(peLocaldWm)) != null)
overrideRegistration.unregisterSubModel(peLocaldWm);
}
@Override
public ManagementResourceRegistration getValue() throws IllegalStateException, IllegalArgumentException {
//TODO implement getValue
throw new UnsupportedOperationException();
}
public Injector<ResourceAdapterDeployment> getResourceAdapterDeploymentInjector() {
return deployment;
}
public Injector<CloneableBootstrapContext> getBootstrapContextInjector() {
return bootstrapContext;
}
}
| 5,710 | 40.384058 | 120 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/statistics/ConnectionDefinitionStatisticsService.java | /*
* 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.services.resourceadapters.statistics;
import static org.jboss.as.connector.logging.ConnectorLogger.ROOT_LOGGER;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import org.jboss.as.connector.dynamicresource.StatisticsResourceDefinition;
import org.jboss.as.connector.metadata.deployment.ResourceAdapterDeployment;
import org.jboss.as.connector.subsystems.common.jndi.Util;
import org.jboss.as.connector.subsystems.resourceadapters.CommonAttributes;
import org.jboss.as.connector.subsystems.resourceadapters.Constants;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.descriptions.OverrideDescriptionProvider;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.jca.core.api.bootstrap.CloneableBootstrapContext;
import org.jboss.jca.core.api.management.ConnectionFactory;
import org.jboss.jca.core.connectionmanager.ConnectionManager;
import org.jboss.jca.core.spi.statistics.StatisticsPlugin;
import org.jboss.jca.deployers.common.CommonDeployment;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
public class ConnectionDefinitionStatisticsService implements Service<ManagementResourceRegistration> {
private final ManagementResourceRegistration overrideRegistration;
private final boolean statsEnabled;
private final String jndiName;
protected final InjectedValue<ResourceAdapterDeployment> deployment = new InjectedValue<>();
protected final InjectedValue<CloneableBootstrapContext> bootstrapContext = new InjectedValue<>();
/**
* create an instance *
*/
public ConnectionDefinitionStatisticsService(final ManagementResourceRegistration registration,
final String jndiName,
final boolean useJavaContext,
final String poolName,
final boolean statsEnabled) {
super();
this.jndiName = Util.cleanJndiName(jndiName, useJavaContext);
if (registration.isAllowsOverride()) {
overrideRegistration = registration.registerOverrideModel(poolName, new OverrideDescriptionProvider() {
@Override
public Map<String, ModelNode> getAttributeOverrideDescriptions(Locale locale) {
return Collections.emptyMap();
}
@Override
public Map<String, ModelNode> getChildTypeOverrideDescriptions(Locale locale) {
return Collections.emptyMap();
}
});
} else {
overrideRegistration = registration;
}
this.statsEnabled = statsEnabled;
}
@Override
public void start(StartContext context) throws StartException {
ROOT_LOGGER.debugf("Starting ConnectionDefinitionStatisticsService %s", jndiName);
synchronized (this) {
final CommonDeployment deploymentMD = deployment.getValue().getDeployment();
PathElement pePoolStats = PathElement.pathElement(Constants.STATISTICS_NAME, "pool");
PathElement peExtendedStats = PathElement.pathElement(Constants.STATISTICS_NAME, "extended");
if (deploymentMD.getConnector() != null && deploymentMD.getConnector().getConnectionFactories() != null) {
for (ConnectionFactory cf : deploymentMD.getConnector().getConnectionFactories()) {
if (cf.getManagedConnectionFactory() != null && cf.getManagedConnectionFactory().getStatistics() != null) {
StatisticsPlugin extendStats = cf.getManagedConnectionFactory().getStatistics();
extendStats.setEnabled(statsEnabled);
if (!extendStats.getNames().isEmpty()
&& overrideRegistration.getSubModel(PathAddress.pathAddress(peExtendedStats)) == null) {
overrideRegistration.registerSubModel(new StatisticsResourceDefinition(peExtendedStats,
CommonAttributes.RESOURCE_NAME, extendStats));
}
}
}
}
if (deploymentMD.getConnectionManagers() != null) {
for (ConnectionManager cm : deploymentMD.getConnectionManagers()) {
if (cm.getPool() != null && cm.getJndiName() != null && cm.getJndiName().equals(jndiName)) {
StatisticsPlugin poolStats = cm.getPool().getStatistics();
poolStats.setEnabled(statsEnabled);
if (!poolStats.getNames().isEmpty()
&& overrideRegistration.getSubModel(PathAddress.pathAddress(pePoolStats)) == null) {
overrideRegistration.registerSubModel(
new StatisticsResourceDefinition(pePoolStats, CommonAttributes.RESOURCE_NAME, poolStats));
}
}
}
}
}
}
@Override
public void stop(StopContext context) {
PathElement peCD = PathElement.pathElement(Constants.STATISTICS_NAME, "pool");
if (overrideRegistration.getSubModel(PathAddress.pathAddress(peCD)) != null) {
overrideRegistration.unregisterSubModel(peCD);
}
PathElement peExtended = PathElement.pathElement(Constants.STATISTICS_NAME, "extended");
if (overrideRegistration.getSubModel(PathAddress.pathAddress(peExtended)) != null) {
overrideRegistration.unregisterSubModel(peExtended);
}
}
@Override
public ManagementResourceRegistration getValue() throws IllegalStateException, IllegalArgumentException {
return overrideRegistration;
}
public Injector<ResourceAdapterDeployment> getResourceAdapterDeploymentInjector() {
return deployment;
}
public Injector<CloneableBootstrapContext> getBootstrapContextInjector() {
return bootstrapContext;
}
}
| 7,433 | 45.173913 | 127 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/repository/ManagementRepositoryService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, 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.services.resourceadapters.repository;
import static org.jboss.as.connector.logging.ConnectorLogger.ROOT_LOGGER;
import org.jboss.jca.core.api.management.ManagementRepository;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
public class ManagementRepositoryService implements Service<ManagementRepository> {
private final ManagementRepository value;
/** create an instance **/
public ManagementRepositoryService() {
super();
this.value = new ManagementRepository();
}
@Override
public ManagementRepository getValue() throws IllegalStateException, IllegalArgumentException {
return value;
}
@Override
public void start(StartContext context) throws StartException {
ROOT_LOGGER.debugf("started ManagementRepositoryService %s", context.getController().getName());
}
@Override
public void stop(StopContext context) {
ROOT_LOGGER.debugf("stopped ManagementRepositoryService %s", context.getController().getName());
}
}
| 2,192 | 34.370968 | 104 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/util/ParserException.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, 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.util;
/**
* A ParserException.
*
* @author <a href="[email protected]">Stefano Maestri</a>
*/
public class ParserException extends Exception {
/**
* The serialVersionUID
*/
private static final long serialVersionUID = 1L;
/**
* Create a new ParserException.
*/
public ParserException() {
super();
}
/**
* Create a new ParserException.
*
* @param message a message
* @param cause a cause
*/
public ParserException(String message, Throwable cause) {
super(message, cause);
}
/**
* Create a new ParserException.
*
* @param message a message
*/
public ParserException(String message) {
super(message);
}
/**
* Create a new ParserException.
*
* @param cause a cause
*/
public ParserException(Throwable cause) {
super(cause);
}
}
| 1,981 | 26.527778 | 70 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/util/ConnectorServices.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.util;
import static org.jboss.as.connector.logging.ConnectorLogger.ROOT_LOGGER;
import java.util.HashMap;
import java.util.Map;
import org.jboss.as.connector.logging.ConnectorLogger;
import org.jboss.as.connector.subsystems.resourceadapters.ModifiableResourceAdapter;
import org.jboss.jca.common.api.metadata.resourceadapter.Activation;
import org.jboss.msc.service.ServiceName;
/**
* ConnectorServices contains some utility methods used internally and constants for all connector's subsystems service names.
*
* @author <a href="mailto:[email protected]">Stefano Maestri</a>
* @author <a href="mailto:[email protected]">Jesper Pedersen</a>
*/
public class ConnectorServices {
/**
* A map whose key corresponds to a ra name and whose value is an identifier with which the RA is registered in the
* {@link org.jboss.jca.core.spi.rar.ResourceAdapterRepository}
*/
private static final Map<String, String> resourceAdapterRepositoryIdentifiers = new HashMap<String, String>();
/**
* A map whose key corresponds to a capability name and whose value is the service name for that capability
*/
private static final Map<String, ServiceName> capabilityServiceNames = new HashMap<String, ServiceName>();
public static final ServiceName CONNECTOR_CONFIG_SERVICE = ServiceName.JBOSS.append("connector", "config");
public static final ServiceName BEAN_VALIDATION_CONFIG_SERVICE = ServiceName.JBOSS.append("connector", "bean_validation",
"config");
public static final ServiceName TRACER_CONFIG_SERVICE = ServiceName.JBOSS.append("connector", "tracer",
"config");
public static final ServiceName ARCHIVE_VALIDATION_CONFIG_SERVICE = ServiceName.JBOSS.append("connector",
"archive_validation", "config");
public static final ServiceName BOOTSTRAP_CONTEXT_SERVICE = ServiceName.JBOSS.append("connector", "bootstrapcontext");
/** @deprecated Use the "org.wildfly.jca.transaction-integration" capability. */
@Deprecated
public static final ServiceName TRANSACTION_INTEGRATION_SERVICE = ServiceName.JBOSS.append("connector",
"transactionintegration");
public static final ServiceName WORKMANAGER_SERVICE = ServiceName.JBOSS.append("connector", "workmanager");
public static final ServiceName WORKMANAGER_STATS_SERVICE = WORKMANAGER_SERVICE.append("statistics");
public static final ServiceName DISTRIBUTED_WORKMANAGER_STATS_SERVICE = WORKMANAGER_SERVICE.append("distributed-statistics");
public static final ServiceName RESOURCE_ADAPTER_SERVICE_PREFIX = ServiceName.JBOSS.append("ra");
public static final String STATISTICS_SUFFIX = "STATISTICS";
public static final ServiceName RESOURCE_ADAPTER_DEPLOYMENT_SERVICE_PREFIX = RESOURCE_ADAPTER_SERVICE_PREFIX
.append("deployment");
public static final ServiceName RESOURCE_ADAPTER_DEPLOYER_SERVICE_PREFIX = RESOURCE_ADAPTER_SERVICE_PREFIX
.append("deployer");
public static final ServiceName RESOURCE_ADAPTER_REGISTRY_SERVICE = ServiceName.JBOSS.append("raregistry");
public static final ServiceName RESOURCE_ADAPTER_ACTIVATOR_SERVICE = ServiceName.JBOSS.append("raactivator");
public static final ServiceName INACTIVE_RESOURCE_ADAPTER_SERVICE = ServiceName.JBOSS.append("rainactive");
/**
* MDR service name *
*/
public static final ServiceName IRONJACAMAR_MDR = ServiceName.JBOSS.append("ironjacamar", "mdr");
public static final ServiceName IRONJACAMAR_RESOURCE = ServiceName.JBOSS.append("ironjacamar", "resource");
public static final ServiceName RA_REPOSITORY_SERVICE = ServiceName.JBOSS.append("rarepository");
public static final ServiceName NON_JTA_DS_RA_REPOSITORY_SERVICE = ServiceName.JBOSS.append("non_jta_ds_rarepository");
public static final ServiceName MANAGEMENT_REPOSITORY_SERVICE = ServiceName.JBOSS.append("management_repository");
public static final ServiceName RESOURCEADAPTERS_SERVICE = ServiceName.JBOSS.append("resourceadapters");
public static final ServiceName RESOURCEADAPTERS_SUBSYSTEM_SERVICE = ServiceName.JBOSS.append("resourceadapters-subsystem");
public static final ServiceName RA_SERVICE = ServiceName.JBOSS.append("resourceadapters", "ra");
public static final ServiceName DATASOURCES_SERVICE = ServiceName.JBOSS.append("datasources");
public static final ServiceName JDBC_DRIVER_REGISTRY_SERVICE = ServiceName.JBOSS.append("jdbc-driver", "registry");
public static final ServiceName CCM_SERVICE = ServiceName.JBOSS.append("cached-connection-manager");
public static final ServiceName NON_TX_CCM_SERVICE = ServiceName.JBOSS.append("non-tx-cached-connection-manager");
public static final ServiceName IDLE_REMOVER_SERVICE = ServiceName.JBOSS.append("ironjacamar", "idle-remover");
public static final ServiceName CONNECTION_VALIDATOR_SERVICE = ServiceName.JBOSS.append("ironjacamar",
"connection-validator");
/**
* convenient method to check notNull of value
*
* @param <T> type of the value
* @param value the value
* @return the value or throw an {@link IllegalStateException} if value is null (a.k.a. service not started)
*/
public static <T> T notNull(T value) {
if (value == null)
throw ConnectorLogger.ROOT_LOGGER.serviceNotStarted();
return value;
}
// resource-adapter DMR resource
public static synchronized ServiceName getDeploymentServiceName(final String raName, final Activation raxml) {
if (raName == null)
throw ConnectorLogger.ROOT_LOGGER.undefinedVar("RaName");
ServiceName serviceName = null;
ModifiableResourceAdapter ra = (ModifiableResourceAdapter) raxml;
if (ra != null && ra.getId() != null) {
serviceName = getDeploymentServiceName(raName,ra.getId());
} else {
serviceName = getDeploymentServiceName(raName,(String)null);
}
ROOT_LOGGER.tracef("ConnectorServices: getDeploymentServiceName(%s,%s) -> %s", raName, raxml,serviceName);
return serviceName;
}
public static synchronized ServiceName getDeploymentServiceName(String raName, String raId) {
if (raName == null)
throw ConnectorLogger.ROOT_LOGGER.undefinedVar("RaName");
// ServiceName entry = deploymentServiceNames.get(raName);
ServiceName serviceName = null;
if (raId == null || raId.equals(raName)) {
serviceName = RESOURCE_ADAPTER_DEPLOYMENT_SERVICE_PREFIX.append(raName);
} else {
serviceName = RESOURCE_ADAPTER_DEPLOYMENT_SERVICE_PREFIX.append(raName + "_" + raId);
}
ROOT_LOGGER.tracef("ConnectorServices: getDeploymentServiceName(%s,%s) -> %s", raName, raId,serviceName);
return serviceName;
}
public static synchronized ServiceName getDeploymentServiceName(final String raName) {
if (raName == null)
throw ConnectorLogger.ROOT_LOGGER.undefinedVar("RaName");
final ServiceName serviceName = RESOURCE_ADAPTER_DEPLOYMENT_SERVICE_PREFIX.append(raName);
ROOT_LOGGER.tracef("ConnectorServices: getDeploymentServiceName(%s) -> %s", raName, serviceName);
return serviceName;
}
public static synchronized ServiceName getResourceAdapterServiceName(final String id) {
if (id == null || id.trim().isEmpty()) {
throw ConnectorLogger.ROOT_LOGGER.undefinedVar("id");
}
ServiceName serviceName = RESOURCE_ADAPTER_SERVICE_PREFIX.append(stripDotRarSuffix(id));
ROOT_LOGGER.tracef("ConnectorServices: getResourceAdapterServiceName(%s) -> %s", id, serviceName);
return serviceName;
}
private static String stripDotRarSuffix(final String raName) {
if (raName == null) {
return null;
}
// See RaDeploymentParsingProcessor
if (raName.endsWith(".rar")) {
return raName.substring(0, raName.indexOf(".rar"));
}
return raName;
}
/**
* Returns the identifier with which the resource adapter named <code>raName</code> is registered in the
* {@link org.jboss.jca.core.spi.rar.ResourceAdapterRepository}. Returns null, if there's no registration for a resource
* adapter named <code>raName</code>
*
* @param raName The resource adapter name
* @return
*/
public static String getRegisteredResourceAdapterIdentifier(final String raName) {
synchronized (resourceAdapterRepositoryIdentifiers) {
return resourceAdapterRepositoryIdentifiers.get(raName);
}
}
/**
* Makes a note of the resource adapter identifier with which a resource adapter named <code>raName</code> is registered in
* the {@link org.jboss.jca.core.spi.rar.ResourceAdapterRepository}.
* <p/>
* Subsequent calls to {@link #getRegisteredResourceAdapterIdentifier(String)} with the passed <code>raName</code> return
* the <code>raIdentifier</code>
*
* @param raName The resource adapter name
* @param raIdentifier The resource adapter identifier
*/
public static void registerResourceAdapterIdentifier(final String raName, final String raIdentifier) {
synchronized (resourceAdapterRepositoryIdentifiers) {
resourceAdapterRepositoryIdentifiers.put(raName, raIdentifier);
}
}
/**
* Clears the mapping between the <code>raName</code> and the resource adapter identifier, with which the resource adapter
* is registered with the {@link org.jboss.jca.core.spi.rar.ResourceAdapterRepository}
* <p/>
* Subsequent calls to {@link #getRegisteredResourceAdapterIdentifier(String)} with the passed <code>raName</code> return
* null
*
* @param raName The resource adapter name
*/
public static void unregisterResourceAdapterIdentifier(final String raName) {
synchronized (resourceAdapterRepositoryIdentifiers) {
resourceAdapterRepositoryIdentifiers.remove(raName);
}
}
public static void registerCapabilityServiceName(String capabilityName, ServiceName serviceName) {
synchronized (capabilityServiceNames) {
// Minor check against misuse
ServiceName existing = capabilityServiceNames.get(capabilityName);
if (existing != null && ! existing.equals(serviceName)) {
throw new IllegalStateException();
}
capabilityServiceNames.put(capabilityName, serviceName);
}
}
/**
* Name of the capability that ensures a local provider of transactions is present.
* Once its service is started, calls to the getInstance() methods of ContextTransactionManager,
* ContextTransactionSynchronizationRegistry and LocalUserTransaction can be made knowing
* that the global default TM, TSR and UT will be from that provider.
*/
public static final String LOCAL_TRANSACTION_PROVIDER_CAPABILITY = "org.wildfly.transactions.global-default-local-provider";
/**
* The capability name for the transaction TransactionSynchronizationRegistry.
*/
public static final String TRANSACTION_SYNCHRONIZATION_REGISTRY_CAPABILITY = "org.wildfly.transactions.transaction-synchronization-registry";
/**
* The capability name for the transaction XAResourceRecoveryRegistry.
*/
public static final String TRANSACTION_XA_RESOURCE_RECOVERY_REGISTRY_CAPABILITY = "org.wildfly.transactions.xa-resource-recovery-registry";
public static ServiceName getCachedCapabilityServiceName(String capabilityName) {
synchronized (capabilityServiceNames) {
return capabilityServiceNames.get(capabilityName);
}
}
/**
* The capability name for the JCA transaction integration TransactionIntegration.
*/
public static final String TRANSACTION_INTEGRATION_CAPABILITY_NAME = "org.wildfly.jca.transaction-integration";
}
| 13,080 | 43.95189 | 145 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/util/SecurityActions.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2013, 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.util;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
/**
* Privileged Blocks
*
* @author <a href="mailto:[email protected]">Jesper Pedersen</a>
*/
class SecurityActions {
/**
* Constructor
*/
private SecurityActions() {
}
/**
* Get the declared methods
*
* @param c The class
* @return The methods
*/
static Method[] getDeclaredMethods(final Class<?> c) {
if (System.getSecurityManager() == null)
return c.getDeclaredMethods();
return AccessController.doPrivileged(new PrivilegedAction<Method[]>() {
public Method[] run() {
return c.getDeclaredMethods();
}
});
}
/**
* Get the declared fields
*
* @param c The class
* @return The fields
*/
static Field[] getDeclaredFields(final Class<?> c) {
if (System.getSecurityManager() == null)
return c.getDeclaredFields();
return AccessController.doPrivileged(new PrivilegedAction<Field[]>() {
public Field[] run() {
return c.getDeclaredFields();
}
});
}
/**
* Set accessibleo
*
* @param ao The object
*/
static void setAccessible(final AccessibleObject ao) {
if (System.getSecurityManager() == null)
ao.setAccessible(true);
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
ao.setAccessible(true);
return null;
}
});
}
/**
* Get the constructor
*
* @param c The class
* @param params The parameters
* @return The constructor
* @throws NoSuchMethodException If a matching method is not found.
*/
static Constructor<?> getConstructor(final Class<?> c, final Class<?>... params)
throws NoSuchMethodException {
if (System.getSecurityManager() == null)
return c.getConstructor(params);
Constructor<?> result = AccessController.doPrivileged(new PrivilegedAction<Constructor<?>>() {
public Constructor<?> run() {
try {
return c.getConstructor(params);
} catch (NoSuchMethodException e) {
return null;
}
}
});
if (result != null)
return result;
throw new NoSuchMethodException();
}
/**
* Get the method
*
* @param c The class
* @param name The name
* @param params The parameters
* @return The method
* @throws NoSuchMethodException If a matching method is not found.
*/
static Method getMethod(final Class<?> c, final String name, final Class<?>... params)
throws NoSuchMethodException {
if (System.getSecurityManager() == null)
return c.getMethod(name, params);
Method result = AccessController.doPrivileged(new PrivilegedAction<Method>() {
public Method run() {
try {
return c.getMethod(name, params);
} catch (NoSuchMethodException e) {
return null;
}
}
});
if (result != null)
return result;
throw new NoSuchMethodException();
}
}
| 4,631 | 28.883871 | 102 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/util/JCAValidatorFactory.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, 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.util;
import org.wildfly.security.manager.WildFlySecurityManager;
import jakarta.validation.ClockProvider;
import jakarta.validation.Configuration;
import jakarta.validation.ConstraintValidatorFactory;
import jakarta.validation.MessageInterpolator;
import jakarta.validation.ParameterNameProvider;
import jakarta.validation.TraversableResolver;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorContext;
import jakarta.validation.ValidatorFactory;
/**
* This class lazily initialize the ValidatorFactory on the first usage One benefit is that no domain class is loaded until the
* ValidatorFactory is really needed. Useful to avoid loading classes before Jakarta Persistence is initialized and has enhanced its classes.
* <p/>
* Note: This class is a copy of {@code org.jboss.as.ee.beanvalidation.LazyValidatorFactory}.
*
* @author Emmanuel Bernard
* @author Stuart Douglas
*/
public class JCAValidatorFactory implements ValidatorFactory {
private final Configuration<?> configuration;
private final ClassLoader classLoader;
private volatile ValidatorFactory delegate; // use as a barrier
/**
* Use the default ValidatorFactory creation routine
*/
public JCAValidatorFactory(ClassLoader classLoader) {
this(null, classLoader);
}
public JCAValidatorFactory(Configuration<?> configuration, ClassLoader classLoader) {
this.configuration = configuration;
this.classLoader = classLoader;
}
private ValidatorFactory getDelegate() {
ValidatorFactory result = delegate;
if (result == null) {
synchronized (this) {
result = delegate;
if (result == null) {
delegate = result = initFactory();
}
}
}
return result;
}
@Override
public Validator getValidator() {
return getDelegate().getValidator();
}
private ValidatorFactory initFactory() {
final ClassLoader oldTCCL = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader);
if (configuration == null) {
return Validation.byDefaultProvider().providerResolver(new WildFlyProviderResolver()).configure()
.buildValidatorFactory();
} else {
return configuration.buildValidatorFactory();
}
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTCCL);
}
}
@Override
public ValidatorContext usingContext() {
return getDelegate().usingContext();
}
@Override
public MessageInterpolator getMessageInterpolator() {
return getDelegate().getMessageInterpolator();
}
@Override
public TraversableResolver getTraversableResolver() {
return getDelegate().getTraversableResolver();
}
@Override
public ConstraintValidatorFactory getConstraintValidatorFactory() {
return getDelegate().getConstraintValidatorFactory();
}
@Override
public ParameterNameProvider getParameterNameProvider() {
return getDelegate().getParameterNameProvider();
}
@Override
public ClockProvider getClockProvider() {
return getDelegate().getClockProvider();
}
@Override
public <T> T unwrap(Class<T> clazz) {
return getDelegate().unwrap(clazz);
}
@Override
public void close() {
getDelegate().close();
}
}
| 4,695 | 32.784173 | 141 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/util/CopyOnWriteArrayListMultiMap.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, 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.util;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class CopyOnWriteArrayListMultiMap<K, V> {
private final ConcurrentMap<K, List<V>> cache = new ConcurrentHashMap<K, List<V>>();
public List<V> get(K k) {
return cache.get(k);
}
public synchronized List<V> remove(K k) {
return cache.remove(k);
}
public synchronized void putIfAbsent(K k, V v) {
List<V> list = cache.get(k);
if (list == null || list.isEmpty()) {
list = new ArrayList<V>();
} else {
list = new ArrayList<V>(list);
}
if (!list.contains(v)) {
list.add(v);
cache.put(k, list);
}
}
public synchronized boolean remove(K k, V v) {
List<V> list = cache.get(k);
if (list == null) {
return false;
}
if (list.isEmpty()) {
cache.remove(k);
return false;
}
boolean removed = list.remove(v);
if (removed) {
if (list.isEmpty()) {
cache.remove(k);
} else {
list = new ArrayList<V>(list);
cache.put(k, list);
}
}
return removed;
}
}
| 2,388 | 30.025974 | 88 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/util/AbstractParser.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, 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.util;
import static javax.xml.stream.XMLStreamConstants.END_ELEMENT;
import static javax.xml.stream.XMLStreamConstants.START_ELEMENT;
import static org.jboss.as.controller.parsing.ParseUtils.isNoNamespaceAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.requireSingleAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.jboss.as.controller.PropertiesAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.parsing.ParseUtils;
import org.jboss.dmr.ModelNode;
import org.jboss.jca.common.CommonBundle;
import org.jboss.jca.common.api.metadata.common.Extension;
import org.jboss.jca.common.api.validator.ValidateException;
import org.jboss.logging.Messages;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* An AbstractParser.
*
* @author <a href="[email protected]">Stefano Maestri</a>
*/
public abstract class AbstractParser {
/**
* The bundle
*/
private static CommonBundle bundle = Messages.getBundle(CommonBundle.class);
/**
* Reads and trims the element text and returns it or {@code null}
*
* @param reader source for the element text
* @return the string representing the trimmed element text or {@code null} if there is none or it is an empty string
* @throws XMLStreamException
*/
public String rawElementText(XMLStreamReader reader) throws XMLStreamException {
String elementText = reader.getElementText();
elementText = elementText == null || elementText.trim().length() == 0 ? null : elementText.trim();
return elementText;
}
/**
* Reads and trims the text for the given attribute and returns it or {@code null}
*
* @param reader source for the attribute text
* @param attributeName the name of the attribute
* @return the string representing trimmed attribute text or {@code null} if there is none
*/
public String rawAttributeText(XMLStreamReader reader, String attributeName) {
return rawAttributeText(reader, attributeName, null);
}
/**
* Reads and trims the text for the given attribute and returns it or {@code defaultValue} if there is no
* value for the attribute
* @param reader source for the attribute text
* @param attributeName the name of the attribute
* @param defaultValue value to return if there is no value for the attribute
* @return the string representing raw attribute text or {@code defaultValue} if there is none
*/
public String rawAttributeText(XMLStreamReader reader, String attributeName, String defaultValue) {
return reader.getAttributeValue("", attributeName) == null
? defaultValue :
reader.getAttributeValue("", attributeName).trim();
}
protected void parseModuleExtension(XMLExtendedStreamReader reader, String enclosingTag, final ModelNode operation,
final SimpleAttributeDefinition extensionClassName, final SimpleAttributeDefinition extensionModuleName,
final PropertiesAttributeDefinition extensionProperties) throws XMLStreamException, ParserException, ValidateException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
}
final Extension.Attribute attribute = Extension.Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case CLASS_NAME: {
final String value = reader.getAttributeValue(i);
extensionClassName.parseAndSetParameter(value, operation, reader);
break;
}
case MODULE: {
final String value = reader.getAttributeValue(i);
extensionModuleName.parseAndSetParameter(value, operation, reader);
break;
}
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
while (reader.hasNext()) {
switch (reader.nextTag()) {
case END_ELEMENT: {
if (reader.getLocalName().equals(enclosingTag)) {
//It's fine doing nothing
return;
} else {
if (Extension.Tag.forName(reader.getLocalName()) == Extension.Tag.UNKNOWN) {
throw ParseUtils.unexpectedEndElement(reader);
}
}
break;
}
case START_ELEMENT: {
switch (Extension.Tag.forName(reader.getLocalName())) {
case CONFIG_PROPERTY: {
requireSingleAttribute(reader, "name");
final String name = reader.getAttributeValue(0);
String value = rawElementText(reader);
final String trimmed = value == null ? null : value.trim();
extensionProperties.parseAndAddParameterElement(name, trimmed, operation, reader);
break;
}
default:
throw new ParserException(bundle.unexpectedElement(reader.getLocalName()));
}
break;
}
}
}
throw new ParserException(bundle.unexpectedEndOfDocument());
}
protected void parseExtension(XMLExtendedStreamReader reader, String enclosingTag, final ModelNode operation,
final SimpleAttributeDefinition extensionClassName, final PropertiesAttributeDefinition extensionProperties)
throws XMLStreamException, ParserException, ValidateException {
for (Extension.Attribute attribute : Extension.Attribute.values()) {
switch (attribute) {
case CLASS_NAME: {
requireSingleAttribute(reader, attribute.getLocalName());
final String value = reader.getAttributeValue(0);
extensionClassName.parseAndSetParameter(value, operation, reader);
break;
}
default:
break;
}
}
while (reader.hasNext()) {
switch (reader.nextTag()) {
case END_ELEMENT: {
if (reader.getLocalName().equals(enclosingTag)) {
//It's fine doing nothing
return;
} else {
if (Extension.Tag.forName(reader.getLocalName()) == Extension.Tag.UNKNOWN) {
throw ParseUtils.unexpectedEndElement(reader);
}
}
break;
}
case START_ELEMENT: {
switch (Extension.Tag.forName(reader.getLocalName())) {
case CONFIG_PROPERTY: {
requireSingleAttribute(reader, "name");
final String name = reader.getAttributeValue(0);
String value = rawElementText(reader);
final String trimmed = value == null ? null : value.trim();
extensionProperties.parseAndAddParameterElement(name, trimmed, operation, reader);
break;
}
default:
throw new ParserException(bundle.unexpectedElement(reader.getLocalName()));
}
break;
}
}
}
throw new ParserException(bundle.unexpectedEndOfDocument());
}
}
| 9,219 | 44.196078 | 160 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/util/RaServicesFactory.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, 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.util;
import static org.jboss.as.connector.subsystems.jca.Constants.DEFAULT_NAME;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import org.jboss.as.connector.metadata.deployment.ResourceAdapterDeployment;
import org.jboss.as.connector.metadata.xmldescriptors.ConnectorXmlDescriptor;
import org.jboss.as.connector.services.mdr.AS7MetadataRepository;
import org.jboss.as.connector.services.resourceadapters.deployment.ResourceAdapterXmlDeploymentService;
import org.jboss.as.connector.services.resourceadapters.deployment.registry.ResourceAdapterDeploymentRegistry;
import org.jboss.as.connector.subsystems.jca.JcaSubsystemConfiguration;
import org.jboss.as.connector.subsystems.resourceadapters.ResourceAdaptersSubsystemService;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.controller.descriptions.OverrideDescriptionProvider;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.naming.service.NamingService;
import org.jboss.as.server.Services;
import org.jboss.dmr.ModelNode;
import org.jboss.jca.common.api.metadata.resourceadapter.Activation;
import org.jboss.jca.core.api.connectionmanager.ccm.CachedConnectionManager;
import org.jboss.jca.core.api.management.ManagementRepository;
import org.jboss.jca.core.spi.rar.ResourceAdapterRepository;
import org.jboss.jca.core.spi.transaction.TransactionIntegration;
import org.jboss.modules.Module;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceRegistry;
import org.jboss.msc.service.ServiceTarget;
public class RaServicesFactory {
public static void createDeploymentService(final ManagementResourceRegistration registration, ConnectorXmlDescriptor connectorXmlDescriptor, Module module,
ServiceTarget serviceTarget, final String deploymentUnitName, ServiceName deploymentUnitServiceName, String deployment,
Activation raxml, final Resource deploymentResource, final ServiceRegistry serviceRegistry, final CapabilityServiceSupport support) {
// Create the service
ServiceName serviceName = ConnectorServices.getDeploymentServiceName(deploymentUnitName,raxml);
ResourceAdapterXmlDeploymentService service = new ResourceAdapterXmlDeploymentService(connectorXmlDescriptor,
raxml, module, deployment, serviceName, deploymentUnitServiceName);
String bootStrapCtxName = DEFAULT_NAME;
if (raxml.getBootstrapContext() != null && !raxml.getBootstrapContext().equals("undefined")) {
bootStrapCtxName = raxml.getBootstrapContext();
}
ServiceBuilder<ResourceAdapterDeployment> builder =
Services.addServerExecutorDependency(
serviceTarget.addService(serviceName, service),
service.getExecutorServiceInjector())
.addDependency(ConnectorServices.IRONJACAMAR_MDR, AS7MetadataRepository.class, service.getMdrInjector())
.addDependency(ConnectorServices.RA_REPOSITORY_SERVICE, ResourceAdapterRepository.class,
service.getRaRepositoryInjector())
.addDependency(ConnectorServices.MANAGEMENT_REPOSITORY_SERVICE, ManagementRepository.class,
service.getManagementRepositoryInjector())
.addDependency(ConnectorServices.RESOURCE_ADAPTER_REGISTRY_SERVICE,
ResourceAdapterDeploymentRegistry.class, service.getRegistryInjector())
.addDependency(support.getCapabilityServiceName(ConnectorServices.TRANSACTION_INTEGRATION_CAPABILITY_NAME), TransactionIntegration.class,
service.getTxIntegrationInjector())
.addDependency(ConnectorServices.CONNECTOR_CONFIG_SERVICE, JcaSubsystemConfiguration.class,
service.getConfigInjector())
.addDependency(ConnectorServices.CCM_SERVICE, CachedConnectionManager.class, service.getCcmInjector())
.addDependency(ConnectorServices.RESOURCEADAPTERS_SUBSYSTEM_SERVICE, ResourceAdaptersSubsystemService.class, service.getResourceAdaptersSubsystem());
builder.requires(ConnectorServices.IDLE_REMOVER_SERVICE);
builder.requires(ConnectorServices.CONNECTION_VALIDATOR_SERVICE);
builder.requires(support.getCapabilityServiceName(NamingService.CAPABILITY_NAME));
builder.requires(ConnectorServices.BOOTSTRAP_CONTEXT_SERVICE.append(bootStrapCtxName));
builder.requires(ConnectorServices.RESOURCE_ADAPTER_DEPLOYER_SERVICE_PREFIX.append(connectorXmlDescriptor.getDeploymentName()));
String raName = deployment;
if (raxml.getId() != null) {
raName = raxml.getId();
}
ServiceName parentName = ServiceName.of(ConnectorServices.RA_SERVICE, raName);
for(ServiceName subServiceName: serviceRegistry.getServiceNames()) {
if (parentName.isParentOf(subServiceName)
&& !subServiceName.getSimpleName().equals(ConnectorServices.STATISTICS_SUFFIX)) {
builder.requires(subServiceName);
}
}
if (registration != null && deploymentResource != null
&& registration.isAllowsOverride()
&& registration.getOverrideModel(deploymentUnitName) == null) {
registration.registerOverrideModel(deploymentUnitName, new OverrideDescriptionProvider() {
@Override
public Map<String, ModelNode> getAttributeOverrideDescriptions(Locale locale) {
return Collections.emptyMap();
}
@Override
public Map<String, ModelNode> getChildTypeOverrideDescriptions(Locale locale) {
return Collections.emptyMap();
}
});
}
builder.setInitialMode(ServiceController.Mode.ACTIVE).install();
}
}
| 7,212 | 55.351563 | 180 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/util/ModelNodeUtil.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2021, 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.util;
import org.jboss.as.connector.logging.ConnectorLogger;
import org.jboss.as.controller.ObjectListAttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PropertiesAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.dmr.ModelNode;
import org.jboss.jca.common.api.metadata.common.Extension;
import org.jboss.jca.common.api.validator.ValidateException;
import org.jboss.logging.Logger;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleLoadException;
import java.util.HashMap;
import java.util.Map;
public class ModelNodeUtil {
private static ConnectorLogger ROOT_LOGGER = Logger.getMessageLogger(ConnectorLogger.class, "org.jboss.as.connector");
public static Long getLongIfSetOrGetDefault(final OperationContext context, final ModelNode dataSourceNode, final SimpleAttributeDefinition key) throws OperationFailedException {
ModelNode resolvedNode = key.resolveModelAttribute(context, dataSourceNode);
return resolvedNode.isDefined() ? resolvedNode.asLong() : null;
}
public static Integer getIntIfSetOrGetDefault(final OperationContext context, final ModelNode dataSourceNode, final SimpleAttributeDefinition key) throws OperationFailedException {
ModelNode resolvedNode = key.resolveModelAttribute(context, dataSourceNode);
return resolvedNode.isDefined() ? resolvedNode.asInt() : null;
}
public static Boolean getBooleanIfSetOrGetDefault(final OperationContext context, final ModelNode dataSourceNode, final SimpleAttributeDefinition key) throws OperationFailedException {
ModelNode resolvedNode = key.resolveModelAttribute(context, dataSourceNode);
return resolvedNode.isDefined() ? resolvedNode.asBoolean() : null;
}
public static String getResolvedStringIfSetOrGetDefault(final OperationContext context, final ModelNode dataSourceNode, final SimpleAttributeDefinition key) throws OperationFailedException {
ModelNode resolvedNode = key.resolveModelAttribute(context, dataSourceNode);
String resolvedString = resolvedNode.isDefined() ? resolvedNode.asString() : null;
if (resolvedString != null && resolvedString.trim().length() == 0) {
resolvedString = null;
}
return resolvedString;
}
public static Extension extractExtension(final OperationContext operationContext, final ModelNode dataSourceNode, final SimpleAttributeDefinition classNameAttribute,
final PropertiesAttributeDefinition propertyNameAttribute) throws ValidateException, OperationFailedException {
return extractExtension(operationContext, dataSourceNode, classNameAttribute, null, propertyNameAttribute);
}
public static Extension extractExtension(final OperationContext operationContext, final ModelNode dataSourceNode, final SimpleAttributeDefinition classNameAttribute,
final SimpleAttributeDefinition moduleNameAttribute, final PropertiesAttributeDefinition propertyNameAttribute)
throws ValidateException, OperationFailedException {
if (dataSourceNode.hasDefined(classNameAttribute.getName())) {
String className = getResolvedStringIfSetOrGetDefault(operationContext, dataSourceNode, classNameAttribute);
String moduleName = null;
if (moduleNameAttribute != null) {
moduleName = getResolvedStringIfSetOrGetDefault(operationContext, dataSourceNode, moduleNameAttribute);
}
ClassLoader moduleClassLoader = null;
if (moduleName != null) {
try {
moduleClassLoader = Module.getCallerModuleLoader().loadModule(moduleName).getClassLoader();
} catch (ModuleLoadException exception) {
throw ROOT_LOGGER.wrongModuleName(exception, moduleName);
}
}
Map<String, String> unwrapped = propertyNameAttribute.unwrap(operationContext, dataSourceNode);
Map<String, String> property = unwrapped.size() > 0 ? unwrapped : null;
return new Extension(className, moduleClassLoader, property);
} else {
return null;
}
}
public static Map<String,String> extractMap(ModelNode operation, ObjectListAttributeDefinition objList, SimpleAttributeDefinition keyAttribute, SimpleAttributeDefinition valueAttribute) {
Map<String, String> returnMap = null;
if (operation.hasDefined(objList.getName())) {
returnMap = new HashMap<String, String>(operation.get(objList.getName()).asList().size());
for (ModelNode node : operation.get(objList.getName()).asList()) {
returnMap.put(node.asObject().get(keyAttribute.getName()).asString(), node.asObject().get(valueAttribute.getName()).asString());
}
}
return returnMap;
}
}
| 6,150 | 51.127119 | 194 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/util/WildFlyProviderResolver.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt 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.util;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import jakarta.validation.ValidationProviderResolver;
import jakarta.validation.spi.ValidationProvider;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* A {@link ValidationProviderResolver} to be used within WildFly. If several BV providers are available,
* {@code HibernateValidator} will be the first element of the returned provider list.
* <p/>
* The providers are loaded via the current thread's context class loader; If no providers are found, the loader of this class
* will be tried as fallback.
* </p>
* Note: This class is a copy of {@code org.jboss.as.ee.beanvalidation.WildFlyProviderResolver}.
*
* @author Hardy Ferentschik
* @author Gunnar Morling
*/
public class WildFlyProviderResolver implements ValidationProviderResolver {
/**
* Returns a list with all {@link ValidationProvider} validation providers.
*
* @return a list with all {@link ValidationProvider} validation providers
*/
@Override
public List<ValidationProvider<?>> getValidationProviders() {
// first try the TCCL
List<ValidationProvider<?>> providers = loadProviders(WildFlySecurityManager.getCurrentContextClassLoaderPrivileged());
if (providers != null && !providers.isEmpty()) {
return providers;
}
// otherwise use the loader of this class
else {
return loadProviders(WildFlySecurityManager.getClassLoaderPrivileged(WildFlyProviderResolver.class));
}
}
/**
* Retrieves the providers from the given loader, using the service loader mechanism.
*
* @param classLoader the class loader to use
* @return a list with providers retrieved via the given loader. May be empty but never {@code null}
*/
private List<ValidationProvider<?>> loadProviders(ClassLoader classLoader) {
@SuppressWarnings("rawtypes")
Iterator<ValidationProvider> providerIterator = ServiceLoader.load(ValidationProvider.class, classLoader).iterator();
LinkedList<ValidationProvider<?>> providers = new LinkedList<ValidationProvider<?>>();
while (providerIterator.hasNext()) {
try {
ValidationProvider<?> provider = providerIterator.next();
// put Hibernate Validator to the beginning of the list
if (provider.getClass().getName().equals("org.hibernate.validator.HibernateValidator")) {
providers.addFirst(provider);
} else {
providers.add(provider);
}
} catch (ServiceConfigurationError e) {
// ignore, because it can happen when multiple
// providers are present and some of them are not class loader
// compatible with our API.
}
}
return providers;
}
}
| 4,057 | 39.989899 | 127 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/util/Injection.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2013, 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.util;
import static org.wildfly.common.Assert.checkNotNullParam;
import java.io.File;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.StringTokenizer;
import org.jboss.as.connector.logging.ConnectorLogger;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Injection utility which can inject values into objects. This file is a copy
* of the <code>com.github.fungal.api.util.Injection</code> class.
*
* @author <a href="mailto:[email protected]">Jesper Pedersen</a>
*/
public class Injection {
/**
* Constructor
*/
public Injection() {
}
/**
* Inject a value into an object property
*
* @param object The object
* @param propertyName The property name
* @param propertyValue The property value
* @throws NoSuchMethodException If the property method cannot be found
* @throws IllegalAccessException If the property method cannot be accessed
* @throws InvocationTargetException If the property method cannot be executed
*/
@SuppressWarnings("unchecked")
public void inject(Object object, String propertyName, Object propertyValue)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
inject(object, propertyName, propertyValue, null, false);
}
/**
* Inject a value into an object property
*
* @param object The object
* @param propertyName The property name
* @param propertyValue The property value
* @param propertyType The property type as a fully quilified class name
* @throws NoSuchMethodException If the property method cannot be found
* @throws IllegalAccessException If the property method cannot be accessed
* @throws InvocationTargetException If the property method cannot be executed
*/
@SuppressWarnings("unchecked")
public void inject(Object object, String propertyName, Object propertyValue, String propertyType)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
inject(object, propertyName, propertyValue, propertyType, false);
}
/**
* Inject a value into an object property
*
* @param object The object
* @param propertyName The property name
* @param propertyValue The property value
* @param propertyType The property type as a fully quilified class name
* @param includeFields Should fields be included for injection if a method can't be found
* @throws NoSuchMethodException If the property method cannot be found
* @throws IllegalAccessException If the property method cannot be accessed
* @throws InvocationTargetException If the property method cannot be executed
*/
@SuppressWarnings("unchecked")
public void inject(Object object,
String propertyName, Object propertyValue, String propertyType,
boolean includeFields)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
checkNotNullParam("object", object);
if (propertyName == null || propertyName.trim().equals(""))
throw ConnectorLogger.ROOT_LOGGER.undefinedVar("PropertyName");
String methodName = "set" + propertyName.substring(0, 1).toUpperCase(Locale.US);
if (propertyName.length() > 1) {
methodName += propertyName.substring(1);
}
Method method = findMethod(object.getClass(), methodName, propertyType);
if (method != null) {
Class<?> parameterClass = method.getParameterTypes()[0];
Object parameterValue = null;
try {
parameterValue = getValue(propertyName, parameterClass, propertyValue,
WildFlySecurityManager.getClassLoaderPrivileged(object.getClass()));
} catch (Throwable t) {
throw new InvocationTargetException(t, t.getMessage());
}
if (!parameterClass.isPrimitive() || parameterValue != null)
method.invoke(object, new Object[]{parameterValue});
} else {
if (!includeFields)
throw ConnectorLogger.ROOT_LOGGER.noSuchMethod(methodName);
// Ok, we didn't find a method - assume field
Field field = findField(object.getClass(), propertyName, propertyType);
if (field != null) {
Class<?> fieldClass = field.getType();
Object fieldValue = null;
try {
fieldValue = getValue(propertyName, fieldClass, propertyValue,
WildFlySecurityManager.getClassLoaderPrivileged(object.getClass()));
} catch (Throwable t) {
throw new InvocationTargetException(t, t.getMessage());
}
field.set(object, fieldValue);
} else {
throw ConnectorLogger.ROOT_LOGGER.noSuchField(propertyName);
}
}
}
/**
* Compare the type of a class with the actual value
*
* @param classType The class type
* @param propertyType The property type
* @return True if they match, or if there is a primitive mapping
*/
private boolean argumentMatches(String classType, String propertyType) {
return (classType.equals(propertyType))
|| (classType.equals("java.lang.Byte") && propertyType.equals("byte"))
|| (classType.equals("java.lang.Short") && propertyType.equals("short"))
|| (classType.equals("java.lang.Integer") && propertyType.equals("int"))
|| (classType.equals("java.lang.Long") && propertyType.equals("long"))
|| (classType.equals("java.lang.Float") && propertyType.equals("float"))
|| (classType.equals("java.lang.Double") && propertyType.equals("double"))
|| (classType.equals("java.lang.Boolean") && propertyType.equals("boolean"))
|| (classType.equals("java.lang.Character") && propertyType.equals("char"));
}
/**
* Find a method
*
* @param clz The class
* @param methodName The method name
* @param propertyType The property type; can be <code>null</code>
* @return The method; <code>null</code> if not found
*/
protected Method findMethod(Class<?> clz, String methodName, String propertyType) {
while (!clz.equals(Object.class)) {
List<Method> hits = null;
Method[] methods = SecurityActions.getDeclaredMethods(clz);
for (int i = 0; i < methods.length; i++) {
final Method method = methods[i];
if (methodName.equals(method.getName())
&& method.getParameterCount() == 1
&& (propertyType == null || argumentMatches(propertyType, method.getParameterTypes()[0].getName()))) {
if (hits == null)
hits = new ArrayList<Method>(1);
SecurityActions.setAccessible(method);
hits.add(method);
}
}
if (hits != null) {
if (hits.size() == 1) {
return hits.get(0);
} else {
Collections.sort(hits, new MethodSorter());
if (propertyType != null) {
for (Method m : hits) {
if (propertyType.equals(m.getParameterTypes()[0].getName()))
return m;
}
}
return hits.get(0);
}
}
clz = clz.getSuperclass();
}
return null;
}
/**
* Find a field
*
* @param clz The class
* @param fieldName The field name
* @param fieldType The field type; can be <code>null</code>
* @return The field; <code>null</code> if not found
*/
protected Field findField(Class<?> clz, String fieldName, String fieldType) {
while (!clz.equals(Object.class)) {
List<Field> hits = null;
Field[] fields = SecurityActions.getDeclaredFields(clz);
for (int i = 0; i < fields.length; i++) {
final Field field = fields[i];
if (fieldName.equals(field.getName())
&& (fieldType == null || argumentMatches(fieldType, field.getType().getName()))) {
if (hits == null)
hits = new ArrayList<Field>(1);
SecurityActions.setAccessible(field);
hits.add(field);
}
}
if (hits != null) {
if (hits.size() == 1) {
return hits.get(0);
} else {
Collections.sort(hits, new FieldSorter());
if (fieldType != null) {
for (Field f : hits) {
if (fieldType.equals(f.getType().getName()))
return f;
}
}
return hits.get(0);
}
}
clz = clz.getSuperclass();
}
return null;
}
/**
* Get the value
*
* @param name The value name
* @param clz The value class
* @param v The value
* @param cl The class loader
* @return The substituted value
* @throws Exception Thrown in case of an error
*/
protected Object getValue(String name, Class<?> clz, Object v, ClassLoader cl) throws Exception {
if (v instanceof String) {
String substituredValue = getSubstitutionValue((String) v);
if (clz.equals(String.class)) {
v = substituredValue;
} else if (clz.equals(byte.class) || clz.equals(Byte.class)) {
if (substituredValue != null && !substituredValue.trim().equals(""))
v = Byte.valueOf(substituredValue);
} else if (clz.equals(short.class) || clz.equals(Short.class)) {
if (substituredValue != null && !substituredValue.trim().equals(""))
v = Short.valueOf(substituredValue);
} else if (clz.equals(int.class) || clz.equals(Integer.class)) {
if (substituredValue != null && !substituredValue.trim().equals(""))
v = Integer.valueOf(substituredValue);
} else if (clz.equals(long.class) || clz.equals(Long.class)) {
if (substituredValue != null && !substituredValue.trim().equals(""))
v = Long.valueOf(substituredValue);
} else if (clz.equals(float.class) || clz.equals(Float.class)) {
if (substituredValue != null && !substituredValue.trim().equals(""))
v = Float.valueOf(substituredValue);
} else if (clz.equals(double.class) || clz.equals(Double.class)) {
if (substituredValue != null && !substituredValue.trim().equals(""))
v = Double.valueOf(substituredValue);
} else if (clz.equals(boolean.class) || clz.equals(Boolean.class)) {
if (substituredValue != null && !substituredValue.trim().equals(""))
v = Boolean.valueOf(substituredValue);
} else if (clz.equals(char.class) || clz.equals(Character.class)) {
if (substituredValue != null && !substituredValue.trim().equals(""))
v = Character.valueOf(substituredValue.charAt(0));
} else if (clz.equals(InetAddress.class)) {
v = InetAddress.getByName(substituredValue);
} else if (clz.equals(Class.class)) {
v = Class.forName(substituredValue, true, cl);
} else if (clz.equals(Properties.class)) {
Properties prop = new Properties();
StringTokenizer st = new StringTokenizer(substituredValue, " ,");
while (st.hasMoreTokens()) {
String token = st.nextToken();
String key = "";
String value = "";
int index = token.indexOf("=");
if (index != -1) {
key = token.substring(0, index);
if (token.length() > index + 1)
value = token.substring(index + 1);
} else {
key = token;
}
if (!"".equals(key))
prop.setProperty(key, value);
}
v = prop;
} else {
try {
Constructor<?> constructor = SecurityActions.getConstructor(clz, String.class);
v = constructor.newInstance(substituredValue);
} catch (Throwable t) {
// Try static String valueOf method
try {
Method valueOf = SecurityActions.getMethod(clz, "valueOf", String.class);
v = valueOf.invoke((Object) null, substituredValue);
} catch (Throwable inner) {
throw ConnectorLogger.ROOT_LOGGER.noPropertyResolution(name);
}
}
}
}
return v;
}
/**
* System property substitution
*
* @param input The input string
* @return The output
*/
protected String getSubstitutionValue(String input) {
if (input == null || input.trim().equals(""))
return input;
while (input.indexOf("${") != -1) {
int from = input.indexOf("${");
int to = input.indexOf("}");
int dv = input.indexOf(":", from + 2);
if (dv != -1 && dv > to) {
dv = -1;
}
String systemProperty = "";
String defaultValue = "";
if (dv == -1) {
String s = input.substring(from + 2, to);
if ("/".equals(s)) {
systemProperty = File.separator;
} else if (":".equals(s)) {
systemProperty = File.pathSeparator;
} else {
systemProperty = WildFlySecurityManager.getSystemPropertiesPrivileged().getProperty(s);
}
} else {
systemProperty = WildFlySecurityManager.getSystemPropertiesPrivileged().getProperty(input.substring(from + 2, dv));
defaultValue = input.substring(dv + 1, to);
}
String prefix = "";
String postfix = "";
if (from != 0) {
prefix = input.substring(0, from);
}
if (to + 1 < input.length() - 1) {
postfix = input.substring(to + 1);
}
if (systemProperty != null && !systemProperty.trim().equals("")) {
input = prefix + systemProperty + postfix;
} else if (!defaultValue.trim().equals("")) {
input = prefix + defaultValue + postfix;
} else {
input = prefix + postfix;
}
}
return input;
}
/**
* Method sorter
*/
static class MethodSorter implements Comparator<Method>, Serializable {
private static final long serialVersionUID = 1L;
/**
* Constructor
*/
MethodSorter() {
}
/**
* {@inheritDoc}
*/
public int compare(Method o1, Method o2) {
int m1 = o1.getModifiers();
int m2 = o2.getModifiers();
if (Modifier.isPublic(m1))
return -1;
if (Modifier.isPublic(m2))
return 1;
if (Modifier.isProtected(m1))
return -1;
if (Modifier.isProtected(m2))
return 1;
if (Modifier.isPrivate(m1))
return -1;
if (Modifier.isPrivate(m2))
return 1;
return 0;
}
/**
* {@inheritDoc}
*/
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || !(o instanceof MethodSorter))
return false;
return true;
}
/**
* {@inheritDoc}
*/
public int hashCode() {
return 42;
}
}
/**
* Field sorter
*/
static class FieldSorter implements Comparator<Field>, Serializable {
private static final long serialVersionUID = 1L;
/**
* Constructor
*/
FieldSorter() {
}
/**
* {@inheritDoc}
*/
public int compare(Field o1, Field o2) {
int m1 = o1.getModifiers();
int m2 = o2.getModifiers();
if (Modifier.isPublic(m1))
return -1;
if (Modifier.isPublic(m2))
return 1;
if (Modifier.isProtected(m1))
return -1;
if (Modifier.isProtected(m2))
return 1;
if (Modifier.isPrivate(m1))
return -1;
if (Modifier.isPrivate(m2))
return 1;
return 0;
}
/**
* {@inheritDoc}
*/
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || !(o instanceof FieldSorter))
return false;
return true;
}
/**
* {@inheritDoc}
*/
public int hashCode() {
return 42;
}
}
}
| 19,433 | 35.189944 | 131 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/dynamicresource/StatisticsResourceDefinition.java | /*
* 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.dynamicresource;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import org.jboss.as.connector.subsystems.common.pool.PoolMetrics;
import org.jboss.as.connector.subsystems.common.pool.PoolStatisticsRuntimeAttributeReadHandler;
import org.jboss.as.connector.subsystems.common.pool.PoolStatisticsRuntimeAttributeWriteHandler;
import org.jboss.as.connector.subsystems.resourceadapters.ResourceAdaptersExtension;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.descriptions.ResourceDescriptionResolver;
import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelType;
import org.jboss.jca.core.spi.statistics.StatisticsPlugin;
/**
* @author Tomaz Cerar
*/
public class StatisticsResourceDefinition extends SimpleResourceDefinition {
private final StatisticsPlugin plugin;
/**
* Constructor for the {@link org.jboss.as.controller.descriptions.OverrideDescriptionProvider} case. Internationalization support is not provided.
*
* @param bundleName name to pass to {@link ResourceBundle#getBundle(String)}
* @param plugin the statistics plugins
*/
public StatisticsResourceDefinition(final PathElement path, final String bundleName, final StatisticsPlugin plugin) {
super(new Parameters(path, getResolver("statistics", bundleName, plugin)).setRuntime());
this.plugin = plugin;
}
private static ResourceDescriptionResolver getResolver(final String keyPrefix, final String bundleName, final StatisticsPlugin plugin) {
return new StandardResourceDescriptionResolver(keyPrefix, bundleName, ResourceAdaptersExtension.class.getClassLoader(), true, false){
@Override
public String getResourceAttributeDescription(String attributeName, Locale locale, ResourceBundle bundle) {
if (bundle.containsKey(keyPrefix + "." + attributeName)){
return super.getResourceAttributeDescription(attributeName, locale, bundle);
}
return plugin.getDescription(attributeName);
}
};
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
super.registerAttributes(resourceRegistration);
for (AttributeDefinition attribute : getAttributesFromPlugin(plugin)) {
resourceRegistration.registerMetric(attribute, new PoolMetrics.ParametrizedPoolMetricsHandler(plugin));
}
//adding enable/disable for pool stats
OperationStepHandler readHandler = new PoolStatisticsRuntimeAttributeReadHandler(plugin);
OperationStepHandler writeHandler = new PoolStatisticsRuntimeAttributeWriteHandler(plugin);
resourceRegistration.registerReadWriteAttribute(org.jboss.as.connector.subsystems.common.pool.Constants.POOL_STATISTICS_ENABLED, readHandler, writeHandler);
}
public static List<AttributeDefinition> getAttributesFromPlugin(StatisticsPlugin plugin) {
LinkedList<AttributeDefinition> result = new LinkedList<>();
for (String name : plugin.getNames()) {
ModelType modelType = ModelType.STRING;
if (plugin.getType(name) == int.class) {
modelType = ModelType.INT;
}
if (plugin.getType(name) == long.class) {
modelType = ModelType.LONG;
}
SimpleAttributeDefinition attribute = new SimpleAttributeDefinitionBuilder(name, modelType)
.setRequired(false)
.setStorageRuntime()
.build();
result.add(attribute);
}
return result;
}
@Override
public void registerOperations(ManagementResourceRegistration resourceRegistration) {
super.registerOperations(resourceRegistration);
resourceRegistration.registerOperationHandler(ClearStatisticsHandler.DEFINITION, new ClearStatisticsHandler(plugin));
}
}
| 5,455 | 44.848739 | 164 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/dynamicresource/ClearStatisticsHandler.java | /*
* 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.dynamicresource;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.CONNECTIONDEFINITIONS_NAME;
import java.util.Arrays;
import java.util.List;
import org.jboss.as.connector.subsystems.resourceadapters.Constants;
import org.jboss.as.connector.subsystems.resourceadapters.ResourceAdaptersExtension;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationDefinition;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.SimpleOperationDefinitionBuilder;
import org.jboss.dmr.ModelNode;
import org.jboss.jca.core.spi.statistics.StatisticsPlugin;
/**
* Clear stats from passed plugins
*
* @author Stefano Maestri
*/
public class ClearStatisticsHandler implements OperationStepHandler {
public static final OperationDefinition DEFINITION = new SimpleOperationDefinitionBuilder(Constants.CLEAR_STATISTICS, ResourceAdaptersExtension.getResourceDescriptionResolver(CONNECTIONDEFINITIONS_NAME))
.build();
private final List<StatisticsPlugin> stats;
public ClearStatisticsHandler(StatisticsPlugin... stats) {
this.stats = Arrays.asList(stats);
}
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
if (context.isNormalServer()) {
context.addStep(new OperationStepHandler() {
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
for (StatisticsPlugin statsPlugin : stats) {
statsPlugin.clear();
}
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
}, OperationContext.Stage.RUNTIME);
}
}
}
| 2,934 | 39.763889 | 207 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/dynamicresource/ClearWorkManagerStatisticsHandler.java | /*
* 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.dynamicresource;
import org.jboss.as.connector.subsystems.resourceadapters.Constants;
import org.jboss.as.connector.subsystems.resourceadapters.ResourceAdaptersExtension;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationDefinition;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.SimpleOperationDefinitionBuilder;
import org.jboss.dmr.ModelNode;
import org.jboss.jca.core.api.workmanager.WorkManager;
import static org.jboss.as.connector.subsystems.resourceadapters.Constants.STATISTICS_NAME;
/**
* Clear stats from passed plugins
*
* @author Stefano Maestri
*/
public class ClearWorkManagerStatisticsHandler implements OperationStepHandler {
public static final OperationDefinition DEFINITION = new SimpleOperationDefinitionBuilder(Constants.CLEAR_STATISTICS, ResourceAdaptersExtension.getResourceDescriptionResolver(STATISTICS_NAME))
.build();
private final WorkManager wm;
public ClearWorkManagerStatisticsHandler(final WorkManager wm) {
this.wm = wm;
}
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
if (context.isNormalServer()) {
context.addStep(new OperationStepHandler() {
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
wm.getStatistics().clear();
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
}, OperationContext.Stage.RUNTIME);
}
}
}
| 2,756 | 40.772727 | 196 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/_drivermanager/DriverManagerAdapter.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2020, 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._drivermanager;
import java.util.Enumeration;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* @author <a href="mailto:[email protected]">Tomasz Adamski</a>
*/
public class DriverManagerAdapter {
private DriverManagerAdapter() {
}
public static Enumeration<Driver> getDrivers() {
return DriverManager.getDrivers();
}
public static void deregisterDriver(final Driver driver) throws SQLException {
DriverManager.deregisterDriver(driver);
}
}
| 1,587 | 32.787234 | 82 | java |
null | wildfly-main/connector/src/main/java/org/jboss/as/connector/deployers/Util.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, 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.deployers;
import org.jboss.as.ee.structure.Attachments;
import org.jboss.as.server.deployment.DeploymentUnit;
/**
* Utilities
*
* @author Jason T. Greene
*/
public class Util {
public static boolean shouldResolveSpec(DeploymentUnit deploymentUnit) {
Boolean attachment = deploymentUnit.getAttachment(Attachments.SPEC_DESCRIPTOR_PROPERTY_REPLACEMENT);
return attachment != null && attachment.booleanValue();
}
public static boolean shouldResolveJBoss(DeploymentUnit deploymentUnit) {
Boolean attachment = deploymentUnit.getAttachment(Attachments.JBOSS_DESCRIPTOR_PROPERTY_REPLACEMENT);
return attachment != null && attachment.booleanValue();
}
}
| 1,756 | 38.931818 | 109 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.