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/xts/src/main/java/org/jboss/as/xts/Element.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.xts;
import java.util.HashMap;
import java.util.Map;
/**
* Enumeration of elements used in the xts subsystem.
*
* @author <a href="mailto:[email protected]">Andrew Dinn</a>
*/
enum Element {
// must be first
UNKNOWN(null),
HOST(CommonAttributes.HOST),
XTS_ENVIRONMENT(CommonAttributes.XTS_ENVIRONMENT),
DEFAULT_CONTEXT_PROPAGATION(CommonAttributes.DEFAULT_CONTEXT_PROPAGATION),
ASYNC_REGISTRATION(CommonAttributes.ASYNC_REGISTRATION),
;
private final String name;
Element(final String name) {
this.name = name;
}
/**
* Get the local name of this element.
*
* @return the local name
*/
public String getLocalName() {
return name;
}
private static final Map<String, Element> MAP;
static {
final Map<String, Element> map = new HashMap<String, Element>();
for (Element element : values()) {
final String name = element.getLocalName();
if (name != null) { map.put(name, element); }
}
MAP = map;
}
public static Element forName(String localName) {
final Element element = MAP.get(localName);
return element == null ? UNKNOWN : element;
}
}
| 2,272 | 29.306667 | 78 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/XTSSubsystemAdd.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.xts;
import static org.jboss.as.xts.XTSSubsystemDefinition.DEFAULT_CONTEXT_PROPAGATION;
import static org.jboss.as.xts.XTSSubsystemDefinition.ENVIRONMENT_URL;
import static org.jboss.as.xts.XTSSubsystemDefinition.HOST_NAME;
import static org.jboss.as.xts.XTSSubsystemDefinition.ASYNC_REGISTRATION;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.arjuna.schemas.ws._2005._10.wsarjtx.TerminationCoordinatorRPCService;
import com.arjuna.schemas.ws._2005._10.wsarjtx.TerminationCoordinatorService;
import com.arjuna.schemas.ws._2005._10.wsarjtx.TerminationParticipantService;
import com.arjuna.webservices11.wsarjtx.sei.TerminationCoordinatorPortTypeImpl;
import com.arjuna.webservices11.wsarjtx.sei.TerminationCoordinatorRPCPortTypeImpl;
import com.arjuna.webservices11.wsarjtx.sei.TerminationParticipantPortTypeImpl;
import com.arjuna.webservices11.wsat.sei.CompletionCoordinatorPortTypeImpl;
import com.arjuna.webservices11.wsat.sei.CompletionCoordinatorRPCPortTypeImpl;
import com.arjuna.webservices11.wsat.sei.CompletionInitiatorPortTypeImpl;
import com.arjuna.webservices11.wsat.sei.CoordinatorPortTypeImpl;
import com.arjuna.webservices11.wsat.sei.ParticipantPortTypeImpl;
import com.arjuna.webservices11.wsba.sei.BusinessAgreementWithCoordinatorCompletionCoordinatorPortTypeImpl;
import com.arjuna.webservices11.wsba.sei.BusinessAgreementWithCoordinatorCompletionParticipantPortTypeImpl;
import com.arjuna.webservices11.wsba.sei.BusinessAgreementWithParticipantCompletionCoordinatorPortTypeImpl;
import com.arjuna.webservices11.wsba.sei.BusinessAgreementWithParticipantCompletionParticipantPortTypeImpl;
import com.arjuna.webservices11.wscoor.sei.ActivationPortTypeImpl;
import com.arjuna.webservices11.wscoor.sei.CoordinationFaultPortTypeImpl;
import com.arjuna.webservices11.wscoor.sei.RegistrationPortTypeImpl;
import com.arjuna.webservices11.wscoor.sei.RegistrationResponsePortTypeImpl;
import org.jboss.as.compensations.CompensationsDependenciesDeploymentProcessor;
import org.jboss.as.controller.AbstractBoottimeAddStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.network.NetworkUtils;
import org.jboss.as.server.AbstractDeploymentChainStep;
import org.jboss.as.server.DeploymentProcessorTarget;
import org.jboss.as.server.deployment.Phase;
import org.jboss.as.txn.service.TxnServices;
import org.jboss.as.webservices.service.EndpointPublishService;
import org.jboss.as.webservices.util.WSServices;
import org.jboss.as.xts.logging.XtsAsLogger;
import org.jboss.dmr.ModelNode;
import org.jboss.jbossts.XTSService;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceController.Mode;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.wsf.spi.invocation.RejectionRule;
import org.jboss.wsf.spi.management.ServerConfig;
import org.jboss.wsf.spi.publish.Context;
import org.oasis_open.docs.ws_tx.wsat._2006._06.CompletionCoordinatorRPCService;
import org.oasis_open.docs.ws_tx.wsat._2006._06.CompletionCoordinatorService;
import org.oasis_open.docs.ws_tx.wsat._2006._06.CompletionInitiatorService;
import org.oasis_open.docs.ws_tx.wsat._2006._06.CoordinatorService;
import org.oasis_open.docs.ws_tx.wsat._2006._06.ParticipantService;
import org.oasis_open.docs.ws_tx.wsba._2006._06.BusinessAgreementWithCoordinatorCompletionCoordinatorService;
import org.oasis_open.docs.ws_tx.wsba._2006._06.BusinessAgreementWithCoordinatorCompletionParticipantService;
import org.oasis_open.docs.ws_tx.wsba._2006._06.BusinessAgreementWithParticipantCompletionCoordinatorService;
import org.oasis_open.docs.ws_tx.wsba._2006._06.BusinessAgreementWithParticipantCompletionParticipantService;
import org.oasis_open.docs.ws_tx.wscoor._2006._06.ActivationService;
import org.oasis_open.docs.ws_tx.wscoor._2006._06.CoordinationFaultService;
import org.oasis_open.docs.ws_tx.wscoor._2006._06.RegistrationResponseService;
import org.oasis_open.docs.ws_tx.wscoor._2006._06.RegistrationService;
/**
* Adds the transaction management subsystem.
*
* @author <a href="mailto:[email protected]">Andrew Dinn</a>
*/
class XTSSubsystemAdd extends AbstractBoottimeAddStepHandler {
static final XTSSubsystemAdd INSTANCE = new XTSSubsystemAdd();
private static final String WSAT_ASYNC_REGISTRATION_PARAM_NAME = "wsat.async.registration";
/**
* class used to record the url pattern and service endpoint implementation class name of
* an XTS JaxWS endpoint associated with one of the XTS context paths. this is equivalent
* to the information contained in a single matched pair of servlet:servletName and
* servlet-mapping:url-pattern fields in the web.xml
*/
private static class EndpointInfo {
String SEIClassname;
String URLPattern;
EndpointInfo(String seiClassname, String urlPattern) {
this.SEIClassname = seiClassname;
this.URLPattern = urlPattern;
}
}
/**
* class grouping togeher details of all XTS JaxWS endpoints associated with a given XTS context
* path. this groups together all the paired servlet:servletName and* servlet-mapping:url-pattern
* fields in the web.xml
*/
static class ContextInfo {
String contextPath;
EndpointInfo[] endpointInfo;
ContextInfo(String contextPath, EndpointInfo[] endpointInfo) {
this.contextPath = contextPath;
this.endpointInfo = endpointInfo;
}
}
/**
* a collection of all the context and associated endpoint information for the XTS JaxWS endpoints.
* this is the bits of the variosu web.xml files which are necessary to deploy via the endpoint
* publisher API rather than via war files containing web.xml descriptors
*/
private static final ContextInfo[] contextDefinitions = {
// ContextInfo ws-c11 filled at method getContextDefinitions
new ContextInfo("ws-t11-coordinator",
new EndpointInfo[]{
new EndpointInfo(CoordinatorPortTypeImpl.class.getName(), CoordinatorService.class.getSimpleName()),
new EndpointInfo(CompletionCoordinatorPortTypeImpl.class.getName(), CompletionCoordinatorService.class.getSimpleName()),
new EndpointInfo(CompletionCoordinatorRPCPortTypeImpl.class.getName(), CompletionCoordinatorRPCService.class.getSimpleName()),
new EndpointInfo(BusinessAgreementWithCoordinatorCompletionCoordinatorPortTypeImpl.class.getName(), BusinessAgreementWithCoordinatorCompletionCoordinatorService.class.getSimpleName()),
new EndpointInfo(BusinessAgreementWithParticipantCompletionCoordinatorPortTypeImpl.class.getName(), BusinessAgreementWithParticipantCompletionCoordinatorService.class.getSimpleName()),
new EndpointInfo(TerminationCoordinatorPortTypeImpl.class.getName(), TerminationCoordinatorService.class.getSimpleName()),
new EndpointInfo(TerminationCoordinatorRPCPortTypeImpl.class.getName(), TerminationCoordinatorRPCService.class.getSimpleName())
}),
new ContextInfo("ws-t11-participant",
new EndpointInfo[]{
new EndpointInfo(ParticipantPortTypeImpl.class.getName(), ParticipantService.class.getSimpleName()),
new EndpointInfo(BusinessAgreementWithCoordinatorCompletionParticipantPortTypeImpl.class.getName(), BusinessAgreementWithCoordinatorCompletionParticipantService.class.getSimpleName()),
new EndpointInfo(BusinessAgreementWithParticipantCompletionParticipantPortTypeImpl.class.getName(), BusinessAgreementWithParticipantCompletionParticipantService.class.getSimpleName()),
}),
new ContextInfo("ws-t11-client",
new EndpointInfo[]{
new EndpointInfo(CompletionInitiatorPortTypeImpl.class.getName(), CompletionInitiatorService.class.getSimpleName()),
new EndpointInfo(TerminationParticipantPortTypeImpl.class.getName(), TerminationParticipantService.class.getSimpleName())
})
};
private static final String WS_C11_CONTEXT_DEFINITION_NAME = "ws-c11";
static final EndpointInfo[] wsC11 = new EndpointInfo[] {
new EndpointInfo(ActivationPortTypeImpl.class.getName(), ActivationService.class.getSimpleName()),
new EndpointInfo(RegistrationPortTypeImpl.class.getName(), RegistrationService.class.getSimpleName())
};
static final EndpointInfo[] wsC11Async = new EndpointInfo[] {
new EndpointInfo(RegistrationResponsePortTypeImpl.class.getName(), RegistrationResponseService.class.getSimpleName()),
new EndpointInfo(CoordinationFaultPortTypeImpl.class.getName(), CoordinationFaultService.class.getSimpleName())
};
private XTSSubsystemAdd() {
}
static Iterable<ContextInfo> getContextDefinitions(OperationContext context, ModelNode model) throws IllegalArgumentException, OperationFailedException {
Collection<ContextInfo> updatedContextDefinitions = new ArrayList<>(Arrays.asList(contextDefinitions));
Collection<EndpointInfo> wsC11EndpointInfos = new ArrayList<>(Arrays.asList(wsC11));
if(ASYNC_REGISTRATION.resolveModelAttribute(context, model).asBoolean() || Boolean.getBoolean(XTSSubsystemAdd.WSAT_ASYNC_REGISTRATION_PARAM_NAME)) {
wsC11EndpointInfos.addAll(Arrays.asList(wsC11Async));
}
ContextInfo wsC11ContextInfo = new ContextInfo(WS_C11_CONTEXT_DEFINITION_NAME, wsC11EndpointInfos.toArray(new EndpointInfo[wsC11EndpointInfos.size()]));
updatedContextDefinitions.add(wsC11ContextInfo);
return updatedContextDefinitions;
}
@Override
protected void populateModel(ModelNode operation, ModelNode model) throws OperationFailedException {
HOST_NAME.validateAndSet(operation, model);
ENVIRONMENT_URL.validateAndSet(operation, model);
DEFAULT_CONTEXT_PROPAGATION.validateAndSet(operation, model);
ASYNC_REGISTRATION.validateAndSet(operation, model);
}
@Override
protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
final String hostName = HOST_NAME.resolveModelAttribute(context, model).asString();
final ModelNode coordinatorURLAttribute = ENVIRONMENT_URL.resolveModelAttribute(context, model);
String coordinatorURL = coordinatorURLAttribute.isDefined() ? coordinatorURLAttribute.asString() : null;
// formatting possible IPv6 address to contain square brackets
if (coordinatorURL != null) {
// [1] http://, [2] ::1, [3] 8080, [4] /ws-c11/ActivationService
Pattern urlPattern = Pattern.compile("^([a-zA-Z]+://)(.*):([^/]*)(/.*)$");
Matcher urlMatcher = urlPattern.matcher(coordinatorURL);
if(urlMatcher.matches()) {
String address = NetworkUtils.formatPossibleIpv6Address(urlMatcher.group(2));
coordinatorURL = String.format("%s%s:%s%s", urlMatcher.group(1), address, urlMatcher.group(3), urlMatcher.group(4));
}
}
if (coordinatorURL != null) {
XtsAsLogger.ROOT_LOGGER.debugf("nodeIdentifier=%s%n", coordinatorURL);
}
final boolean isDefaultContextPropagation = DEFAULT_CONTEXT_PROPAGATION.resolveModelAttribute(context, model).asBoolean(false); // TODO WFLY-14350 make the 'false' the default value of DEFAULT_CONTEXT_PROPAGATION
context.addStep(new AbstractDeploymentChainStep() {
protected void execute(DeploymentProcessorTarget processorTarget) {
processorTarget.addDeploymentProcessor(XTSExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_XTS_SOAP_HANDLERS, new XTSHandlerDeploymentProcessor());
processorTarget.addDeploymentProcessor(XTSExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_XTS, new XTSDependenciesDeploymentProcessor());
processorTarget.addDeploymentProcessor(XTSExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_XTS_PORTABLE_EXTENSIONS, new GracefulShutdownDeploymentProcessor());
processorTarget.addDeploymentProcessor(XTSExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_TRANSACTIONS, new CompensationsDependenciesDeploymentProcessor());
}
}, OperationContext.Stage.RUNTIME);
final ServiceTarget target = context.getServiceTarget();
// TODO eventually we should add a config service which manages the XTS configuration
// this will allow us to include a switch enabling or disabling deployment of
// endpoints specific to client, coordinator or participant and then deploy
// and redeploy the relevant endpoints as needed/ the same switches can be used
// byte the XTS service to decide whether to perfomr client, coordinator or
// participant initialisation. we should also provide config switches which
// decide whether to initialise classes and deploy services for AT, BA or both.
// for now we will just deploy all the endpoints and always do client, coordinator
// and participant init for both AT and BA.
// add an endpoint publisher service for each of the required endpoint contexts
// specifying all the relevant URL patterns and SEI classes
final ClassLoader loader = XTSService.class.getClassLoader();
ServiceBuilder<Context> endpointBuilder;
ArrayList<ServiceController<Context>> controllers = new ArrayList<ServiceController<Context>>();
Map<Class<?>, Object> attachments = new HashMap<>();
attachments.put(RejectionRule.class, new GracefulShutdownRejectionRule());
for (ContextInfo contextInfo : getContextDefinitions(context, model)) {
String contextName = contextInfo.contextPath;
Map<String, String> map = new HashMap<String, String>();
for (EndpointInfo endpointInfo : contextInfo.endpointInfo) {
map.put(endpointInfo.URLPattern, endpointInfo.SEIClassname);
}
endpointBuilder = EndpointPublishService.createServiceBuilder(target, contextName, loader, hostName, map, null,
null, null, attachments, context.getCapabilityServiceSupport());
controllers.add(endpointBuilder.setInitialMode(Mode.ACTIVE)
.install());
}
XTSHandlersService.install(target, isDefaultContextPropagation);
// add an XTS service which depends on all the WS endpoints
final XTSManagerService xtsService = new XTSManagerService(coordinatorURL);
// this service needs to depend on the transaction recovery service
// because it can only initialise XTS recovery once the transaction recovery
// service has initialised the orb layer
ServiceBuilder<?> xtsServiceBuilder = target.addService(XTSServices.JBOSS_XTS_MAIN, xtsService);
xtsServiceBuilder.requires(TxnServices.JBOSS_TXN_ARJUNA_TRANSACTION_MANAGER);
// this service needs to depend on JBossWS Config Service to be notified of the JBoss WS config (bind address, port etc)
xtsServiceBuilder.addDependency(WSServices.CONFIG_SERVICE, ServerConfig.class, xtsService.getWSServerConfig());
xtsServiceBuilder.requires(WSServices.XTS_CLIENT_INTEGRATION_SERVICE);
// the service also needs to depend on the endpoint services
for (ServiceController<Context> controller : controllers) {
xtsServiceBuilder.requires(controller.getName());
}
xtsServiceBuilder
.setInitialMode(Mode.ACTIVE)
.install();
// WS-AT / Jakarta Transactions Transaction bridge services:
final TxBridgeInboundRecoveryService txBridgeInboundRecoveryService = new TxBridgeInboundRecoveryService();
ServiceBuilder<?> txBridgeInboundRecoveryServiceBuilder =
target.addService(XTSServices.JBOSS_XTS_TXBRIDGE_INBOUND_RECOVERY, txBridgeInboundRecoveryService);
txBridgeInboundRecoveryServiceBuilder.requires(XTSServices.JBOSS_XTS_MAIN);
txBridgeInboundRecoveryServiceBuilder.setInitialMode(Mode.ACTIVE).install();
final TxBridgeOutboundRecoveryService txBridgeOutboundRecoveryService = new TxBridgeOutboundRecoveryService();
ServiceBuilder<?> txBridgeOutboundRecoveryServiceBuilder =
target.addService(XTSServices.JBOSS_XTS_TXBRIDGE_OUTBOUND_RECOVERY, txBridgeOutboundRecoveryService);
txBridgeOutboundRecoveryServiceBuilder.requires(XTSServices.JBOSS_XTS_MAIN);
txBridgeOutboundRecoveryServiceBuilder.setInitialMode(Mode.ACTIVE).install();
}
}
| 18,202 | 57.530547 | 220 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/XTSSubsystemDefinition.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.xts;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.ObjectTypeAttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.ReloadRequiredWriteAttributeHandler;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
/**
* @author <a href="mailto:[email protected]">Tomaz Cerar</a>
*/
public class XTSSubsystemDefinition extends SimpleResourceDefinition {
protected static final SimpleAttributeDefinition HOST_NAME =
new SimpleAttributeDefinitionBuilder(CommonAttributes.HOST, ModelType.STRING)
.setRequired(false)
.setDefaultValue(new ModelNode("default-host"))
.setAllowExpression(true)
.setXmlName(Attribute.NAME.getLocalName())
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.build();
protected static final SimpleAttributeDefinition ENVIRONMENT_URL =
new SimpleAttributeDefinitionBuilder(ModelDescriptionConstants.URL, ModelType.STRING, true)
.setAllowExpression(true)
.setXmlName(Attribute.URL.getLocalName())
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
//.setDefaultValue(new ModelNode().setExpression("http://${jboss.bind.address:127.0.0.1}:8080/ws-c11/ActivationService"))
.build();
protected static final SimpleAttributeDefinition DEFAULT_CONTEXT_PROPAGATION =
new SimpleAttributeDefinitionBuilder(CommonAttributes.DEFAULT_CONTEXT_PROPAGATION, ModelType.BOOLEAN, true)
.setAllowExpression(false)
.setXmlName(Attribute.ENABLED.getLocalName())
.setFlags(AttributeAccess.Flag.RESTART_JVM)
.build();
protected static final SimpleAttributeDefinition ASYNC_REGISTRATION =
new SimpleAttributeDefinitionBuilder(CommonAttributes.ASYNC_REGISTRATION, ModelType.BOOLEAN, true)
.setAllowExpression(true)
.setXmlName(Attribute.ENABLED.getLocalName())
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) // we need to register new WS endpoints
.setDefaultValue(ModelNode.FALSE)
.build();
@Deprecated //just legacy support
private static final ObjectTypeAttributeDefinition ENVIRONMENT = ObjectTypeAttributeDefinition.
Builder.of(CommonAttributes.XTS_ENVIRONMENT, ENVIRONMENT_URL)
.setDeprecated(ModelVersion.create(2,0,0))
.build();
protected XTSSubsystemDefinition() {
super(XTSExtension.SUBSYSTEM_PATH,
XTSExtension.getResourceDescriptionResolver(null),
XTSSubsystemAdd.INSTANCE,
XTSSubsystemRemove.INSTANCE);
setDeprecated(ModelVersion.create(3,0,0));
}
/**
* {@inheritDoc}
* Registers an add operation handler or a remove operation handler if one was provided to the constructor.
*/
@Override
public void registerOperations(ManagementResourceRegistration registration) {
super.registerOperations(registration);
registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE);
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerReadWriteAttribute(HOST_NAME, null, new ReloadRequiredWriteAttributeHandler(HOST_NAME));
resourceRegistration.registerReadWriteAttribute(ENVIRONMENT_URL, null, new ReloadRequiredWriteAttributeHandler(ENVIRONMENT_URL));
resourceRegistration.registerReadWriteAttribute(DEFAULT_CONTEXT_PROPAGATION, null, new ReloadRequiredWriteAttributeHandler(DEFAULT_CONTEXT_PROPAGATION));
resourceRegistration.registerReadWriteAttribute(ASYNC_REGISTRATION, null, new ReloadRequiredWriteAttributeHandler(ASYNC_REGISTRATION));
//this here just for legacy support!
resourceRegistration.registerReadOnlyAttribute(ENVIRONMENT, new OperationStepHandler() {
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
ModelNode url = context.readResource(PathAddress.EMPTY_ADDRESS).getModel().get(ModelDescriptionConstants.URL);
context.getResult().get(ModelDescriptionConstants.URL).set(url);
}
});
}
}
| 6,196 | 50.641667 | 161 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/XTSHandlersManager.java
|
package org.jboss.as.xts;
import java.util.ArrayList;
import java.util.List;
import com.arjuna.mw.wst11.client.DisabledWSTXHandler;
import com.arjuna.mw.wst11.client.EnabledWSTXHandler;
import com.arjuna.mw.wst11.service.JaxWSHeaderContextProcessor;
import org.jboss.jbossts.txbridge.outbound.DisabledJTAOverWSATHandler;
import org.jboss.jbossts.txbridge.outbound.EnabledJTAOverWSATHandler;
import org.jboss.jbossts.txbridge.outbound.JaxWSTxOutboundBridgeHandler;
import org.jboss.wsf.spi.metadata.j2ee.serviceref.UnifiedHandlerChainMetaData;
import org.jboss.wsf.spi.metadata.j2ee.serviceref.UnifiedHandlerMetaData;
/**
* Class responsible for registering WSTX and JTAOverWSAT handlers.
*
* @author <a href="mailto:[email protected]">Gytis Trikleris</a>
*
*/
public final class XTSHandlersManager {
private static final String HANDLER_CHAIN_ID = "xts-handler-chain";
private static final String HANDLER_PROTOCOL_BINDINGS = "##SOAP11_HTTP ##SOAP12_HTTP";
private static final String WSAT_HANDLER_NAME = JaxWSHeaderContextProcessor.class.getSimpleName();
/**
* WS-AT handler used when default context propagation is enabled.
*/
private static final String WSAT_ENABLED_HANDLER_CLASS = EnabledWSTXHandler.class.getName();
/**
* WS-AT handler used when default context propagation is disabled.
*/
private static final String WSAT_DISABLED_HANDLER_CLASS = DisabledWSTXHandler.class.getName();
private static final String BRIDGE_HANDLER_NAME = JaxWSTxOutboundBridgeHandler.class.getSimpleName();
/**
* JTAOverWSAT handler used when default context propagation is enabled.
*/
private static final String BRIDGE_ENABLED_HANDLER_CLASS = EnabledJTAOverWSATHandler.class.getName();
/**
* JTAOverWSAT handler used when default context propagation is disabled.
*/
private static final String BRIDGE_DISABLED_HANDLER_CLASS = DisabledJTAOverWSATHandler.class.getName();
private final boolean enabled;
public XTSHandlersManager(final boolean enabled) {
this.enabled = enabled;
}
public UnifiedHandlerChainMetaData getHandlerChain() {
List<UnifiedHandlerMetaData> handlers = new ArrayList<UnifiedHandlerMetaData>(2);
if (enabled) {
handlers.add(new UnifiedHandlerMetaData(BRIDGE_ENABLED_HANDLER_CLASS, BRIDGE_HANDLER_NAME, null, null, null,
null));
handlers.add(new UnifiedHandlerMetaData(WSAT_ENABLED_HANDLER_CLASS, WSAT_HANDLER_NAME, null, null, null, null));
} else {
handlers.add(new UnifiedHandlerMetaData(BRIDGE_DISABLED_HANDLER_CLASS, BRIDGE_HANDLER_NAME, null, null, null,
null));
handlers.add(new UnifiedHandlerMetaData(WSAT_DISABLED_HANDLER_CLASS, WSAT_HANDLER_NAME, null, null, null, null));
}
return new UnifiedHandlerChainMetaData(null, null, HANDLER_PROTOCOL_BINDINGS, handlers, false, HANDLER_CHAIN_ID);
}
}
| 2,969 | 40.830986 | 125 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/TxBridgeOutboundRecoveryService.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.xts;
import org.jboss.as.xts.logging.XtsAsLogger;
import org.jboss.jbossts.txbridge.outbound.OutboundBridgeRecoveryManager;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.service.StartException;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Jakarta Transactions / WS-AT transaction bridge - outbound recovery handling.
*
* @author <a href="mailto:[email protected]">Jonathan Halliday</a>
*/
public class TxBridgeOutboundRecoveryService implements Service<OutboundBridgeRecoveryManager> {
private OutboundBridgeRecoveryManager outboundBridgeRecoveryManager;
public TxBridgeOutboundRecoveryService() {
}
@Override
public synchronized OutboundBridgeRecoveryManager getValue() throws IllegalStateException {
return outboundBridgeRecoveryManager;
}
@Override
public synchronized void start(final StartContext context) throws StartException {
// XTS expects the TCCL to be set to something that will locate the XTS service implementation classes.
final ClassLoader loader = TxBridgeOutboundRecoveryService.class.getClassLoader();
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(loader);
try {
OutboundBridgeRecoveryManager service = new OutboundBridgeRecoveryManager();
try {
service.start();
} catch (Exception e) {
throw XtsAsLogger.ROOT_LOGGER.txBridgeOutboundRecoveryServiceFailedToStart();
}
outboundBridgeRecoveryManager = service;
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged((ClassLoader) null);
}
}
public synchronized void stop(final StopContext context) {
if (outboundBridgeRecoveryManager != null) {
try {
outboundBridgeRecoveryManager.stop();
} catch (Exception e) {
// ignore?
}
}
}
}
| 3,111 | 37.419753 | 111 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/XTSSubsystemRemove.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.xts;
import org.jboss.as.controller.AbstractRemoveStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.webservices.util.WSServices;
import org.jboss.as.xts.XTSSubsystemAdd.ContextInfo;
import org.jboss.dmr.ModelNode;
/**
* Adds the transaction management subsystem.
*
* @author <a href="mailto:[email protected]">Andrew Dinn</a>
*/
class XTSSubsystemRemove extends AbstractRemoveStepHandler {
static final XTSSubsystemRemove INSTANCE = new XTSSubsystemRemove();
private XTSSubsystemRemove() {
}
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
for (ContextInfo contextInfo : XTSSubsystemAdd.getContextDefinitions(context, model)) {
String contextName = contextInfo.contextPath;
context.removeService(WSServices.ENDPOINT_PUBLISH_SERVICE.append(contextName));
}
context.removeService(XTSServices.JBOSS_XTS_MAIN);
context.removeService(XTSServices.JBOSS_XTS_TXBRIDGE_INBOUND_RECOVERY);
context.removeService(XTSServices.JBOSS_XTS_TXBRIDGE_OUTBOUND_RECOVERY);
}
}
| 2,279 | 38.310345 | 131 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/TxBridgeInboundRecoveryService.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.xts;
import org.jboss.as.xts.logging.XtsAsLogger;
import org.jboss.jbossts.txbridge.inbound.InboundBridgeRecoveryManager;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.service.StartException;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Jakarta Transactions / WS-AT transaction bridge - inbound recovery handling.
*
* @author <a href="mailto:[email protected]">Jonathan Halliday</a>
*/
public class TxBridgeInboundRecoveryService implements Service<InboundBridgeRecoveryManager> {
private volatile InboundBridgeRecoveryManager inboundBridgeRecoveryManager;
public TxBridgeInboundRecoveryService() {
}
@Override
public InboundBridgeRecoveryManager getValue() throws IllegalStateException {
return inboundBridgeRecoveryManager;
}
@Override
public synchronized void start(final StartContext context) throws StartException {
// XTS expects the TCCL to be set to something that will locate the XTS service implementation classes.
final ClassLoader loader = TxBridgeInboundRecoveryService.class.getClassLoader();
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(loader);
try {
InboundBridgeRecoveryManager service = new InboundBridgeRecoveryManager();
try {
service.start();
} catch (Exception e) {
throw XtsAsLogger.ROOT_LOGGER.txBridgeInboundRecoveryServiceFailedToStart();
}
inboundBridgeRecoveryManager = service;
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged((ClassLoader) null);
}
}
public synchronized void stop(final StopContext context) {
if (inboundBridgeRecoveryManager != null) {
try {
inboundBridgeRecoveryManager.stop();
} catch (Exception e) {
// ignore?
}
}
}
}
| 3,090 | 37.160494 | 111 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/XTSExtension.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.xts;
import org.jboss.as.controller.Extension;
import org.jboss.as.controller.ExtensionContext;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SubsystemRegistration;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver;
import org.jboss.as.controller.parsing.ExtensionParsingContext;
import org.jboss.as.xts.logging.XtsAsLogger;
/**
* The web services transactions extension.
*
* @author <a href="mailto:[email protected]">Andrew Dinn</a>
* @author <a href="mailto:[email protected]">Tomaz Cerar</a>
*/
public class XTSExtension implements Extension {
public static final String SUBSYSTEM_NAME = "xts";
protected static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, SUBSYSTEM_NAME);
static final ModelVersion CURRENT_MODEL_VERSION = ModelVersion.create(3, 0, 0);
private static final String RESOURCE_NAME = XTSExtension.class.getPackage().getName() + ".LocalDescriptions";
static StandardResourceDescriptionResolver getResourceDescriptionResolver(final String keyPrefix) {
String prefix = SUBSYSTEM_NAME + (keyPrefix == null ? "" : "." + keyPrefix);
return new StandardResourceDescriptionResolver(prefix, RESOURCE_NAME, XTSExtension.class.getClassLoader(), true, false);
}
public void initialize(ExtensionContext context) {
XtsAsLogger.ROOT_LOGGER.debug("Initializing XTS Extension");
final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION, true);
subsystem.registerSubsystemModel(new XTSSubsystemDefinition());
subsystem.registerXMLElementWriter(new XTSSubsystemParser());
}
public void initializeParsers(ExtensionParsingContext context) {
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.XTS_1_0.getUriString(), XTSSubsystemParser::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.XTS_2_0.getUriString(), XTSSubsystemParser::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.XTS_3_0.getUriString(), XTSSubsystemParser::new);
}
}
| 3,312 | 46.328571 | 133 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/CommonAttributes.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.xts;
/**
* @author <a href="mailto:[email protected]">Andrew Dinn</a>
*/
interface CommonAttributes {
String HOST = "host";
String XTS_ENVIRONMENT= "xts-environment";
String DEFAULT_CONTEXT_PROPAGATION = "default-context-propagation";
String ASYNC_REGISTRATION = "async-registration";
// TODO, many more!
}
| 1,374 | 38.285714 | 71 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/XTSHandlersService.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.xts;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController.Mode;
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.wsf.spi.metadata.j2ee.serviceref.UnifiedHandlerChainMetaData;
/**
* A service providing metadata for the ws handlers contributed by XTS subsystem
*
* @author <a href="mailto:[email protected]">Alessio Soldano</a>
*/
public class XTSHandlersService implements Service<UnifiedHandlerChainMetaData> {
private final boolean isDefaultContextPropagation;
private volatile UnifiedHandlerChainMetaData handlerChainMetaData;
private XTSHandlersService(boolean isDefaultContextPropagation) {
this.isDefaultContextPropagation = isDefaultContextPropagation;
}
@Override
public UnifiedHandlerChainMetaData getValue() throws IllegalStateException {
return handlerChainMetaData;
}
@Override
public void start(final StartContext context) throws StartException {
final XTSHandlersManager xtsHandlerManager = new XTSHandlersManager(isDefaultContextPropagation);
handlerChainMetaData = xtsHandlerManager.getHandlerChain();
}
public void stop(final StopContext context) {
handlerChainMetaData = null;
}
public static void install(final ServiceTarget target, final boolean isDefaultContextPropagation) {
final XTSHandlersService xtsHandlersService = new XTSHandlersService(isDefaultContextPropagation);
ServiceBuilder<?> builder = target.addService(XTSServices.JBOSS_XTS_HANDLERS, xtsHandlersService);
builder.setInitialMode(Mode.ACTIVE);
builder.install();
}
}
| 2,865 | 40.536232 | 106 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/Attribute.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.xts;
import java.util.HashMap;
import java.util.Map;
/**
* Enumeration of attributes used in the transactions subsystem.
*
* @author <a href="mailto:[email protected]">Andrew Dinn</a>
*/
enum Attribute {
UNKNOWN(null),
URL("url"),
ENABLED("enabled"),
NAME("name"),
;
private final String name;
Attribute(final String name) {
this.name = name;
}
/**
* Get the local name of this attribute.
*
* @return the local name
*/
public String getLocalName() {
return name;
}
private static final Map<String, Attribute> MAP;
static {
final Map<String, Attribute> map = new HashMap<String, Attribute>();
for (Attribute element : values()) {
final String name = element.getLocalName();
if (name != null) map.put(name, element);
}
MAP = map;
}
public static Attribute forName(String localName) {
final Attribute element = MAP.get(localName);
return element == null ? UNKNOWN : element;
}
public String toString() {
return getLocalName();
}
}
| 2,172 | 28.364865 | 76 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/XTSHandlerDeploymentProcessor.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.xts;
import com.arjuna.mw.wst11.service.JaxWSHeaderContextProcessor;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.xts.jandex.CompensatableAnnotation;
import org.jboss.as.xts.jandex.EndpointMetaData;
import org.jboss.as.xts.jandex.TransactionalAnnotation;
import org.jboss.as.xts.txnclient.WildflyTransactionClientTxBridgeIntegrationHandler;
import org.jboss.as.webservices.injection.WSEndpointHandlersMapping;
import org.jboss.as.webservices.util.ASHelper;
import org.jboss.as.webservices.util.WSAttachmentKeys;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.MethodInfo;
import org.jboss.jbossts.txbridge.inbound.OptionalJaxWSTxInboundBridgeHandler;
import org.jboss.wsf.spi.metadata.j2ee.serviceref.UnifiedHandlerChainMetaData;
import org.jboss.wsf.spi.metadata.j2ee.serviceref.UnifiedHandlerChainsMetaData;
import org.jboss.wsf.spi.metadata.j2ee.serviceref.UnifiedHandlerMetaData;
import org.jboss.wsf.spi.metadata.webservices.PortComponentMetaData;
import org.jboss.wsf.spi.metadata.webservices.WebserviceDescriptionMetaData;
import org.jboss.wsf.spi.metadata.webservices.WebservicesMetaData;
import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author <a href="mailto:[email protected]">Gytis Trikleris</a>
* @author <a href="mailto:[email protected]">Paul Robinson</a>
*/
public class XTSHandlerDeploymentProcessor implements DeploymentUnitProcessor {
private static final String TX_BRIDGE_WFTC_INTEGRATION_HANDLER = WildflyTransactionClientTxBridgeIntegrationHandler.class.getName();
private static final String TX_BRIDGE_HANDLER = OptionalJaxWSTxInboundBridgeHandler.class.getName();
private static final String TX_CONTEXT_HANDLER = JaxWSHeaderContextProcessor.class.getName();
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit unit = phaseContext.getDeploymentUnit();
final List<WebserviceDescriptionMetaData> webserviceDescriptions = new ArrayList<WebserviceDescriptionMetaData>();
boolean modifiedWSMeta = false;
for (String endpoint : getDeploymentClasses(unit)) {
try {
final EndpointMetaData endpointMetaData = EndpointMetaData.build(unit, endpoint);
if (endpointMetaData.isXTSEnabled()) {
XTSDeploymentMarker.mark(unit);
final boolean result = updateXTSEndpoint(endpoint, endpointMetaData, webserviceDescriptions, unit);
modifiedWSMeta = modifiedWSMeta || result;
}
} catch (XTSException e) {
throw new DeploymentUnitProcessingException("Error processing endpoint '" + endpoint + "'", e);
}
}
if (modifiedWSMeta) {
unit.putAttachment(WSAttachmentKeys.WEBSERVICES_METADATA_KEY, new WebservicesMetaData(null, webserviceDescriptions));
}
}
private boolean updateXTSEndpoint(final String endpoint, final EndpointMetaData endpointMetaData,
final List<WebserviceDescriptionMetaData> webserviceDescriptions, final DeploymentUnit unit) {
if (endpointMetaData.isWebservice()) {
final List<String> handlers = new ArrayList<String>();
if (endpointMetaData.isBridgeEnabled()) {
handlers.add(TX_BRIDGE_WFTC_INTEGRATION_HANDLER);
handlers.add(TX_BRIDGE_HANDLER);
}
handlers.add(TX_CONTEXT_HANDLER);
if (!isAnyOfHandlersRegistered(unit, endpoint, handlers)) {
final UnifiedHandlerChainsMetaData unifiedHandlerChainsMetaData = buildHandlerChains(handlers);
final QName portQname = endpointMetaData.getWebServiceAnnotation().buildPortQName();
webserviceDescriptions.add(new WebserviceDescriptionMetaData(null, null, null,
buildPortComponent(endpointMetaData.isEJB(), endpoint, portQname, unifiedHandlerChainsMetaData)));
registerHandlersWithAS(unit, endpoint, handlers);
return true;
}
}
return false;
}
private PortComponentMetaData buildPortComponent(boolean isEJB, String endpointClass, QName portQname, UnifiedHandlerChainsMetaData unifiedHandlerChainsMetaData) {
return new PortComponentMetaData(null, portQname, endpointClass, isEJB ? getClassName(endpointClass) : null, isEJB ? null : endpointClass, null, null, null, null, unifiedHandlerChainsMetaData);
}
private UnifiedHandlerChainsMetaData buildHandlerChains(List<String> handlerClasses) {
List<UnifiedHandlerMetaData> handlers = new ArrayList<UnifiedHandlerMetaData>();
for (String handlerClass : handlerClasses) {
handlers.add(new UnifiedHandlerMetaData(handlerClass, null, null, null, null, null));
}
return new UnifiedHandlerChainsMetaData(new UnifiedHandlerChainMetaData(null, null, null, handlers, false, null));
}
private void registerHandlersWithAS(DeploymentUnit unit, String endpointClass, List<String> handlersToAdd) {
WSEndpointHandlersMapping mapping = unit.getAttachment(WSAttachmentKeys.WS_ENDPOINT_HANDLERS_MAPPING_KEY);
if (mapping == null) {
mapping = new WSEndpointHandlersMapping();
unit.putAttachment(WSAttachmentKeys.WS_ENDPOINT_HANDLERS_MAPPING_KEY, mapping);
}
Set<String> existingHandlers = mapping.getHandlers(endpointClass);
if (existingHandlers == null) {
existingHandlers = new HashSet<String>();
} else {
//Existing collection is an unmodifiableSet
existingHandlers = new HashSet<String>(existingHandlers);
}
for (String handler : handlersToAdd) {
existingHandlers.add(handler);
}
mapping.registerEndpointHandlers(endpointClass, existingHandlers);
}
private String getClassName(String fQClass) {
String[] split = fQClass.split("\\.");
return split[split.length - 1];
}
private Set<String> getDeploymentClasses(DeploymentUnit unit) {
final Set<String> endpoints = new HashSet<String>();
for (final String annotation : CompensatableAnnotation.COMPENSATABLE_ANNOTATIONS) {
addEndpointsToList(endpoints, ASHelper.getAnnotations(unit, DotName.createSimple(annotation)));
}
for (final String annotation : TransactionalAnnotation.TRANSACTIONAL_ANNOTATIONS) {
addEndpointsToList(endpoints, ASHelper.getAnnotations(unit, DotName.createSimple(annotation)));
}
return endpoints;
}
private void addEndpointsToList(Set<String> endpoints, List<AnnotationInstance> annotations) {
for (AnnotationInstance annotationInstance : annotations) {
Object target = annotationInstance.target();
if (target instanceof ClassInfo) {
final ClassInfo classInfo = (ClassInfo) annotationInstance.target();
final String endpointClass = classInfo.name().toString();
endpoints.add(endpointClass);
} else if (target instanceof MethodInfo) {
final MethodInfo methodInfo = (MethodInfo) target;
final String endpointClass = methodInfo.declaringClass().name().toString();
endpoints.add(endpointClass);
}
}
}
private boolean isAnyOfHandlersRegistered(final DeploymentUnit unit, final String endpointClass,
final List<String> handlers) {
final WSEndpointHandlersMapping mapping = unit.getAttachment(WSAttachmentKeys.WS_ENDPOINT_HANDLERS_MAPPING_KEY);
if (mapping == null) {
return false;
}
final Set<String> existingHandlers = mapping.getHandlers(endpointClass);
if (existingHandlers == null) {
return false;
}
for (final String handler : handlers) {
if (existingHandlers.contains(handler)) {
return true;
}
}
return false;
}
}
| 9,501 | 43.820755 | 201 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/XTSServices.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.xts;
import org.jboss.as.xts.logging.XtsAsLogger;
import org.jboss.msc.service.ServiceName;
/**
* @author <a href="mailto:[email protected]">Andrew Dinn</a>
*/
public final class XTSServices {
public static final ServiceName JBOSS_XTS = ServiceName.JBOSS.append("xts");
public static final ServiceName JBOSS_XTS_MAIN = JBOSS_XTS.append("main");
public static final ServiceName JBOSS_XTS_HANDLERS = JBOSS_XTS.append("handlers");
public static final ServiceName JBOSS_XTS_ENDPOINT = JBOSS_XTS.append("endpoint");
public static final ServiceName JBOSS_XTS_TXBRIDGE_INBOUND_RECOVERY = JBOSS_XTS.append("txbridgeInboundRecovery");
public static final ServiceName JBOSS_XTS_TXBRIDGE_OUTBOUND_RECOVERY = JBOSS_XTS.append("txbridgeOutboundRecovery");
public static ServiceName endpointServiceName(String name) {
return JBOSS_XTS_ENDPOINT.append(name);
}
public static <T> T notNull(T value) {
if (value == null) throw XtsAsLogger.ROOT_LOGGER.xtsServiceIsNotStarted();
return value;
}
private XTSServices() {
}
}
| 2,133 | 36.438596 | 120 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/XTSException.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.xts;
/**
* @author [email protected], 2012-02-06
*/
public class XTSException extends Exception {
public XTSException(String message) {
super(message);
}
public XTSException(String message, Throwable cause) {
super(message, cause);
}
}
| 1,325 | 33.894737 | 70 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/Namespace.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.xts;
import java.util.HashMap;
import java.util.Map;
/**
* The namespaces supported by the xts extension.
*
* @author <a href="mailto:[email protected]">Andrew Dinn</a>
*/
enum Namespace {
// must be first
UNKNOWN(null),
XTS_1_0("urn:jboss:domain:xts:1.0"),
XTS_2_0("urn:jboss:domain:xts:2.0"),
XTS_3_0("urn:jboss:domain:xts:3.0"),
;
/**
* The current namespace version.
*/
public static final Namespace CURRENT = XTS_3_0;
private final String name;
Namespace(final String name) {
this.name = name;
}
/**
* Get the URI of this namespace.
*
* @return the URI
*/
public String getUriString() {
return name;
}
private static final Map<String, Namespace> MAP;
static {
final Map<String, Namespace> map = new HashMap<String, Namespace>();
for (Namespace namespace : values()) {
final String name = namespace.getUriString();
if (name != null) map.put(name, namespace);
}
MAP = map;
}
public static Namespace forUri(String uri) {
final Namespace element = MAP.get(uri);
return element == null ? UNKNOWN : element;
}
}
| 2,263 | 28.025641 | 76 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/GracefulShutdownDeploymentProcessor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, 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.xts;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.webservices.util.WSAttachmentKeys;
/**
* @author <a href="mailto:[email protected]">Gytis Trikleris</a>
*/
public class GracefulShutdownDeploymentProcessor implements DeploymentUnitProcessor {
@Override
public void deploy(DeploymentPhaseContext deploymentPhaseContext) throws DeploymentUnitProcessingException {
deploymentPhaseContext.getDeploymentUnit().putAttachment(WSAttachmentKeys.REJECTION_RULE_KEY,
new GracefulShutdownRejectionRule());
}
}
| 1,756 | 41.853659 | 112 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/XTSDependenciesDeploymentProcessor.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.xts;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.annotation.CompositeIndex;
import org.jboss.as.server.deployment.module.ModuleDependency;
import org.jboss.as.server.deployment.module.ModuleSpecification;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoader;
import org.jboss.narayana.compensations.api.CancelOnFailure;
import org.jboss.narayana.compensations.api.Compensatable;
import org.jboss.narayana.compensations.api.CompensationScoped;
import org.jboss.narayana.compensations.api.TxCompensate;
import org.jboss.narayana.compensations.api.TxConfirm;
import org.jboss.narayana.compensations.api.TxLogged;
import jakarta.ejb.TransactionAttribute;
import jakarta.jws.WebService;
import jakarta.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
/**
* @author <a href="mailto:[email protected]">Gytis Trikleris</a>
*/
public class XTSDependenciesDeploymentProcessor implements DeploymentUnitProcessor {
private static final ModuleIdentifier XTS_MODULE = ModuleIdentifier.create("org.jboss.xts");
private static final Class[] COMPENSATABLE_ANNOTATIONS = {
Compensatable.class,
CancelOnFailure.class,
CompensationScoped.class,
TxCompensate.class,
TxConfirm.class,
TxLogged.class
};
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit unit = phaseContext.getDeploymentUnit();
final CompositeIndex compositeIndex = unit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
if (compositeIndex == null) {
return;
}
if (isCompensationAnnotationPresent(compositeIndex) || isTransactionalEndpointPresent(compositeIndex)) {
addXTSModuleDependency(unit);
}
}
private boolean isCompensationAnnotationPresent(final CompositeIndex compositeIndex) {
for (Class annotation : COMPENSATABLE_ANNOTATIONS) {
if (!compositeIndex.getAnnotations(DotName.createSimple(annotation.getName())).isEmpty()) {
return true;
}
}
return false;
}
private boolean isTransactionalEndpointPresent(final CompositeIndex compositeIndex) {
final List<AnnotationInstance> annotations = new ArrayList<>();
annotations.addAll(compositeIndex.getAnnotations(DotName.createSimple(Transactional.class.getName())));
annotations.addAll(compositeIndex.getAnnotations(DotName.createSimple(TransactionAttribute.class.getName())));
for (final AnnotationInstance annotation : annotations) {
final Object target = annotation.target();
if (target instanceof ClassInfo) {
final ClassInfo classInfo = (ClassInfo) target;
if (classInfo.annotationsMap().get(DotName.createSimple(WebService.class.getName())) != null) {
return true;
}
}
}
return false;
}
private void addXTSModuleDependency(final DeploymentUnit unit) {
final ModuleLoader moduleLoader = Module.getBootModuleLoader();
final ModuleSpecification moduleSpec = unit.getAttachment(Attachments.MODULE_SPECIFICATION);
moduleSpec.addSystemDependency(new ModuleDependency(moduleLoader, XTS_MODULE, false, false, false, false));
}
}
| 4,893 | 40.474576 | 118 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/XTSManagerService.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.xts;
import org.jboss.as.xts.logging.XtsAsLogger;
import org.jboss.jbossts.XTSService;
import org.jboss.jbossts.xts.environment.WSCEnvironmentBean;
import org.jboss.jbossts.xts.environment.XTSPropertyManager;
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.wsf.spi.management.ServerConfig;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Main XTS service
*
* @author <a href="mailto:[email protected]">Andrew Dinn</a>
*/
public class XTSManagerService implements Service<XTSService> {
private final String coordinatorURL;
private volatile org.jboss.jbossts.XTSService xtsService;
private InjectedValue<ServerConfig> wsServerConfig = new InjectedValue<ServerConfig>();
public XTSManagerService(String coordinatorURL) {
this.coordinatorURL = coordinatorURL;
this.xtsService = null;
}
@Override
public XTSService getValue() throws IllegalStateException {
return xtsService;
}
@Override
public synchronized void start(final StartContext context) throws StartException {
// XTS expects the TCCL to be set to something that will locate the XTS service implementation classes.
final ClassLoader loader = XTSService.class.getClassLoader();
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(loader);
try {
ServerConfig serverConfigValue = wsServerConfig.getValue();
WSCEnvironmentBean wscEnVBean = XTSPropertyManager.getWSCEnvironmentBean();
if (coordinatorURL !=null ) {
wscEnVBean.setCoordinatorURL11(coordinatorURL);
}
else {
//Defaults to insecure (http) on this server's bind address.
String defaultCoordinatorUrl = "http://" + serverConfigValue.getWebServiceHost() + ":" +
serverConfigValue.getWebServicePort() + "/" + wscEnVBean.getCoordinatorPath11();
wscEnVBean.setCoordinatorURL11(defaultCoordinatorUrl);
}
wscEnVBean.setBindAddress11(serverConfigValue.getWebServiceHost());
wscEnVBean.setBindPort11(serverConfigValue.getWebServicePort());
wscEnVBean.setBindPortSecure11(serverConfigValue.getWebServiceSecurePort());
XTSService service = new XTSService();
try {
service.start();
} catch (Exception e) {
throw XtsAsLogger.ROOT_LOGGER.xtsServiceFailedToStart();
}
xtsService = service;
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged((ClassLoader) null);
}
}
public synchronized void stop(final StopContext context) {
if (xtsService != null) {
try {
xtsService.stop();
} catch (Exception e) {
// ignore?
}
}
}
public InjectedValue<ServerConfig> getWSServerConfig() {
return wsServerConfig;
}
}
| 4,213 | 38.018519 | 111 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/XTSDeploymentMarker.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.xts;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.server.deployment.DeploymentUnit;
/**
* @author [email protected], 2012-02-13
*/
public class XTSDeploymentMarker {
private static final AttachmentKey<XTSDeploymentMarker> MARKER = AttachmentKey.create(XTSDeploymentMarker.class);
private XTSDeploymentMarker() {
}
public static void mark(DeploymentUnit unit) {
unit.putAttachment(MARKER, new XTSDeploymentMarker());
}
public static boolean isXTSAnnotationDeployment(DeploymentUnit unit) {
return unit.hasAttachment(MARKER);
}
}
| 1,661 | 34.361702 | 117 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/GracefulShutdownRejectionRule.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, 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.xts;
import com.arjuna.webservices.wsarj.ArjunaConstants;
import com.arjuna.webservices11.wscoor.CoordinationConstants;
import org.jboss.as.xts.logging.XtsAsLogger;
import org.jboss.wsf.spi.invocation.RejectionRule;
import javax.xml.namespace.QName;
import java.util.Map;
/**
* @author <a href="mailto:[email protected]">Gytis Trikleris</a>
*/
public class GracefulShutdownRejectionRule implements RejectionRule {
@Override
public boolean rejectMessage(Map<QName, Object> headers) {
if (headers.containsKey(ArjunaConstants.WSARJ_ELEMENT_INSTANCE_IDENTIFIER_QNAME)
|| headers.containsKey(CoordinationConstants.WSCOOR_ELEMENT_COORDINATION_CONTEXT_QNAME)) {
return false;
}
XtsAsLogger.ROOT_LOGGER.rejectingCallBecauseNotPartOfXtsTx();
return true;
}
}
| 1,872 | 38.020833 | 106 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/logging/XtsAsLogger.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.xts.logging;
import static org.jboss.logging.Logger.Level.WARN;
import static org.jboss.logging.Logger.Level.ERROR;
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.msc.service.StartException;
/**
* Date: 05.11.2011
*
* @author <a href="mailto:[email protected]">James R. Perkins</a>
*/
@MessageLogger(projectCode = "WFLYXTS", length = 4)
public interface XtsAsLogger extends BasicLogger {
/**
* A logger with the category of the package name.
*/
XtsAsLogger ROOT_LOGGER = Logger.getMessageLogger(XtsAsLogger.class, "org.jboss.as.xts");
/**
* Creates an exception indicating that the TxBridge inbound recovery service failed to start.
*
* @return a {@link org.jboss.msc.service.StartException} for the error.
*/
@Message(id = 1, value = "TxBridge inbound recovery service start failed")
StartException txBridgeInboundRecoveryServiceFailedToStart();
/**
* Creates an exception indicating that the TxBridge outbound recovery service failed to start.
*
* @return a {@link StartException} for the error.
*/
@Message(id = 2, value = "TxBridge outbound recovery service start failed")
StartException txBridgeOutboundRecoveryServiceFailedToStart();
/**
* Creates an exception indicating that the XTS service failed to start.
*
* @return a {@link StartException} for the error.
*/
@Message(id = 3, value = "XTS service start failed")
StartException xtsServiceFailedToStart();
/**
* Creates an exception indicating that this operation can not be performed when the XTS service is not started.
*
* @return a {@link IllegalStateException} for the error.
*/
@Message(id = 4, value = "Service not started")
IllegalStateException xtsServiceIsNotStarted();
// /**
// * Creates an exception indicating that configuration service is not available.
// *
// * @return a {@link IllegalStateException} for the error.
// */
// @Message(id = 5, value = "Configuration service is not available")
// IllegalStateException configurationServiceUnavailable();
//
// /**
// * Creates an exception indicating that common configuration is not available.
// *
// * @return a {@link IllegalStateException} for the error.
// */
// @Message(id = 6, value = "Common configuration is not available")
// IllegalStateException commonConfigurationUnavailable();
// /**
// * Creates an exception indicating that the Jakarta Contexts and Dependency Injection extension could not be loaded.
// *
// * @return a {@link org.jboss.as.server.deployment.DeploymentUnitProcessingException} for the error.
// */
// @Message(id = 7, value = "Cannot load Jakarta Contexts and Dependency Injection Extension")
// DeploymentUnitProcessingException cannotLoadCDIExtension();
// /**
// * Warning that coordination context deserialization has failed
// */
// @LogMessage(level = WARN)
// @Message(id = 8, value = "Coordination context deserialization failed")
// void coordinationContextDeserializationFailed(@Cause Throwable cause);
@LogMessage(level = WARN)
@Message(id = 9, value = "Rejecting call because it is not part of any XTS transaction")
void rejectingCallBecauseNotPartOfXtsTx();
@LogMessage(level = ERROR)
@Message(id = 10, value = "Cannot get transaction status on handling context %s")
void cannotGetTransactionStatus(jakarta.xml.ws.handler.MessageContext ctx, @Cause Throwable cause);
}
| 4,810 | 38.760331 | 122 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/txnclient/WildflyTransactionClientTxBridgeIntegrationHandler.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.xts.txnclient;
import jakarta.transaction.Status;
import jakarta.transaction.SystemException;
import jakarta.xml.ws.handler.Handler;
import jakarta.xml.ws.handler.MessageContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.txn.deployment.TransactionRollbackSetupAction;
import org.jboss.as.xts.XTSHandlerDeploymentProcessor;
import org.jboss.as.xts.jandex.EndpointMetaData;
import org.jboss.as.xts.logging.XtsAsLogger;
import org.jboss.wsf.spi.deployment.Endpoint;
import org.jboss.wsf.spi.invocation.Invocation;
import org.wildfly.transaction.client.ContextTransactionManager;
import java.util.List;
/**
* <p>
* Handler integrating the handle message event with WildFly Transaction Client (WFTC) SPI.
* </p>
* <p>
* This handler manages the outbound processing where it has to be processed
* before the {@link org.jboss.jbossts.txbridge.inbound.OptionalJaxWSTxInboundBridgeHandler}.
* Check the handler enlistment at {@link XTSHandlerDeploymentProcessor#updateXTSEndpoint(String, EndpointMetaData, List, DeploymentUnit)}.
* <p>
* <p>
* <i>NOTE:</i> the order of the Jakarta XML Web Services handlers are defined as:
* <q>For outbound messages handler processing starts with the first handler in the chain
* and proceeds in the same order as the handler chain.
* For inbound messages the order of processing is reversed.
* </q>
* </p>
* <p>
* This handler works on outbound side. The inbound side is handled by WS integration class:
* {@link org.jboss.as.webservices.invocation.AbstractInvocationHandler#invokeInternal(Endpoint, Invocation)}.
* There is the place where WFTC imports the Narayana transaction for the incoming WS message.
* </p>
* <p>
* The outbound filter is useful for suspending the WFTC wrapper transaction. Otherwise only the underlaying Narayana transaction is suspended
* (Narayana XTS txbridge inbound filter does so).
* Then when the call leaves EJB there is invoked handler {@link TransactionRollbackSetupAction} verifying existence of the transactions.
* If the the WFTC transaction is not suspended then the setup action rolls-back it which leads to an errors in the server log.
* </p>
*/
public class WildflyTransactionClientTxBridgeIntegrationHandler implements Handler<MessageContext> {
@Override
public boolean handleMessage(MessageContext messageContext) {
final Boolean isOutbound = (Boolean) messageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
try {
if (isOutbound != null && isOutbound
// suspending context before returning to the client
&& ContextTransactionManager.getInstance() != null
&& ContextTransactionManager.getInstance().getStatus() != Status.STATUS_NO_TRANSACTION) {
ContextTransactionManager.getInstance().suspend();
}
} catch (SystemException se) {
XtsAsLogger.ROOT_LOGGER.cannotGetTransactionStatus(messageContext, se);
}
// continue with message handling
return true;
}
@Override
public boolean handleFault(MessageContext context) {
// do nothing just continue with processing
return true;
}
@Override
public void close(MessageContext context) {
// no action needed
}
}
| 4,401 | 42.584158 | 144 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/jandex/WebServiceAnnotation.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.xts.jandex;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.xts.XTSException;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationValue;
import jakarta.jws.WebService;
import javax.xml.namespace.QName;
/**
* @author [email protected], 2012-02-06
*/
public class WebServiceAnnotation {
private static final String WEBSERVICE_ANNOTATION = WebService.class.getName();
private final String portName;
private final String serviceName;
private final String name;
private final String targetNamespace;
private WebServiceAnnotation(String portName, String serviceName, String name, String targetNamespace) {
this.portName = portName;
this.serviceName = serviceName;
this.name = name;
this.targetNamespace = targetNamespace;
}
public static WebServiceAnnotation build(DeploymentUnit unit, String endpoint) throws XTSException {
AnnotationInstance annotationInstance = JandexHelper.getAnnotation(unit, endpoint, WEBSERVICE_ANNOTATION);
if (annotationInstance == null) {
return null;
}
final String portName = getStringValue(annotationInstance, "portName");
final String serviceName = getStringValue(annotationInstance, "serviceName");
final String name = getStringValue(annotationInstance, "name");
final String targetNamespace = getStringValue(annotationInstance, "targetNamespace");
return new WebServiceAnnotation(portName, serviceName, name, targetNamespace);
}
private static String getStringValue(AnnotationInstance annotationInstance, String key) {
final AnnotationValue value = annotationInstance.value(key);
if (value != null) {
return value.asString();
} else if ("portName".equals(key)) {
return getTargetClassName(annotationInstance) + "Port";
} else if ("serviceName".equals(key)) {
return getTargetClassName(annotationInstance) + "Service";
} else if ("name".equals(key)) {
return getTargetClassName(annotationInstance);
} else if ("targetNamespace".equals(key)) {
return getTargetNamespace(annotationInstance);
} else {
return "";
}
}
private static String getTargetClassName(final AnnotationInstance annotationInstance) {
final String fullName = annotationInstance.target().toString();
final int lastDotIndex = fullName.lastIndexOf(".");
if (lastDotIndex == -1) {
return fullName;
} else {
return fullName.substring(lastDotIndex + 1);
}
}
private static String getTargetNamespace(final AnnotationInstance annotationInstance) {
final String[] parts = annotationInstance.target().toString().split("\\.");
if (parts.length < 2) {
return "";
}
String targetNamespace = "http://";
for (int i = parts.length - 2; i >= 0; i--) {
targetNamespace += parts[i] + ".";
}
return targetNamespace.substring(0, targetNamespace.length() - 1) + "/";
}
public QName buildPortQName() {
return new QName(targetNamespace, portName);
}
public String getPortName() {
return portName;
}
public String getServiceName() {
return serviceName;
}
public String getName() {
return name;
}
public String getTargetNamespace() {
return targetNamespace;
}
}
| 4,591 | 32.764706 | 114 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/jandex/TransactionalAnnotation.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.xts.jandex;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.xts.XTSException;
import jakarta.ejb.TransactionAttribute;
import jakarta.transaction.Transactional;
/**
* @author <a href="mailto:[email protected]">Gytis Trikleris</a>
* @author <a href="mailto:[email protected]">Paul Robinson</a>
*/
public class TransactionalAnnotation {
public static final String[] TRANSACTIONAL_ANNOTATIONS = {
TransactionAttribute.class.getName(),
Transactional.class.getName()
};
private TransactionalAnnotation() {
}
public static TransactionalAnnotation build(DeploymentUnit unit, String endpoint) throws XTSException {
for (final String annotation : TRANSACTIONAL_ANNOTATIONS) {
if (JandexHelper.getAnnotation(unit, endpoint, annotation) != null) {
return new TransactionalAnnotation();
}
}
return null;
}
}
| 1,994 | 35.944444 | 107 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/jandex/BridgeType.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.xts.jandex;
import org.jboss.as.xts.XTSException;
import org.jboss.jandex.AnnotationInstance;
/**
* @author [email protected], 2012-02-06
*/
public enum BridgeType {
DEFAULT, NONE, JTA;
public static BridgeType build(AnnotationInstance annotationInstance) throws XTSException {
if (annotationInstance.value("bridgeType") == null) {
return DEFAULT;
}
String bridgeType = annotationInstance.value("bridgeType").asString();
if (bridgeType.equals("DEFAULT")) {
return DEFAULT;
} else if (bridgeType.equals("NONE")) {
return NONE;
} else if (bridgeType.equals("JTA")) {
return JTA;
} else {
throw new XTSException("Unexpected bridge type: '" + bridgeType + "'");
}
}
}
| 1,859 | 34.769231 | 95 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/jandex/CompensatableAnnotation.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.xts.jandex;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.xts.XTSException;
import org.jboss.narayana.compensations.api.CancelOnFailure;
import org.jboss.narayana.compensations.api.Compensatable;
import org.jboss.narayana.compensations.api.CompensationScoped;
import org.jboss.narayana.compensations.api.TxCompensate;
import org.jboss.narayana.compensations.api.TxConfirm;
import org.jboss.narayana.compensations.api.TxLogged;
/**
* @author <a href="mailto:[email protected]">Gytis Trikleris</a>
* @author <a href="mailto:[email protected]">Paul Robinson</a>
*/
public class CompensatableAnnotation {
public static final String[] COMPENSATABLE_ANNOTATIONS = {
Compensatable.class.getName(),
CancelOnFailure.class.getName(),
CompensationScoped.class.getName(),
TxCompensate.class.getName(),
TxConfirm.class.getName(),
TxLogged.class.getName()
};
private CompensatableAnnotation() {
}
public static CompensatableAnnotation build(final DeploymentUnit unit, final String endpoint) throws XTSException {
for (final String annotation : COMPENSATABLE_ANNOTATIONS) {
if (JandexHelper.getAnnotation(unit, endpoint, annotation) != null) {
return new CompensatableAnnotation();
}
}
return null;
}
}
| 2,435 | 38.934426 | 119 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/jandex/EndpointMetaData.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.xts.jandex;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.xts.XTSException;
/**
* @author <a href="mailto:[email protected]">Gytis Trikleris</a>
* @author <a href="mailto:[email protected]">Paul Robinson</a>
*/
public class EndpointMetaData {
private final TransactionalAnnotation transactionalAnnotation;
private final CompensatableAnnotation compensatableAnnotation;
private final StatelessAnnotation statelessAnnotation;
private final WebServiceAnnotation webServiceAnnotation;
private EndpointMetaData(final StatelessAnnotation statelessAnnotation,
final TransactionalAnnotation transactionalAnnotation, final CompensatableAnnotation compensatableAnnotation,
final WebServiceAnnotation webServiceAnnotation) {
this.statelessAnnotation = statelessAnnotation;
this.transactionalAnnotation = transactionalAnnotation;
this.compensatableAnnotation = compensatableAnnotation;
this.webServiceAnnotation = webServiceAnnotation;
}
public static EndpointMetaData build(final DeploymentUnit unit, final String endpoint) throws XTSException {
final TransactionalAnnotation transactionalAnnotation = TransactionalAnnotation.build(unit, endpoint);
final CompensatableAnnotation compensatableAnnotation = CompensatableAnnotation.build(unit, endpoint);
final StatelessAnnotation statelessAnnotation = StatelessAnnotation.build(unit, endpoint);
final WebServiceAnnotation webServiceAnnotation = WebServiceAnnotation.build(unit, endpoint);
return new EndpointMetaData(statelessAnnotation, transactionalAnnotation, compensatableAnnotation, webServiceAnnotation);
}
public WebServiceAnnotation getWebServiceAnnotation() {
return webServiceAnnotation;
}
public boolean isWebservice() {
return webServiceAnnotation != null;
}
public boolean isEJB() {
return statelessAnnotation != null;
}
public boolean isBridgeEnabled() {
return transactionalAnnotation != null;
}
public boolean isXTSEnabled() {
return transactionalAnnotation != null || compensatableAnnotation != null;
}
}
| 3,261 | 40.820513 | 129 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/jandex/StatelessAnnotation.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.xts.jandex;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.xts.XTSException;
import org.jboss.jandex.AnnotationInstance;
import jakarta.ejb.Stateless;
/**
* @author [email protected], 2012-02-06
*/
public class StatelessAnnotation {
private static final String STATELESS_ANNOTATION = Stateless.class.getName();
public static StatelessAnnotation build(DeploymentUnit unit, String endpoint) throws XTSException {
final AnnotationInstance annotationInstance = JandexHelper.getAnnotation(unit, endpoint, STATELESS_ANNOTATION);
if (annotationInstance == null) {
return null;
}
return new StatelessAnnotation();
}
}
| 1,755 | 34.836735 | 119 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/xts/jandex/JandexHelper.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.xts.jandex;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.webservices.util.ASHelper;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.MethodInfo;
import java.util.List;
/**
* @author [email protected], 2012-02-06
*/
public class JandexHelper {
public static AnnotationInstance getAnnotation(DeploymentUnit unit, String endpoint, String annotationClassName) {
final List<AnnotationInstance> annotations = ASHelper.getAnnotations(unit, DotName.createSimple(annotationClassName));
for (AnnotationInstance annotationInstance : annotations) {
Object target = annotationInstance.target();
if (target instanceof ClassInfo) {
final ClassInfo classInfo = (ClassInfo) target;
final String endpointClass = classInfo.name().toString();
if (endpointClass.equals(endpoint)) {
return annotationInstance;
}
} else if (target instanceof MethodInfo) {
final MethodInfo methodInfo = (MethodInfo) target;
final String endpointClass = methodInfo.declaringClass().name().toString();
if (endpointClass.equals(endpoint)) {
return annotationInstance;
}
}
}
return null;
}
}
| 2,485 | 36.104478 | 126 |
java
|
null |
wildfly-main/xts/src/main/java/org/jboss/as/compensations/CompensationsDependenciesDeploymentProcessor.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.compensations;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.annotation.CompositeIndex;
import org.jboss.as.server.deployment.module.ModuleDependency;
import org.jboss.as.server.deployment.module.ModuleSpecification;
import org.jboss.jandex.DotName;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoader;
import org.jboss.narayana.compensations.api.CancelOnFailure;
import org.jboss.narayana.compensations.api.Compensatable;
import org.jboss.narayana.compensations.api.CompensationScoped;
import org.jboss.narayana.compensations.api.TxCompensate;
import org.jboss.narayana.compensations.api.TxConfirm;
import org.jboss.narayana.compensations.api.TxLogged;
/**
* @author <a href="mailto:[email protected]">Gytis Trikleris</a>
*/
public class CompensationsDependenciesDeploymentProcessor implements DeploymentUnitProcessor {
private static final ModuleIdentifier COMPENSATIONS_MODULE = ModuleIdentifier.create("org.jboss.narayana.compensations");
private static final Class<?>[] COMPENSATABLE_ANNOTATIONS = {
Compensatable.class,
CancelOnFailure.class,
CompensationScoped.class,
TxCompensate.class,
TxConfirm.class,
TxLogged.class
};
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit unit = phaseContext.getDeploymentUnit();
final CompositeIndex compositeIndex = unit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
if (compositeIndex == null) {
return;
}
if (isCompensationAnnotationPresent(compositeIndex)) {
addCompensationsModuleDependency(unit);
}
}
private boolean isCompensationAnnotationPresent(final CompositeIndex compositeIndex) {
for (Class<?> annotation : COMPENSATABLE_ANNOTATIONS) {
if (!compositeIndex.getAnnotations(DotName.createSimple(annotation.getName())).isEmpty()) {
return true;
}
}
return false;
}
private void addCompensationsModuleDependency(final DeploymentUnit unit) {
final ModuleLoader moduleLoader = Module.getBootModuleLoader();
final ModuleSpecification moduleSpec = unit.getAttachment(Attachments.MODULE_SPECIFICATION);
moduleSpec.addSystemDependency(new ModuleDependency(moduleLoader, COMPENSATIONS_MODULE, false, false, true, false));
}
}
| 3,838 | 41.186813 | 125 |
java
|
null |
wildfly-main/spec-api/test/src/test/java/org/jboss/as/spec/api/test/SpecApiDependencyCheck.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2020, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.spec.api.test;
import jakarta.annotation.*;
import jakarta.annotation.security.*;
import jakarta.annotation.sql.*;
import jakarta.batch.api.*;
import jakarta.batch.api.chunk.*;
import jakarta.batch.api.chunk.listener.*;
import jakarta.batch.api.listener.*;
import jakarta.batch.api.partition.*;
import jakarta.batch.operations.*;
import jakarta.batch.runtime.*;
import jakarta.batch.runtime.context.*;
import jakarta.decorator.*;
import jakarta.ejb.*;
import jakarta.ejb.embeddable.*;
import jakarta.ejb.spi.*;
import jakarta.el.*;
import jakarta.enterprise.concurrent.*;
import jakarta.enterprise.context.*;
import jakarta.enterprise.context.spi.*;
import jakarta.enterprise.event.*;
import jakarta.enterprise.inject.*;
import jakarta.enterprise.inject.spi.*;
import jakarta.enterprise.lang.model.*;
import jakarta.enterprise.util.*;
import jakarta.faces.*;
import jakarta.faces.application.*;
import jakarta.faces.component.*;
import jakarta.faces.component.behavior.*;
import jakarta.faces.component.html.*;
import jakarta.faces.component.visit.*;
import jakarta.faces.context.*;
import jakarta.faces.convert.*;
import jakarta.faces.el.*;
import jakarta.faces.event.*;
import jakarta.faces.flow.*;
import jakarta.faces.lifecycle.*;
import jakarta.faces.model.*;
import jakarta.faces.render.*;
import jakarta.faces.validator.*;
import jakarta.faces.view.*;
import jakarta.faces.view.facelets.*;
import jakarta.faces.webapp.*;
import jakarta.inject.*;
import jakarta.interceptor.*;
import jakarta.jms.*;
import jakarta.json.*;
import jakarta.json.spi.*;
import jakarta.json.stream.*;
import jakarta.jws.*;
import jakarta.jws.soap.*;
import jakarta.mail.*;
import jakarta.mail.event.*;
import jakarta.mail.internet.*;
import jakarta.mail.search.*;
import jakarta.mail.util.*;
import jakarta.persistence.*;
import jakarta.persistence.criteria.*;
import jakarta.persistence.metamodel.*;
import jakarta.persistence.spi.*;
import jakarta.resource.*;
import jakarta.resource.cci.*;
import jakarta.resource.spi.*;
import jakarta.resource.spi.endpoint.*;
import jakarta.resource.spi.security.*;
import jakarta.resource.spi.work.*;
import jakarta.security.auth.message.*;
import jakarta.security.auth.message.callback.*;
import jakarta.security.auth.message.config.*;
import jakarta.security.auth.message.module.*;
import jakarta.security.jacc.*;
import jakarta.servlet.*;
import jakarta.servlet.annotation.*;
import jakarta.servlet.descriptor.*;
import jakarta.servlet.http.*;
import jakarta.servlet.jsp.*;
import jakarta.servlet.jsp.el.*;
import jakarta.servlet.jsp.jstl.core.*;
import jakarta.servlet.jsp.jstl.fmt.*;
import jakarta.servlet.jsp.jstl.sql.*;
import jakarta.servlet.jsp.jstl.tlv.*;
import jakarta.servlet.jsp.tagext.*;
import jakarta.transaction.*;
import jakarta.validation.*;
import jakarta.validation.bootstrap.*;
import jakarta.validation.constraints.*;
import jakarta.validation.constraintvalidation.*;
import jakarta.validation.executable.*;
import jakarta.validation.groups.*;
import jakarta.validation.metadata.*;
import jakarta.validation.spi.*;
import jakarta.websocket.*;
import jakarta.websocket.server.*;
import jakarta.ws.rs.*;
import jakarta.ws.rs.client.*;
import jakarta.ws.rs.container.*;
import jakarta.ws.rs.core.*;
import jakarta.ws.rs.ext.*;
import jakarta.xml.bind.*;
import jakarta.xml.bind.annotation.*;
import jakarta.xml.bind.annotation.adapters.*;
import jakarta.xml.bind.attachment.*;
import jakarta.xml.bind.helpers.*;
import jakarta.xml.bind.util.*;
import jakarta.xml.soap.*;
import jakarta.xml.ws.*;
import jakarta.xml.ws.handler.*;
import jakarta.xml.ws.handler.soap.*;
import jakarta.xml.ws.http.*;
import jakarta.xml.ws.soap.*;
import jakarta.xml.ws.spi.*;
import jakarta.xml.ws.spi.http.*;
import jakarta.xml.ws.wsaddressing.*;
/**
* This class checks the dependencies as exported by the
* "spec-api" module to ensure that compilation of all Jakarta EE
* 7 Specification Platform APIs are reachable. As such, no runtime
* assertions are required here, only references. If this class compiles,
* all noted references are reachable within the spec-api dependency chain.
*
* @author <a href="mailto:[email protected]">Andrew Lee Rubinger</a>
* @see http://docs.oracle.com/javaee/7/api/
*/
@SuppressWarnings("unused")
public class SpecApiDependencyCheck {
}
| 5,128 | 33.655405 | 76 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jboss/as/jpa/spi/ManagementAdaptor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jpa.spi;
/**
* Defines persistence provider management operations/statistics
*
* @author Scott Marlow
* @deprecated replaced by {@link org.jipijapa.plugin.spi.ManagementAdaptor}
*/
@Deprecated
public interface ManagementAdaptor extends org.jipijapa.plugin.spi.ManagementAdaptor {
}
| 1,335 | 37.171429 | 86 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jboss/as/jpa/spi/PersistenceUnitServiceRegistry.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jpa.spi;
/**
* Registry of started persistence unit services.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
* @deprecated replaced by {@link org.jipijapa.plugin.spi.PersistenceUnitServiceRegistry}
*/
public interface PersistenceUnitServiceRegistry extends org.jipijapa.plugin.spi.PersistenceUnitServiceRegistry {
}
| 1,373 | 39.411765 | 112 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jboss/as/jpa/spi/TempClassLoaderFactory.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jpa.spi;
/**
* Factory for creating temporary classloaders used by persistence providers.
*
* @author Antti Laisi
* @deprecated replaced by {@link org.jipijapa.plugin.spi.TempClassLoaderFactory}
*/
@Deprecated
public interface TempClassLoaderFactory extends org.jipijapa.plugin.spi.TempClassLoaderFactory {
}
| 1,363 | 36.888889 | 96 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jboss/as/jpa/spi/JtaManager.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jpa.spi;
/**
* Provides access to TSR + TM
*
* @author Scott Marlow
* @deprecated replaced by {@link org.jipijapa.plugin.spi.JtaManager}
*/
@Deprecated
public interface JtaManager extends org.jipijapa.plugin.spi.JtaManager {
}
| 1,280 | 35.6 | 72 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jboss/as/jpa/spi/PersistenceUnitService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jpa.spi;
/**
* Persistence unit service
*
* @author Scott Marlow
* @deprecated replaced by {@link org.jipijapa.plugin.spi.PersistenceUnitService}
*/
@Deprecated
public interface PersistenceUnitService extends org.jipijapa.plugin.spi.PersistenceUnitService {
}
| 1,313 | 36.542857 | 96 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jboss/as/jpa/spi/PersistenceUnitMetadata.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jpa.spi;
/**
* Represents the persistence unit definition
*
* @author Scott Marlow
* @deprecated replaced by {@link org.jipijapa.plugin.spi.PersistenceUnitMetadata}
*/
@Deprecated
public interface PersistenceUnitMetadata extends org.jipijapa.plugin.spi.PersistenceUnitMetadata {
}
| 1,333 | 38.235294 | 98 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jboss/as/jpa/spi/PersistenceProviderAdaptor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jpa.spi;
/**
* PersistenceProvider adaptor
*
* @author Scott Marlow
* @deprecated replaced by {@link org.jipijapa.plugin.spi.PersistenceProviderAdaptor}
*/
@Deprecated
public interface PersistenceProviderAdaptor extends org.jipijapa.plugin.spi.PersistenceProviderAdaptor {
}
| 1,329 | 35.944444 | 104 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jipijapa/JipiLogger.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jipijapa;
import static org.jboss.logging.Logger.Level.WARN;
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;
/**
* JipiJapa integration layer message range is 20200-20299
* @author <a href="mailto:[email protected]">James R. Perkins</a>
* @author Scott Marlow
*/
@MessageLogger(projectCode = "JIPI")
public interface JipiLogger extends BasicLogger {
/**
* A logger with the category {@code org.jboss.jpa}.
*/
JipiLogger JPA_LOGGER = Logger.getMessageLogger(JipiLogger.class, "org.jipijapa");
/**
* warn that the entity class could not be loaded with the
* {@link jakarta.persistence.spi.PersistenceUnitInfo#getClassLoader()}.
*
* @param cause the cause of the error.
* @param className the entity class name.
*/
@LogMessage(level = WARN)
@Message(id = 20200, value = "Could not load entity class '%s', ignoring this error and continuing with application deployment")
void cannotLoadEntityClass(@Cause Throwable cause, String className);
/**
* Creates an exception indicating the input stream reference cannot be changed.
*
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 20201, value = "Cannot change input stream reference.")
IllegalArgumentException cannotChangeInputStream();
/**
* Creates an exception indicating the parameter, likely a collection, is empty.
*
* @param parameterName the parameter name.
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 20202, value = "Parameter %s is empty")
IllegalArgumentException emptyParameter(String parameterName);
/**
* Creates an exception indicating the persistence unit metadata likely because thread local was not set.
*
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 20203, value = "Missing PersistenceUnitMetadata (thread local wasn't set)")
RuntimeException missingPersistenceUnitMetadata();
/**
* Creates an exception indicating the method is not yet implemented.
*
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 20204, value = "Not yet implemented")
RuntimeException notYetImplemented();
/**
* Creates an exception indicating the variable is {@code null}.
*
* @param varName the variable name.
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 20205, value = "Parameter %s is null")
IllegalArgumentException nullVar(String varName);
/**
* Could not open VFS stream
*
* @param cause the cause of the error.
* @param name of VFS file
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 20250, value = "Unable to open VirtualFile-based InputStream %s")
RuntimeException cannotOpenVFSStream(@Cause Throwable cause, String name);
/**
* URI format is incorrect, which results in a syntax error
*
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 20251, value = "URI syntax error")
IllegalArgumentException uriSyntaxException(@Cause Throwable cause);
/**
* warn that the 2nd is not integrated
*
* @param scopedPuName identifies the app specific persistence unit name
*/
@LogMessage(level = WARN)
@Message(id = 20252, value = "second level cache not integrated - %s")
void cannotUseSecondLevelCache(String scopedPuName);
}
| 4,765 | 35.945736 | 132 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jipijapa/management/spi/Statistics.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jipijapa.management.spi;
import java.util.Collection;
import java.util.Set;
/**
* SPI for statistic plugins to implement.
*
* @author Scott Marlow
*/
public interface Statistics {
/**
* Get the statistics names
*
* @return The value
*/
Set<String> getNames();
Collection<String> getDynamicChildrenNames(EntityManagerFactoryAccess entityManagerFactoryAccess, PathAddress pathAddress);
/**
* Get the type
*
* @param name of the statistic
* @return The value
*/
Class getType(String name);
/**
* return true if the specified name represents an operation.
*
* @param name of the statistic
* @return
*/
boolean isOperation(String name);
/**
* return true if the specified name represents an attribute.
*
* @param name of the statistic
* @return
*/
boolean isAttribute(String name);
/**
* return true if the specified name represents a writeable attribute
* @param name of the statistics
* @return
*/
boolean isWriteable(String name);
/**
* for loading descriptions of statistics/operations
*
* @return name of resource bundle name
*/
String getResourceBundleName();
/**
* gets the key prefix for referencing descriptions of statistics/operations
*
* @return
*/
String getResourceBundleKeyPrefix();
/**
* Get the value of the statistics
*
* @param name The name of the statistics
* @return The value
*/
Object getValue(String name, EntityManagerFactoryAccess entityManagerFactoryAccess, StatisticName statisticName, PathAddress pathAddress);
/**
* Set the value of the statistic (isWriteable must return true)
* @param name
* @param newValue
*/
void setValue(String name, Object newValue, EntityManagerFactoryAccess entityManagerFactoryAccess, StatisticName statisticName, PathAddress pathAddress);
/**
* get the names of the children statistic levels (if any)
* @return set of names
*/
Set<String> getChildrenNames();
/**
* get the specified children statistics
* @param childName name of the statistics to return
* @return
*/
Statistics getChild(String childName);
}
| 3,347 | 26.9 | 157 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jipijapa/management/spi/EntityManagerFactoryAccess.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jipijapa.management.spi;
import jakarta.persistence.EntityManagerFactory;
/**
* EntityManagerFactoryAccess
*
* @author Scott Marlow
*/
public interface EntityManagerFactoryAccess {
/**
* returns the entity manager factory that statistics should be obtained for.
*
* @throws IllegalStateException if scopedPersistenceUnitName is not found
*
* @param scopedPersistenceUnitName is persistence unit name scoped to the current platform
*
* @return EntityManagerFactory
*/
EntityManagerFactory entityManagerFactory(String scopedPersistenceUnitName) throws IllegalStateException;
}
| 1,666 | 36.044444 | 109 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jipijapa/management/spi/Operation.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jipijapa.management.spi;
/**
* Operation
*
* @author Scott Marlow
*/
public interface Operation {
/**
* Invoke operation
* @param args will be passed to invoked operation
* @return
*/
Object invoke(Object... args);
}
| 1,287 | 32.025641 | 70 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jipijapa/management/spi/PathAddress.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jipijapa.management.spi;
/**
* PathAddress is an ordered set of name/value pairs representing the management path.
*
* The names are based on the statistic child names (e.g. name=entity value=Employee)
*
* @author Scott Marlow
*/
public interface PathAddress {
int size();
String getValue(String name);
String getValue(int index);
}
| 1,390 | 34.666667 | 86 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jipijapa/management/spi/StatisticName.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jipijapa.management.spi;
/**
* StatisticName
*
* @author Scott Marlow
*/
public interface StatisticName {
/**
* returns the statistic name
* @return
*/
String getName();
}
| 1,236 | 32.432432 | 70 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jipijapa/cache/spi/Wrapper.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jipijapa.cache.spi;
/**
* Opaque cache wrapper
*
* @author Scott Marlow
*/
public interface Wrapper {
Object getValue();
}
| 1,170 | 32.457143 | 70 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jipijapa/cache/spi/Classification.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jipijapa.cache.spi;
import java.util.HashMap;
import java.util.Map;
/**
* Type of cache
*
* @author Scott Marlow
*/
public enum Classification {
INFINISPAN("Infinispan"),
NONE(null);
private final String name;
Classification(final String name) {
this.name = name;
}
/**
* Get the local name of this element.
*
* @return the local name
*/
public String getLocalName() {
return name;
}
private static final Map<String, Classification> MAP;
static {
final Map<String, Classification> map = new HashMap<String, Classification>();
for (Classification element : values()) {
final String name = element.getLocalName();
if (name != null) map.put(name, element);
}
MAP = map;
}
public static Classification forName(String localName) {
final Classification element = MAP.get(localName);
return element == null ? NONE : element;
}
}
| 2,031 | 28.449275 | 86 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jipijapa/plugin/spi/ManagementAdaptor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jipijapa.plugin.spi;
import org.jipijapa.management.spi.Statistics;
/**
* Defines persistence provider management operations/statistics
*
* @author Scott Marlow
*/
public interface ManagementAdaptor {
/**
* Get the short identification string that represents the management adaptor (e.g Hibernate)
*
* @return id label
*/
String getIdentificationLabel();
/**
* Version that uniquely identifies the management adapter (can be used to tell the difference between
* Hibernate 4.1 vs 4.3).
*
* @return version string
*/
String getVersion();
Statistics getStatistics();
}
| 1,678 | 31.288462 | 106 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jipijapa/plugin/spi/PersistenceUnitServiceRegistry.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jipijapa.plugin.spi;
/**
* Registry of started persistence unit services.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public interface PersistenceUnitServiceRegistry {
/**
* Get the persistence unit service associated with the given management resource name.
*
* @param persistenceUnitResourceName the name of the management resource representing persistence unit
*
* @return a PersistenceUnitService or {@code null} if the persistence unit service has not been started or has been stopped
*/
PersistenceUnitService getPersistenceUnitService(String persistenceUnitResourceName);
}
| 1,673 | 37.930233 | 128 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jipijapa/plugin/spi/TempClassLoaderFactory.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jipijapa.plugin.spi;
/**
* Factory for creating temporary classloaders used by persistence providers.
*
* @author Antti Laisi
*/
public interface TempClassLoaderFactory {
/**
* Creates a temporary classloader with the same scope and classpath as the persistence unit classloader.
*
* @see jakarta.persistence.spi.PersistenceUnitInfo#getNewTempClassLoader()
*/
ClassLoader createNewTempClassLoader();
}
| 1,473 | 35.85 | 109 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jipijapa/plugin/spi/EntityManagerFactoryBuilder.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jipijapa.plugin.spi;
import jakarta.persistence.EntityManagerFactory;
/**
* EntityManagerFactoryBuilder is based on org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder.
* Represents a 2-phase JPA bootstrap process for building an EntityManagerFactory.
*
* @author Scott Marlow
* @author Steve Ebersole
*/
public interface EntityManagerFactoryBuilder {
/**
* Build {@link EntityManagerFactory} instance
*
* @return The built {@link EntityManagerFactory}
*/
EntityManagerFactory build();
/**
* Cancel the building processing. This is used to signal the builder to release any resources in the case of
* something having gone wrong during the bootstrap process
*/
void cancel();
/**
* Allows passing in a Jakarta EE ValidatorFactory (delayed from constructing the builder, AKA phase 2) to be used
* in building the EntityManagerFactory
*
* @param validatorFactory The ValidatorFactory
*
* @return {@code this}, for method chaining
*/
EntityManagerFactoryBuilder withValidatorFactory(Object validatorFactory);
}
| 2,152 | 35.491525 | 118 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jipijapa/plugin/spi/JtaManager.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jipijapa.plugin.spi;
import jakarta.transaction.TransactionManager;
import jakarta.transaction.TransactionSynchronizationRegistry;
/**
* Provides access to TSR + TM
*
* @author Scott Marlow
*/
public interface JtaManager {
TransactionSynchronizationRegistry getSynchronizationRegistry();
TransactionManager locateTransactionManager();
}
| 1,389 | 34.641026 | 70 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jipijapa/plugin/spi/Platform.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jipijapa.plugin.spi;
import java.util.Set;
import org.jipijapa.cache.spi.Classification;
/**
* describes the platform that is in use
*
* @author Scott Marlow
*/
public interface Platform {
/**
* obtain the default second level cache classification
* @return default 2lc type
*/
Classification defaultCacheClassification();
/**
* get the second level cache classifications
* @return Set<Classification>
*/
Set<Classification> cacheClassifications();
}
| 1,542 | 31.145833 | 70 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jipijapa/plugin/spi/PersistenceUnitService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jipijapa.plugin.spi;
import jakarta.persistence.EntityManagerFactory;
/**
* Persistence unit service
*
* @author Scott Marlow
*/
public interface PersistenceUnitService {
/**
* get the entity manager factory that represents the persistence unit service. This corresponds to a
* persistence unit definition in a persistence.xml
*
* @return EntityManagerFactory or {@code null} if this service has not been started or has been stopped
*/
EntityManagerFactory getEntityManagerFactory();
/**
* Gets the scoped name of this persistence unit.
*
* @return the name
*/
String getScopedPersistenceUnitName();
}
| 1,707 | 34.583333 | 108 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jipijapa/plugin/spi/PersistenceUnitMetadata.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jipijapa.plugin.spi;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import jakarta.persistence.SharedCacheMode;
import jakarta.persistence.ValidationMode;
import jakarta.persistence.spi.ClassTransformer;
import jakarta.persistence.spi.PersistenceUnitInfo;
import jakarta.persistence.spi.PersistenceUnitTransactionType;
import javax.sql.DataSource;
import org.jboss.jandex.Index;
/**
* Represents the persistence unit definition
*
* @author Scott Marlow
*/
public interface PersistenceUnitMetadata extends PersistenceUnitInfo {
void setPersistenceUnitName(String name);
void setScopedPersistenceUnitName(String scopedName);
String getScopedPersistenceUnitName();
void setContainingModuleName(ArrayList<String> getContainingModuleName);
ArrayList<String> getContainingModuleName();
void setPersistenceProviderClassName(String provider);
void setJtaDataSource(DataSource jtaDataSource);
void setNonJtaDataSource(DataSource nonJtaDataSource);
void setJtaDataSourceName(String jtaDatasource);
String getJtaDataSourceName();
void setNonJtaDataSourceName(String nonJtaDatasource);
String getNonJtaDataSourceName();
void setPersistenceUnitRootUrl(URL persistenceUnitRootUrl);
void setAnnotationIndex(Map<URL, Index> indexes);
Map<URL, Index> getAnnotationIndex();
void setManagedClassNames(List<String> classes);
void setExcludeUnlistedClasses(boolean excludeUnlistedClasses);
void setTransactionType(PersistenceUnitTransactionType transactionType);
void setMappingFiles(List<String> mappingFiles);
void setJarFileUrls(List<URL> jarFilesUrls);
List<String> getJarFiles();
void setJarFiles(List<String> jarFiles);
void setValidationMode(ValidationMode validationMode);
void setProperties(Properties props);
void setPersistenceXMLSchemaVersion(String version);
void setClassLoader(ClassLoader cl);
void setTempClassLoaderFactory(TempClassLoaderFactory tempClassLoaderFactory);
/**
* Cache a (new, on first use) temp classloader and return it for all subsequent calls.
* The cached temp classloader is only to be reused by the caller, at the per persistence unit level.
* @return the cached temp classloader
*/
ClassLoader cacheTempClassLoader();
void setSharedCacheMode(SharedCacheMode sharedCacheMode);
List<ClassTransformer> getTransformers();
}
| 3,531 | 30.81982 | 105 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jipijapa/plugin/spi/PersistenceProviderAdaptor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jipijapa.plugin.spi;
import java.util.Map;
import jakarta.enterprise.inject.spi.BeanManager;
/**
* PersistenceProvider adaptor
*
* @author Scott Marlow
*/
public interface PersistenceProviderAdaptor {
/**
* pass the JtaManager in for internal use by PersistenceProviderAdaptor implementer
*
* @param jtaManager
*/
void injectJtaManager(JtaManager jtaManager);
/**
* pass the platform in use
* @param platform
*/
void injectPlatform(Platform platform);
/**
* Adds any provider specific properties
*
* @param properties
* @param pu
*/
void addProviderProperties(Map properties, PersistenceUnitMetadata pu);
/**
* Persistence provider integration code might need dependencies that must be started
* for the deployment. Note that these dependency classes are expected to be already available to the provider.
*
* @param pu
* @return
*/
void addProviderDependencies(PersistenceUnitMetadata pu);
/**
* Called right before persistence provider is invoked to create container entity manager factory.
* afterCreateContainerEntityManagerFactory() will always be called after the container entity manager factory
* is created.
*
* @param pu
*/
void beforeCreateContainerEntityManagerFactory(PersistenceUnitMetadata pu);
/**
* Called right after persistence provider is invoked to create container entity manager factory.
*/
void afterCreateContainerEntityManagerFactory(PersistenceUnitMetadata pu);
/**
* Get the management adaptor
*
* @return ManagementAdaptor or null
*/
ManagementAdaptor getManagementAdaptor();
/**
* for adapters that support getManagementAdaptor(), does the scoped persistence unit name
* correctly identify cache entities. This is intended for Hibernate, other adapters can return true.
*
* @return the Hibernate adapter will return false if
* the persistence unit has specified a custom "hibernate.cache.region_prefix" property. True otherwise.
*
*/
boolean doesScopedPersistenceUnitNameIdentifyCacheRegionName(PersistenceUnitMetadata pu);
/**
* Called when we are done with the persistence unit metadata
*/
void cleanup(PersistenceUnitMetadata pu);
/**
* Some persistence provider adapters may handle life cycle notification services for when the CDI bean manager
* can lookup the persistence unit that is using the CDI bean manager (e.g. for handling self referencing cycles).
* <p>
* persistence provider BeanManager extension.
*
* @param beanManager
* @return wrapper object representing BeanManager lifecycle
*/
Object beanManagerLifeCycle(BeanManager beanManager);
void markPersistenceUnitAvailable(Object wrapperBeanManagerLifeCycle);
}
| 3,934 | 32.922414 | 118 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jipijapa/plugin/spi/PersistenceProviderIntegratorAdaptor.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.jipijapa.plugin.spi;
import org.jboss.jandex.Index;
import java.util.Collection;
import java.util.Map;
/**
* Adaptor for integrators into persistence providers, e.g. Hibernate Search.
*/
public interface PersistenceProviderIntegratorAdaptor {
/**
* @param indexes The index views for the unit being deployed
*/
void injectIndexes(Collection<Index> indexes);
/**
* Adds any integrator-specific persistence unit properties
*
* @param properties
* @param pu
*/
void addIntegratorProperties(Map<String, Object> properties, PersistenceUnitMetadata pu);
/**
* Called right after persistence provider is invoked to create container entity manager factory.
*/
void afterCreateContainerEntityManagerFactory(PersistenceUnitMetadata pu);
}
| 1,844 | 32.545455 | 101 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jipijapa/plugin/spi/TwoPhaseBootstrapCapable.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jipijapa.plugin.spi;
import java.util.Map;
import jakarta.persistence.spi.PersistenceUnitInfo;
/**
* TwoPhaseBootstrapCapable obtains a two phase EntityManagerFactory builder
*
* @author Scott Marlow
* @author Steve Ebersole
*/
public interface TwoPhaseBootstrapCapable {
/**
* Returns a two phase EntityManagerFactory builder
*
* @param info
* @param map
* @return
*/
EntityManagerFactoryBuilder getBootstrap(final PersistenceUnitInfo info, final Map map);
}
| 1,543 | 32.565217 | 92 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jipijapa/event/spi/EventListener.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jipijapa.event.spi;
import java.util.Properties;
import org.jipijapa.cache.spi.Classification;
import org.jipijapa.cache.spi.Wrapper;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
/**
* lifecycle EventListener
*
* @author Scott Marlow
*/
public interface EventListener {
/**
* called before call to PersistenceProvider.createContainerEntityManagerFactory(PersistenceUnit, Map)
* @param cacheType
* @param persistenceUnitMetadata
*/
void beforeEntityManagerFactoryCreate(Classification cacheType, PersistenceUnitMetadata persistenceUnitMetadata);
/**
* called after call to PersistenceProvider.createContainerEntityManagerFactory(PersistenceUnit, Map)
* @param persistenceUnitMetadata
*/
void afterEntityManagerFactoryCreate(Classification cacheType, PersistenceUnitMetadata persistenceUnitMetadata);
/**
* start cache
*
* @param cacheType
* @param properties
* @return an opaque cache wrapper that is later passed to stopCache
*/
Wrapper startCache(Classification cacheType, Properties properties) throws Exception;
/**
* add dependencies on a cache
*
* @param cacheType
* @param properties
*/
void addCacheDependencies(Classification cacheType, Properties properties);
/**
* Stop cache
*
* @param cacheType
* @param wrapper
*/
void stopCache(Classification cacheType, Wrapper wrapper);
}
| 2,502 | 31.934211 | 117 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jipijapa/event/impl/EventListenerRegistration.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jipijapa.event.impl;
import org.jipijapa.event.impl.internal.Notification;
import org.jipijapa.event.spi.EventListener;
/**
* System level EventListenerRegistration
*
* @author Scott Marlow
*/
public class EventListenerRegistration {
public static void add(EventListener eventListener) {
Notification.add(eventListener);
}
public static void remove(EventListener eventListener) {
Notification.remove(eventListener);
}
}
| 1,498 | 32.311111 | 70 |
java
|
null |
wildfly-main/jpa/spi/src/main/java/org/jipijapa/event/impl/internal/Notification.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jipijapa.event.impl.internal;
import java.util.Properties;
import java.util.concurrent.CopyOnWriteArrayList;
import org.jipijapa.cache.spi.Classification;
import org.jipijapa.cache.spi.Wrapper;
import org.jipijapa.event.spi.EventListener;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
/**
* Event Notification
*
* @author Scott Marlow
*/
public class Notification {
private static final CopyOnWriteArrayList<EventListener> eventListeners = new CopyOnWriteArrayList<EventListener>();
public static void add(EventListener eventListener) {
eventListeners.add(eventListener);
}
public static void remove(EventListener eventListener) {
eventListeners.remove(eventListener);
}
/**
* called before call to PersistenceProvider.createContainerEntityManagerFactory(PersistenceUnit, Map)
* @param persistenceUnitMetadata
*/
public static void beforeEntityManagerFactoryCreate(Classification cacheType, PersistenceUnitMetadata persistenceUnitMetadata) {
for(EventListener eventListener: eventListeners) {
eventListener.beforeEntityManagerFactoryCreate(cacheType, persistenceUnitMetadata);
}
}
/**
* called after call to PersistenceProvider.createContainerEntityManagerFactory(PersistenceUnit, Map)
* @param persistenceUnitMetadata
*/
public static void afterEntityManagerFactoryCreate(Classification cacheType, PersistenceUnitMetadata persistenceUnitMetadata) {
for(EventListener eventListener: eventListeners) {
eventListener.afterEntityManagerFactoryCreate(cacheType, persistenceUnitMetadata);
}
}
/**
* start cache
*
* @param cacheType
* @param properties
* @return an opaque cache wrapper that is later passed to stopCache
*/
public static Wrapper startCache(Classification cacheType, Properties properties) throws Exception {
Wrapper result = null;
for(EventListener eventListener: eventListeners) {
Wrapper value = eventListener.startCache(cacheType, properties);
if (value != null && result == null) {
result = value; // return the first non-null wrapper value returned from a listener
}
}
return result;
}
/**
* add cache dependencies
*
* @param properties
*/
public static void addCacheDependencies(Classification cacheType, Properties properties) {
for(EventListener eventListener: eventListeners) {
eventListener.addCacheDependencies(cacheType, properties);
}
}
/**
* Stop cache
* @param cacheType
* @param wrapper
*/
public static void stopCache(Classification cacheType, Wrapper wrapper) {
for(EventListener eventListener: eventListeners) {
eventListener.stopCache(cacheType, wrapper);
}
}
}
| 3,952 | 34.294643 | 132 |
java
|
null |
wildfly-main/jpa/subsystem/src/test/java/org/jboss/as/jpa/subsystem/JPA11SubsystemTestCase.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.jpa.subsystem;
import java.io.IOException;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.junit.Test;
/**
* @author <a href="[email protected]">Kabir Khan</a>
*/
public class JPA11SubsystemTestCase extends AbstractSubsystemBaseTest {
public JPA11SubsystemTestCase() {
super(JPAExtension.SUBSYSTEM_NAME, new JPAExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource("subsystem-1.1.xml");
}
@Override
protected String getSubsystemXsdPath() throws Exception {
return "schema/jboss-as-jpa_1_1.xsd";
}
@Test
public void testEmptySubsystem() throws Exception {
standardSubsystemTest("subsystem-1.1-empty.xml");
}
}
| 1,804 | 32.425926 | 71 |
java
|
null |
wildfly-main/jpa/subsystem/src/test/java/org/jboss/as/jpa/subsystem/JPA10SubsystemTestCase.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.jpa.subsystem;
import java.io.IOException;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.junit.Test;
/**
* @author <a href="[email protected]">Kabir Khan</a>
*/
public class JPA10SubsystemTestCase extends AbstractSubsystemBaseTest {
public JPA10SubsystemTestCase() {
super(JPAExtension.SUBSYSTEM_NAME, new JPAExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource("subsystem-1.0.xml");
}
@Override
protected void compareXml(String configId, String original, String marshalled) throws Exception {
//no need to compare
}
@Test
public void testEmptySubsystem() throws Exception {
standardSubsystemTest("subsystem-1.0-empty.xml");
}
}
| 1,827 | 32.851852 | 101 |
java
|
null |
wildfly-main/jpa/subsystem/src/test/java/org/jboss/as/jpa/puparser/PersistenceUnitXmlParserTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright (c) 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.jpa.puparser;
import java.io.StringReader;
import jakarta.persistence.SharedCacheMode;
import jakarta.persistence.ValidationMode;
import jakarta.persistence.spi.PersistenceUnitTransactionType;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.jboss.as.jpa.config.PersistenceUnitMetadataHolder;
import org.jboss.metadata.property.PropertyReplacers;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
*/
public class PersistenceUnitXmlParserTestCase {
/**
* See http://issues.jboss.org/browse/STXM-8
*/
@Test
public void testVersion() throws Exception {
final String persistence_xml =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?> " +
"<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">" +
" <persistence-unit name=\"mypc\">" +
" <description>Persistence Unit." +
" </description>" +
" <jta-data-source>java:/H2DS</jta-data-source>" +
" <class>org.jboss.as.test.integration.jpa.epcpropagation.MyEntity</class>" +
" <properties> <property name=\"hibernate.hbm2ddl.auto\" value=\"create-drop\"/></properties>" +
" </persistence-unit>" +
"</persistence>";
XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(persistence_xml));
PersistenceUnitMetadataHolder metadataHolder = PersistenceUnitXmlParser.parse(reader, PropertyReplacers.noop());
PersistenceUnitMetadata metadata = metadataHolder.getPersistenceUnits().get(0);
String version = metadata.getPersistenceXMLSchemaVersion();
assertEquals("1.0", version);
}
@Test
public void testVersion22() throws XMLStreamException {
testEverything("http://java.sun.com/xml/ns/persistence", "2.2");
}
@Test
public void testVersion30() throws XMLStreamException {
testEverything("https://jakarta.ee/xml/ns/persistence", "3.0");
}
private void testEverything(String namespace, String version) throws XMLStreamException {
final String persistence_xml =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?> " +
"<persistence xmlns=\"" + namespace + "\" version=\"" + version + "\">" +
" <persistence-unit name=\"mypc\" transaction-type=\"RESOURCE_LOCAL\">" +
" <description>Persistence Unit." +
" </description>" +
" <jta-data-source>java:/H2DS</jta-data-source>" +
" <class>org.jboss.as.test.integration.jpa.epcpropagation.MyEntity</class>" +
" <exclude-unlisted-classes/>" +
" <jar-file>foo.jar</jar-file>" +
" <mapping-file>mapping.xml</mapping-file>" +
" <non-jta-data-source>java:/FooDS</non-jta-data-source>" +
" <properties> <property name=\"hibernate.hbm2ddl.auto\" value=\"create-drop\"/></properties>" +
" <provider>org.foo.Provider</provider>" +
" <shared-cache-mode>DISABLE_SELECTIVE</shared-cache-mode>" +
" <validation-mode>CALLBACK</validation-mode>" +
" </persistence-unit>" +
"</persistence>";
XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(persistence_xml));
PersistenceUnitMetadataHolder metadataHolder = PersistenceUnitXmlParser.parse(reader, PropertyReplacers.noop());
assertEquals(1, metadataHolder.getPersistenceUnits().size());
PersistenceUnitMetadata metadata = metadataHolder.getPersistenceUnits().get(0);
assertEquals("mypc", metadata.getPersistenceUnitName());
assertEquals(version, metadata.getPersistenceXMLSchemaVersion());
assertEquals("java:/H2DS", metadata.getJtaDataSourceName());
assertEquals("java:/FooDS", metadata.getNonJtaDataSourceName());
assertEquals(1, metadata.getManagedClassNames().size());
assertEquals("org.jboss.as.test.integration.jpa.epcpropagation.MyEntity", metadata.getManagedClassNames().get(0));
assertTrue(metadata.excludeUnlistedClasses());
assertEquals(1, metadata.getJarFiles().size());
assertEquals("foo.jar", metadata.getJarFiles().get(0));
assertEquals(1, metadata.getMappingFileNames().size());
assertEquals("mapping.xml", metadata.getMappingFileNames().get(0));
assertEquals(1, metadata.getProperties().size());
assertEquals("create-drop", metadata.getProperties().get("hibernate.hbm2ddl.auto"));
assertEquals("org.foo.Provider", metadata.getPersistenceProviderClassName());
assertEquals(SharedCacheMode.DISABLE_SELECTIVE, metadata.getSharedCacheMode());
assertEquals(ValidationMode.CALLBACK, metadata.getValidationMode());
assertEquals(PersistenceUnitTransactionType.RESOURCE_LOCAL, metadata.getTransactionType());
}
}
| 6,462 | 52.413223 | 123 |
java
|
null |
wildfly-main/jpa/subsystem/src/test/java/org/jboss/as/jpa/classloader/TempClassLoaderTestCase.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.jpa.classloader;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import jakarta.persistence.Entity;
import org.junit.Test;
/**
* @author Antti Laisi
*/
public class TempClassLoaderTestCase {
private TempClassLoaderFactoryImpl factory = new TempClassLoaderFactoryImpl(getClass().getClassLoader());
@Test
public void testLoadEntityClass() throws Exception {
ClassLoader tempClassLoader = factory.createNewTempClassLoader();
String className = TestEntity.class.getName();
Class<?> entityClass = tempClassLoader.loadClass(className);
Object entity = entityClass.newInstance();
assertFalse(entityClass.equals(TestEntity.class));
assertFalse(entity instanceof TestEntity);
assertTrue("entity.getClass() is not a Persistence.Entity (" + annotations(entity.getClass()) + ")", entity.getClass().isAnnotationPresent(Entity.class));
assertTrue(entityClass == tempClassLoader.loadClass(className));
}
private String annotations(Class<?> aClass) {
for(Annotation annotation : aClass.getAnnotations()) {
if (annotation.toString().contains(Entity.class.getName()))
return "found " + Entity.class.getName();
}
return aClass.getName() + " is missing annotation " + Entity.class.getName();
}
@Test
public void testLoadResources() throws IOException {
ClassLoader tempClassLoader = factory.createNewTempClassLoader();
String resource = TestEntity.class.getName().replace('.', '/') + ".class";
assertNotNull(tempClassLoader.getResource(resource));
assertTrue(tempClassLoader.getResources(resource).hasMoreElements());
InputStream resourceStream = tempClassLoader.getResourceAsStream(resource);
assertNotNull(resourceStream);
resourceStream.close();
}
@Test
public void testLoadEntityClassPackage() throws Exception {
ClassLoader tempClassLoader = factory.createNewTempClassLoader();
String className = TestEntity.class.getName();
Class<?> entityClass = tempClassLoader.loadClass(className);
assertNotNull("could not load package for entity class that came from NewTempClassLoader", entityClass.getPackage());
}
@Entity
public static class TestEntity {
}
}
| 3,545 | 37.129032 | 162 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/messages/JpaLogger.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.jpa.messages;
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 jakarta.ejb.EJBException;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceException;
import jakarta.persistence.TransactionRequiredException;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.jandex.MethodInfo;
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.vfs.VirtualFile;
/**
* Date: 07.06.2011
*
* @author <a href="mailto:[email protected]">James R. Perkins</a>
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
@MessageLogger(projectCode = "WFLYJPA", length = 4)
public interface JpaLogger extends BasicLogger {
/**
* Default root level logger with the package name for he category.
*/
JpaLogger ROOT_LOGGER = Logger.getMessageLogger(JpaLogger.class, "org.jboss.as.jpa");
/**
* Logs a warning message indicating duplicate persistence.xml files were found.
*
* @param puName the persistence XML file.
* @param ogPuName the original persistence.xml file.
* @param dupPuName the duplicate persistence.xml file.
*/
@LogMessage(level = WARN)
@Message(id = 1, value = "Duplicate Persistence Unit definition for %s " +
"in application. One of the duplicate persistence.xml should be removed from the application." +
" Application deployment will continue with the persistence.xml definitions from %s used. " +
"The persistence.xml definitions from %s will be ignored.")
void duplicatePersistenceUnitDefinition(String puName, String ogPuName, String dupPuName);
/**
* Logs an informational message indicating the persistence.xml file is being read.
*
* @param puUnitName the persistence unit name.
*/
@LogMessage(level = INFO)
@Message(id = 2, value = "Read persistence.xml for %s")
void readingPersistenceXml(String puUnitName);
/**
* Logs an informational message indicating the service, represented by the {@code serviceName} parameter, is
* starting.
*
* @param serviceName the name of the service.
* @param name an additional name for the service.
*/
@LogMessage(level = INFO)
@Message(id = 3, value = "Starting %s Service '%s'")
void startingService(String serviceName, String name);
/**
* Logs an informational message indicating the service, represented by the {@code serviceName} parameter, is
* stopping.
*
* @param serviceName the name of the service.
* @param name an additional name for the service.
*/
@LogMessage(level = INFO)
@Message(id = 4, value = "Stopping %s Service '%s'")
void stoppingService(String serviceName, String name);
// /**
// * Logs an error message indicating an exception occurred while preloading the default persistence provider adapter module.
// * Initialization continues after logging the error.
// *
// * @param cause the cause of the error.
// */
// @LogMessage(level = ERROR)
// @Message(id = 5, value = "Could not load default persistence provider adaptor module. Management attributes will not be registered for the adaptor")
// void errorPreloadingDefaultProviderAdaptor(@Cause Throwable cause);
/**
* Logs an error message indicating an exception occurred while preloading the default persistence provider module.
* Initialization continues after logging the error.
*
* @param cause the cause of the error.
*/
@LogMessage(level = ERROR)
@Message(id = 6, value = "Could not load default persistence provider module. ")
void errorPreloadingDefaultProvider(@Cause Throwable cause);
/**
* Logs an error message indicating the persistence unit was not stopped
*
* @param cause the cause of the error.
* @param name name of the persistence unit
*/
@LogMessage(level = ERROR)
@Message(id = 7, value = "Failed to stop persistence unit service %s")
void failedToStopPUService(@Cause Throwable cause, String name);
// /**
// * Creates an exception indicating a failure to get the module for the deployment unit represented by the
// * {@code deploymentUnit} parameter.
// *
// * @param deploymentUnit the deployment unit that failed.
// */
//@LogMessage(level = WARN)
//@Message(id = 8, value = "Failed to get module attachment for %s")
//void failedToGetModuleAttachment(DeploymentUnit deploymentUnit);
// /**
// * warn that the entity class could not be loaded with the
// * {@link jakarta.persistence.spi.PersistenceUnitInfo#getClassLoader()}.
// *
// * @param cause the cause of the error.
// * @param className the entity class name.
// */
//@LogMessage(level = WARN)
//@Message(id = 9, value = "Could not load entity class '%s', ignoring this error and continuing with application deployment")
//void cannotLoadEntityClass(@Cause Throwable cause, String className);
/**
* Logs an informational message indicating the persistence unit service is starting phase n of 2.
*
* @param phase is the phase number (1 or 2)
* @param name an additional name for the service.
*/
@LogMessage(level = INFO)
@Message(id = 10, value = "Starting Persistence Unit (phase %d of 2) Service '%s'")
void startingPersistenceUnitService(int phase, String name);
/**
* Logs an informational message indicating the service is stopping.
*
* @param phase is the phase number (1 or 2)
* @param name an additional name for the service.
*/
@LogMessage(level = INFO)
@Message(id = 11, value = "Stopping Persistence Unit (phase %d of 2) Service '%s'")
void stoppingPersistenceUnitService(int phase, String name);
/**
* Logs warning about unexpected problem gathering statistics.
*
* @param cause is the cause of the warning
*/
@LogMessage(level = WARN)
@Message(id = 12, value = "Unexpected problem gathering statistics")
void unexpectedStatisticsProblem(@Cause RuntimeException cause);
// /**
// * Creates an exception indicating the inability ot add the integration, represented by the {@code name} parameter,
// * module to the deployment.
// *
// * @param cause the cause of the error.
// * @param name the name of the integration.
// * @return a {@link RuntimeException} for the error.
// */
//@Message(id = 13, value = "Could not add %s integration module to deployment")
// RuntimeException cannotAddIntegration(@Cause Throwable cause, String name);
// /**
// * Creates an exception indicating the input stream reference cannot be changed.
// *
// * @return an {@link IllegalArgumentException} for the error.
// */
//@Message(id = 14, value = "Cannot change input stream reference.")
//IllegalArgumentException cannotChangeInputStream();
/**
* Creates an exception indicating the entity manager cannot be closed when it is managed by the container.
*
* @return an {@link IllegalStateException} for the error.
*/
@Message(id = 15, value = "Container managed entity manager can only be closed by the container " +
"(will happen when @remove method is invoked on containing SFSB)")
IllegalStateException cannotCloseContainerManagedEntityManager();
// /**
// * Creates an exception indicating only ExtendedEntityMangers can be closed.
// *
// * @param entityManagerTypeName the entity manager type name.
// * @return a {@link RuntimeException} for the error.
// */
//@Message(id = 16, value = "Can only close SFSB XPC entity manager that are instances of ExtendedEntityManager %s")
//RuntimeException cannotCloseNonExtendedEntityManager(String entityManagerTypeName);
/**
* Creates an exception indicating the transactional entity manager cannot be closed when it is managed by the
* container.
*
* @return an {@link IllegalStateException} for the error.
*/
@Message(id = 17, value = "Container managed entity manager can only be closed by the container " +
"(auto-cleared at tx/invocation end and closed when owning component is closed.)")
IllegalStateException cannotCloseTransactionContainerEntityManger();
/**
* Creates an exception indicating the inability to create an instance of the adapter class represented by the
* {@code className} parameter.
*
* @param cause the cause of the error.
* @param className the adapter class name.
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 18, value = "Could not create instance of adapter class '%s'")
DeploymentUnitProcessingException cannotCreateAdapter(@Cause Throwable cause, String className);
/**
* Creates an exception indicating the application could not be deployed with the persistence provider, represented
* by the {@code providerName} parameter, packaged.
*
* @param cause the cause of the error.
* @param providerName the persistence provider.
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 19, value = "Could not deploy application packaged persistence provider '%s'")
DeploymentUnitProcessingException cannotDeployApp(@Cause Throwable cause, String providerName);
/**
* Creates an exception indicating a failure to get the Hibernate session factory from the entity manager.
*
* @param cause the cause of the error.
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 20, value = "Couldn't get Hibernate session factory from entity manager")
RuntimeException cannotGetSessionFactory(@Cause Throwable cause);
/**
* A message indicating the inability to inject a
* {@link jakarta.persistence.spi.PersistenceUnitTransactionType#RESOURCE_LOCAL} container managed EntityManager
* using the {@link jakarta.persistence.PersistenceContext} annotation.
*
* @return the message.
*/
@Message(id = 21, value = "Cannot inject RESOURCE_LOCAL container managed EntityManagers using @PersistenceContext")
String cannotInjectResourceLocalEntityManager();
// /**
// * Creates an exception indicating the inability to inject a
// * {@link jakarta.persistence.spi.PersistenceUnitTransactionType#RESOURCE_LOCAL} entity manager, represented by the
// * {@code unitName} parameter, using the {@code <persistence-context-ref>}.
// *
// * @param unitName the unit name.
// * @return a {@link DeploymentUnitProcessingException} for the error.
// */
//@Message(id = 22, value = "Cannot inject RESOURCE_LOCAL entity manager %s using <persistence-context-ref>")
//DeploymentUnitProcessingException cannotInjectResourceLocalEntityManager(String unitName);
// /**
// * Creates an exception indicating the persistence provider adapter module, represented by the {@code adapterModule}
// * parameter, had an error loading.
// *
// * @param cause the cause of the error.
// * @param adapterModule the name of the adapter module.
// * @param persistenceProviderClass the persistence provider class.
// * @return a {@link DeploymentUnitProcessingException} for the error.
// */
//@Message(id = 23, value = "Persistence provider adapter module (%s) load error (class %s)")
//DeploymentUnitProcessingException cannotLoadAdapterModule(@Cause Throwable cause, String adapterModule, String persistenceProviderClass);
// /**
// * Creates an exception indicating the entity class could not be loaded with the
// * {@link jakarta.persistence.spi.PersistenceUnitInfo#getClassLoader()}.
// *
// * @param cause the cause of the error.
// * @param className the entity class name.
// * @return a {@link RuntimeException} for the error.
// */
//@Message(id = 24, value = "Could not load entity class '%s' with PersistenceUnitInfo.getClassLoader()")
//RuntimeException cannotLoadEntityClass(@Cause Throwable cause, String className);
/**
* Creates an exception indicating the {@code injectionTypeName} could not be loaded from the Jakarta Persistence modules class
* loader.
*
* @param cause the cause of the error.
* @param injectionTypeName the name of the type.
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 25, value = "Couldn't load %s from Jakarta Persistence modules classloader")
RuntimeException cannotLoadFromJpa(@Cause Throwable cause, String injectionTypeName);
// /**
// * Creates an exception indicating the module, represented by the {@code moduleId} parameter, could not be loaded
// * for the adapter, represented by the {@code name} parameter.
// *
// * @param cause the cause of the error.
// * @param moduleId the module id that was attempting to be loaded.
// * @param name the name of the adapter.
// * @return a {@link RuntimeException} for the error.
// */
//@Message(id = 26, value = "Could not load module %s to add %s adapter to deployment")
//RuntimeException cannotLoadModule(@Cause Throwable cause, ModuleIdentifier moduleId, String name);
/**
* Creates an exception indicating the persistence provider module, represented by the
* {@code persistenceProviderModule} parameter, had an error loading.
*
* @param cause the cause of the error.
* @param persistenceProviderModule the name of the adapter module.
* @param persistenceProviderClass the persistence provider class.
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 27, value = "Persistence provider module load error %s (class %s)")
DeploymentUnitProcessingException cannotLoadPersistenceProviderModule(@Cause Throwable cause, String persistenceProviderModule, String persistenceProviderClass);
// /**
// * Creates an exception indicating the top of the stack could not be replaced because the stack is {@code null}.
// *
// * @return a {@link RuntimeException} for the error.
// */
//@Message(id = 28, value = "Internal error: Cannot replace top of stack as stack is null (same as being empty).")
//RuntimeException cannotReplaceStack();
/**
* Creates an exception indicating that both {@code key1} and {@code key2} cannot be specified for the object.
*
* @param key1 the first key/tag.
* @param value1 the first value.
* @param key2 the second key/tag.
* @param value2 the second value.
* @param parentTag the parent tag.
* @param object the object the values are being specified for.
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 29, value = "Cannot specify both %s (%s) and %s (%s) in %s for %s")
DeploymentUnitProcessingException cannotSpecifyBoth(String key1, Object value1, String key2, Object value2, String parentTag, Object object);
/**
* Creates an exception indicating the extended persistence context for the SFSB already exists.
*
* @param puScopedName the persistence unit name.
* @param existingEntityManager the existing transactional entity manager.
* @param self the entity manager attempting to be created.
* @return an {@link jakarta.ejb.EJBException} for the error.
*/
@Message(id = 30, value = "Found extended persistence context in SFSB invocation call stack but that cannot be used " +
"because the transaction already has a transactional context associated with it. " +
"This can be avoided by changing application code, either eliminate the extended " +
"persistence context or the transactional context. See JPA spec 2.0 section 7.6.3.1. " +
"Scoped persistence unit name=%s, persistence context already in transaction =%s, extended persistence context =%s.")
EJBException cannotUseExtendedPersistenceTransaction(String puScopedName, EntityManager existingEntityManager, EntityManager self);
/**
* Creates an exception indicating the child could not be found on the parent.
*
* @param child the child that could not be found.
* @param parent the parent.
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 31, value = "Could not find child '%s' on '%s'")
RuntimeException childNotFound(String child, VirtualFile parent);
/**
* Creates an exception indicating the class level annotation must provide the parameter specified.
*
* @param annotation the annotation.
* @param className the class name
* @param parameter the parameter.
* @return a string for the error.
*/
@Message(id = 32, value = "Class level %s annotation on class %s must provide a %s")
String classLevelAnnotationParameterRequired(String annotation, String className, String parameter);
/**
* A message indicating that the persistence unit, represented by the {@code path} parameter, could not be found at
* the current deployment unit, represented by the {@code deploymentUnit} parameter.
*
* @param puName the persistence unit name.
* @param deploymentUnit the deployment unit.
* @return the message.
*/
@Message(id = 33, value = "Can't find a persistence unit named %s in %s")
String persistenceUnitNotFound(String puName, DeploymentUnit deploymentUnit);
/**
* Creates an exception indicating that the persistence unit, represented by the {@code path} and {@code puName}
* parameters, could not be found at the current deployment unit, represented by the {@code deploymentUnit}
* parameter.
*
* @param path the path.
* @param puName the persistence unit name.
* @param deploymentUnit the deployment unit.
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 34, value = "Can't find a persistence unit named %s#%s at %s")
IllegalArgumentException persistenceUnitNotFound(String path, String puName, DeploymentUnit deploymentUnit);
// /**
// * Creates an exception indicating the parameter, likely a collection, is empty.
// *
// * @param parameterName the parameter name.
// * @return an {@link IllegalArgumentException} for the error.
// */
//@Message(id = 35, value = "Parameter %s is empty")
//IllegalArgumentException emptyParameter(String parameterName);
/**
* Creates an exception indicating there was an error when trying to get the transaction associated with the
* current thread.
*
* @param cause the cause of the error.
* @return an {@link IllegalStateException} for the error.
*/
@Message(id = 36, value = "An error occurred while getting the transaction associated with the current thread: %s")
IllegalStateException errorGettingTransaction(Exception cause);
/**
* Creates an exception indicating a failure to get the adapter for the persistence provider.
*
* @param className the adapter class name.
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 37, value = "Failed to get adapter for persistence provider '%s'")
DeploymentUnitProcessingException failedToGetAdapter(String className);
/**
* Creates an exception indicating a failure to add the persistence unit service.
*
* @param cause the cause of the error.
* @param puName the persistence unit name.
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 38, value = "Failed to add persistence unit service for %s")
DeploymentUnitProcessingException failedToAddPersistenceUnit(@Cause Throwable cause, String puName);
// /**
// * Creates an exception indicating a failure to get the module for the deployment unit represented by the
// * {@code deploymentUnit} parameter.
// *
// * @param deploymentUnit the deployment unit that failed.
// * @return a {@link DeploymentUnitProcessingException} for the error.
// */
//@Message(id = 39, value = "Failed to get module attachment for %s")
//DeploymentUnitProcessingException failedToGetModuleAttachment(DeploymentUnit deploymentUnit);
/**
* A message indicating a failure to parse the file.
*
* @param file the file that could not be parsed.
* @return the message.
*/
@Message(id = 40, value = "Failed to parse %s")
String failedToParse(VirtualFile file);
/**
* Creates an exception indicating the entity manager factory implementation can only be a Hibernate version.
*
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 41, value = "Can only inject from a Hibernate EntityManagerFactoryImpl")
RuntimeException hibernateOnlyEntityManagerFactory();
// /**
// * Creates an exception indicating the entity manager factory implementation can only be a Hibernate version.
// *
// * @return a {@link RuntimeException} for the error.
// */
//@Message(id = 42, value = "File %s not found")
//RuntimeException fileNotFound(File file);
/**
* Creates an exception indicating the persistence unit name contains an invalid character.
*
* @param persistenceUnitName the persistence unit name.
* @param c the invalid character.
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 43, value = "Persistence unit name (%s) contains illegal '%s' character")
IllegalArgumentException invalidPersistenceUnitName(String persistenceUnitName, char c);
/**
* Creates an exception indicating the (custom) scoped persistence unit name is invalid.
*
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 44, value = "jboss.as.jpa.scopedname hint (%s) contains illegal '%s' character")
IllegalArgumentException invalidScopedName(String persistenceUnitName, char c);
// /**
// * Creates an exception indicating the inability to integrate the module, represented by the {@code integrationName}
// * parameter, to the deployment as it expected a {@link java.net.JarURLConnection}.
// *
// * @param integrationName the name of the integration that could not be integrated.
// * @param connection the invalid connection.
// * @return a {@link RuntimeException} for the error.
// */
//@Message(id = 45, value = "Could not add %s integration module to deployment, did not get expected JarUrlConnection, got %s")
//RuntimeException invalidUrlConnection(String integrationName, URLConnection connection);
//@Message(id = 46, value = "Could not load %s")
//XMLStreamException errorLoadingJBossJPAFile(@Cause Throwable cause, String path);
// /**
// * Creates an exception indicating the persistence unit metadata likely because thread local was not set.
// *
// * @return a {@link RuntimeException} for the error.
// */
//@Message(id = 47, value = "Missing PersistenceUnitMetadata (thread local wasn't set)")
//RuntimeException missingPersistenceUnitMetadata();
/**
* Creates an exception indicating the persistence provider adapter module, represented by the {@code adapterModule}
* parameter, has more than one adapter.
*
* @param adapterModule the adapter module name.
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 48, value = "Persistence provider adapter module (%s) has more than one adapter")
RuntimeException multipleAdapters(String adapterModule);
// /**
// * Creates an exception indicating more than one thread is invoking the stateful session bean at the same time.
// *
// * @param sessionBean the stateful session bean.
// * @return a {@link RuntimeException} for the error.
// */
//@Message(id = 49, value = "More than one thread is invoking stateful session bean '%s' at the same time")
//RuntimeException multipleThreadsInvokingSfsb(Object sessionBean);
// /**
// * Creates an exception indicating more than one thread is using the entity manager instance at the same time.
// *
// * @param entityManager the entity manager.
// * @return a {@link RuntimeException} for the error.
// */
//@Message(id = 50, value = "More than one thread is using EntityManager instance '%s' at the same time")
//RuntimeException multipleThreadsUsingEntityManager(EntityManager entityManager);
// /**
// * Creates an exception indicating the {@code name} was not set in the {@link org.jboss.invocation.InterceptorContext}.
// *
// * @param name the name of the field not set.
// * @param context the context.
// * @return an {@link IllegalArgumentException} for the error.
// */
//@Message(id = 51, value = "%s not set in InterceptorContext: %s")
//IllegalArgumentException notSetInInterceptorContext(String name, InterceptorContext context);
// /**
// * Creates an exception indicating the method is not yet implemented.
// *
// * @return a {@link RuntimeException} for the error.
// */
//@Message(id = 52, value = "Not yet implemented")
//RuntimeException notYetImplemented();
/**
* Creates an exception indicating the {@code description} is {@code null}.
*
* @param description the description of the parameter.
* @param parameterName the parameter name.
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 53, value = "Internal %s error, null %s passed in")
RuntimeException nullParameter(String description, String parameterName);
// /**
// * Creates an exception indicating the variable is {@code null}.
// *
// * @param varName the variable name.
// * @return an {@link IllegalArgumentException} for the error.
// */
//@Message(id = 54, value = "Parameter %s is null")
//IllegalArgumentException nullVar(String varName);
// /**
// * A message indicating the object for the class ({@code cls} has been defined and is not {@code null}.
// *
// * @param cls the class for the object.
// * @param previous the previously defined object.
// * @return the message.
// */
//@Message(id = 55, value = "Previous object for class %s is %s instead of null")
//String objectAlreadyDefined(Class<?> cls, Object previous);
// /**
// * Creates an exception indicating the parameter must be an ExtendedEntityManager
// *
// * @param gotClass
// * @return a {@link RuntimeException} for the error.
// */
//@Message(id = 56, value = "Internal error, expected parameter of type ExtendedEntityManager but instead got %s")
//RuntimeException parameterMustBeExtendedEntityManager(String gotClass);
/**
* Creates an exception indicating the persistence provider could not be found.
*
* @param providerName the provider name.
* @return a {@link jakarta.persistence.PersistenceException} for the error.
*/
@Message(id = 57, value = "PersistenceProvider '%s' not found")
PersistenceException persistenceProviderNotFound(String providerName);
/**
* Creates an exception indicating the relative path could not be found.
*
* @param cause the cause of the error.
* @param path the path that could not be found.
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 58, value = "Could not find relative path: %s")
RuntimeException relativePathNotFound(@Cause Throwable cause, String path);
/**
* A message indicating the annotation is only valid on setter method targets.
*
* @param annotation the annotation.
* @param methodInfo the method information.
* @return the message.
*/
@Message(id = 59, value = "%s injection target is invalid. Only setter methods are allowed: %s")
String setterMethodOnlyAnnotation(String annotation, MethodInfo methodInfo);
/**
* Creates an exception indicating a transaction is required for the operation.
*
* @return a {@link jakarta.persistence.TransactionRequiredException} for the error.
*/
@Message(id = 60, value = "Transaction is required to perform this operation (either use a transaction or extended persistence context)")
TransactionRequiredException transactionRequired();
/**
* JBoss 4 prevented applications from referencing the persistence unit without specifying the pu name, if there
* were multiple persistence unit definitions in the app. JBoss 5 loosened the checking up, to let applications,
* just use any PU definition that they find. For AS7, we are strictly enforcing this again just like we did in
* JBoss 4.
* AS7-2275
*
* @param deploymentUnit the deployment unit.
* @param puCount is number of persistence units defined in application
*
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 61, value = "Persistence unitName was not specified and there are %d persistence unit definitions in application deployment %s."+
" Either change the application deployment to have only one persistence unit definition or specify the unitName for each reference to a persistence unit.")
IllegalArgumentException noPUnitNameSpecifiedAndMultiplePersistenceUnits(int puCount, DeploymentUnit deploymentUnit);
/**
* Creates an exception indicating the persistence provider could not be instantiated ,
*
* @param cause the cause of the error.
* @param providerClassName name of the provider class
*
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 62, value = "Could not create instance of persistence provider class %s")
RuntimeException couldNotCreateInstanceProvider(@Cause Throwable cause, String providerClassName);
/**
* internal error indicating that the number of stateful session beans associated with a
* extended persistence context has reached a negative count.
*
* @return a {@link RuntimeException} for the error
*/
@Message(id = 63, value = "internal error, the number of stateful session beans (%d) associated " +
"with an extended persistence context (%s) cannot be a negative number.")
RuntimeException referenceCountedEntityManagerNegativeCount(int referenceCount, String scopedPuName);
/**
* Can't use a new unsynchronization persistence context when transaction already has a synchronized persistence context.
*
* @param puScopedName the persistence unit name.
* @return an {@link IllegalStateException} for the error.
*/
@Message(id = 64, value =
"Jakarta Transactions transaction already has a 'SynchronizationType.UNSYNCHRONIZED' persistence context (EntityManager) joined to it " +
"but a component with a 'SynchronizationType.SYNCHRONIZED' is now being used. " +
"Change the calling component code to join the persistence context (EntityManager) to the transaction or "+
"change the called component code to also use 'SynchronizationType.UNSYNCHRONIZED'. "+
"See JPA spec 2.1 section 7.6.4.1. " +
"Scoped persistence unit name=%s.")
IllegalStateException badSynchronizationTypeCombination(String puScopedName);
@Message(id = 65, value = "Resources of type %s cannot be registered")
UnsupportedOperationException resourcesOfTypeCannotBeRegistered(String key);
@Message(id = 66, value = "Resources of type %s cannot be removed")
UnsupportedOperationException resourcesOfTypeCannotBeRemoved(String key);
/**
* Only one persistence provider adapter per (persistence provider or application) classloader is allowed
*
* @param classloader offending classloader
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 67, value = "Classloader '%s' has more than one Persistence provider adapter")
RuntimeException classloaderHasMultipleAdapters(String classloader);
// /**
// * Likely cause is that the application deployment did not complete successfully
// *
// * @param scopedPuName
// * @return
// */
// @Message(id = 68, value = "Persistence unit '%s' is not available")
// IllegalStateException PersistenceUnitNotAvailable(String scopedPuName);
/**
* persistence provider adaptor module load error
*
* @param cause the cause of the error.
* @param adaptorModule name of persistence provider adaptor module that couldn't be loaded.
* @return the exception
*/
@Message(id = 69, value = "Persistence provider adapter module load error %s")
DeploymentUnitProcessingException persistenceProviderAdaptorModuleLoadError(@Cause Throwable cause, String adaptorModule);
/**
* extended persistence context can only be used within a stateful session bean. WFLY-69
*
* @param scopedPuName name of the persistence unit
* @return the exception
*/
@Message(id = 70, value = "A container-managed extended persistence context can only be initiated within the scope of a stateful session bean (persistence unit '%s').")
IllegalStateException xpcOnlyFromSFSB(String scopedPuName);
@Message(id = 71, value = "Deployment '%s' specified more than one Hibernate Search module name ('%s','%s')")
DeploymentUnitProcessingException differentSearchModuleDependencies(String deployment, String searchModuleName1, String searchModuleName2);
// id = 72, value = "Could not obtain TransactionListenerRegistry from transaction manager")
@Message(id = 73, value = "Transformation of class %s failed")
IllegalStateException invalidClassFormat(@Cause Exception cause, String className);
// @Message(id = 74, value = "Deprecated Hibernate51CompatibilityTransformer is enabled for all application deployments.")
/**
* Creates an exception indicating the persistence provider integrator module, represented by the
* {@code persistenceProviderModule} parameter, had an error loading.
*
* @param cause the cause of the error.
* @param persistenceProviderModule the name of the adapter module.
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 74, value = "Persistence provider integrator module load error for %s")
DeploymentUnitProcessingException cannotLoadPersistenceProviderIntegratorModule(@Cause Throwable cause, String persistenceProviderModule);
}
| 36,456 | 46.163001 | 172 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/validator/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.jpa.validator;
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,056 | 39.979798 | 127 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/interceptor/SFSBPreCreateInterceptor.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.jpa.interceptor;
import org.jboss.as.jpa.container.SFSBCallStack;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
/**
* Runs early in the SFSB chain, to make sure that SFSB creation operations can inherit extended persistence contexts properly
* <p/>
*
* @author Stuart Douglas
*/
public class SFSBPreCreateInterceptor implements Interceptor {
public static final InterceptorFactory FACTORY = new ImmediateInterceptorFactory(new SFSBPreCreateInterceptor());
@Override
public Object processInvocation(InterceptorContext interceptorContext) throws Exception {
try {
// beginSfsbCreation() will setup a "creation time" thread local store for tracking references to extended
// persistence contexts.
SFSBCallStack.beginSfsbCreation();
return interceptorContext.proceed();
} finally {
// bean PostCreate event lifecycle has already completed.
// endSfsbCreation() will clear the thread local knowledge of "creation time" referenced extended
// persistence contexts.
SFSBCallStack.endSfsbCreation();
}
}
private SFSBPreCreateInterceptor() {
}
}
| 2,384 | 39.423729 | 126 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/interceptor/SFSBCreateInterceptor.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.jpa.interceptor;
import java.util.HashMap;
import java.util.Map;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.as.jpa.container.ExtendedEntityManager;
import org.jboss.as.jpa.container.CreatedEntityManagers;
import org.jboss.as.naming.ImmediateManagedReference;
import org.jboss.as.naming.ManagedReference;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
/**
* For SFSB life cycle management.
* Handles the (@PostConstruct time) creation of the extended persistence context (XPC).
*
* @author Scott Marlow
*/
public class SFSBCreateInterceptor implements Interceptor {
public static final InterceptorFactory FACTORY = new ImmediateInterceptorFactory(new SFSBCreateInterceptor());
@Override
public Object processInvocation(InterceptorContext interceptorContext) throws Exception {
ComponentInstance componentInstance = interceptorContext.getPrivateData(ComponentInstance.class);
Map<String, ExtendedEntityManager> entityManagers = null;
if(componentInstance.getInstanceData(SFSBInvocationInterceptor.CONTEXT_KEY) == null) {
// Get all of the extended persistence contexts in use by the bean (some of which may of been inherited from
// other beans).
entityManagers = new HashMap<String, ExtendedEntityManager>();
componentInstance.setInstanceData(SFSBInvocationInterceptor.CONTEXT_KEY, new ImmediateManagedReference(entityManagers));
} else {
ManagedReference entityManagerRef = (ManagedReference) componentInstance.getInstanceData(SFSBInvocationInterceptor.CONTEXT_KEY);
entityManagers = (Map<String, ExtendedEntityManager>)entityManagerRef.getInstance();
}
final ExtendedEntityManager[] ems = CreatedEntityManagers.getDeferredEntityManagers();
for (ExtendedEntityManager e : ems) {
entityManagers.put(e.getScopedPuName(), e);
}
return interceptorContext.proceed();
}
}
| 3,166 | 45.573529 | 140 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/interceptor/SFSBInvocationInterceptor.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.jpa.interceptor;
import java.util.Map;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.as.jpa.container.ExtendedEntityManager;
import org.jboss.as.jpa.container.SFSBCallStack;
import org.jboss.as.naming.ManagedReference;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
/**
* Stateful session bean Invocation interceptor that is responsible for the SFSBCallStack being set for each
* SFSB invocation that Jakarta Persistence is interested in.
*
* @author Scott Marlow
*/
public class SFSBInvocationInterceptor implements Interceptor {
public static final String CONTEXT_KEY = "org.jboss.as.jpa.InterceptorContextKey";
public static final InterceptorFactory FACTORY = new ImmediateInterceptorFactory(new SFSBInvocationInterceptor());
@Override
public Object processInvocation(InterceptorContext context) throws Exception {
final ComponentInstance componentInstance = context.getPrivateData(ComponentInstance.class);
ManagedReference entityManagerRef = (ManagedReference) componentInstance.getInstanceData(SFSBInvocationInterceptor.CONTEXT_KEY);
if(entityManagerRef != null) {
Map<String, ExtendedEntityManager> entityManagers = (Map<String, ExtendedEntityManager>) entityManagerRef.getInstance();
SFSBCallStack.pushCall(entityManagers);
}
try {
return context.proceed(); // call the next interceptor or target
} finally {
if(entityManagerRef != null) {
SFSBCallStack.popCall();
}
}
}
}
| 2,761 | 41.492308 | 136 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/interceptor/SBInvocationInterceptor.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.jpa.interceptor;
import org.jboss.as.jpa.container.NonTxEmCloser;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
/**
* Session bean Invocation interceptor.
* Used for stateless session bean invocations to allow NonTxEmCloser to close the
* underlying entity manager after a non-transactional invocation.
*
* @author Scott Marlow
*/
public class SBInvocationInterceptor implements Interceptor {
public static final InterceptorFactory FACTORY = new ImmediateInterceptorFactory(new SBInvocationInterceptor());
@Override
public Object processInvocation(InterceptorContext context) throws Exception {
NonTxEmCloser.pushCall();
try {
return context.proceed(); // call the next interceptor or target
} finally {
NonTxEmCloser.popCall();
}
}
private SBInvocationInterceptor() {
}
}
| 2,060 | 35.803571 | 116 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/interceptor/SFSBDestroyInterceptor.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.jpa.interceptor;
import java.util.Map;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.as.jpa.container.ExtendedEntityManager;
import org.jboss.as.naming.ManagedReference;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
/**
* For SFSB life cycle management.
* Handles the closing of XPC after last SFSB using it is destroyed.
*
* @author Scott Marlow
*/
public class SFSBDestroyInterceptor implements Interceptor {
public static final InterceptorFactory FACTORY = new ImmediateInterceptorFactory(new SFSBDestroyInterceptor());
@Override
public Object processInvocation(InterceptorContext interceptorContext) throws Exception {
final ComponentInstance componentInstance = interceptorContext.getPrivateData(ComponentInstance.class);
try {
return interceptorContext.proceed();
} finally {
ManagedReference entityManagerRef = (ManagedReference) componentInstance.getInstanceData(SFSBInvocationInterceptor.CONTEXT_KEY);
if(entityManagerRef != null) {
Map<String, ExtendedEntityManager> entityManagers = (Map<String, ExtendedEntityManager>) entityManagerRef.getInstance();
for(Map.Entry<String, ExtendedEntityManager> entry : entityManagers.entrySet()) {
// close all extended persistence contexts that are referenced by the bean being destroyed
entry.getValue().refCountedClose();
}
}
}
}
}
| 2,692 | 42.435484 | 140 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/interceptor/WebNonTxEmCloserAction.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.jpa.interceptor;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.jboss.as.jpa.container.NonTxEmCloser;
import org.jboss.as.server.deployment.SetupAction;
import org.jboss.msc.service.ServiceName;
/**
* Web setup action that closes the entity managers created during the servlet invocation.
* This provides a thread local collection of all created transactional entity managers (created without a
* transaction).
*
* @author Scott Marlow
*/
public class WebNonTxEmCloserAction implements SetupAction {
@Override
public void setup(final Map<String, Object> properties) {
NonTxEmCloser.pushCall(); // create a thread local place to hold created transactional entity managers
}
@Override
public void teardown(final Map<String, Object> properties) {
NonTxEmCloser.popCall(); // close any transactional entity managers that were created without a Jakarta Transactions transaction.
}
@Override
public int priority() {
return 0;
}
@Override
public Set<ServiceName> dependencies() {
return Collections.emptySet();
}
}
| 2,193 | 34.387097 | 140 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/service/JPAService.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.jpa.service;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
import java.util.HashSet;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Set;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.descriptions.ResourceDescriptionResolver;
import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.jpa.config.ExtendedPersistenceInheritance;
import org.jboss.as.jpa.management.DynamicManagementStatisticsResource;
import org.jboss.as.jpa.management.EntityManagerFactoryLookup;
import org.jboss.as.jpa.management.ManagementResourceDefinition;
import org.jboss.as.jpa.processor.CacheDeploymentHelper;
import org.jboss.as.jpa.processor.PersistenceUnitServiceHandler;
import org.jboss.as.jpa.subsystem.JPAExtension;
import org.jboss.as.jpa.util.JPAServiceNames;
import org.jboss.as.server.deployment.DeploymentModelUtils;
import org.jboss.as.server.deployment.DeploymentUnit;
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.jipijapa.management.spi.Statistics;
import org.jipijapa.plugin.spi.ManagementAdaptor;
/**
* represents the global Jakarta Persistence Service
*
* @author Scott Marlow
*/
public class JPAService implements Service<Void> {
public static final ServiceName SERVICE_NAME = JPAServiceNames.getJPAServiceName();
private static volatile String defaultDataSourceName = null;
private static volatile ExtendedPersistenceInheritance defaultExtendedPersistenceInheritance = null;
private static final Set<String> existingResourceDescriptionResolver = new HashSet<>();
private final CacheDeploymentHelper cacheDeploymentHelper = new CacheDeploymentHelper();
public static String getDefaultDataSourceName() {
ROOT_LOGGER.tracef("JPAService.getDefaultDataSourceName() == %s", JPAService.defaultDataSourceName);
return defaultDataSourceName;
}
public static void setDefaultDataSourceName(String dataSourceName) {
ROOT_LOGGER.tracef("JPAService.setDefaultDataSourceName(%s), previous value = %s", dataSourceName, JPAService.defaultDataSourceName);
defaultDataSourceName = dataSourceName;
}
public static ExtendedPersistenceInheritance getDefaultExtendedPersistenceInheritance() {
ROOT_LOGGER.tracef("JPAService.getDefaultExtendedPersistenceInheritance() == %s", defaultExtendedPersistenceInheritance.toString());
return defaultExtendedPersistenceInheritance;
}
public static void setDefaultExtendedPersistenceInheritance(ExtendedPersistenceInheritance defaultExtendedPersistenceInheritance) {
ROOT_LOGGER.tracef("JPAService.setDefaultExtendedPersistenceInheritance(%s)", defaultExtendedPersistenceInheritance.toString());
JPAService.defaultExtendedPersistenceInheritance = defaultExtendedPersistenceInheritance;
}
public static void addService(
final ServiceTarget target,
final String defaultDataSourceName,
final ExtendedPersistenceInheritance defaultExtendedPersistenceInheritance) {
JPAService jpaService = new JPAService();
setDefaultDataSourceName(defaultDataSourceName);
setDefaultExtendedPersistenceInheritance(defaultExtendedPersistenceInheritance);
final ServiceBuilder sb = target.addService(SERVICE_NAME, jpaService);
sb.setInitialMode(ServiceController.Mode.ACTIVE);
sb.requires(JPAUserTransactionListenerService.SERVICE_NAME);
sb.install();
}
/**
* Create single instance of management statistics resource per managementAdaptor version.
*
* ManagementAccess
*
* The persistence provider and jipijapa adapters will be in the same classloader,
* either a static module or included directly in the application. Those are the two supported use
* cases for management of deployment persistence units also.
*
* From a management point of view, the requirements are:
* 1. show management statistics for static persistence provider modules and applications that have
* their own persistence provider module.
*
* 2. persistence provider adapters will provide a unique key that identifies the management version of supported
* management statistics/operations. For example, Hibernate 3.x might be 1.0, Hibernate 4.1/4.2 might
* be version 2.0 and Hibernate 4.3 could be 2.0 also as long as its compatible (same stats) with 4.1/4.2.
* Eventually, a Hibernate (later version) change in statistics is likely to happen, the management version
* will be incremented.
*
*
* @param managementAdaptor the management adaptor that will provide statistics
* @param scopedPersistenceUnitName name of the persistence unit
* @param deploymentUnit deployment unit for the deployment requesting a resource
* @return the management resource
*/
public static Resource createManagementStatisticsResource(
final ManagementAdaptor managementAdaptor,
final String scopedPersistenceUnitName,
final DeploymentUnit deploymentUnit) {
synchronized (existingResourceDescriptionResolver) {
final EntityManagerFactoryLookup entityManagerFactoryLookup = new EntityManagerFactoryLookup();
final Statistics statistics = managementAdaptor.getStatistics();
if (false == existingResourceDescriptionResolver.contains(managementAdaptor.getVersion())) {
// setup statistics (this used to be part of Jakarta Persistence subsystem startup)
ResourceDescriptionResolver resourceDescriptionResolver = new StandardResourceDescriptionResolver(
statistics.getResourceBundleKeyPrefix(), statistics.getResourceBundleName(), statistics.getClass().getClassLoader()){
private ResourceDescriptionResolver fallback = JPAExtension.getResourceDescriptionResolver();
//add a fallback in case provider doesn't have all properties properly defined
@Override
public String getResourceAttributeDescription(String attributeName, Locale locale, ResourceBundle bundle) {
if (bundle.containsKey(getBundleKey(attributeName))) {
return super.getResourceAttributeDescription(attributeName, locale, bundle);
}else{
return fallback.getResourceAttributeDescription(attributeName, locale, fallback.getResourceBundle(locale));
}
}
};
PathElement subsystemPE = PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, JPAExtension.SUBSYSTEM_NAME);
ManagementResourceRegistration deploymentResourceRegistration = deploymentUnit.getAttachment(DeploymentModelUtils.MUTABLE_REGISTRATION_ATTACHMENT);
ManagementResourceRegistration deploymentSubsystemRegistration =
deploymentResourceRegistration.getSubModel(PathAddress.pathAddress(subsystemPE));
ManagementResourceRegistration subdeploymentSubsystemRegistration =
deploymentResourceRegistration.getSubModel(PathAddress.pathAddress(PathElement.pathElement(ModelDescriptionConstants.SUBDEPLOYMENT), subsystemPE));
ManagementResourceRegistration providerResource = deploymentSubsystemRegistration.registerSubModel(
new ManagementResourceDefinition(PathElement.pathElement(managementAdaptor.getIdentificationLabel()), resourceDescriptionResolver, statistics, entityManagerFactoryLookup));
providerResource.registerReadOnlyAttribute(PersistenceUnitServiceHandler.SCOPED_UNIT_NAME, null);
providerResource = subdeploymentSubsystemRegistration.registerSubModel(
new ManagementResourceDefinition(PathElement.pathElement(managementAdaptor.getIdentificationLabel()), resourceDescriptionResolver, statistics, entityManagerFactoryLookup));
providerResource.registerReadOnlyAttribute(PersistenceUnitServiceHandler.SCOPED_UNIT_NAME, null);
existingResourceDescriptionResolver.add(managementAdaptor.getVersion());
}
// create (per deployment) dynamic Resource implementation that can reflect the deployment specific names (e.g. Jakarta Persistence entity classname/Hibernate region name)
return new DynamicManagementStatisticsResource(statistics, scopedPersistenceUnitName, managementAdaptor.getIdentificationLabel(), entityManagerFactoryLookup);
}
}
@Override
public void start(StartContext startContext) throws StartException {
cacheDeploymentHelper.register();
}
@Override
public void stop(StopContext stopContext) {
cacheDeploymentHelper.unregister();
synchronized (existingResourceDescriptionResolver) {
existingResourceDescriptionResolver.clear();
}
}
@Override
public Void getValue() throws IllegalStateException, IllegalArgumentException {
return null;
}
}
| 10,792 | 52.965 | 196 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/service/JPAUserTransactionListenerService.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.jpa.service;
import org.jboss.as.jpa.container.JPAUserTransactionListener;
import org.jboss.as.txn.service.UserTransactionRegistryService;
import org.jboss.msc.service.Service;
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;
import org.jboss.tm.usertx.UserTransactionRegistry;
/**
* listen for user transaction begin events
*
* @author Scott Marlow
*/
public class JPAUserTransactionListenerService implements Service<Void> {
public static final ServiceName SERVICE_NAME = ServiceName.JBOSS.append("jpa-usertransactionlistener");
private final InjectedValue<UserTransactionRegistry> userTransactionRegistryInjectedValue = new InjectedValue<UserTransactionRegistry>();
private volatile JPAUserTransactionListener jpaUserTransactionListener = null;
@Override
public void start(StartContext context) throws StartException {
jpaUserTransactionListener = new JPAUserTransactionListener();
userTransactionRegistryInjectedValue.getValue().addListener(jpaUserTransactionListener);
}
@Override
public void stop(StopContext context) {
userTransactionRegistryInjectedValue.getValue().removeListener(jpaUserTransactionListener);
jpaUserTransactionListener = null;
}
@Override
public Void getValue() throws IllegalStateException, IllegalArgumentException {
return null;
}
public InjectedValue<UserTransactionRegistry> getUserTransactionRegistryInjectedValue() {
return userTransactionRegistryInjectedValue;
}
public static void addService(ServiceTarget target) {
JPAUserTransactionListenerService jpaUserTransactionListenerService = new JPAUserTransactionListenerService();
target.addService(SERVICE_NAME, jpaUserTransactionListenerService)
.addDependency(UserTransactionRegistryService.SERVICE_NAME, UserTransactionRegistry.class, jpaUserTransactionListenerService.getUserTransactionRegistryInjectedValue())
.setInitialMode(ServiceController.Mode.ACTIVE)
.install();
}
}
| 3,352 | 41.443038 | 183 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/service/PersistenceUnitServiceImpl.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.jpa.service;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import jakarta.enterprise.inject.spi.BeanManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.spi.PersistenceProvider;
import javax.sql.DataSource;
import jakarta.validation.ValidatorFactory;
import org.jboss.as.jpa.beanmanager.BeanManagerAfterDeploymentValidation;
import org.jboss.as.jpa.beanmanager.ProxyBeanManager;
import org.jboss.as.jpa.classloader.TempClassLoaderFactoryImpl;
import org.jboss.as.jpa.spi.PersistenceUnitService;
import org.jboss.as.jpa.subsystem.PersistenceUnitRegistryImpl;
import org.jboss.as.jpa.util.JPAServiceNames;
import org.jboss.as.naming.WritableServiceBasedNamingStore;
import org.jboss.as.server.deployment.SetupAction;
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;
import org.jipijapa.plugin.spi.EntityManagerFactoryBuilder;
import org.jipijapa.plugin.spi.PersistenceProviderAdaptor;
import org.jipijapa.plugin.spi.PersistenceProviderIntegratorAdaptor;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
import org.wildfly.security.manager.action.GetAccessControlContextAction;
import org.wildfly.security.manager.WildFlySecurityManager;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
/**
* Persistence Unit service that is created for each deployed persistence unit that will be referenced by the
* persistence context/unit injector.
* <p/>
* The persistence unit scoped
*
* @author Scott Marlow
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class PersistenceUnitServiceImpl implements Service<PersistenceUnitService>, PersistenceUnitService {
private final InjectedValue<DataSource> jtaDataSource = new InjectedValue<DataSource>();
private final InjectedValue<DataSource> nonJtaDataSource = new InjectedValue<DataSource>();
private final InjectedValue<ExecutorService> executorInjector = new InjectedValue<ExecutorService>();
private final InjectedValue<BeanManager> beanManagerInjector = new InjectedValue<>();
private final InjectedValue<PhaseOnePersistenceUnitServiceImpl> phaseOnePersistenceUnitServiceInjectedValue = new InjectedValue<>();
private static final String EE_NAMESPACE = BeanManager.class.getName().startsWith("javax") ? "javax" : "jakarta";
private static final String CDI_BEAN_MANAGER = ".persistence.bean.manager";
private static final String VALIDATOR_FACTORY = ".persistence.validation.factory";
private final Map properties;
private final PersistenceProviderAdaptor persistenceProviderAdaptor;
private final List<PersistenceProviderIntegratorAdaptor> persistenceProviderIntegratorAdaptors;
private final PersistenceProvider persistenceProvider;
private final PersistenceUnitMetadata pu;
private final ClassLoader classLoader;
private final PersistenceUnitRegistryImpl persistenceUnitRegistry;
private final ServiceName deploymentUnitServiceName;
private final ValidatorFactory validatorFactory;
private final BeanManagerAfterDeploymentValidation beanManagerAfterDeploymentValidation;
private volatile EntityManagerFactory entityManagerFactory;
private volatile ProxyBeanManager proxyBeanManager;
private final SetupAction javaNamespaceSetup;
public PersistenceUnitServiceImpl(
final Map properties,
final ClassLoader classLoader,
final PersistenceUnitMetadata pu,
final PersistenceProviderAdaptor persistenceProviderAdaptor,
final List<PersistenceProviderIntegratorAdaptor> persistenceProviderIntegratorAdaptors,
final PersistenceProvider persistenceProvider,
final PersistenceUnitRegistryImpl persistenceUnitRegistry,
final ServiceName deploymentUnitServiceName,
final ValidatorFactory validatorFactory, SetupAction javaNamespaceSetup,
BeanManagerAfterDeploymentValidation beanManagerAfterDeploymentValidation) {
this.properties = properties;
this.pu = pu;
this.persistenceProviderAdaptor = persistenceProviderAdaptor;
this.persistenceProviderIntegratorAdaptors = persistenceProviderIntegratorAdaptors;
this.persistenceProvider = persistenceProvider;
this.classLoader = classLoader;
this.persistenceUnitRegistry = persistenceUnitRegistry;
this.deploymentUnitServiceName = deploymentUnitServiceName;
this.validatorFactory = validatorFactory;
this.javaNamespaceSetup = javaNamespaceSetup;
this.beanManagerAfterDeploymentValidation = beanManagerAfterDeploymentValidation;
}
@Override
public void start(final StartContext context) throws StartException {
final ExecutorService executor = executorInjector.getValue();
final AccessControlContext accessControlContext =
AccessController.doPrivileged(GetAccessControlContextAction.getInstance());
final Runnable task = new Runnable() {
// run async in a background thread
@Override
public void run() {
PrivilegedAction<Void> privilegedAction =
new PrivilegedAction<Void>() {
// run as security privileged action
@Override
public Void run() {
ClassLoader old = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
if(javaNamespaceSetup != null) {
javaNamespaceSetup.setup(Collections.<String, Object>emptyMap());
}
try {
PhaseOnePersistenceUnitServiceImpl phaseOnePersistenceUnitService = phaseOnePersistenceUnitServiceInjectedValue.getOptionalValue();
WritableServiceBasedNamingStore.pushOwner(deploymentUnitServiceName);
Object wrapperBeanManagerLifeCycle=null;
// as per Jakarta Persistence specification contract, always pass ValidatorFactory in via standard property before
// creating container EntityManagerFactory
if (validatorFactory != null) {
properties.put(EE_NAMESPACE + VALIDATOR_FACTORY, validatorFactory);
}
// handle phase 2 of 2 of bootstrapping the persistence unit
if (phaseOnePersistenceUnitService != null) {
ROOT_LOGGER.startingPersistenceUnitService(2, pu.getScopedPersistenceUnitName());
// indicate that the second phase of bootstrapping the persistence unit has started
phaseOnePersistenceUnitService.setSecondPhaseStarted(true);
if (beanManagerInjector.getOptionalValue() != null) {
wrapperBeanManagerLifeCycle = phaseOnePersistenceUnitService.getBeanManagerLifeCycle();
// update the bean manager proxy to the actual Jakarta Contexts and Dependency Injection bean manager
proxyBeanManager = phaseOnePersistenceUnitService.getBeanManager();
proxyBeanManager.setDelegate(beanManagerInjector.getOptionalValue());
}
EntityManagerFactoryBuilder emfBuilder = phaseOnePersistenceUnitService.getEntityManagerFactoryBuilder();
// always pass the ValidatorFactory before starting the second phase of the
// persistence unit bootstrap.
if (validatorFactory != null) {
emfBuilder.withValidatorFactory(validatorFactory);
}
// get the EntityManagerFactory from the second phase of the persistence unit bootstrap
entityManagerFactory = emfBuilder.build();
} else {
ROOT_LOGGER.startingService("Persistence Unit", pu.getScopedPersistenceUnitName());
// start the persistence unit in one pass (1 of 1)
pu.setTempClassLoaderFactory(new TempClassLoaderFactoryImpl(classLoader));
pu.setJtaDataSource(jtaDataSource.getOptionalValue());
pu.setNonJtaDataSource(nonJtaDataSource.getOptionalValue());
if (beanManagerInjector.getOptionalValue() != null) {
proxyBeanManager = new ProxyBeanManager();
proxyBeanManager.setDelegate(beanManagerInjector.getOptionalValue());
wrapperBeanManagerLifeCycle = persistenceProviderAdaptor.beanManagerLifeCycle(proxyBeanManager);
if (wrapperBeanManagerLifeCycle != null) {
// pass the wrapper object representing the bean manager life cycle object
properties.put(EE_NAMESPACE + CDI_BEAN_MANAGER, wrapperBeanManagerLifeCycle);
}
else {
properties.put(EE_NAMESPACE + CDI_BEAN_MANAGER, proxyBeanManager);
}
}
entityManagerFactory = createContainerEntityManagerFactory();
}
persistenceUnitRegistry.add(getScopedPersistenceUnitName(), getValue());
if(wrapperBeanManagerLifeCycle != null) {
beanManagerAfterDeploymentValidation.register(persistenceProviderAdaptor, wrapperBeanManagerLifeCycle);
}
context.complete();
} catch (Throwable t) {
context.failed(new StartException(t));
} finally {
Thread.currentThread().setContextClassLoader(old);
pu.setAnnotationIndex(null); // close reference to Annotation Index
pu.setTempClassLoaderFactory(null); // release the temp classloader factory (only needed when creating the EMF)
WritableServiceBasedNamingStore.popOwner();
if (javaNamespaceSetup != null) {
javaNamespaceSetup.teardown(Collections.<String, Object>emptyMap());
}
}
return null;
}
};
WildFlySecurityManager.doChecked(privilegedAction, accessControlContext);
}
};
try {
executor.execute(task);
} catch (RejectedExecutionException e) {
task.run();
} finally {
context.asynchronous();
}
}
@Override
public void stop(final StopContext context) {
final ExecutorService executor = executorInjector.getValue();
final AccessControlContext accessControlContext =
AccessController.doPrivileged(GetAccessControlContextAction.getInstance());
final Runnable task = new Runnable() {
// run async in a background thread
@Override
public void run() {
PrivilegedAction<Void> privilegedAction =
new PrivilegedAction<Void>() {
// run as security privileged action
@Override
public Void run() {
if (phaseOnePersistenceUnitServiceInjectedValue.getOptionalValue() != null) {
ROOT_LOGGER.stoppingPersistenceUnitService(2, pu.getScopedPersistenceUnitName());
} else {
ROOT_LOGGER.stoppingService("Persistence Unit", pu.getScopedPersistenceUnitName());
}
ClassLoader old = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
if(javaNamespaceSetup != null) {
javaNamespaceSetup.setup(Collections.<String, Object>emptyMap());
}
try {
if (entityManagerFactory != null) {
// protect against race condition reported by WFLY-11563
synchronized (this) {
if (entityManagerFactory != null) {
WritableServiceBasedNamingStore.pushOwner(deploymentUnitServiceName);
try {
if (entityManagerFactory.isOpen()) {
entityManagerFactory.close();
}
} catch (Throwable t) {
ROOT_LOGGER.failedToStopPUService(t, pu.getScopedPersistenceUnitName());
} finally {
entityManagerFactory = null;
pu.setTempClassLoaderFactory(null);
WritableServiceBasedNamingStore.popOwner();
persistenceUnitRegistry.remove(getScopedPersistenceUnitName());
}
}
}
}
} finally {
Thread.currentThread().setContextClassLoader(old);
if (javaNamespaceSetup != null) {
javaNamespaceSetup.teardown(Collections.<String, Object>emptyMap());
}
}
if (proxyBeanManager != null) {
synchronized (this) {
if (proxyBeanManager != null) {
proxyBeanManager.setDelegate(null);
proxyBeanManager = null;
}
}
}
context.complete();
return null;
}
};
WildFlySecurityManager.doChecked(privilegedAction, accessControlContext);
}
};
try {
executor.execute(task);
} catch (RejectedExecutionException e) {
task.run();
} finally {
context.asynchronous();
}
}
public InjectedValue<ExecutorService> getExecutorInjector() {
return executorInjector;
}
@Override
public PersistenceUnitServiceImpl getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
/**
* Get the entity manager factory
*
* @return the entity manager factory
*/
@Override
public EntityManagerFactory getEntityManagerFactory() {
return entityManagerFactory;
}
@Override
public String getScopedPersistenceUnitName() {
return pu.getScopedPersistenceUnitName();
}
public Injector<DataSource> getJtaDataSourceInjector() {
return jtaDataSource;
}
public Injector<DataSource> getNonJtaDataSourceInjector() {
return nonJtaDataSource;
}
public Injector<BeanManager> getBeanManagerInjector() {
return beanManagerInjector;
}
/**
* Returns the Persistence Unit service name used for creation or lookup.
* The service name contains the unique fully scoped persistence unit name
*
* @param pu persistence unit definition
* @return
*/
public static ServiceName getPUServiceName(PersistenceUnitMetadata pu) {
return JPAServiceNames.getPUServiceName(pu.getScopedPersistenceUnitName());
}
public static ServiceName getPUServiceName(String scopedPersistenceUnitName) {
return JPAServiceNames.getPUServiceName(scopedPersistenceUnitName);
}
/**
* Create EE container entity manager factory
*
* @return EntityManagerFactory
*/
private EntityManagerFactory createContainerEntityManagerFactory() {
persistenceProviderAdaptor.beforeCreateContainerEntityManagerFactory(pu);
try {
ROOT_LOGGER.tracef("calling createContainerEntityManagerFactory for pu=%s with integration properties=%s, application properties=%s",
pu.getScopedPersistenceUnitName(), properties, pu.getProperties());
return persistenceProvider.createContainerEntityManagerFactory(pu, properties);
} finally {
persistenceProviderAdaptor.afterCreateContainerEntityManagerFactory(pu);
for (PersistenceProviderIntegratorAdaptor adaptor : persistenceProviderIntegratorAdaptors) {
adaptor.afterCreateContainerEntityManagerFactory(pu);
}
}
}
public Injector<PhaseOnePersistenceUnitServiceImpl> getPhaseOnePersistenceUnitServiceImplInjector() {
return phaseOnePersistenceUnitServiceInjectedValue;
}
}
| 20,419 | 52.038961 | 167 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/service/PhaseOnePersistenceUnitServiceImpl.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.jpa.service;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import jakarta.enterprise.inject.spi.BeanManager;
import javax.sql.DataSource;
import org.jboss.as.jpa.beanmanager.ProxyBeanManager;
import org.jboss.as.jpa.classloader.TempClassLoaderFactoryImpl;
import org.jboss.as.naming.WritableServiceBasedNamingStore;
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;
import org.jipijapa.plugin.spi.EntityManagerFactoryBuilder;
import org.jipijapa.plugin.spi.PersistenceProviderAdaptor;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
import org.jipijapa.plugin.spi.TwoPhaseBootstrapCapable;
import org.wildfly.security.manager.action.GetAccessControlContextAction;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Handles the first phase of the EntityManagerFactoryBuilder for starting the Persistence Unit service.
* The PersistenceUnitServiceImpl service handles the second phase and will not start until after PhaseOnePersistenceUnitServiceImpl starts.
*
* @author Scott Marlow
*/
public class PhaseOnePersistenceUnitServiceImpl implements Service<PhaseOnePersistenceUnitServiceImpl> {
private final InjectedValue<Map> properties = new InjectedValue<>();
private final InjectedValue<DataSource> jtaDataSource = new InjectedValue<>();
private final InjectedValue<DataSource> nonJtaDataSource = new InjectedValue<>();
private final InjectedValue<ExecutorService> executorInjector = new InjectedValue<>();
private static final String EE_NAMESPACE = BeanManager.class.getName().startsWith("javax") ? "javax" : "jakarta";
private static final String CDI_BEAN_MANAGER = ".persistence.bean.manager";
private final PersistenceProviderAdaptor persistenceProviderAdaptor;
private final PersistenceUnitMetadata pu;
private final ClassLoader classLoader;
private final ServiceName deploymentUnitServiceName;
private final ProxyBeanManager proxyBeanManager;
private final Object wrapperBeanManagerLifeCycle;
private volatile EntityManagerFactoryBuilder entityManagerFactoryBuilder;
private volatile boolean secondPhaseStarted = false;
public PhaseOnePersistenceUnitServiceImpl(
final ClassLoader classLoader,
final PersistenceUnitMetadata pu,
final PersistenceProviderAdaptor persistenceProviderAdaptor,
final ServiceName deploymentUnitServiceName,
final ProxyBeanManager proxyBeanManager) {
this.pu = pu;
this.persistenceProviderAdaptor = persistenceProviderAdaptor;
this.classLoader = classLoader;
this.deploymentUnitServiceName = deploymentUnitServiceName;
this.proxyBeanManager = proxyBeanManager;
this.wrapperBeanManagerLifeCycle = proxyBeanManager != null ? persistenceProviderAdaptor.beanManagerLifeCycle(proxyBeanManager): null;
}
@Override
public void start(final StartContext context) throws StartException {
final ExecutorService executor = executorInjector.getValue();
final AccessControlContext accessControlContext =
AccessController.doPrivileged(GetAccessControlContextAction.getInstance());
final Runnable task = new Runnable() {
// run async in a background thread
@Override
public void run() {
PrivilegedAction<Void> privilegedAction =
new PrivilegedAction<Void>() {
// run as security privileged action
@Override
public Void run() {
try {
ROOT_LOGGER.startingPersistenceUnitService(1, pu.getScopedPersistenceUnitName());
pu.setTempClassLoaderFactory(new TempClassLoaderFactoryImpl(classLoader));
pu.setJtaDataSource(jtaDataSource.getOptionalValue());
pu.setNonJtaDataSource(nonJtaDataSource.getOptionalValue());
if (proxyBeanManager != null) {
if (wrapperBeanManagerLifeCycle != null) {
// pass the wrapper object representing the bean manager life cycle object
properties.getValue().put(EE_NAMESPACE + CDI_BEAN_MANAGER, wrapperBeanManagerLifeCycle);
}
else {
properties.getValue().put(EE_NAMESPACE + CDI_BEAN_MANAGER, proxyBeanManager);
}
}
WritableServiceBasedNamingStore.pushOwner(deploymentUnitServiceName);
entityManagerFactoryBuilder = createContainerEntityManagerFactoryBuilder();
context.complete();
} catch (Throwable t) {
context.failed(new StartException(t));
} finally {
pu.setTempClassLoaderFactory(null); // release the temp classloader factory (only needed when creating the EMF)
WritableServiceBasedNamingStore.popOwner();
}
return null;
}
};
WildFlySecurityManager.doChecked(privilegedAction, accessControlContext);
}
};
try {
executor.execute(task);
} catch (RejectedExecutionException e) {
task.run();
} finally {
context.asynchronous();
}
}
@Override
public void stop(final StopContext context) {
final ExecutorService executor = executorInjector.getValue();
final AccessControlContext accessControlContext =
AccessController.doPrivileged(GetAccessControlContextAction.getInstance());
final Runnable task = new Runnable() {
// run async in a background thread
@Override
public void run() {
PrivilegedAction<Void> privilegedAction =
new PrivilegedAction<Void>() {
// run as security privileged action
@Override
public Void run() {
ROOT_LOGGER.stoppingPersistenceUnitService(1, pu.getScopedPersistenceUnitName());
if (entityManagerFactoryBuilder != null) {
WritableServiceBasedNamingStore.pushOwner(deploymentUnitServiceName);
try {
if (secondPhaseStarted == false) {
ROOT_LOGGER.tracef("PhaseOnePersistenceUnitServiceImpl cancelling %s " +
"which didn't start (phase 2 not reached)", pu.getScopedPersistenceUnitName());
entityManagerFactoryBuilder.cancel();
}
} catch (Throwable t) {
ROOT_LOGGER.failedToStopPUService(t, pu.getScopedPersistenceUnitName());
} finally {
entityManagerFactoryBuilder = null;
pu.setTempClassLoaderFactory(null);
WritableServiceBasedNamingStore.popOwner();
}
}
properties.getValue().remove(EE_NAMESPACE + CDI_BEAN_MANAGER);
context.complete();
return null;
}
};
WildFlySecurityManager.doChecked(privilegedAction, accessControlContext);
}
};
try {
executor.execute(task);
} catch (RejectedExecutionException e) {
task.run();
} finally {
context.asynchronous();
}
}
public InjectedValue<ExecutorService> getExecutorInjector() {
return executorInjector;
}
@Override
public PhaseOnePersistenceUnitServiceImpl getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
/**
* Get the entity manager factory
*
* @return the entity manager factory
*/
public EntityManagerFactoryBuilder getEntityManagerFactoryBuilder() {
return entityManagerFactoryBuilder;
}
public void setSecondPhaseStarted(boolean secondPhaseStarted) {
this.secondPhaseStarted = secondPhaseStarted;
}
public Injector<Map> getPropertiesInjector() {
return properties;
}
public Injector<DataSource> getJtaDataSourceInjector() {
return jtaDataSource;
}
public Injector<DataSource> getNonJtaDataSourceInjector() {
return nonJtaDataSource;
}
public ProxyBeanManager getBeanManager() {
return proxyBeanManager;
}
public Object getBeanManagerLifeCycle() {
return wrapperBeanManagerLifeCycle;
}
/**
* Create EE container entity manager factory
*
* @return EntityManagerFactory
*/
private EntityManagerFactoryBuilder createContainerEntityManagerFactoryBuilder() {
persistenceProviderAdaptor.beforeCreateContainerEntityManagerFactory(pu);
try {
TwoPhaseBootstrapCapable twoPhaseBootstrapCapable = (TwoPhaseBootstrapCapable)persistenceProviderAdaptor;
return twoPhaseBootstrapCapable.getBootstrap(pu, properties.getValue());
} finally {
try {
persistenceProviderAdaptor.afterCreateContainerEntityManagerFactory(pu);
} finally {
pu.setAnnotationIndex(null); // close reference to Annotation Index (only needed during call to createContainerEntityManagerFactory)
}
}
}
}
| 11,880 | 43.665414 | 151 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/config/PersistenceProviderDeploymentHolder.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.jpa.config;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jakarta.persistence.spi.PersistenceProvider;
import org.jboss.as.jpa.processor.JpaAttachments;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUtils;
import org.jipijapa.plugin.spi.PersistenceProviderAdaptor;
/**
* holds the persistence providers + adaptors associated with a deployment
*
* @author Scott Marlow
*/
public class PersistenceProviderDeploymentHolder {
private final Map<String, PersistenceProvider> providerMap = Collections.synchronizedMap(new HashMap<>());
private final List<PersistenceProviderAdaptor> adapterList = Collections.synchronizedList(new ArrayList<>());
public PersistenceProviderDeploymentHolder(final List<PersistenceProvider> providerList, final List<PersistenceProviderAdaptor> adapterList) {
synchronized (this.providerMap) {
for(PersistenceProvider persistenceProvider : providerList){
providerMap.put(persistenceProvider.getClass().getName(), persistenceProvider);
}
}
if (adapterList != null) {
this.adapterList.addAll(adapterList);
}
}
/**
* get the persistence providers adapters associated with an application deployment
*
* @return list of persistence provider adapters
*/
public List<PersistenceProviderAdaptor> getAdapters() {
return adapterList;
}
/**
* get the persistence providers associated with an application deployment
*
* @return the persistence providers list
*/
public Map<String, PersistenceProvider> getProviders() {
return providerMap;
}
public static PersistenceProviderDeploymentHolder getPersistenceProviderDeploymentHolder(DeploymentUnit deploymentUnit) {
deploymentUnit = DeploymentUtils.getTopDeploymentUnit(deploymentUnit);
return deploymentUnit.getAttachment(JpaAttachments.DEPLOYED_PERSISTENCE_PROVIDER);
}
public static void savePersistenceProviderInDeploymentUnit(
DeploymentUnit deploymentUnit, final List<PersistenceProvider> providerList, final List<PersistenceProviderAdaptor> adaptorList) {
deploymentUnit = DeploymentUtils.getTopDeploymentUnit(deploymentUnit);
PersistenceProviderDeploymentHolder persistenceProviderDeploymentHolder = getPersistenceProviderDeploymentHolder(deploymentUnit);
if (persistenceProviderDeploymentHolder == null) {
persistenceProviderDeploymentHolder = new PersistenceProviderDeploymentHolder(providerList, adaptorList);
deploymentUnit.putAttachment(JpaAttachments.DEPLOYED_PERSISTENCE_PROVIDER, persistenceProviderDeploymentHolder);
} else {
synchronized (persistenceProviderDeploymentHolder.providerMap) {
for(PersistenceProvider persistenceProvider : providerList){
persistenceProviderDeploymentHolder.providerMap.put(persistenceProvider.getClass().getName(), persistenceProvider);
}
}
if (adaptorList != null) {
persistenceProviderDeploymentHolder.adapterList.addAll(adaptorList);
}
}
}
}
| 4,362 | 41.359223 | 146 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/config/PersistenceUnitMetadataHolder.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.jpa.config;
import java.util.List;
import jakarta.persistence.spi.PersistenceUnitInfo;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
/**
* Holds the defined persistence units
*
* @author Scott Marlow
*/
public class PersistenceUnitMetadataHolder {
/**
* List<PersistenceUnitMetadataImpl> that represents the Jakarta Persistence persistent units
*/
public static final AttachmentKey<PersistenceUnitMetadataHolder> PERSISTENCE_UNITS = AttachmentKey.create(PersistenceUnitMetadataHolder.class);
private final List<PersistenceUnitMetadata> persistenceUnits;
public List<PersistenceUnitMetadata> getPersistenceUnits() {
return persistenceUnits;
}
public PersistenceUnitMetadataHolder(List<PersistenceUnitMetadata> persistenceUnits) {
this.persistenceUnits = persistenceUnits;
}
public String toString() {
StringBuffer result = new StringBuffer();
for (PersistenceUnitInfo pu : persistenceUnits) {
result.append(pu.toString());
}
return result.toString();
}
}
| 2,181 | 34.193548 | 147 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/config/PersistenceUnitsInApplication.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.jpa.config;
import java.util.ArrayList;
import java.util.List;
import org.jboss.as.server.deployment.AttachmentKey;
/**
* Count and collection of the persistence units deployed with the application
*
* @author Scott Marlow
*/
public class PersistenceUnitsInApplication {
public static final AttachmentKey<PersistenceUnitsInApplication> PERSISTENCE_UNITS_IN_APPLICATION = AttachmentKey.create(PersistenceUnitsInApplication.class);
private int count = 0;
private List<PersistenceUnitMetadataHolder> persistenceUnitMetadataHolderList = new ArrayList<PersistenceUnitMetadataHolder>(1);
/**
* Gets the number of persistence units deployed with the applicatino
* @return
*/
public int getCount() {
return count;
}
/**
* Increment the count of persistence units in application
* @param incrementValue
*/
public void increment(int incrementValue) {
count += incrementValue;
}
/**
* Track the passed Persistence units for the application
*
* @param persistenceUnitMetadataHolder
*/
public void addPersistenceUnitHolder(PersistenceUnitMetadataHolder persistenceUnitMetadataHolder) {
persistenceUnitMetadataHolderList.add(persistenceUnitMetadataHolder);
}
public List<PersistenceUnitMetadataHolder> getPersistenceUnitHolders() {
return persistenceUnitMetadataHolderList;
}
}
| 2,459 | 34.142857 | 162 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/config/PersistenceUnitMetadataImpl.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.jpa.config;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.concurrent.CopyOnWriteArrayList;
import jakarta.persistence.SharedCacheMode;
import jakarta.persistence.ValidationMode;
import jakarta.persistence.spi.ClassTransformer;
import jakarta.persistence.spi.PersistenceUnitTransactionType;
import javax.sql.DataSource;
import org.jboss.jandex.Index;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
import org.jipijapa.plugin.spi.TempClassLoaderFactory;
/**
* Represents the persistence unit definition
*
* @author Scott Marlow (based on work by Bill Burke)
*/
public class PersistenceUnitMetadataImpl implements PersistenceUnitMetadata {
// required: name of the persistent unit
private volatile String name;
// required: name of the persistent unit scoped to deployment file
private volatile String scopedName;
private volatile ArrayList<String> containingModuleName;
// optional: jndi name of non-jta datasource
private volatile String nonJtaDataSourceName;
// optional: jndi name of jta datasource
private volatile String jtaDataSourceName;
private volatile DataSource jtaDatasource;
private volatile DataSource nonJtaDataSource;
// optional: provider classname (must implement jakarta.persistence.spi.PersistenceProvider)
private volatile String provider;
// optional: specifies if EntityManagers will be JTA (default) or RESOURCE_LOCAL
private volatile PersistenceUnitTransactionType transactionType;
// optional: collection of individually named managed entity classes
private volatile List<String> classes = new ArrayList<String>(1);
// optional:
private final List<String> packages = new ArrayList<String>(1);
// optional: collection of jar file names that contain entity classes
private volatile List<String> jarFiles = new ArrayList<String>(1);
private volatile List<URL> jarFilesUrls = new ArrayList<URL>();
private volatile URL persistenceUnitRootUrl;
// optional: collection of orm.xml style entity mapping files
private volatile List<String> mappingFiles = new ArrayList<String>(1);
// collection of properties for the persistence provider
private volatile Properties props = new Properties();
// optional: specifies whether to include entity classes in the root folder containing the persistence unit.
private volatile boolean excludeUnlistedClasses;
// optional: validation mode can be "auto", "callback", "none".
private volatile ValidationMode validationMode;
// optional: version of the Jakarta Persistence specification
private volatile String version;
// transformers will be written to when the Jakarta Persistence persistence provider adds their transformer.
// there should be very few calls to add transformers but potentially many calls to get the
// transformer list (once per application class loaded).
private final List<ClassTransformer> transformers = new CopyOnWriteArrayList<ClassTransformer>();
private volatile SharedCacheMode sharedCacheMode;
private volatile ClassLoader classloader;
private volatile TempClassLoaderFactory tempClassLoaderFactory;
private volatile ClassLoader cachedTempClassLoader;
private volatile Map<URL, Index> annotationIndex;
@Override
public void setPersistenceUnitName(String name) {
this.name = name;
}
@Override
public String getPersistenceUnitName() {
return name;
}
@Override
public void setScopedPersistenceUnitName(String scopedName) {
this.scopedName = scopedName;
}
@Override
public String getScopedPersistenceUnitName() {
return scopedName;
}
@Override
public void setContainingModuleName(ArrayList<String> containingModuleName) {
this.containingModuleName = containingModuleName;
}
@Override
public ArrayList<String> getContainingModuleName() {
return containingModuleName;
}
@Override
public void setPersistenceProviderClassName(String provider) {
if (provider != null && provider.endsWith(".class")) {
this.provider = provider.substring(0, provider.length() - 6);
}
this.provider = provider;
}
@Override
public String getPersistenceProviderClassName() {
return provider;
}
@Override
public PersistenceUnitTransactionType getTransactionType() {
return transactionType;
}
@Override
public DataSource getJtaDataSource() {
return jtaDatasource;
}
@Override
public void setJtaDataSource(DataSource jtaDataSource) {
this.jtaDatasource = jtaDataSource;
}
@Override
public void setNonJtaDataSource(DataSource nonJtaDataSource) {
this.nonJtaDataSource = nonJtaDataSource;
}
@Override
public DataSource getNonJtaDataSource() {
return nonJtaDataSource;
}
@Override
public void setJtaDataSourceName(String jtaDatasource) {
this.jtaDataSourceName = jtaDatasource;
}
@Override
public String getJtaDataSourceName() {
return jtaDataSourceName;
}
@Override
public void setNonJtaDataSourceName(String nonJtaDatasource) {
this.nonJtaDataSourceName = nonJtaDatasource;
}
@Override
public String getNonJtaDataSourceName() {
return this.nonJtaDataSourceName;
}
@Override
public void setPersistenceUnitRootUrl(URL persistenceUnitRootUrl) {
this.persistenceUnitRootUrl = persistenceUnitRootUrl;
}
@Override
public URL getPersistenceUnitRootUrl() {
return persistenceUnitRootUrl;
}
@Override
public void setAnnotationIndex(Map<URL, Index> indexes) {
annotationIndex = indexes;
}
@Override
public Map<URL, Index> getAnnotationIndex() {
return annotationIndex;
}
@Override
public List<String> getManagedClassNames() {
return classes;
}
@Override
public void setManagedClassNames(List<String> classes) {
this.classes = classes;
}
@Override
public boolean excludeUnlistedClasses() {
return excludeUnlistedClasses;
}
@Override
public void setExcludeUnlistedClasses(boolean excludeUnlistedClasses) {
this.excludeUnlistedClasses = excludeUnlistedClasses;
}
@Override
public void setTransactionType(PersistenceUnitTransactionType transactionType) {
this.transactionType = transactionType;
}
@Override
public void setMappingFiles(List<String> mappingFiles) {
this.mappingFiles = mappingFiles;
}
@Override
public List<String> getMappingFileNames() {
return mappingFiles;
}
@Override
public List<URL> getJarFileUrls() {
return jarFilesUrls;
}
@Override
public void setJarFileUrls(List<URL> jarFilesUrls) {
this.jarFilesUrls = jarFilesUrls;
}
@Override
public List<String> getJarFiles() {
return jarFiles;
}
@Override
public void setJarFiles(List<String> jarFiles) {
this.jarFiles = jarFiles;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("PersistenceUnitMetadataImpl(version=")
.append(version)
.append(") [\n")
.append("\tname: ").append(name).append("\n")
.append("\tjtaDataSource: ").append(jtaDataSourceName).append("\n")
.append("\tnonJtaDataSource: ").append(nonJtaDataSourceName).append("\n")
.append("\ttransactionType: ").append(transactionType).append("\n")
.append("\tprovider: ").append(provider).append("\n")
.append("\tclasses[\n");
if (classes != null) {
for (String elt : classes) {
sb.append("\t\t").append(elt);
}
}
sb.append("\t]\n")
.append("\tpackages[\n");
if (packages != null) {
for (String elt : packages) {
sb.append("\t\t").append(elt).append("\n");
}
}
sb.append("\t]\n")
.append("\tmappingFiles[\n");
if (mappingFiles != null) {
for (String elt : mappingFiles) {
sb.append("\t\t").append(elt).append("\n");
}
}
sb.append("\t]\n")
.append("\tjarFiles[\n");
if (jarFiles != null) {
for (String elt : jarFiles) {
sb.append("\t\t").append(elt).append("\n");
}
}
sb.append("\t]\n");
if (validationMode != null) {
sb.append("\tvalidation-mode: ").append(validationMode).append("\n");
}
if (sharedCacheMode != null) {
sb.append("\tshared-cache-mode: ").append(sharedCacheMode).append("\n");
}
sb.append("\tproperties[\n");
if (props != null) {
for (Entry<Object, Object> elt : props.entrySet()) {
sb.append("\t\t").append(elt.getKey()).append(": ").append(elt.getValue()).append("\n");
}
}
sb.append("\t]").append("]");
return sb.toString();
}
@Override
public void setValidationMode(ValidationMode validationMode) {
this.validationMode = validationMode;
}
@Override
public ValidationMode getValidationMode() {
return validationMode;
}
@Override
public void setProperties(Properties props) {
this.props = props;
}
@Override
public Properties getProperties() {
return props;
}
@Override
public void setPersistenceXMLSchemaVersion(String version) {
this.version = version;
}
@Override
public String getPersistenceXMLSchemaVersion() {
return version;
}
@Override
public void setClassLoader(ClassLoader cl) {
classloader = cl;
}
/**
* Return a classloader that the provider can use to load the entity classes.
* <p/>
* Note from Jakarta Persistence 8.2:
* All persistence classes defined at the level of the Jakarta EE EAR must be accessible to other Java EE
* components in the application—i.e. loaded by the application classloader—such that if the same entity
* class is referenced by two different Jakarta EE components (which may be using different persistence
* units), the referenced class is the same identical class.
*
* @return
*/
@Override
public ClassLoader getClassLoader() {
return classloader;
}
@Override
public List<ClassTransformer> getTransformers() {
return transformers;
}
@Override
public void addTransformer(ClassTransformer classTransformer) {
transformers.add(classTransformer);
if (ROOT_LOGGER.isTraceEnabled()) {
ROOT_LOGGER.tracef("added entity class transformer '%s' for '%s'",
classTransformer.getClass().getName(),
getScopedPersistenceUnitName());
}
}
@Override
public void setTempClassLoaderFactory(TempClassLoaderFactory tempClassloaderFactory) {
this.tempClassLoaderFactory = tempClassloaderFactory;
cachedTempClassLoader = null; // always clear the cached temp classloader when a new tempClassloaderFactory is set.
}
@Override
public ClassLoader cacheTempClassLoader() {
if(cachedTempClassLoader == null && tempClassLoaderFactory != null) {
cachedTempClassLoader = tempClassLoaderFactory.createNewTempClassLoader();
}
return cachedTempClassLoader;
}
@Override
public ClassLoader getNewTempClassLoader() {
return tempClassLoaderFactory != null ?
tempClassLoaderFactory.createNewTempClassLoader() : null;
}
@Override
public SharedCacheMode getSharedCacheMode() {
return sharedCacheMode;
}
@Override
public void setSharedCacheMode(SharedCacheMode sharedCacheMode) {
this.sharedCacheMode = sharedCacheMode;
}
}
| 13,329 | 29.364465 | 124 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/config/JPADeploymentSettings.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.jpa.config;
/**
* Represents the Jakarta Persistence per application deployment settings read from jboss-all.xml
*
* @author Scott Marlow
*/
public class JPADeploymentSettings {
private ExtendedPersistenceInheritance extendedPersistenceInheritanceType = ExtendedPersistenceInheritance.SHALLOW;
public ExtendedPersistenceInheritance getExtendedPersistenceInheritanceType() {
return extendedPersistenceInheritanceType;
}
public void setExtendedPersistenceInheritanceType(ExtendedPersistenceInheritance extendedPersistenceInheritanceType) {
this.extendedPersistenceInheritanceType = extendedPersistenceInheritanceType;
}
}
| 1,708 | 38.744186 | 122 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/config/Configuration.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.jpa.config;
import java.util.HashMap;
import java.util.Map;
import jakarta.persistence.EntityManagerFactory;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
/**
* configuration properties that may appear in persistence.xml
*
* @author Scott Marlow
*/
public class Configuration {
/**
* name of the AS module that contains the persistence provider
*/
public static final String PROVIDER_MODULE = "jboss.as.jpa.providerModule";
/**
* Hibernate main module (default) persistence provider
*/
public static final String PROVIDER_MODULE_HIBERNATE = "org.hibernate";
/**
* Hibernate 4.1.x persistence provider, note that Hibernate 4.1.x is expected to be in the 4.1 slot
*/
public static final String PROVIDER_MODULE_HIBERNATE4_1 = "org.hibernate:4.1";
/**
* Hibernate OGM persistence provider
*/
public static final String PROVIDER_MODULE_HIBERNATE_OGM = "org.hibernate.ogm";
public static final String PROVIDER_MODULE_ECLIPSELINK = "org.eclipse.persistence";
public static final String PROVIDER_MODULE_TOPLINK = "oracle.toplink";
public static final String PROVIDER_MODULE_DATANUCLEUS = "org.datanucleus";
public static final String PROVIDER_MODULE_DATANUCLEUS_GAE = "org.datanucleus:appengine";
public static final String PROVIDER_MODULE_OPENJPA = "org.apache.openjpa";
/**
* default if no PROVIDER_MODULE is specified.
*/
public static final String PROVIDER_MODULE_DEFAULT = PROVIDER_MODULE_HIBERNATE;
/**
* Hibernate 4.1.x persistence provider class
*/
public static final String PROVIDER_CLASS_HIBERNATE4_1 = "org.hibernate.ejb.HibernatePersistence";
/**
* Hibernate 4.3.x persistence provider class
*/
public static final String PROVIDER_CLASS_HIBERNATE = "org.hibernate.jpa.HibernatePersistenceProvider";
/**
* Hibernate OGM persistence provider class
*/
public static final String PROVIDER_CLASS_HIBERNATE_OGM = "org.hibernate.ogm.jpa.HibernateOgmPersistence";
/**
* TopLink provider class names
*/
public static final String PROVIDER_CLASS_TOPLINK_ESSENTIALS = "oracle.toplink.essentials.PersistenceProvider";
public static final String PROVIDER_CLASS_TOPLINK = "oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider";
/**
* EclipseLink provider class name
*/
public static final String PROVIDER_CLASS_ECLIPSELINK = "org.eclipse.persistence.jpa.PersistenceProvider";
/**
* DataNucleus provider
*/
public static final String PROVIDER_CLASS_DATANUCLEUS = "org.datanucleus.api.jpa.PersistenceProviderImpl";
/**
* DataNucleus provider GAE
*/
public static final String PROVIDER_CLASS_DATANUCLEUS_GAE = "org.datanucleus.store.appengine.jpa.DatastorePersistenceProvider";
public static final String PROVIDER_CLASS_OPENJPA = "org.apache.openjpa.persistence.PersistenceProviderImpl";
/**
* default provider class
*/
public static final String PROVIDER_CLASS_DEFAULT = PROVIDER_CLASS_HIBERNATE;
/**
* if the PROVIDER_MODULE is this value, it is expected that the application has its own provider
* in the deployment.
*/
public static final String PROVIDER_MODULE_APPLICATION_SUPPLIED = "application";
public static final String ADAPTER_MODULE_OPENJPA = "org.jboss.as.jpa.openjpa";
/**
* name of the AS module that contains the persistence provider adapter
*/
public static final String ADAPTER_MODULE = "jboss.as.jpa.adapterModule";
/**
* defaults to true, if changed to false (in the persistence.xml),
* the Jakarta Persistence container will not start the persistence unit service.
*/
public static final String JPA_CONTAINER_MANAGED = "jboss.as.jpa.managed";
public static final String JPA_DEFAULT_PERSISTENCE_UNIT = "wildfly.jpa.default-unit";
/**
* defaults to true, if false, persistence unit will not support jakarta.persistence.spi.ClassTransformer Interface
* which means no application class rewriting
*/
public static final String JPA_CONTAINER_CLASS_TRANSFORMER = "jboss.as.jpa.classtransformer";
/**
* set to false to force a single phase persistence unit bootstrap to be used (default is true
* which uses two phases to start the persistence unit).
*/
public static final String JPA_ALLOW_TWO_PHASE_BOOTSTRAP = "wildfly.jpa.twophasebootstrap";
private static final String JPA_ALLOW_APPLICATION_DEFINED_DATASOURCE = "wildfly.jpa.applicationdatasource";
/**
* set to false to ignore default data source (defaults to true)
*/
private static final String JPA_ALLOW_DEFAULT_DATA_SOURCE_USE = "wildfly.jpa.allowdefaultdatasourceuse";
/**
* set to true to defer detaching entities until persistence context is closed (WFLY-3674)
*/
private static final String JPA_DEFER_DETACH = "jboss.as.jpa.deferdetach";
/**
* set to true to defer detaching query results until persistence context is closed (WFLY-12674)
*/
private static final String JPA_SKIP_QUERY_DETACH = "wildfly.jpa.skipquerydetach";
/**
* unique name for the persistence unit that is unique across all deployments (
* defaults to include the application name prepended to the persistence unit name)
*/
private static final String JPA_SCOPED_PERSISTENCE_UNIT_NAME = "jboss.as.jpa.scopedname";
/**
* name of the persistence provider adapter class
*/
public static final String ADAPTER_CLASS = "jboss.as.jpa.adapterClass";
public static final String ALLOWJOINEDUNSYNCPC = "wildfly.jpa.allowjoinedunsync";
public static final String SKIPMIXEDSYNCTYPECHECKING = "wildfly.jpa.skipmixedsynctypechecking";
/**
* Document properties that allow Jakarta Persistence apps to disable WildFly Jakarta Transactions platform/2lc integration for Hibernate ORM 5.3+ (WFLY-10433)
* public static final String CONTROLJTAINTEGRATION = "wildfly.jpa.jtaplatform";
* public static final String CONTROL2LCINTEGRATION = "wildfly.jpa.regionfactory";
*/
/**
* name of the Hibernate Search module name configuration setting in persistence unit definition
*/
public static final String HIBERNATE_SEARCH_MODULE = "wildfly.jpa.hibernate.search.module";
/**
* name of the Hibernate Search integrator adaptor module
*/
public static final String HIBERNATE_SEARCH_INTEGRATOR_ADAPTOR_MODULE_NAME = "org.hibernate.search.jipijapa-hibernatesearch";
/**
* name of the Hibernate Search module providing the ORM mapper
*/
public static final String HIBERNATE_SEARCH_MODULE_MAPPER_ORM = "org.hibernate.search.mapper.orm";
/**
* name of the Hibernate Search module providing the outbox-polling coordination strategy
*/
public static final String HIBERNATE_SEARCH_MODULE_MAPPER_ORM_COORDINATION_OUTBOXPOLLING = "org.hibernate.search.mapper.orm.coordination.outboxpolling";
/**
* name of the Hibernate Search module providing the Lucene backend
*/
public static final String HIBERNATE_SEARCH_MODULE_BACKEND_LUCENE = "org.hibernate.search.backend.lucene";
/**
* name of the Hibernate Search module providing the Elasticsearch backend
*/
public static final String HIBERNATE_SEARCH_MODULE_BACKEND_ELASTICSEARCH = "org.hibernate.search.backend.elasticsearch";
/**
* name of the Hibernate Search configuration property allowing to set the backend type
*/
public static final String HIBERNATE_SEARCH_BACKEND_TYPE = "hibernate.search.backend.type";
/**
* The value of the {@link #HIBERNATE_SEARCH_BACKEND_TYPE} property that identifies the use of a Lucene backend.
*/
public static final String HIBERNATE_SEARCH_BACKEND_TYPE_VALUE_LUCENE = "lucene";
/**
* The value of the {@link #HIBERNATE_SEARCH_BACKEND_TYPE} property that identifies the use of an Elasticsearch backend.
*/
public static final String HIBERNATE_SEARCH_BACKEND_TYPE_VALUE_ELASTICSEARCH = "elasticsearch";
/**
* Name of the Hibernate Search configuration property allowing to set the coordination strategy
*/
public static final String HIBERNATE_SEARCH_COORDINATION_STRATEGY = "hibernate.search.coordination.strategy";
/**
* The value of the {@link #HIBERNATE_SEARCH_COORDINATION_STRATEGY} property that identifies the use of an Elasticsearch backend.
*/
public static final String HIBERNATE_SEARCH_COORDINATION_STRATEGY_VALUE_OUTBOX_POLLING = "outbox-polling";
private static final String EE_DEFAULT_DATASOURCE = "java:comp/DefaultDataSource";
// key = provider class name, value = module name
private static final Map<String, String> providerClassToModuleName = new HashMap<String, String>();
private static final String HIBERNATE = "Hibernate";
static {
// always choose the default hibernate version for the Hibernate provider class mapping
// if the user wants a different version. they can specify the provider module name
providerClassToModuleName.put(PROVIDER_CLASS_HIBERNATE, PROVIDER_MODULE_HIBERNATE);
// WFLY-2136/HHH-8543 to make migration to Hibernate 4.3.x easier, we also map the (now)
// deprecated PROVIDER_CLASS_HIBERNATE4_1 to the org.hibernate:main module
// when PROVIDER_CLASS_HIBERNATE4_1 is no longer in a future Hibernate version (5.x?)
// we can map PROVIDER_CLASS_HIBERNATE4_1 to org.hibernate:4.3 at that time.
// persistence units can set "jboss.as.jpa.providerModule=org.hibernate:4.1" to use Hibernate 4.1.x/4.2.x
providerClassToModuleName.put(PROVIDER_CLASS_HIBERNATE4_1, PROVIDER_MODULE_HIBERNATE);
providerClassToModuleName.put(PROVIDER_CLASS_HIBERNATE_OGM, PROVIDER_MODULE_HIBERNATE_OGM);
providerClassToModuleName.put(PROVIDER_CLASS_TOPLINK_ESSENTIALS, PROVIDER_MODULE_TOPLINK);
providerClassToModuleName.put(PROVIDER_CLASS_TOPLINK, PROVIDER_MODULE_TOPLINK);
providerClassToModuleName.put(PROVIDER_CLASS_ECLIPSELINK, PROVIDER_MODULE_ECLIPSELINK);
providerClassToModuleName.put(PROVIDER_CLASS_DATANUCLEUS, PROVIDER_MODULE_DATANUCLEUS);
providerClassToModuleName.put(PROVIDER_CLASS_DATANUCLEUS_GAE, PROVIDER_MODULE_DATANUCLEUS_GAE);
providerClassToModuleName.put(PROVIDER_CLASS_OPENJPA, PROVIDER_MODULE_OPENJPA);
}
/**
* Get the provider module name for the specified provider class.
*
* @param providerClassName the PU class name
* @return provider module name or null if not known
*/
public static String getProviderModuleNameFromProviderClassName(final String providerClassName) {
return providerClassToModuleName.get(providerClassName);
}
/**
* Determine if class file transformer is needed for the specified persistence unit
*
* for all persistence providers, the transformer is assumed to be needed unless the application indicates otherwise.
*
* @param pu the PU
* @return true if class file transformer support is needed for pu
*/
public static boolean needClassFileTransformer(PersistenceUnitMetadata pu) {
if (pu.getProperties().containsKey(Configuration.JPA_CONTAINER_CLASS_TRANSFORMER)) {
return Boolean.parseBoolean(pu.getProperties().getProperty(Configuration.JPA_CONTAINER_CLASS_TRANSFORMER));
}
if (isHibernateProvider(pu.getPersistenceProviderClassName())) {
return false;
}
return true;
}
private static boolean isHibernateProvider(String provider) {
// If the persistence provider is not specified (null case), Hibernate ORM will be used as the persistence provider.
return provider == null || provider.contains(HIBERNATE);
}
// key = provider class name, value = adapter module name
private static final Map<String, String> providerClassToAdapterModuleName = new HashMap<String, String>();
static {
providerClassToAdapterModuleName.put(PROVIDER_CLASS_OPENJPA, ADAPTER_MODULE_OPENJPA);
}
public static String getProviderAdapterModuleNameFromProviderClassName(final String providerClassName) {
return providerClassToAdapterModuleName.get(providerClassName);
}
public static String getDefaultProviderModuleName() {
return PROVIDER_MODULE_DEFAULT;
}
/**
* Determine if two phase persistence unit start is allowed
*
* @param pu
* @return
*/
public static boolean allowTwoPhaseBootstrap(PersistenceUnitMetadata pu) {
boolean result = true;
if (EE_DEFAULT_DATASOURCE.equals(pu.getJtaDataSourceName())) {
result = false;
}
if (pu.getProperties().containsKey(Configuration.JPA_ALLOW_TWO_PHASE_BOOTSTRAP)) {
result = Boolean.parseBoolean(pu.getProperties().getProperty(Configuration.JPA_ALLOW_TWO_PHASE_BOOTSTRAP));
}
return result;
}
/**
* Determine if persistence unit can use application defined DataSource (e.g. DataSourceDefinition or resource ref).
*
* @param pu
* @return true if application defined DataSource can be used, false (default) if not.
*/
public static boolean allowApplicationDefinedDatasource(PersistenceUnitMetadata pu) {
boolean result = false;
if (pu.getProperties().containsKey(Configuration.JPA_ALLOW_APPLICATION_DEFINED_DATASOURCE)) {
result = Boolean.parseBoolean(pu.getProperties().getProperty(Configuration.JPA_ALLOW_APPLICATION_DEFINED_DATASOURCE));
}
return result;
}
/**
* Determine if the default data-source should be used
*
* @param pu
* @return true if the default data-source should be used
*/
public static boolean allowDefaultDataSourceUse(PersistenceUnitMetadata pu) {
boolean result = true;
if (pu.getProperties().containsKey(Configuration.JPA_ALLOW_DEFAULT_DATA_SOURCE_USE)) {
result = Boolean.parseBoolean(pu.getProperties().getProperty(Configuration.JPA_ALLOW_DEFAULT_DATA_SOURCE_USE));
}
return result;
}
/**
* Return true if detaching of managed entities should be deferred until the entity manager is closed.
* Note: only applies to transaction scoped entity managers used without an active Jakarta Transactions transaction.
*
* @param properties
* @return
*/
public static boolean deferEntityDetachUntilClose(final Map<String, Object> properties) {
boolean result = false;
if ( properties.containsKey(JPA_DEFER_DETACH))
result = Boolean.parseBoolean((String)properties.get(JPA_DEFER_DETACH));
return result;
}
/**
* Return true if detaching of query results (entities) should be deferred until the entity manager is closed.
* Note: only applies to transaction scoped entity managers used without an active Jakarta Transactions transaction.
*
* @param properties
* @return
*/
public static boolean skipQueryDetach(final Map<String, Object> properties) {
boolean result = false;
if ( properties.containsKey(JPA_SKIP_QUERY_DETACH))
result = Boolean.parseBoolean((String)properties.get(JPA_SKIP_QUERY_DETACH));
return result;
}
public static String getScopedPersistenceUnitName(PersistenceUnitMetadata pu) {
Object name = pu.getProperties().get(JPA_SCOPED_PERSISTENCE_UNIT_NAME);
if (name instanceof String) {
return (String)name;
}
return null;
}
/**
* Allow the mixed synchronization checking to be skipped for backward compatibility with WildFly 10.1.0
*
*
* @param emf
* @param targetEntityManagerProperties
* @return
*/
public static boolean skipMixedSynchronizationTypeCheck(EntityManagerFactory emf, Map targetEntityManagerProperties) {
boolean result = false;
// EntityManager properties will take priority over persistence.xml level (emf) properties
if(targetEntityManagerProperties != null && targetEntityManagerProperties.containsKey(SKIPMIXEDSYNCTYPECHECKING)) {
result = Boolean.parseBoolean((String) targetEntityManagerProperties.get(SKIPMIXEDSYNCTYPECHECKING));
}
else if(emf.getProperties() != null && emf.getProperties().containsKey(SKIPMIXEDSYNCTYPECHECKING)) {
result = Boolean.parseBoolean((String) emf.getProperties().get(SKIPMIXEDSYNCTYPECHECKING));
}
return result;
}
/**
* Allow an unsynchronized persistence context that is joined to the transaction, be treated the same as a synchronized
* persistence context, with respect to the checking for mixed unsync/sync types.
*
*
* @param emf
* @param targetEntityManagerProperties
* @return
*/
public static boolean allowJoinedUnsyncPersistenceContext(EntityManagerFactory emf, Map targetEntityManagerProperties) {
boolean result = false;
// EntityManager properties will take priority over persistence.xml (emf) properties
if(targetEntityManagerProperties != null && targetEntityManagerProperties.containsKey(ALLOWJOINEDUNSYNCPC)) {
result = Boolean.parseBoolean((String) targetEntityManagerProperties.get(ALLOWJOINEDUNSYNCPC));
}
else if(emf.getProperties() != null && emf.getProperties().containsKey(ALLOWJOINEDUNSYNCPC)) {
result = Boolean.parseBoolean((String) emf.getProperties().get(ALLOWJOINEDUNSYNCPC));
}
return result;
}
}
| 18,745 | 41.604545 | 163 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/config/ExtendedPersistenceInheritance.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.jpa.config;
/**
* Possible choices for how extended persistence context inheritance is performed.
*
* @author Scott Marlow
*/
public enum ExtendedPersistenceInheritance {
DEEP, // extended persistence context can be inherited from sibling beans as well as a parent (or
// recursively parents of parent) bean.
// the parent can be the injecting bean (creation time inheritance) or from the bean call stack.
// JNDI lookup of a bean, also qualifies for inheritance
SHALLOW // extended persistence context can only be inherited from a single level (immediate) parent bean.
// the parent can be the injecting bean (creation time inheritance) or from the bean call stack.
}
| 1,802 | 45.230769 | 114 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/jbossjpaparser/JBossJPAParser.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.jpa.jbossjpaparser;
import java.util.HashMap;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.stream.Location;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.jboss.as.jpa.config.ExtendedPersistenceInheritance;
import org.jboss.as.jpa.config.JPADeploymentSettings;
import org.jboss.as.server.logging.ServerLogger;
import org.jboss.metadata.property.PropertyReplacer;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* Parse the jboss-jpa settings in jboss-all.xml.
*
* @author Scott Marlow
*/
public class JBossJPAParser {
public static final String NAMESPACE_1_0 = "http://www.jboss.com/xml/ns/javaee";
private static final JBossJPAParser INSTANCE = new JBossJPAParser();
private static final String INHERITANCE_CONSTANT = "inheritance";
public static JPADeploymentSettings parser(XMLExtendedStreamReader reader, PropertyReplacer propertyReplacer) throws XMLStreamException {
JPADeploymentSettings result = new JPADeploymentSettings();
INSTANCE.readElement(reader, result, propertyReplacer);
return result;
}
enum Element {
JBOSS_JPA_DESCRIPTOR,
EXTENDED_PERSISTENCE,
// default unknown element
UNKNOWN;
private static final Map<QName, Element> elements;
static {
Map<QName, Element> elementsMap = new HashMap<QName, Element>();
elementsMap.put(new QName(NAMESPACE_1_0, "jboss-jpa"), Element.JBOSS_JPA_DESCRIPTOR);
elementsMap.put(new QName(NAMESPACE_1_0, "extended-persistence"), Element.EXTENDED_PERSISTENCE);
elements = elementsMap;
}
static Element of(QName qName) {
QName name;
if (qName.getNamespaceURI().equals("")) {
name = new QName(NAMESPACE_1_0, qName.getLocalPart());
} else {
name = qName;
}
final Element element = elements.get(name);
return element == null ? UNKNOWN : element;
}
}
enum Version {
JBOSS_JPA_1_0,
UNKNOWN
}
private JBossJPAParser() {
}
public void readElement(final XMLExtendedStreamReader reader, final JPADeploymentSettings result, PropertyReplacer propertyReplacer) throws XMLStreamException {
final int count = reader.getAttributeCount();
if (count != 0) {
throw unexpectedContent(reader);
}
// xsd:sequence
while (reader.hasNext()) {
switch (reader.nextTag()) {
case XMLStreamConstants.END_ELEMENT: {
return;
}
case XMLStreamConstants.START_ELEMENT: {
final Element element = Element.of(reader.getName());
switch (element) {
case EXTENDED_PERSISTENCE:
final String value = getAttributeValue(reader, null, INHERITANCE_CONSTANT, propertyReplacer);
if (value == null || value.isEmpty()) {
result.setExtendedPersistenceInheritanceType(ExtendedPersistenceInheritance.SHALLOW);
} else {
result.setExtendedPersistenceInheritanceType(ExtendedPersistenceInheritance.valueOf(value));
}
break;
default:
throw unexpectedContent(reader);
}
break;
}
default: {
throw unexpectedContent(reader);
}
}
}
throw endOfDocument(reader.getLocation());
}
private static XMLStreamException unexpectedContent(final XMLStreamReader reader) {
final String kind;
switch (reader.getEventType()) {
case XMLStreamConstants.ATTRIBUTE:
kind = "attribute";
break;
case XMLStreamConstants.CDATA:
kind = "cdata";
break;
case XMLStreamConstants.CHARACTERS:
kind = "characters";
break;
case XMLStreamConstants.COMMENT:
kind = "comment";
break;
case XMLStreamConstants.DTD:
kind = "dtd";
break;
case XMLStreamConstants.END_DOCUMENT:
kind = "document end";
break;
case XMLStreamConstants.END_ELEMENT:
kind = "element end";
break;
case XMLStreamConstants.ENTITY_DECLARATION:
kind = "entity declaration";
break;
case XMLStreamConstants.ENTITY_REFERENCE:
kind = "entity ref";
break;
case XMLStreamConstants.NAMESPACE:
kind = "namespace";
break;
case XMLStreamConstants.NOTATION_DECLARATION:
kind = "notation declaration";
break;
case XMLStreamConstants.PROCESSING_INSTRUCTION:
kind = "processing instruction";
break;
case XMLStreamConstants.SPACE:
kind = "whitespace";
break;
case XMLStreamConstants.START_DOCUMENT:
kind = "document start";
break;
case XMLStreamConstants.START_ELEMENT:
kind = "element start";
break;
default:
kind = "unknown";
break;
}
return ServerLogger.ROOT_LOGGER.unexpectedContent(kind, (reader.hasName() ? reader.getName() : null),
(reader.hasText() ? reader.getText() : null), reader.getLocation());
}
private static String getAttributeValue(final XMLStreamReader reader,final String namespaceURI, final String localName, final PropertyReplacer propertyReplacer) throws XMLStreamException {
return propertyReplacer.replaceProperties(reader.getAttributeValue(namespaceURI,localName));
}
private static XMLStreamException endOfDocument(final Location location) {
return ServerLogger.ROOT_LOGGER.unexpectedEndOfDocument(location);
}
}
| 7,443 | 36.59596 | 192 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/container/ExtendedPersistenceShallowInheritance.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.jpa.container;
import java.util.Map;
/**
*
* @author Scott Marlow
*/
public final class ExtendedPersistenceShallowInheritance implements ExtendedPersistenceInheritanceStrategy {
public static final ExtendedPersistenceShallowInheritance INSTANCE = new ExtendedPersistenceShallowInheritance();
@Override
public void registerExtendedPersistenceContext(String scopedPuName, ExtendedEntityManager entityManager) {
if (SFSBCallStack.getSFSBCreationBeanNestingLevel() > 0) {
SFSBCallStack.getSFSBCreationTimeInjectedXPCs(scopedPuName).registerShallowInheritance(scopedPuName, entityManager);
}
}
@Override
public ExtendedEntityManager findExtendedPersistenceContext(String puScopedName) {
ExtendedEntityManager result = null;
// if current bean is injected from a parent bean that is also being created, current bean
// can inherit only from the parent bean.
if (SFSBCallStack.getSFSBCreationBeanNestingLevel() > 1) {
SFSBInjectedXPCs currentInjectedXPCs = SFSBCallStack.getSFSBCreationTimeInjectedXPCs(puScopedName);
result = currentInjectedXPCs.findExtendedPersistenceContextShallowInheritance(puScopedName);
} else {
// else inherit from parent bean that created current bean (if any). The parent bean is the one
// that did a JNDI lookup of the current bean.
Map<String, ExtendedEntityManager> handle = SFSBCallStack.getCurrentCall();
if (handle != null) {
result = handle.get(puScopedName);
if (result != null) {
return result;
}
}
}
return result;
}
}
| 2,770 | 41.630769 | 128 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/container/TransactionScopedEntityManager.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.jpa.container;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
import java.io.IOException;
import java.io.Serializable;
import java.security.AccessController;
import java.util.Map;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.SynchronizationType;
import jakarta.transaction.TransactionManager;
import jakarta.transaction.TransactionSynchronizationRegistry;
import org.jboss.as.jpa.config.Configuration;
import org.jboss.as.jpa.messages.JpaLogger;
import org.jboss.as.jpa.service.PersistenceUnitServiceImpl;
import org.jboss.as.jpa.transaction.TransactionUtil;
import org.jboss.as.jpa.util.JPAServiceNames;
import org.jboss.as.server.CurrentServiceContainer;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.wildfly.transaction.client.ContextTransactionManager;
/**
* Transaction scoped entity manager will be injected into SLSB or SFSB beans. At bean invocation time, they
* will join the active transaction if one is present. Otherwise, they will simply be cleared at the end of
* the bean invocation.
* <p/>
* This is a proxy for the underlying persistent provider EntityManager.
*
* @author Scott Marlow
*/
public class TransactionScopedEntityManager extends AbstractEntityManager implements Serializable {
private static final long serialVersionUID = 455498112L;
private final String puScopedName; // Scoped name of the persistent unit
private final Map properties;
private transient EntityManagerFactory emf;
private final SynchronizationType synchronizationType;
private transient TransactionSynchronizationRegistry transactionSynchronizationRegistry;
private transient TransactionManager transactionManager;
private transient Boolean deferDetach;
private transient Boolean skipQueryDetach;
public TransactionScopedEntityManager(String puScopedName, Map properties, EntityManagerFactory emf, SynchronizationType synchronizationType, TransactionSynchronizationRegistry transactionSynchronizationRegistry, TransactionManager transactionManager) {
this.puScopedName = puScopedName;
this.properties = properties;
this.emf = emf;
this.synchronizationType = synchronizationType;
this.transactionSynchronizationRegistry = transactionSynchronizationRegistry;
this.transactionManager = transactionManager;
}
@Override
protected EntityManager getEntityManager() {
EntityManager entityManager;
boolean isInTx;
isInTx = TransactionUtil.isInTx(transactionManager);
if (isInTx) {
entityManager = getOrCreateTransactionScopedEntityManager(emf, puScopedName, properties, synchronizationType);
} else {
entityManager = NonTxEmCloser.get(puScopedName);
if (entityManager == null) {
entityManager = createEntityManager(emf, properties, synchronizationType);
NonTxEmCloser.add(puScopedName, entityManager);
}
}
return entityManager;
}
@Override
protected boolean isExtendedPersistenceContext() {
return false;
}
@Override
protected boolean isInTx() {
return TransactionUtil.isInTx(transactionManager);
}
/**
* Catch the application trying to close the container managed entity manager and throw an IllegalStateException
*/
@Override
public void close() {
// Transaction scoped entity manager will be closed when the (owning) component invocation completes
throw JpaLogger.ROOT_LOGGER.cannotCloseTransactionContainerEntityManger();
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
// read all non-transient fields
in.defaultReadObject();
final ServiceController<?> controller = currentServiceContainer().getService(JPAServiceNames.getPUServiceName(puScopedName));
final PersistenceUnitServiceImpl persistenceUnitService = (PersistenceUnitServiceImpl) controller.getService();
transactionManager = ContextTransactionManager.getInstance();
transactionSynchronizationRegistry = (TransactionSynchronizationRegistry) currentServiceContainer().getService(JPAServiceNames.TRANSACTION_SYNCHRONIZATION_REGISTRY_SERVICE).getValue();
emf = persistenceUnitService.getEntityManagerFactory();
}
private static ServiceContainer currentServiceContainer() {
if(System.getSecurityManager() == null) {
return CurrentServiceContainer.getServiceContainer();
}
return AccessController.doPrivileged(CurrentServiceContainer.GET_ACTION);
}
@Override
public SynchronizationType getSynchronizationType() {
return synchronizationType;
}
/**
* get or create a Transactional entity manager.
* Only call while a transaction is active in the current thread.
*
* @param emf
* @param scopedPuName
* @param properties
* @param synchronizationType
* @return
*/
private EntityManager getOrCreateTransactionScopedEntityManager(
final EntityManagerFactory emf,
final String scopedPuName,
final Map properties,
final SynchronizationType synchronizationType) {
EntityManager entityManager = TransactionUtil.getTransactionScopedEntityManager(puScopedName, transactionSynchronizationRegistry);
if (entityManager == null) {
entityManager = createEntityManager(emf, properties, synchronizationType);
if (ROOT_LOGGER.isDebugEnabled()) {
ROOT_LOGGER.debugf("%s: created entity manager session %s", TransactionUtil.getEntityManagerDetails(entityManager, scopedPuName),
TransactionUtil.getTransaction(transactionManager).toString());
}
TransactionUtil.registerSynchronization(entityManager, scopedPuName, transactionSynchronizationRegistry, transactionManager);
TransactionUtil.putEntityManagerInTransactionRegistry(scopedPuName, entityManager, transactionSynchronizationRegistry);
}
else {
testForMixedSynchronizationTypes(emf, entityManager, puScopedName, synchronizationType, properties);
if (ROOT_LOGGER.isDebugEnabled()) {
ROOT_LOGGER.debugf("%s: reuse entity manager session already in tx %s", TransactionUtil.getEntityManagerDetails(entityManager, scopedPuName),
TransactionUtil.getTransaction(transactionManager).toString());
}
}
return entityManager;
}
private EntityManager createEntityManager(
EntityManagerFactory emf, Map properties, final SynchronizationType synchronizationType) {
// only JPA 2.1 applications can specify UNSYNCHRONIZED.
// Default is SYNCHRONIZED if synchronizationType is not passed to createEntityManager
if (SynchronizationType.UNSYNCHRONIZED.equals(synchronizationType)) {
// properties are allowed to be be null in jpa 2.1
return unsynchronizedEntityManagerWrapper(emf.createEntityManager(synchronizationType, properties));
}
if (properties != null && properties.size() > 0) {
return emf.createEntityManager(properties);
}
return emf.createEntityManager();
}
private EntityManager unsynchronizedEntityManagerWrapper(EntityManager entityManager) {
return new UnsynchronizedEntityManagerWrapper(entityManager);
}
/**
* return true if non-tx invocations should defer detaching of entities until entity manager is closed.
* Note that this is an extension for compatibility with JBoss application server 5.0/6.0 (see AS7-2781)
*/
@Override
protected boolean deferEntityDetachUntilClose() {
if (deferDetach == null)
deferDetach =
(true == Configuration.deferEntityDetachUntilClose(emf.getProperties())? Boolean.TRUE : Boolean.FALSE);
return deferDetach.booleanValue();
}
/**
* return true if non-tx invocations should defer detaching of query results until entity manager is closed.
* Note that this is an extension for compatibility with JBoss application server 5.0/6.0 (see WFLY-12674)
*/
@Override
protected boolean skipQueryDetach() {
if (skipQueryDetach == null)
skipQueryDetach =
(true == Configuration.skipQueryDetach(emf.getProperties())? Boolean.TRUE : Boolean.FALSE);
return skipQueryDetach.booleanValue();
}
/**
* throw error if Jakarta Transactions transaction already has an UNSYNCHRONIZED persistence context and a SYNCHRONIZED persistence context
* is requested. We are only fussy in this test, if the target component persistence context is SYNCHRONIZED.
*
* WFLY-7075 introduces two extensions, allow a (transaction) joined UNSYNCHRONIZED persistence context to be treated as SYNCHRONIZED,
* allow the checking for mixed SynchronizationType to be skipped.
*/
private static void testForMixedSynchronizationTypes(EntityManagerFactory emf, EntityManager entityManagerFromJTA, String scopedPuName, final SynchronizationType targetSynchronizationType, Map targetProperties) {
boolean skipMixedSyncTypeChecking = Configuration.skipMixedSynchronizationTypeCheck(emf, targetProperties); // extension to allow skipping of check based on properties of target entity manager
boolean allowJoinedUnsyncPersistenceContext = Configuration.allowJoinedUnsyncPersistenceContext(emf, targetProperties); // extension to allow joined unsync persistence context to be treated as sync persistence context
if (!skipMixedSyncTypeChecking &&
SynchronizationType.SYNCHRONIZED.equals(targetSynchronizationType) &&
entityManagerFromJTA instanceof SynchronizationTypeAccess &&
SynchronizationType.UNSYNCHRONIZED.equals(((SynchronizationTypeAccess) entityManagerFromJTA).getSynchronizationType())
&& (!allowJoinedUnsyncPersistenceContext || !entityManagerFromJTA.isJoinedToTransaction())) {
throw JpaLogger.ROOT_LOGGER.badSynchronizationTypeCombination(scopedPuName);
}
}
}
| 11,433 | 46.443983 | 257 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/container/SynchronizationTypeAccess.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, 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.jpa.container;
import jakarta.persistence.SynchronizationType;
/**
* SynchronizationTypeAccess provides access to the SynchronizationType for an EntityManager.
*
* @author Scott Marlow
*/
public interface SynchronizationTypeAccess {
SynchronizationType getSynchronizationType();
}
| 1,337 | 36.166667 | 93 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/container/SFSBInjectedXPCs.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.jpa.container;
import java.util.HashMap;
import java.util.Map;
/**
* Tracks extended persistence context that have been injected into a bean.
* Supports two different inheritance models, in an efficient manner.
*
* The reason why both strategies are handled by one class, is to make it easier to use both
* (DEEP + SHALLOW) in the same application as recommended to the Jakarta Persistence EG
* see http://java.net/projects/jpa-spec/lists/jsr338-experts/archive/2012-06/message/13 and the rest of the thread.
*
* Deep (JBoss legacy) mode will inherit across sibling beans and travel several levels up the beans in the
* current Jakarta Enterprise Beans container instance.
*
* Shallow (EE standard) mode will inherit only from the immediate parent bean (in the current Jakarta Enterprise Beans container instance).
*
* @author Scott Marlow
*/
class SFSBInjectedXPCs {
private Map<String, ExtendedEntityManager> injectedXPCsByPuName;
private SFSBInjectedXPCs parent; // parent or null if at top level
private SFSBInjectedXPCs toplevel; // null if already at top level, otherwise references the toplevel
SFSBInjectedXPCs(SFSBInjectedXPCs parent, SFSBInjectedXPCs toplevel) {
this.parent = parent;
this.toplevel = toplevel;
}
SFSBInjectedXPCs getParent() {
return parent;
}
/**
* Note that InjectedXPCs is about creation time of a stateful bean.
* If deep inheritance is enabled, return the top most bean's XPCs
* For shallow inheritance, return the current bean being created XPCs
*/
SFSBInjectedXPCs getTopLevel() {
return toplevel != null ? toplevel : this;
}
void registerDeepInheritance(String scopedPuName, ExtendedEntityManager entityManager) {
SFSBInjectedXPCs target = this;
if (toplevel != null) { // all XPCs are registered at the top level bean
target = toplevel;
}
if (target.injectedXPCsByPuName == null) {
target.injectedXPCsByPuName = new HashMap<String, ExtendedEntityManager>();
}
target.injectedXPCsByPuName.put(scopedPuName, entityManager);
}
void registerShallowInheritance(String scopedPuName, ExtendedEntityManager entityManager) {
SFSBInjectedXPCs target = this;
if (target.injectedXPCsByPuName == null) {
target.injectedXPCsByPuName = new HashMap<String, ExtendedEntityManager>();
}
target.injectedXPCsByPuName.put(scopedPuName, entityManager);
}
ExtendedEntityManager findExtendedPersistenceContextDeepInheritance(String puScopedName) {
SFSBInjectedXPCs target = this;
if (toplevel != null) { // all XPCs are registered at the top level bean
target = toplevel;
}
return target.injectedXPCsByPuName != null ?
target.injectedXPCsByPuName.get(puScopedName) :
null;
}
ExtendedEntityManager findExtendedPersistenceContextShallowInheritance(String puScopedName) {
SFSBInjectedXPCs target = this;
return target.injectedXPCsByPuName != null ?
target.injectedXPCsByPuName.get(puScopedName) :
null;
}
}
| 4,263 | 38.119266 | 140 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/container/CreatedEntityManagers.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.jpa.container;
import java.util.ArrayList;
import java.util.List;
import org.jboss.as.jpa.messages.JpaLogger;
/**
* Tracks the lifecycle of created XPC Entity Managers
*
* @author Scott Marlow
*/
public class CreatedEntityManagers {
private static ExtendedEntityManager[] EMPTY = new ExtendedEntityManager[0];
// at injection time, the SFSB that is being created isn't registered right away
// that happens later at postConstruct time.
//
// The deferToPostConstruct is a one item length store (hack)
private static ThreadLocal<List<ExtendedEntityManager>> deferToPostConstruct = new ThreadLocal<List<ExtendedEntityManager>>() {
protected List<ExtendedEntityManager> initialValue() {
return new ArrayList<ExtendedEntityManager>(1);
}
};
/**
* At injection time of a XPC, register the XPC (step 1 of 2)
* finishRegistrationOfPersistenceContext is step 2
*
* @param xpc The ExtendedEntityManager
*/
public static void registerPersistenceContext(ExtendedEntityManager xpc) {
if (xpc == null) {
throw JpaLogger.ROOT_LOGGER.nullParameter("SFSBXPCMap.RegisterPersistenceContext", "EntityManager");
}
final List<ExtendedEntityManager> store = deferToPostConstruct.get();
store.add(xpc);
}
/**
* Called by postconstruct interceptor
*/
public static ExtendedEntityManager[] getDeferredEntityManagers() {
List<ExtendedEntityManager> store = deferToPostConstruct.get();
try {
if(store.isEmpty()) {
return EMPTY;
} else {
return store.toArray(new ExtendedEntityManager[store.size()]);
}
} finally {
store.clear();
}
}
}
| 2,836 | 34.4625 | 131 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/container/QueryNonTxInvocationDetacher.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.jpa.container;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import jakarta.persistence.EntityManager;
import jakarta.persistence.FlushModeType;
import jakarta.persistence.LockModeType;
import jakarta.persistence.Parameter;
import jakarta.persistence.Query;
import jakarta.persistence.TemporalType;
/**
* for JPA 2.0 section 3.8.6
* used by TransactionScopedEntityManager to detach entities loaded by a query in a non-Jakarta Transactions invocation.
* This could be a proxy but wrapper classes give faster performance.
*
* @author Scott Marlow
*/
public class QueryNonTxInvocationDetacher implements Query {
private final Query underlyingQuery;
private final EntityManager underlyingEntityManager;
QueryNonTxInvocationDetacher(EntityManager underlyingEntityManager, Query underlyingQuery) {
this.underlyingQuery = underlyingQuery;
this.underlyingEntityManager = underlyingEntityManager;
}
@Override
public List getResultList() {
List result = underlyingQuery.getResultList();
/**
* The purpose of this wrapper class is so that we can detach the returned entities from this method.
* Call EntityManager.clear will accomplish that.
*/
underlyingEntityManager.clear();
return result;
}
@Override
public Object getSingleResult() {
Object result = underlyingQuery.getSingleResult();
/**
* The purpose of this wrapper class is so that we can detach the returned entities from this method.
* Call EntityManager.clear will accomplish that.
*/
underlyingEntityManager.clear();
return result;
}
@Override
public int executeUpdate() {
return underlyingQuery.executeUpdate();
}
@Override
public Query setMaxResults(int maxResult) {
underlyingQuery.setMaxResults(maxResult);
return this;
}
@Override
public int getMaxResults() {
return underlyingQuery.getMaxResults();
}
@Override
public Query setFirstResult(int startPosition) {
underlyingQuery.setFirstResult(startPosition);
return this;
}
@Override
public int getFirstResult() {
return underlyingQuery.getFirstResult();
}
@Override
public Query setHint(String hintName, Object value) {
underlyingQuery.setHint(hintName, value);
return this;
}
@Override
public Map<String, Object> getHints() {
return underlyingQuery.getHints();
}
@Override
public <T> Query setParameter(Parameter<T> param, T value) {
underlyingQuery.setParameter(param, value);
return this;
}
@Override
public Query setParameter(Parameter<Calendar> param, Calendar value, TemporalType temporalType) {
underlyingQuery.setParameter(param, value, temporalType);
return this;
}
@Override
public Query setParameter(Parameter<Date> param, Date value, TemporalType temporalType) {
underlyingQuery.setParameter(param, value, temporalType);
return this;
}
@Override
public Query setParameter(String name, Object value) {
underlyingQuery.setParameter(name, value);
return this;
}
@Override
public Query setParameter(String name, Calendar value, TemporalType temporalType) {
underlyingQuery.setParameter(name, value, temporalType);
return this;
}
@Override
public Query setParameter(String name, Date value, TemporalType temporalType) {
underlyingQuery.setParameter(name, value, temporalType);
return this;
}
@Override
public Query setParameter(int position, Object value) {
underlyingQuery.setParameter(position, value);
return this;
}
@Override
public Query setParameter(int position, Calendar value, TemporalType temporalType) {
underlyingQuery.setParameter(position, value, temporalType);
return this;
}
@Override
public Query setParameter(int position, Date value, TemporalType temporalType) {
underlyingQuery.setParameter(position, value, temporalType);
return this;
}
@Override
public Set<Parameter<?>> getParameters() {
return underlyingQuery.getParameters();
}
@Override
public Parameter<?> getParameter(String name) {
return underlyingQuery.getParameter(name);
}
@Override
public <T> Parameter<T> getParameter(String name, Class<T> type) {
return underlyingQuery.getParameter(name, type);
}
@Override
public Parameter<?> getParameter(int position) {
return underlyingQuery.getParameter(position);
}
@Override
public <T> Parameter<T> getParameter(int position, Class<T> type) {
return underlyingQuery.getParameter(position, type);
}
@Override
public boolean isBound(Parameter<?> param) {
return underlyingQuery.isBound(param);
}
@Override
public <T> T getParameterValue(Parameter<T> param) {
return underlyingQuery.getParameterValue(param);
}
@Override
public Object getParameterValue(String name) {
return underlyingQuery.getParameterValue(name);
}
@Override
public Object getParameterValue(int position) {
return underlyingQuery.getParameterValue(position);
}
@Override
public Query setFlushMode(FlushModeType flushMode) {
underlyingQuery.setFlushMode(flushMode);
return this;
}
@Override
public FlushModeType getFlushMode() {
return underlyingQuery.getFlushMode();
}
@Override
public Query setLockMode(LockModeType lockMode) {
underlyingQuery.setLockMode(lockMode);
return this;
}
@Override
public LockModeType getLockMode() {
return underlyingQuery.getLockMode();
}
@Override
public <T> T unwrap(Class<T> cls) {
return underlyingQuery.unwrap(cls);
}
}
| 7,108 | 28.376033 | 120 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/container/StoredProcedureQueryNonTxInvocationDetacher.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.jpa.container;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import jakarta.persistence.EntityManager;
import jakarta.persistence.FlushModeType;
import jakarta.persistence.LockModeType;
import jakarta.persistence.Parameter;
import jakarta.persistence.ParameterMode;
import jakarta.persistence.Query;
import jakarta.persistence.StoredProcedureQuery;
import jakarta.persistence.TemporalType;
/**
* StoredProcedureQueryNonTxInvocationDetacher
*
* for JPA 2.1 (Query Execution) section 3.10.7
* used by TransactionScopedEntityManager to clear persistence context after StoredProcedureQuery (non-Jakarta Transactions) calls.
*
* @author Scott Marlow
*/
public class StoredProcedureQueryNonTxInvocationDetacher implements StoredProcedureQuery {
private final EntityManager underlyingEntityManager;
private final StoredProcedureQuery underlyingStoredProcedureQuery;
public StoredProcedureQueryNonTxInvocationDetacher(EntityManager underlyingEntityManager, StoredProcedureQuery underlyingStoredProcedureQuery) {
this.underlyingEntityManager = underlyingEntityManager;
this.underlyingStoredProcedureQuery = underlyingStoredProcedureQuery;
}
@Override
public List getResultList() {
try {
return underlyingStoredProcedureQuery.getResultList();
} finally {
underlyingEntityManager.clear();
}
}
@Override
public Object getSingleResult() {
try {
return underlyingStoredProcedureQuery.getSingleResult();
} finally {
underlyingEntityManager.clear();
}
}
@Override
public int executeUpdate() {
return underlyingStoredProcedureQuery.executeUpdate();
}
@Override
public Query setMaxResults(int maxResult) {
return underlyingStoredProcedureQuery.setMaxResults(maxResult);
}
@Override
public int getMaxResults() {
return underlyingStoredProcedureQuery.getMaxResults();
}
@Override
public Query setFirstResult(int startPosition) {
return underlyingStoredProcedureQuery.setFirstResult(startPosition);
}
@Override
public int getFirstResult() {
return underlyingStoredProcedureQuery.getFirstResult();
}
@Override
public StoredProcedureQuery setHint(String hintName, Object value) {
return underlyingStoredProcedureQuery.setHint(hintName, value);
}
@Override
public Map<String, Object> getHints() {
return underlyingStoredProcedureQuery.getHints();
}
@Override
public <T> StoredProcedureQuery setParameter(Parameter<T> param, T value) {
return underlyingStoredProcedureQuery.setParameter(param, value);
}
@Override
public StoredProcedureQuery setParameter(Parameter<Calendar> param, Calendar value, TemporalType temporalType) {
return underlyingStoredProcedureQuery.setParameter(param, value, temporalType);
}
@Override
public StoredProcedureQuery setParameter(Parameter<Date> param, Date value, TemporalType temporalType) {
return underlyingStoredProcedureQuery.setParameter(param, value, temporalType);
}
@Override
public StoredProcedureQuery setParameter(String name, Object value) {
return underlyingStoredProcedureQuery.setParameter(name, value);
}
@Override
public StoredProcedureQuery setParameter(String name, Calendar value, TemporalType temporalType) {
return underlyingStoredProcedureQuery.setParameter(name, value, temporalType);
}
@Override
public StoredProcedureQuery setParameter(String name, Date value, TemporalType temporalType) {
return underlyingStoredProcedureQuery.setParameter(name, value, temporalType);
}
@Override
public StoredProcedureQuery setParameter(int position, Object value) {
return underlyingStoredProcedureQuery.setParameter(position, value);
}
@Override
public StoredProcedureQuery setParameter(int position, Calendar value, TemporalType temporalType) {
return underlyingStoredProcedureQuery.setParameter(position, value, temporalType);
}
@Override
public StoredProcedureQuery setParameter(int position, Date value, TemporalType temporalType) {
return underlyingStoredProcedureQuery.setParameter(position, value, temporalType);
}
@Override
public Set<Parameter<?>> getParameters() {
return underlyingStoredProcedureQuery.getParameters();
}
@Override
public Parameter<?> getParameter(String name) {
return underlyingStoredProcedureQuery.getParameter(name);
}
@Override
public <T> Parameter<T> getParameter(String name, Class<T> type) {
return underlyingStoredProcedureQuery.getParameter(name, type);
}
@Override
public Parameter<?> getParameter(int position) {
return underlyingStoredProcedureQuery.getParameter(position);
}
@Override
public <T> Parameter<T> getParameter(int position, Class<T> type) {
return underlyingStoredProcedureQuery.getParameter(position, type);
}
@Override
public boolean isBound(Parameter<?> param) {
return underlyingStoredProcedureQuery.isBound(param);
}
@Override
public <T> T getParameterValue(Parameter<T> param) {
return underlyingStoredProcedureQuery.getParameterValue(param);
}
@Override
public Object getParameterValue(String name) {
return underlyingStoredProcedureQuery.getParameterValue(name);
}
@Override
public Object getParameterValue(int position) {
return underlyingStoredProcedureQuery.getParameterValue(position);
}
@Override
public StoredProcedureQuery setFlushMode(FlushModeType flushMode) {
return underlyingStoredProcedureQuery.setFlushMode(flushMode);
}
@Override
public FlushModeType getFlushMode() {
return underlyingStoredProcedureQuery.getFlushMode();
}
@Override
public Query setLockMode(LockModeType lockMode) {
return underlyingStoredProcedureQuery.setLockMode(lockMode);
}
@Override
public LockModeType getLockMode() {
return underlyingStoredProcedureQuery.getLockMode();
}
@Override
public <T> T unwrap(Class<T> cls) {
return underlyingStoredProcedureQuery.unwrap(cls);
}
@Override
public StoredProcedureQuery registerStoredProcedureParameter(int position, Class type, ParameterMode mode) {
return underlyingStoredProcedureQuery.registerStoredProcedureParameter(position, type, mode);
}
@Override
public StoredProcedureQuery registerStoredProcedureParameter(String parameterName, Class type, ParameterMode mode) {
return underlyingStoredProcedureQuery.registerStoredProcedureParameter(parameterName, type, mode);
}
@Override
public Object getOutputParameterValue(int position) {
return underlyingStoredProcedureQuery.getOutputParameterValue(position);
}
@Override
public Object getOutputParameterValue(String parameterName) {
return underlyingStoredProcedureQuery.getOutputParameterValue(parameterName);
}
@Override
public boolean execute() {
return underlyingStoredProcedureQuery.execute();
}
@Override
public boolean hasMoreResults() {
return underlyingStoredProcedureQuery.hasMoreResults();
}
@Override
public int getUpdateCount() {
return underlyingStoredProcedureQuery.getUpdateCount();
}
}
| 8,626 | 32.05364 | 148 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/container/SFSBCallStack.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.jpa.container;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.jboss.as.jpa.messages.JpaLogger;
/**
* For tracking of SFSB call stack on a per thread basis.
* When a SFSB with an extended persistence context (XPC) is injected, the SFSB call stack is searched for
* a XPC that can be inherited from.
*
* @author Scott Marlow
*/
public class SFSBCallStack {
private static final ThreadLocal<SFSBCallStackThreadData> CURRENT = new ThreadLocal<SFSBCallStackThreadData>() {
@Override
protected SFSBCallStackThreadData initialValue() {
return new SFSBCallStackThreadData();
}
};
public static int getSFSBCreationBeanNestingLevel() {
return CURRENT.get().creationBeanNestingLevel;
}
/**
* called from SFSBPreCreateInterceptor, before bean creation
*/
public static void beginSfsbCreation() {
SFSBCallStackThreadData data = CURRENT.get();
int no = data.creationBeanNestingLevel;
if (no == 0) {
data.creationTimeXPCRegistration = new HashMap<String, ExtendedEntityManager>();
// create new tracking structure (passing in parent levels tracking structure or null if toplevel)
data.creationTimeInjectedXPCs = new SFSBInjectedXPCs(data.creationTimeInjectedXPCs, null);
}
else {
// create new tracking structure (passing in parent levels tracking structure or null if toplevel)
SFSBInjectedXPCs parent = data.creationTimeInjectedXPCs;
data.creationTimeInjectedXPCs = new SFSBInjectedXPCs(parent, parent.getTopLevel());
}
data.creationBeanNestingLevel++;
}
/**
* called from SFSBPreCreateInterceptor, after bean creation
*/
public static void endSfsbCreation() {
SFSBCallStackThreadData data = CURRENT.get();
int no = data.creationBeanNestingLevel;
no--;
data.creationBeanNestingLevel = no;
if (no == 0) {
// Completed creating top level bean, remove 'xpc creation tracking' thread local
data.creationTimeXPCRegistration = null;
data.creationTimeInjectedXPCs = null;
}
else {
// finished creating a sub-bean, switch to parent level 'xpc creation tracking'
data.creationTimeInjectedXPCs = data.creationTimeInjectedXPCs.getParent();
}
}
static SFSBInjectedXPCs getSFSBCreationTimeInjectedXPCs(final String puScopedName) {
SFSBInjectedXPCs result = CURRENT.get().creationTimeInjectedXPCs;
if (result == null) {
throw JpaLogger.ROOT_LOGGER.xpcOnlyFromSFSB(puScopedName);
}
return result;
}
/**
* Return the current entity manager call stack
*
* @return call stack (may be empty but never null)
*/
public static ArrayList<Map<String, ExtendedEntityManager>> currentSFSBCallStack() {
return CURRENT.get().invocationStack;
}
/**
* return for just the current entity manager invocation
*
* @return
*/
public static Map<String, ExtendedEntityManager> currentSFSBCallStackInvocation() {
ArrayList<Map<String, ExtendedEntityManager>> stack = CURRENT.get().invocationStack;
if ( stack != null && !stack.isEmpty()) {
return stack.get(stack.size() - 1);
}
return null;
}
/**
* Push the passed SFSB context handle onto the invocation call stack
*
* @param entityManagers the entity manager map
*/
public static void pushCall(Map<String, ExtendedEntityManager> entityManagers) {
currentSFSBCallStack().add(entityManagers);
if (entityManagers != null) {
/**
* JPA 2.0 spec section 7.9.1 Container Responsibilities:
* "When a business method of the stateful session bean is invoked,
* if the stateful session bean uses container managed transaction demarcation,
* and the entity manager is not already associated with the current Jakarta Transactions transaction,
* the container associates the entity manager with the current Jakarta Transactions transaction and
* calls EntityManager.joinTransaction.
* "
*/
for(ExtendedEntityManager extendedEntityManager: entityManagers.values()) {
extendedEntityManager.internalAssociateWithJtaTx();
}
}
}
/**
* Pops the current SFSB invocation off the invocation call stack
*
* @return the entity manager map
*/
public static Map<String, ExtendedEntityManager> popCall() {
ArrayList<Map<String, ExtendedEntityManager>> stack = currentSFSBCallStack();
Map<String, ExtendedEntityManager> result = stack.remove(stack.size() - 1);
stack.trimToSize();
return result;
}
/**
* gets the current SFSB invocation off the invocation call stack
*
* @return the entity manager map
*/
static Map<String, ExtendedEntityManager> getCurrentCall() {
ArrayList<Map<String, ExtendedEntityManager>> stack = currentSFSBCallStack();
Map<String, ExtendedEntityManager> result = null;
if (stack != null) {
result = stack.get(stack.size() - 1);
}
return result;
}
private static class SFSBCallStackThreadData {
/**
* Each thread will have its own list of SFSB invocations in progress.
*/
private ArrayList<Map<String, ExtendedEntityManager>> invocationStack = new ArrayList<Map<String, ExtendedEntityManager>>();
/**
* During SFSB creation, track the injected extended persistence contexts
*/
private Map<String, ExtendedEntityManager> creationTimeXPCRegistration = null;
private SFSBInjectedXPCs creationTimeInjectedXPCs;
/**
* Track the SFSB bean injection nesting level. Zero indicates the top level bean, one is the first level of SFSBs injected,
* two is the second level of SFSBs injected...
*/
private int creationBeanNestingLevel = 0;
}
}
| 7,258 | 36.611399 | 133 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/container/UnsynchronizedEntityManagerWrapper.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, 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.jpa.container;
import java.util.List;
import java.util.Map;
import jakarta.persistence.EntityGraph;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityTransaction;
import jakarta.persistence.FlushModeType;
import jakarta.persistence.LockModeType;
import jakarta.persistence.Query;
import jakarta.persistence.StoredProcedureQuery;
import jakarta.persistence.SynchronizationType;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaDelete;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.CriteriaUpdate;
import jakarta.persistence.metamodel.Metamodel;
/**
* UnsynchronizedEntityManagerWrapper helps track transaction scoped persistence contexts that are SynchronizationType.UNSYNCHRONIZED,
* for error checking.
*
* If an SynchronizationType.SYNCHRONIZED transaction scoped persistence context is accessed
* while there is already an SynchronizationType.UNSYNCHRONIZED (with the same pu name + in active Jakarta Transactions TX),
* an IllegalStateException needs to be thrown as per the JPA 2.1 spec (see 7.6.4.1 Requirements for Persistence Context Propagation).
*
* @author Scott Marlow
*/
public class UnsynchronizedEntityManagerWrapper implements EntityManager, SynchronizationTypeAccess {
private final EntityManager entityManager;
public UnsynchronizedEntityManagerWrapper(EntityManager entityManager) {
this.entityManager = entityManager;
}
/* SynchronizationTypeAccess methods */
@Override
public SynchronizationType getSynchronizationType() {
return SynchronizationType.UNSYNCHRONIZED;
}
/* EntityManager methods */
@Override
public void clear() {
entityManager.clear();
}
@Override
public void close() {
entityManager.close();
}
@Override
public boolean contains(Object entity) {
return entityManager.contains(entity);
}
@Override
public EntityGraph<?> createEntityGraph(String graphName) {
return entityManager.createEntityGraph(graphName);
}
@Override
public <T> EntityGraph<T> createEntityGraph(Class<T> rootType) {
return entityManager.createEntityGraph(rootType);
}
@Override
public Query createNamedQuery(String name) {
return entityManager.createNamedQuery(name);
}
@Override
public <T> TypedQuery<T> createNamedQuery(String name, Class<T> resultClass) {
return entityManager.createNamedQuery(name, resultClass);
}
@Override
public StoredProcedureQuery createNamedStoredProcedureQuery(String name) {
return entityManager.createNamedStoredProcedureQuery(name);
}
@Override
public Query createNativeQuery(String sqlString) {
return entityManager.createNativeQuery(sqlString);
}
@Override
public Query createNativeQuery(String sqlString, Class resultClass) {
return entityManager.createNativeQuery(sqlString, resultClass);
}
@Override
public Query createNativeQuery(String sqlString, String resultSetMapping) {
return entityManager.createNativeQuery(sqlString, resultSetMapping);
}
@Override
public <T> TypedQuery<T> createQuery(CriteriaQuery<T> criteriaQuery) {
return entityManager.createQuery(criteriaQuery);
}
@Override
public Query createQuery(CriteriaDelete deleteQuery) {
return entityManager.createQuery(deleteQuery);
}
@Override
public Query createQuery(String qlString) {
return entityManager.createQuery(qlString);
}
@Override
public <T> TypedQuery<T> createQuery(String qlString, Class<T> resultClass) {
return entityManager.createQuery(qlString, resultClass);
}
@Override
public Query createQuery(CriteriaUpdate updateQuery) {
return entityManager.createQuery(updateQuery);
}
@Override
public StoredProcedureQuery createStoredProcedureQuery(String procedureName) {
return entityManager.createStoredProcedureQuery(procedureName);
}
@Override
public StoredProcedureQuery createStoredProcedureQuery(String procedureName, Class... resultClasses) {
return entityManager.createStoredProcedureQuery(procedureName, resultClasses);
}
@Override
public StoredProcedureQuery createStoredProcedureQuery(String procedureName, String... resultSetMappings) {
return entityManager.createStoredProcedureQuery(procedureName, resultSetMappings);
}
@Override
public void detach(Object entity) {
entityManager.detach(entity);
}
@Override
public <T> T find(Class<T> entityClass, Object primaryKey) {
return entityManager.find(entityClass, primaryKey);
}
@Override
public <T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockMode) {
return entityManager.find(entityClass, primaryKey, lockMode);
}
@Override
public <T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockMode, Map<String, Object> properties) {
return entityManager.find(entityClass, primaryKey, lockMode, properties);
}
@Override
public <T> T find(Class<T> entityClass, Object primaryKey, Map<String, Object> properties) {
return entityManager.find(entityClass, primaryKey, properties);
}
@Override
public void flush() {
entityManager.flush();
}
@Override
public CriteriaBuilder getCriteriaBuilder() {
return entityManager.getCriteriaBuilder();
}
@Override
public Object getDelegate() {
return entityManager.getDelegate();
}
@Override
public EntityGraph<?> getEntityGraph(String graphName) {
return entityManager.getEntityGraph(graphName);
}
@Override
public <T> List<EntityGraph<? super T>> getEntityGraphs(Class<T> entityClass) {
return entityManager.getEntityGraphs(entityClass);
}
@Override
public EntityManagerFactory getEntityManagerFactory() {
return entityManager.getEntityManagerFactory();
}
@Override
public FlushModeType getFlushMode() {
return entityManager.getFlushMode();
}
@Override
public LockModeType getLockMode(Object entity) {
return entityManager.getLockMode(entity);
}
@Override
public Metamodel getMetamodel() {
return entityManager.getMetamodel();
}
@Override
public Map<String, Object> getProperties() {
return entityManager.getProperties();
}
@Override
public <T> T getReference(Class<T> entityClass, Object primaryKey) {
return entityManager.getReference(entityClass, primaryKey);
}
@Override
public EntityTransaction getTransaction() {
return entityManager.getTransaction();
}
@Override
public boolean isJoinedToTransaction() {
return entityManager.isJoinedToTransaction();
}
@Override
public boolean isOpen() {
return entityManager.isOpen();
}
@Override
public void joinTransaction() {
entityManager.joinTransaction();
}
@Override
public void lock(Object entity, LockModeType lockMode) {
entityManager.lock(entity, lockMode);
}
@Override
public void lock(Object entity, LockModeType lockMode, Map<String, Object> properties) {
entityManager.lock(entity, lockMode, properties);
}
@Override
public <T> T merge(T entity) {
return entityManager.merge(entity);
}
@Override
public void persist(Object entity) {
entityManager.persist(entity);
}
@Override
public void refresh(Object entity) {
entityManager.refresh(entity);
}
@Override
public void refresh(Object entity, LockModeType lockMode) {
entityManager.refresh(entity, lockMode);
}
@Override
public void refresh(Object entity, LockModeType lockMode, Map<String, Object> properties) {
entityManager.refresh(entity, lockMode, properties);
}
@Override
public void refresh(Object entity, Map<String, Object> properties) {
entityManager.refresh(entity, properties);
}
@Override
public void remove(Object entity) {
entityManager.remove(entity);
}
@Override
public void setFlushMode(FlushModeType flushMode) {
entityManager.setFlushMode(flushMode);
}
@Override
public void setProperty(String propertyName, Object value) {
entityManager.setProperty(propertyName, value);
}
@Override
public <T> T unwrap(Class<T> cls) {
return entityManager.unwrap(cls);
}
}
| 9,799 | 29.153846 | 134 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/container/ExtendedEntityManager.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.jpa.container;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
import java.io.IOException;
import java.io.Serializable;
import java.security.AccessController;
import java.security.PrivilegedAction;
import jakarta.persistence.EntityManager;
import jakarta.persistence.SynchronizationType;
import jakarta.transaction.TransactionManager;
import jakarta.transaction.TransactionSynchronizationRegistry;
import org.jboss.as.jpa.messages.JpaLogger;
import org.jboss.as.jpa.transaction.TransactionUtil;
import org.jboss.as.jpa.util.JPAServiceNames;
import org.jboss.as.server.CurrentServiceContainer;
import org.wildfly.security.manager.WildFlySecurityManager;
import org.wildfly.transaction.client.ContextTransactionManager;
/**
* Represents the Extended persistence context injected into a stateful bean. At bean invocation time,
* will join the active Jakarta Transactions transaction if one is present. If no active Jakarta Transactions transaction is present,
* created/deleted/updated/loaded entities will remain associated with the entity manager until it is joined with a
* transaction (commit will save the changes, rollback will lose them).
* <p/>
* At injection time, an instance of this class is associated with the SFSB.
* During a SFSB1 invocation, if a new SFSB2 is created with an XPC referencing the same
* persistence unit, the new SFSB2 will inherit the same persistence context from SFSB1.
* Both SFSB1 + SFSB2 will maintain a reference to the underlying persistence context, such that
* the underlying persistence context will be kept around until both SFSB1 + SFSB2 are destroyed.
* At cluster replication time or passivation, both SFSB1 + SFSB2 will be serialized consecutively and this
* instance will only be serialized once.
* <p/>
* Note: Unlike TransactionScopedEntityManager, ExtendedEntityManager will directly be shared instead of the
* underlying EntityManager.
* <p/>
*
* During serialization, A NotSerializableException will be thrown if the following conditions are not met:
* - The underlying persistence provider (entity manager) must be Serializable.
* - The entity classes in the extended persistence context must also be Serializable.
*
* @author Scott Marlow
*/
public class ExtendedEntityManager extends AbstractEntityManager implements Serializable, SynchronizationTypeAccess {
/**
* Adding fields to this class, may require incrementing the serialVersionUID (always increment it).
* If a transient field is added that isn't serialized, serialVersionUID doesn't need to change.
* By default transient fields are not serialized but can be manually (de)serialized in readObject/writeObject.
* Just make sure you think about whether the newly added field should be serialized.
*/
private static final long serialVersionUID = 432438L;
/**
* EntityManager obtained from the persistence provider that represents the XPC.
*/
private EntityManager underlyingEntityManager;
/**
* fully application scoped persistence unit name
*/
private String puScopedName;
private transient boolean isInTx;
/**
* Track the number of stateful session beans that are referencing the extended persistence context.
* when the reference count reaches zero, the persistence context is closed.
*/
private int referenceCount = 1;
/**
* the UUID representing the extended persistence context
*/
private final ExtendedEntityManagerKey ID = ExtendedEntityManagerKey.extendedEntityManagerID();
private final transient boolean isTraceEnabled = ROOT_LOGGER.isTraceEnabled();
private final SynchronizationType synchronizationType;
private transient TransactionSynchronizationRegistry transactionSynchronizationRegistry;
private transient TransactionManager transactionManager;
public ExtendedEntityManager(final String puScopedName, final EntityManager underlyingEntityManager, final SynchronizationType synchronizationType, TransactionSynchronizationRegistry transactionSynchronizationRegistry, TransactionManager transactionManager) {
this.underlyingEntityManager = underlyingEntityManager;
this.puScopedName = puScopedName;
this.synchronizationType = synchronizationType;
this.transactionSynchronizationRegistry = transactionSynchronizationRegistry;
this.transactionManager = transactionManager;
}
/**
* The Jakarta Persistence SFSB interceptor will track the stack of SFSB invocations. The underlying EM will be obtained from
* the current SFSB being invoked (via our Jakarta Persistence SFSB interceptor).
*
* Every entity manager call (to AbstractEntityManager) will call this method to get the underlying entity manager
* (e.g. the Hibernate persistence provider).
*
* See org.jboss.ejb3.stateful.EJB3XPCResolver.getExtendedPersistenceContext() to see the as6 implementation of this.
*
* @return EntityManager
*/
@Override
protected EntityManager getEntityManager() {
internalAssociateWithJtaTx();
return underlyingEntityManager;
}
/**
* Associate the extended persistence context with the current Jakarta Transactions transaction (if one is found)
*
* this method is private to the Jakarta Persistence subsystem
*/
public void internalAssociateWithJtaTx() {
isInTx = TransactionUtil.isInTx(transactionManager);
// ensure that a different XPC (with same name) is not already present in the TX
if (isInTx) {
// 7.6.3.1 throw EJBException if a different persistence context is already joined to the
// transaction (with the same puScopedName).
EntityManager existing = TransactionUtil.getTransactionScopedEntityManager(puScopedName, transactionSynchronizationRegistry);
if (existing != null && existing != this) {
// should be enough to test if not the same object
throw JpaLogger.ROOT_LOGGER.cannotUseExtendedPersistenceTransaction(puScopedName, existing, this);
} else if (existing == null) {
if (SynchronizationType.SYNCHRONIZED.equals(synchronizationType)) {
// Jakarta Persistence 7.9.1 join the transaction if not already done for SynchronizationType.SYNCHRONIZED.
underlyingEntityManager.joinTransaction();
}
// associate the entity manager with the current transaction
TransactionUtil.putEntityManagerInTransactionRegistry(puScopedName, this, transactionSynchronizationRegistry);
}
}
}
@Override
protected boolean isExtendedPersistenceContext() {
return true;
}
@Override
protected boolean isInTx() {
return this.isInTx;
}
/**
* Catch the application trying to close the container managed entity manager and throw an IllegalStateException
*/
@Override
public void close() {
// An extended entity manager will be closed when the Jakarta Enterprise Beans SFSB @remove method is invoked.
throw JpaLogger.ROOT_LOGGER.cannotCloseContainerManagedEntityManager();
}
/**
* Start of reference count handling.
* synchronize on *this* to protect access to the referenceCount (should be mostly uncontended locks).
*
*/
public synchronized void increaseReferenceCount() {
referenceCount++;
}
public synchronized int getReferenceCount() {
return referenceCount;
}
public synchronized void refCountedClose() {
referenceCount--;
if (referenceCount == 0) {
if (underlyingEntityManager.isOpen()) {
underlyingEntityManager.close();
if (isTraceEnabled) {
ROOT_LOGGER.tracef("closed extended persistence context (%s)", puScopedName);
}
}
}
else if (isTraceEnabled) {
ROOT_LOGGER.tracef("decremented extended persistence context (%s) owner count to %d",
puScopedName, referenceCount);
}
// referenceCount should never be negative, if it is we need to fix the bug that caused it to decrement too much
if (referenceCount < 0) {
throw JpaLogger.ROOT_LOGGER.referenceCountedEntityManagerNegativeCount(referenceCount, getScopedPuName());
}
}
/**
* End of reference count handling
*/
@Override
public String toString() {
return "ExtendedEntityManager [" + puScopedName + "]";
}
/**
* Get the fully application scoped persistence unit name
* Private api
* @return scoped pu name
*/
public String getScopedPuName() {
return puScopedName;
}
/**
* Check if this object's UUID is equal to the otherObject's UUID
*
* @param otherObject
* @return
*/
@Override
public boolean equals(Object otherObject) {
if (this == otherObject) return true;
if (otherObject == null || getClass() != otherObject.getClass()) return false;
ExtendedEntityManager that = (ExtendedEntityManager) otherObject;
if (!ID.equals(that.ID)) return false;
return true;
}
@Override
public int hashCode() {
// return hashCode of the ExtendedEntityManagerKey
return ID != null ? ID.hashCode() : 0;
}
@Override // SynchronizationTypeAccess
public SynchronizationType getSynchronizationType() {
return synchronizationType;
}
@Override
protected boolean deferEntityDetachUntilClose() {
return false;
}
@Override
protected boolean skipQueryDetach() {
return false;
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
if(WildFlySecurityManager.isChecking()) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
transactionManager = ContextTransactionManager.getInstance();
transactionSynchronizationRegistry = (TransactionSynchronizationRegistry) CurrentServiceContainer.getServiceContainer().getService(JPAServiceNames.TRANSACTION_SYNCHRONIZATION_REGISTRY_SERVICE).getValue();
return null;
}
});
} else {
transactionManager = ContextTransactionManager.getInstance();
transactionSynchronizationRegistry = (TransactionSynchronizationRegistry) CurrentServiceContainer.getServiceContainer().getService(JPAServiceNames.TRANSACTION_SYNCHRONIZATION_REGISTRY_SERVICE).getValue();
}
}
}
| 11,884 | 39.016835 | 263 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/container/TypedQueryNonTxInvocationDetacher.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.jpa.container;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import jakarta.persistence.EntityManager;
import jakarta.persistence.FlushModeType;
import jakarta.persistence.LockModeType;
import jakarta.persistence.Parameter;
import jakarta.persistence.TemporalType;
import jakarta.persistence.TypedQuery;
/**
* for JPA 2.0 section 3.8.6
* used by TransactionScopedEntityManager to detach entities loaded by a query in a non-Jakarta Transactions invocation.
* This could be a proxy but wrapper classes give faster performance.
*
* @author Scott Marlow
*/
public class TypedQueryNonTxInvocationDetacher<X> implements TypedQuery<X> {
private final TypedQuery<X> underlyingQuery;
private final EntityManager underlyingEntityManager;
TypedQueryNonTxInvocationDetacher(EntityManager underlyingEntityManager, TypedQuery<X> underlyingQuery) {
this.underlyingQuery = underlyingQuery;
this.underlyingEntityManager = underlyingEntityManager;
}
@Override
public List<X> getResultList() {
List<X> result = underlyingQuery.getResultList();
/**
* The purpose of this wrapper class is so that we can detach the returned entities from this method.
* Call EntityManager.clear will accomplish that.
*/
underlyingEntityManager.clear();
return result;
}
@Override
public X getSingleResult() {
X result = (X)underlyingQuery.getSingleResult();
/**
* The purpose of this wrapper class is so that we can detach the returned entities from this method.
* Call EntityManager.clear will accomplish that.
*/
underlyingEntityManager.clear();
return result;
}
@Override
public int executeUpdate() {
return underlyingQuery.executeUpdate();
}
@Override
public TypedQuery<X> setMaxResults(int maxResult) {
underlyingQuery.setMaxResults(maxResult);
return this;
}
@Override
public int getMaxResults() {
return underlyingQuery.getMaxResults();
}
@Override
public TypedQuery<X> setFirstResult(int startPosition) {
underlyingQuery.setFirstResult(startPosition);
return this;
}
@Override
public int getFirstResult() {
return underlyingQuery.getFirstResult();
}
@Override
public TypedQuery<X> setHint(String hintName, Object value) {
underlyingQuery.setHint(hintName, value);
return this;
}
@Override
public <T> TypedQuery<X> setParameter(Parameter<T> param, T value) {
underlyingQuery.setParameter(param, value);
return this;
}
@Override
public TypedQuery<X> setParameter(Parameter<Calendar> param, Calendar value, TemporalType temporalType) {
underlyingQuery.setParameter(param, value, temporalType);
return this;
}
@Override
public TypedQuery<X> setParameter(Parameter<Date> param, Date value, TemporalType temporalType) {
underlyingQuery.setParameter(param, value, temporalType);
return this;
}
@Override
public Map<String, Object> getHints() {
return underlyingQuery.getHints();
}
@Override
public TypedQuery<X> setParameter(String name, Object value) {
underlyingQuery.setParameter(name, value);
return this;
}
@Override
public TypedQuery<X> setParameter(String name, Calendar value, TemporalType temporalType) {
underlyingQuery.setParameter(name, value, temporalType);
return this;
}
@Override
public TypedQuery<X> setParameter(String name, Date value, TemporalType temporalType) {
underlyingQuery.setParameter(name, value, temporalType);
return this;
}
@Override
public TypedQuery<X> setParameter(int position, Object value) {
underlyingQuery.setParameter(position, value);
return this;
}
@Override
public TypedQuery<X> setParameter(int position, Calendar value, TemporalType temporalType) {
underlyingQuery.setParameter(position, value, temporalType);
return this;
}
@Override
public TypedQuery<X> setParameter(int position, Date value, TemporalType temporalType) {
underlyingQuery.setParameter(position, value, temporalType);
return this;
}
@Override
public Set<Parameter<?>> getParameters() {
return underlyingQuery.getParameters();
}
@Override
public Parameter<?> getParameter(String name) {
return underlyingQuery.getParameter(name);
}
@Override
public <T> Parameter<T> getParameter(String name, Class<T> type) {
return underlyingQuery.getParameter(name, type);
}
@Override
public Parameter<?> getParameter(int position) {
return underlyingQuery.getParameter(position);
}
@Override
public <T> Parameter<T> getParameter(int position, Class<T> type) {
return underlyingQuery.getParameter(position, type);
}
@Override
public boolean isBound(Parameter<?> param) {
return underlyingQuery.isBound(param);
}
@Override
public <T> T getParameterValue(Parameter<T> param) {
return underlyingQuery.getParameterValue(param);
}
@Override
public Object getParameterValue(String name) {
return underlyingQuery.getParameterValue(name);
}
@Override
public Object getParameterValue(int position) {
return underlyingQuery.getParameterValue(position);
}
@Override
public TypedQuery<X> setFlushMode(FlushModeType flushMode) {
underlyingQuery.setFlushMode(flushMode);
return this;
}
@Override
public FlushModeType getFlushMode() {
return underlyingQuery.getFlushMode();
}
@Override
public TypedQuery<X> setLockMode(LockModeType lockMode) {
underlyingQuery.setLockMode(lockMode);
return this;
}
@Override
public LockModeType getLockMode() {
return underlyingQuery.getLockMode();
}
@Override
public <T> T unwrap(Class<T> cls) {
return underlyingQuery.unwrap(cls);
}
}
| 7,260 | 29.128631 | 120 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/container/ExtendedEntityManagerKey.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.jpa.container;
import java.io.Serializable;
import java.util.UUID;
/**
* Uniquely identifies an ExtendedEntityManager instance.
*
* @author Scott Marlow
*/
public class ExtendedEntityManagerKey implements Serializable {
private static final long serialVersionUID = 135790L;
private final String ID = UUID.randomUUID().toString();
/**
* generates a new unique ExtendedEntityManagerID
* @return unique ExtendedEntityManagerID
*/
public static ExtendedEntityManagerKey extendedEntityManagerID() {
return new ExtendedEntityManagerKey();
}
@Override
public String toString() {
return "ExtendedEntityManagerKey{" +
"ID='" + ID + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || ! (o instanceof ExtendedEntityManagerKey))
return false;
ExtendedEntityManagerKey that = (ExtendedEntityManagerKey) o;
if (ID != null ? !ID.equals(that.getKey()) : that.getKey() != null)
return false;
return true;
}
@Override
public int hashCode() {
return ID != null ? ID.hashCode() : 0;
}
public String getKey() {
return ID;
}
}
| 2,329 | 28.871795 | 75 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/container/EntityManagerUnwrappedTargetInvocationHandler.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.jpa.container;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import jakarta.persistence.EntityManager;
/**
* Handle method execution delegation to a wrapped object using the passed entity manager to obtain the target
* invocation target. Forked from Emmanuel's org.jboss.ejb3.entity.hibernate.TransactionScopedSessionInvocationHandler.
*
* @author Emmanuel Bernard
* @author Scott Marlow
*/
public class EntityManagerUnwrappedTargetInvocationHandler implements InvocationHandler, Serializable {
private static final long serialVersionUID = 5254527687L;
private Class<?> wrappedClass;
private EntityManager targetEntityManager;
public EntityManagerUnwrappedTargetInvocationHandler() {
}
public EntityManagerUnwrappedTargetInvocationHandler(EntityManager targetEntityManager, Class<?> wrappedClass) {
this.targetEntityManager = targetEntityManager;
this.wrappedClass = wrappedClass;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("close".equals(method.getName())) {
throw new IllegalStateException("Illegal to call this method from injected, managed EntityManager");
} else {
//catch all
try {
return method.invoke(getWrappedObject(), args);
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof RuntimeException) {
throw (RuntimeException) e.getTargetException();
} else {
throw e;
}
}
}
}
private Object getWrappedObject() {
return targetEntityManager.unwrap(wrappedClass);
}
}
| 2,876 | 36.363636 | 120 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/container/JPAUserTransactionListener.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.jpa.container;
import java.util.Map;
import jakarta.transaction.SystemException;
/**
* Listens for UserTransaction events and handles associating the extended persistence context with the Jakarta Transactions transaction.
*
* JPA 2.0 section 7.9.1 Container Responsibilities:
* "For stateful session beans with extended persistence contexts:
* When a business method of the stateful session bean is invoked, if the stateful session bean
* uses bean managed transaction demarcation and a UserTransaction is begun within the
* method, the container associates the persistence context with the Jakarta Transactions transaction and calls
* EntityManager.joinTransaction.
* "
*
* @author Scott Marlow
*/
public class JPAUserTransactionListener implements org.jboss.tm.usertx.UserTransactionListener {
@Override
public void userTransactionStarted() throws SystemException {
Map<String, ExtendedEntityManager> currentActiveEntityManagers = SFSBCallStack.currentSFSBCallStackInvocation();
if (currentActiveEntityManagers != null && currentActiveEntityManagers.size() > 0) {
for (ExtendedEntityManager extendedEntityManager: currentActiveEntityManagers.values()) {
extendedEntityManager.internalAssociateWithJtaTx();
}
}
}
}
| 2,368 | 42.072727 | 137 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/container/PersistenceUnitSearch.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.jpa.container;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
import java.util.List;
import org.jboss.as.jpa.config.Configuration;
import org.jboss.as.jpa.config.PersistenceUnitMetadataHolder;
import org.jboss.as.jpa.messages.JpaLogger;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUtils;
import org.jboss.as.server.deployment.SubDeploymentMarker;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.vfs.VirtualFile;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
/**
* Perform scoped search for persistence unit name
*
* @author Scott Marlow (forked from Carlo de Wolf code).
* @author Stuart Douglas
*/
public class PersistenceUnitSearch {
// cache the trace enabled flag
private static final boolean traceEnabled = ROOT_LOGGER.isTraceEnabled();
public static PersistenceUnitMetadata resolvePersistenceUnitSupplier(DeploymentUnit deploymentUnit, String persistenceUnitName) {
if (traceEnabled) {
ROOT_LOGGER.tracef("pu search for name '%s' inside of %s", persistenceUnitName, deploymentUnit.getName());
}
int scopeSeparatorCharacter = (persistenceUnitName == null ? -1 : persistenceUnitName.indexOf('#'));
if (scopeSeparatorCharacter != -1) {
final String path = persistenceUnitName.substring(0, scopeSeparatorCharacter);
final String name = persistenceUnitName.substring(scopeSeparatorCharacter + 1);
PersistenceUnitMetadata pu = getPersistenceUnit(deploymentUnit, path, name);
if (traceEnabled) {
ROOT_LOGGER.tracef("pu search found %s", pu.getScopedPersistenceUnitName());
}
return pu;
} else {
PersistenceUnitMetadata name = findPersistenceUnitSupplier(deploymentUnit, persistenceUnitName);
if (traceEnabled && name != null) {
ROOT_LOGGER.tracef("pu search found %s", name.getScopedPersistenceUnitName());
}
return name;
}
}
private static PersistenceUnitMetadata findPersistenceUnitSupplier(DeploymentUnit deploymentUnit, String persistenceUnitName) {
PersistenceUnitMetadata name = findWithinDeployment(deploymentUnit, persistenceUnitName);
if (name == null) {
name = findWithinApplication(DeploymentUtils.getTopDeploymentUnit(deploymentUnit), persistenceUnitName);
}
return name;
}
private static PersistenceUnitMetadata findWithinApplication(DeploymentUnit unit, String persistenceUnitName) {
if (traceEnabled) {
ROOT_LOGGER.tracef("pu findWithinApplication for %s", persistenceUnitName);
}
PersistenceUnitMetadata name = findWithinDeployment(unit, persistenceUnitName);
if (name != null) {
if (traceEnabled) {
ROOT_LOGGER.tracef("pu findWithinApplication matched for %s", persistenceUnitName);
}
return name;
}
List<ResourceRoot> resourceRoots = unit.getAttachmentList(Attachments.RESOURCE_ROOTS);
for (ResourceRoot resourceRoot : resourceRoots) {
if (!SubDeploymentMarker.isSubDeployment(resourceRoot)) {
name = findWithinLibraryJar(unit, resourceRoot, persistenceUnitName);
if (name != null) {
return name;
}
}
}
return null;
}
private static PersistenceUnitMetadata findWithinLibraryJar(DeploymentUnit unit, ResourceRoot moduleResourceRoot, String persistenceUnitName) {
final ResourceRoot deploymentRoot = moduleResourceRoot;
PersistenceUnitMetadataHolder holder = deploymentRoot.getAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS);
if (holder == null || holder.getPersistenceUnits() == null) {
if (traceEnabled) {
ROOT_LOGGER.tracef("findWithinLibraryJar checking for '%s' found no persistence units", persistenceUnitName);
}
return null;
}
ambiguousPUError(unit, persistenceUnitName, holder);
persistenceUnitName = defaultPersistenceUnitName(persistenceUnitName, holder);
for (PersistenceUnitMetadata persistenceUnit : holder.getPersistenceUnits()) {
if (traceEnabled) {
ROOT_LOGGER.tracef("findWithinLibraryJar check '%s' against pu '%s'", persistenceUnitName, persistenceUnit.getPersistenceUnitName());
}
if (persistenceUnitName == null || persistenceUnitName.length() == 0 || persistenceUnit.getPersistenceUnitName().equals(persistenceUnitName)) {
if (traceEnabled) {
ROOT_LOGGER.tracef("findWithinLibraryJar matched '%s' against pu '%s'", persistenceUnitName, persistenceUnit.getPersistenceUnitName());
}
return persistenceUnit;
}
}
return null;
}
/*
* When finding the default persistence unit, the first persistence unit encountered is returned.
*/
private static PersistenceUnitMetadata findWithinDeployment(DeploymentUnit unit, String persistenceUnitName) {
if (traceEnabled) {
ROOT_LOGGER.tracef("pu findWithinDeployment searching for %s", persistenceUnitName);
}
for (ResourceRoot root : DeploymentUtils.allResourceRoots(unit)) {
PersistenceUnitMetadataHolder holder = root.getAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS);
if (holder == null || holder.getPersistenceUnits() == null) {
if (traceEnabled) {
ROOT_LOGGER.tracef("pu findWithinDeployment skipping empty pu holder for %s", persistenceUnitName);
}
continue;
}
ambiguousPUError(unit, persistenceUnitName, holder);
persistenceUnitName = defaultPersistenceUnitName(persistenceUnitName, holder);
for (PersistenceUnitMetadata persistenceUnit : holder.getPersistenceUnits()) {
if (traceEnabled) {
ROOT_LOGGER.tracef("findWithinDeployment check '%s' against pu '%s'", persistenceUnitName, persistenceUnit.getPersistenceUnitName());
}
if (persistenceUnitName == null || persistenceUnitName.length() == 0 || persistenceUnit.getPersistenceUnitName().equals(persistenceUnitName)) {
if (traceEnabled) {
ROOT_LOGGER.tracef("findWithinDeployment matched '%s' against pu '%s'", persistenceUnitName, persistenceUnit.getPersistenceUnitName());
}
return persistenceUnit;
}
}
}
return null;
}
private static void ambiguousPUError(DeploymentUnit unit, String persistenceUnitName, PersistenceUnitMetadataHolder holder) {
if (holder.getPersistenceUnits().size() > 1 && (persistenceUnitName == null || persistenceUnitName.length() == 0)) {
int numberOfDefaultPersistenceUnits = 0;
// get number of persistence units that are marked as default
for (PersistenceUnitMetadata persistenceUnit : holder.getPersistenceUnits()) {
String defaultPU = persistenceUnit.getProperties().getProperty(Configuration.JPA_DEFAULT_PERSISTENCE_UNIT);
if(Boolean.TRUE.toString().equals(defaultPU)) {
numberOfDefaultPersistenceUnits++;
}
}
ROOT_LOGGER.tracef("checking for ambiguous persistence unit injection error, " +
"number of persistence units marked default (%s) = %d", Configuration.JPA_DEFAULT_PERSISTENCE_UNIT, numberOfDefaultPersistenceUnits);
// don't throw an error if there is exactly one default persistence unit
if (numberOfDefaultPersistenceUnits != 1) {
// AS7-2275 no unitName and there is more than one persistence unit;
throw JpaLogger.ROOT_LOGGER.noPUnitNameSpecifiedAndMultiplePersistenceUnits(holder.getPersistenceUnits().size(), unit);
}
}
}
/**
* if no persistence unit name is specified, return name of default persistence unit
*
* @param persistenceUnitName that was specified to be used (null means to use the default persistence unit)
* @param holder
* @return
*/
private static String defaultPersistenceUnitName(String persistenceUnitName, PersistenceUnitMetadataHolder holder) {
if ((persistenceUnitName == null || persistenceUnitName.length() == 0)) {
for (PersistenceUnitMetadata persistenceUnit : holder.getPersistenceUnits()) {
String defaultPU = persistenceUnit.getProperties().getProperty(Configuration.JPA_DEFAULT_PERSISTENCE_UNIT);
if(Boolean.TRUE.toString().equals(defaultPU)) {
persistenceUnitName = persistenceUnit.getPersistenceUnitName();
}
}
}
return persistenceUnitName;
}
private static PersistenceUnitMetadata getPersistenceUnit(DeploymentUnit current, final String absolutePath, String puName) {
final String path;
if (absolutePath.startsWith("../")) {
path = absolutePath.substring(3);
} else {
path = absolutePath;
}
final VirtualFile parent = current.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot().getParent();
final VirtualFile resolvedPath = parent.getChild(path);
List<ResourceRoot> resourceRoots = DeploymentUtils.allResourceRoots(DeploymentUtils.getTopDeploymentUnit(current));
for (ResourceRoot resourceRoot : resourceRoots) {
if (resourceRoot.getRoot().equals(resolvedPath)) {
PersistenceUnitMetadataHolder holder = resourceRoot.getAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS);
if (holder != null) {
for (PersistenceUnitMetadata pu : holder.getPersistenceUnits()) {
if (traceEnabled) {
ROOT_LOGGER.tracef("getPersistenceUnit check '%s' against pu '%s'", puName, pu.getPersistenceUnitName());
}
if (pu.getPersistenceUnitName().equals(puName)) {
if (traceEnabled) {
ROOT_LOGGER.tracef("getPersistenceUnit matched '%s' against pu '%s'", puName, pu.getPersistenceUnitName());
}
return pu;
}
}
}
}
}
throw JpaLogger.ROOT_LOGGER.persistenceUnitNotFound(absolutePath, puName, current);
}
}
| 11,902 | 47.583673 | 159 |
java
|
null |
wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/container/ExtendedPersistenceInheritanceStrategy.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.jpa.container;
/**
* for extended persistence inheritance strategies.
*
* @author Scott Marlow
*/
public interface ExtendedPersistenceInheritanceStrategy {
/**
* Register the extended persistence context so it is accessible to other SFSB's during the
* creation process.
*
* Used when the SFSB bean is injecting fields (at creation time), after the bean is created but before its
* PostConstruct has been invoked.
*
* @param scopedPuName
* @param entityManager
*/
void registerExtendedPersistenceContext(
String scopedPuName,
ExtendedEntityManager entityManager);
/**
* Check if the current EJB container instance contains the specified extended persistence context.
*
* This is expected to be used when the SFSB bean is injecting fields, after it the bean is created but before its
* PostConstruct has been invoked.
*
* @param puScopedName Scoped pu name
*
* @return the extended persistence context that matches puScopedName or null if not found
*/
ExtendedEntityManager findExtendedPersistenceContext(String puScopedName);
}
| 2,212 | 36.508475 | 118 |
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.