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/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/MdbDeliveryGroupAdd.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.ejb3.subsystem;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.CapabilityServiceTarget;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceController;
/**
* Adds a mdb delivery group.
*
* @author Flavia Rainone
*/
public class MdbDeliveryGroupAdd extends AbstractAddStepHandler {
static final MdbDeliveryGroupAdd INSTANCE = new MdbDeliveryGroupAdd();
private MdbDeliveryGroupAdd() {
super(MdbDeliveryGroupResourceDefinition.ACTIVE);
}
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
installServices(context, operation, model);
}
protected void installServices(final OperationContext context, final ModelNode operation, final ModelNode model) throws OperationFailedException {
final boolean active = MdbDeliveryGroupResourceDefinition.ACTIVE.resolveModelAttribute(context, model).asBoolean();
CapabilityServiceTarget serviceTarget = context.getCapabilityServiceTarget();
serviceTarget.addCapability(MdbDeliveryGroupResourceDefinition.MDB_DELIVERY_GROUP_CAPABILITY).setInstance(Service.NULL)
.setInitialMode(active? ServiceController.Mode.ACTIVE: ServiceController.Mode.NEVER)
.install();
}
}
| 2,541 | 41.366667 | 150 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/EJBStatistics.java | /*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2018, 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.ejb3.subsystem;
/**
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public final class EJBStatistics {
private static final EJBStatistics INSTANCE = new EJBStatistics();
private volatile boolean enabled;
private EJBStatistics() {}
public boolean isEnabled() {
return enabled;
}
void setEnabled(final boolean enabled) {
this.enabled = enabled;
}
public static EJBStatistics getInstance() {
return INSTANCE;
}
}
| 1,548 | 31.270833 | 70 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/LegacyPassivationStoreResourceDefinition.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.ejb3.subsystem;
import java.util.concurrent.TimeUnit;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.DeprecationData;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathElement;
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.capability.RuntimeCapability;
import org.jboss.as.controller.operations.validation.LongRangeValidator;
import org.jboss.as.controller.operations.validation.TimeUnitValidator;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.OperationEntry;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
/**
* @author Paul Ferraro
*/
@Deprecated
public abstract class LegacyPassivationStoreResourceDefinition extends SimpleResourceDefinition {
static final ModelVersion DEPRECATED_VERSION = ModelVersion.create(2, 0, 0);
@Deprecated
static final SimpleAttributeDefinition IDLE_TIMEOUT = new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.IDLE_TIMEOUT, ModelType.LONG, true)
.setXmlName(EJB3SubsystemXMLAttribute.IDLE_TIMEOUT.getLocalName())
.setDefaultValue(new ModelNode().set(300))
.setAllowExpression(true)
.setValidator(new LongRangeValidator(1, Integer.MAX_VALUE, true, true))
.setFlags(AttributeAccess.Flag.RESTART_NONE)
.build()
;
@Deprecated
static final SimpleAttributeDefinition IDLE_TIMEOUT_UNIT = new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.IDLE_TIMEOUT_UNIT, ModelType.STRING, true)
.setXmlName(EJB3SubsystemXMLAttribute.IDLE_TIMEOUT_UNIT.getLocalName())
.setValidator(new TimeUnitValidator(true,true))
.setDefaultValue(new ModelNode().set(TimeUnit.SECONDS.name()))
.setFlags(AttributeAccess.Flag.RESTART_NONE)
.setAllowExpression(true)
.setDeprecated(DEPRECATED_VERSION)
.build()
;
@Deprecated
static final SimpleAttributeDefinitionBuilder MAX_SIZE_BUILDER = new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.MAX_SIZE, ModelType.INT, true)
.setXmlName(EJB3SubsystemXMLAttribute.MAX_SIZE.getLocalName())
.setDefaultValue(new ModelNode().set(100000))
.setAllowExpression(true)
.setValidator(new LongRangeValidator(1, Integer.MAX_VALUE, true, true))
.setFlags(AttributeAccess.Flag.RESTART_NONE)
;
private final AttributeDefinition[] attributes;
LegacyPassivationStoreResourceDefinition(String element, OperationStepHandler addHandler, OperationStepHandler removeHandler, OperationEntry.Flag addRestartLevel, OperationEntry.Flag removeRestartLevel, AttributeDefinition... attributes) {
super(new SimpleResourceDefinition.Parameters(PathElement.pathElement(element), EJB3Extension.getResourceDescriptionResolver(element))
.setAddHandler(addHandler)
.setRemoveHandler(removeHandler)
.setAddRestartLevel(addRestartLevel)
.setRemoveRestartLevel(removeRestartLevel)
.setDeprecationData(new DeprecationData(DEPRECATED_VERSION)));
this.attributes = attributes;
}
LegacyPassivationStoreResourceDefinition(String element, OperationStepHandler addHandler, OperationStepHandler removeHandler, OperationEntry.Flag addRestartLevel, OperationEntry.Flag removeRestartLevel, RuntimeCapability capability, AttributeDefinition... attributes) {
super(new SimpleResourceDefinition.Parameters(PathElement.pathElement(element), EJB3Extension.getResourceDescriptionResolver(element))
.setAddHandler(addHandler)
.setRemoveHandler(removeHandler)
.setAddRestartLevel(addRestartLevel)
.setRemoveRestartLevel(removeRestartLevel)
.setDeprecationData(new DeprecationData(DEPRECATED_VERSION))
.setCapabilities(capability));
this.attributes = attributes;
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
OperationStepHandler writeHandler = new ReloadRequiredWriteAttributeHandler(this.attributes);
for (AttributeDefinition definition: this.attributes) {
resourceRegistration.registerReadWriteAttribute(definition, null, writeHandler);
}
}
}
| 5,775 | 50.115044 | 273 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/ExceptionLoggingWriteHandler.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 2110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ejb3.subsystem;
import org.jboss.as.controller.AbstractWriteAttributeHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.ejb3.component.interceptors.LoggingInterceptor;
import org.jboss.dmr.ModelNode;
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.ServiceRegistry;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author Stuart Douglas
*/
class ExceptionLoggingWriteHandler extends AbstractWriteAttributeHandler<Void> {
static final ExceptionLoggingWriteHandler INSTANCE = new ExceptionLoggingWriteHandler();
private ExceptionLoggingWriteHandler() {
super(EJB3SubsystemRootResourceDefinition.LOG_EJB_EXCEPTIONS);
}
@Override
protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<Void> voidHandbackHolder) throws OperationFailedException {
final ModelNode model = context.readResource(PathAddress.EMPTY_ADDRESS).getModel();
updateOrCreateDefaultExceptionLoggingEnabledService(context, model);
return false;
}
@Override
protected void revertUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode valueToRestore, ModelNode valueToRevert, Void handback) throws OperationFailedException {
final ModelNode restored = context.readResource(PathAddress.EMPTY_ADDRESS).getModel().clone();
restored.get(attributeName).set(valueToRestore);
updateOrCreateDefaultExceptionLoggingEnabledService(context, restored);
}
void updateOrCreateDefaultExceptionLoggingEnabledService(final OperationContext context, final ModelNode model) throws OperationFailedException {
final boolean enabled = EJB3SubsystemRootResourceDefinition.LOG_EJB_EXCEPTIONS.resolveModelAttribute(context, model).asBoolean();
final ServiceName serviceName = LoggingInterceptor.LOGGING_ENABLED_SERVICE_NAME;
final ServiceRegistry registry = context.getServiceRegistry(true);
final ServiceController sc = registry.getService(serviceName);
if (sc != null) {
final AtomicBoolean value = (AtomicBoolean) sc.getValue();
value.set(enabled);
} else {
// create and install the service
final ServiceBuilder<?> sb = context.getServiceTarget().addService(serviceName);
sb.setInstance(new ValueService(new AtomicBoolean(enabled))).install();
}
}
private static final class ValueService implements Service<AtomicBoolean> {
private final AtomicBoolean value;
public ValueService(final AtomicBoolean value) {
this.value = value;
}
public void start(final StartContext context) {
// noop
}
public void stop(final StopContext context) {
// noop
}
public AtomicBoolean getValue() throws IllegalStateException {
return value;
}
}
}
| 4,402 | 42.166667 | 235 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/EJBNameRegexWriteHandler.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
* 2110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ejb3.subsystem;
import org.jboss.as.controller.AbstractWriteAttributeHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceRegistry;
/**
* @author Stuart Douglas
*/
class EJBNameRegexWriteHandler extends AbstractWriteAttributeHandler<Void> {
public static final EJBNameRegexWriteHandler INSTANCE = new EJBNameRegexWriteHandler(EJB3SubsystemRootResourceDefinition.ALLOW_EJB_NAME_REGEX);
private final AttributeDefinition attributeDefinition;
private EJBNameRegexWriteHandler(final AttributeDefinition attributeDefinition) {
super(attributeDefinition);
this.attributeDefinition = attributeDefinition;
}
@Override
protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName,
ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<Void> handbackHolder) throws OperationFailedException {
final ModelNode model = context.readResource(PathAddress.EMPTY_ADDRESS).getModel();
updateRegexAllowed(context, model);
return false;
}
@Override
protected void revertUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName,
ModelNode valueToRestore, ModelNode valueToRevert, Void handback) throws OperationFailedException {
final ModelNode restored = context.readResource(PathAddress.EMPTY_ADDRESS).getModel().clone();
restored.get(attributeName).set(valueToRestore);
updateRegexAllowed(context, restored);
}
void updateRegexAllowed(final OperationContext context, final ModelNode model) throws OperationFailedException {
final ModelNode allowRegex = this.attributeDefinition.resolveModelAttribute(context, model);
final ServiceRegistry registry = context.getServiceRegistry(true);
final ServiceController<?> ejbNameServiceController = registry.getService(EjbNameRegexService.SERVICE_NAME);
EjbNameRegexService service = (EjbNameRegexService) ejbNameServiceController.getValue();
if (!allowRegex.isDefined()) {
service.setEjbNameRegexAllowed(false);
} else {
service.setEjbNameRegexAllowed(allowRegex.asBoolean());
}
}
}
| 3,595 | 43.95 | 162 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/EJB3SubsystemXMLElement.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.ejb3.subsystem;
import java.util.HashMap;
import java.util.Map;
/**
* Enumeration of elements used in the EJB3 subsystem
*
* @author Jaikiran Pai
*/
public enum EJB3SubsystemXMLElement {
// must be first
UNKNOWN(null),
ASYNC("async"),
ALLOW_EJB_NAME_REGEX("allow-ejb-name-regex"),
BEAN_INSTANCE_POOLS("bean-instance-pools"),
BEAN_INSTANCE_POOL_REF("bean-instance-pool-ref"),
ENTITY_BEAN("entity-bean"),
DATA_STORE("data-store"),
DATA_STORES("data-stores"),
DEFAULT_DISTINCT_NAME("default-distinct-name"),
DEFAULT_SECURITY_DOMAIN("default-security-domain"),
DEFAULT_MISSING_METHOD_PERMISSIONS_DENY_ACCESS(EJB3SubsystemModel.DEFAULT_MISSING_METHOD_PERMISSIONS_DENY_ACCESS),
DISABLE_DEFAULT_EJB_PERMISSIONS(EJB3SubsystemModel.DISABLE_DEFAULT_EJB_PERMISSIONS),
DISTRIBUTABLE_CACHE(EJB3SubsystemModel.DISTRIBUTABLE_CACHE),
ENABLE_GRACEFUL_TXN_SHUTDOWN(EJB3SubsystemModel.ENABLE_GRACEFUL_TXN_SHUTDOWN),
FILE_DATA_STORE("file-data-store"),
IIOP("iiop"),
IN_VM_REMOTE_INTERFACE_INVOCATION("in-vm-remote-interface-invocation"),
MDB("mdb"),
POOLS("pools"),
@Deprecated CACHE("cache"),
CACHES("caches"),
CHANNEL_CREATION_OPTIONS("channel-creation-options"),
DATABASE_DATA_STORE("database-data-store"),
OPTIMISTIC_LOCKING("optimistic-locking"),
OPTION("option"),
OUTBOUND_CONNECTION_REF("outbound-connection-ref"),
@Deprecated PASSIVATION_STORE("passivation-store"),
@Deprecated PASSIVATION_STORES("passivation-stores"),
PROFILE("profile"),
PROFILES("profiles"),
PROPERTY("property"),
@Deprecated CLUSTER_PASSIVATION_STORE("cluster-passivation-store"),
@Deprecated FILE_PASSIVATION_STORE("file-passivation-store"),
REMOTE("remote"),
REMOTING_EJB_RECEIVER("remoting-ejb-receiver"),
REMOTE_HTTP_CONNECTION("remote-http-connection"),
RESOURCE_ADAPTER_NAME("resource-adapter-name"),
RESOURCE_ADAPTER_REF("resource-adapter-ref"),
SESSION_BEAN("session-bean"),
SIMPLE_CACHE("simple-cache"),
SINGLETON("singleton"),
STATEFUL("stateful"),
STATELESS("stateless"),
STATISTICS("statistics"),
STRICT_MAX_POOL("strict-max-pool"),
CONNECTIONS("connections"),
THREAD_POOL("thread-pool"),
THREAD_POOLS("thread-pools"),
TIMER_SERVICE("timer-service"),
LOG_SYSTEM_EXCEPTIONS(EJB3SubsystemModel.LOG_SYSTEM_EXCEPTIONS),
DELIVERY_GROUPS("delivery-groups"),
DELIVERY_GROUP("delivery-group"),
// Elytron integration
APPLICATION_SECURITY_DOMAIN("application-security-domain"),
APPLICATION_SECURITY_DOMAINS("application-security-domains"),
IDENTITY("identity"),
STATIC_EJB_DISCOVERY("static-ejb-discovery"),
MODULES("modules"),
MODULE("module"),
//server interceptors
SERVER_INTERCEPTORS("server-interceptors"),
CLIENT_INTERCEPTORS("client-interceptors"),
INTERCEPTOR("interceptor")
;
private final String name;
EJB3SubsystemXMLElement(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, EJB3SubsystemXMLElement> MAP;
static {
final Map<String, EJB3SubsystemXMLElement> map = new HashMap<String, EJB3SubsystemXMLElement>();
for (EJB3SubsystemXMLElement element : values()) {
final String name = element.getLocalName();
if (name != null) map.put(name, element);
}
MAP = map;
}
public static EJB3SubsystemXMLElement forName(String localName) {
final EJB3SubsystemXMLElement element = MAP.get(localName);
return element == null ? UNKNOWN : element;
}
}
| 4,841 | 31.28 | 118 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/EJB3Subsystem30Parser.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.ejb3.subsystem;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLExtendedStreamReader;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADDRESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequired;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoAttributes;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoContent;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoNamespaceAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
import static org.jboss.as.ejb3.subsystem.EJB3SubsystemModel.DATABASE_DATA_STORE;
import static org.jboss.as.ejb3.subsystem.EJB3SubsystemModel.REMOTE;
import static org.jboss.as.ejb3.subsystem.EJB3SubsystemModel.SERVICE;
import static org.jboss.as.ejb3.subsystem.EJB3SubsystemModel.TIMER_SERVICE;
/**
* @author <a href="mailto:[email protected]">Tomasz Adamski</a>
*/
public class EJB3Subsystem30Parser extends EJB3Subsystem20Parser {
protected EJB3Subsystem30Parser() {
}
@Override
protected EJB3SubsystemNamespace getExpectedNamespace() {
return EJB3SubsystemNamespace.EJB3_3_0;
}
@Override
protected void readElement(final XMLExtendedStreamReader reader, final EJB3SubsystemXMLElement element, final List<ModelNode> operations, final ModelNode ejb3SubsystemAddOperation) throws XMLStreamException {
switch (element) {
case LOG_SYSTEM_EXCEPTIONS: {
parseLogEjbExceptions(reader, ejb3SubsystemAddOperation);
break;
}
default: {
super.readElement(reader, element, operations, ejb3SubsystemAddOperation);
}
}
}
private void parseLogEjbExceptions(XMLExtendedStreamReader reader, ModelNode ejb3SubsystemAddOperation) throws XMLStreamException {
final int count = reader.getAttributeCount();
final EnumSet<EJB3SubsystemXMLAttribute> missingRequiredAttributes = EnumSet.of(EJB3SubsystemXMLAttribute.VALUE);
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final EJB3SubsystemXMLAttribute attribute = EJB3SubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case VALUE:
EJB3SubsystemRootResourceDefinition.LOG_EJB_EXCEPTIONS.parseAndSetParameter(value, ejb3SubsystemAddOperation, reader);
// found the mandatory attribute
missingRequiredAttributes.remove(EJB3SubsystemXMLAttribute.VALUE);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
requireNoContent(reader);
if (!missingRequiredAttributes.isEmpty()) {
throw missingRequired(reader, missingRequiredAttributes);
}
}
@Override
protected void parseDatabaseDataStore(final XMLExtendedStreamReader reader, final List<ModelNode> operations) throws XMLStreamException {
String name = null;
final ModelNode databaseDataStore = new ModelNode();
final EnumSet<EJB3SubsystemXMLAttribute> required = EnumSet.of(EJB3SubsystemXMLAttribute.NAME, EJB3SubsystemXMLAttribute.DATASOURCE_JNDI_NAME);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final EJB3SubsystemXMLAttribute attribute = EJB3SubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME:
if (name != null) {
throw unexpectedAttribute(reader, i);
}
name = reader.getAttributeValue(i);
break;
case DATASOURCE_JNDI_NAME:
DatabaseDataStoreResourceDefinition.DATASOURCE_JNDI_NAME.parseAndSetParameter(value, databaseDataStore, reader);
break;
case DATABASE:
DatabaseDataStoreResourceDefinition.DATABASE.parseAndSetParameter(value, databaseDataStore, reader);
break;
case PARTITION:
DatabaseDataStoreResourceDefinition.PARTITION.parseAndSetParameter(value, databaseDataStore, reader);
break;
case REFRESH_INTERVAL:
DatabaseDataStoreResourceDefinition.REFRESH_INTERVAL.parseAndSetParameter(value, databaseDataStore, reader);
break;
case ALLOW_EXECUTION:
DatabaseDataStoreResourceDefinition.ALLOW_EXECUTION.parseAndSetParameter(value, databaseDataStore, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
final ModelNode address = new ModelNode();
address.add(SUBSYSTEM, EJB3Extension.SUBSYSTEM_NAME);
address.add(SERVICE, TIMER_SERVICE);
address.add(DATABASE_DATA_STORE, name);
databaseDataStore.get(OP).set(ADD);
databaseDataStore.get(ADDRESS).set(address);
operations.add(databaseDataStore);
requireNoContent(reader);
}
protected void parseRemote(final XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
final int count = reader.getAttributeCount();
final PathAddress ejb3RemoteServiceAddress = SUBSYSTEM_PATH.append(SERVICE, REMOTE);
ModelNode operation = Util.createAddOperation(ejb3RemoteServiceAddress);
final EnumSet<EJB3SubsystemXMLAttribute> required = EnumSet.of(EJB3SubsystemXMLAttribute.CONNECTOR_REF,
EJB3SubsystemXMLAttribute.THREAD_POOL_NAME);
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final EJB3SubsystemXMLAttribute attribute = EJB3SubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case CONNECTOR_REF:
EJB3RemoteResourceDefinition.CONNECTOR_REF.parseAndSetParameter(value, operation, reader);
break;
case THREAD_POOL_NAME:
EJB3RemoteResourceDefinition.THREAD_POOL_NAME.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
operation.get(EJB3SubsystemModel.EXECUTE_IN_WORKER).set(ModelNode.FALSE);
// each profile adds it's own operation
operations.add(operation);
final Set<EJB3SubsystemXMLElement> parsedElements = new HashSet<EJB3SubsystemXMLElement>();
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
EJB3SubsystemXMLElement element = EJB3SubsystemXMLElement.forName(reader.getLocalName());
switch (element) {
case CHANNEL_CREATION_OPTIONS: {
if (parsedElements.contains(EJB3SubsystemXMLElement.CHANNEL_CREATION_OPTIONS)) {
throw unexpectedElement(reader);
}
parsedElements.add(EJB3SubsystemXMLElement.CHANNEL_CREATION_OPTIONS);
this.parseChannelCreationOptions(reader, ejb3RemoteServiceAddress, operations);
break;
}
case PROFILES: {
parseProfiles(reader, operations);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
protected void parseProfiles(final XMLExtendedStreamReader reader, final List<ModelNode> operations)
throws XMLStreamException {
// no attributes expected
requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (EJB3SubsystemXMLElement.forName(reader.getLocalName())) {
case PROFILE: {
this.parseProfile(reader, operations);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
protected void parseProfile(final XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
final int count = reader.getAttributeCount();
String profileName = null;
final ModelNode operation = Util.createAddOperation();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final EJB3SubsystemXMLAttribute attribute = EJB3SubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NAME:
profileName = value;
break;
case EXCLUDE_LOCAL_RECEIVER:
RemotingProfileResourceDefinition.EXCLUDE_LOCAL_RECEIVER.parseAndSetParameter(value, operation, reader);
break;
case LOCAL_RECEIVER_PASS_BY_VALUE:
RemotingProfileResourceDefinition.LOCAL_RECEIVER_PASS_BY_VALUE.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
final PathAddress address = SUBSYSTEM_PATH.append(EJB3SubsystemModel.REMOTING_PROFILE, profileName);
operation.get(OP_ADDR).set(address.toModelNode());
operations.add(operation);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (EJB3SubsystemXMLElement.forName(reader.getLocalName())) {
case REMOTING_EJB_RECEIVER: {
parseRemotingReceiver(reader, address, operations);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
if (profileName == null) {
throw missingRequired(reader, Collections.singleton(EJB3SubsystemXMLAttribute.NAME.getLocalName()));
}
}
protected void parseRemotingReceiver(final XMLExtendedStreamReader reader, final PathAddress profileAddress,
final List<ModelNode> operations) throws XMLStreamException {
final ModelNode operation = Util.createAddOperation();
String name = null;
final Set<EJB3SubsystemXMLAttribute> required = EnumSet.of(EJB3SubsystemXMLAttribute.OUTBOUND_CONNECTION_REF);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
final EJB3SubsystemXMLAttribute attribute = EJB3SubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME:
name = value;
break;
case OUTBOUND_CONNECTION_REF:
RemotingEjbReceiverDefinition.OUTBOUND_CONNECTION_REF.parseAndSetParameter(value, operation, reader);
break;
case CONNECT_TIMEOUT:
RemotingEjbReceiverDefinition.CONNECT_TIMEOUT.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
final PathAddress receiverAddress = profileAddress.append(EJB3SubsystemModel.REMOTING_EJB_RECEIVER, name);
operation.get(OP_ADDR).set(receiverAddress.toModelNode());
operations.add(operation);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (EJB3SubsystemXMLElement.forName(reader.getLocalName())) {
case CHANNEL_CREATION_OPTIONS:
parseChannelCreationOptions(reader, receiverAddress, operations);
break;
default:
throw unexpectedElement(reader);
}
}
}
}
| 14,749 | 45.529968 | 212 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/ClusterPassivationStoreResourceDefinition.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.ejb3.subsystem;
import org.jboss.as.clustering.controller.CapabilityReference;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.OperationEntry;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.wildfly.clustering.ejb.bean.LegacyBeanManagementConfiguration;
import org.wildfly.clustering.infinispan.service.InfinispanCacheRequirement;
import org.wildfly.clustering.infinispan.service.InfinispanDefaultCacheRequirement;
/**
* @author Paul Ferraro
*/
@Deprecated
public class ClusterPassivationStoreResourceDefinition extends LegacyPassivationStoreResourceDefinition {
protected static final String INFINISPAN_CACHE_CONTAINER_CAPABILITY_NAME = "org.wildfly.clustering.infinispan.cache-container";
public static final String CLUSTER_PASSIVATION_STORE_CAPABILITY_NAME = "org.wildfly.ejb.cluster-passivation-store";
public static final RuntimeCapability<Void> CLUSTER_PASSIVATION_STORE_CAPABILITY = RuntimeCapability.Builder.of(CLUSTER_PASSIVATION_STORE_CAPABILITY_NAME)
.setServiceType(Void.class)
.build();
@Deprecated
static final SimpleAttributeDefinition MAX_SIZE = new SimpleAttributeDefinitionBuilder(MAX_SIZE_BUILDER.build())
.setDefaultValue(new ModelNode(10000))
.build()
;
@Deprecated
static final SimpleAttributeDefinition CACHE_CONTAINER = new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.CACHE_CONTAINER, ModelType.STRING, true)
.setXmlName(EJB3SubsystemXMLAttribute.CACHE_CONTAINER.getLocalName())
.setDefaultValue(new ModelNode(LegacyBeanManagementConfiguration.DEFAULT_CONTAINER_NAME))
// Capability references should not allow expressions
.setAllowExpression(false)
.setFlags(AttributeAccess.Flag.RESTART_NONE)
// a CapabilityReference to a UnaryRequirement
.setCapabilityReference(new CapabilityReference(()->CLUSTER_PASSIVATION_STORE_CAPABILITY, InfinispanDefaultCacheRequirement.CONFIGURATION))
.build()
;
@Deprecated
static final SimpleAttributeDefinition BEAN_CACHE = new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.BEAN_CACHE, ModelType.STRING, true)
.setXmlName(EJB3SubsystemXMLAttribute.BEAN_CACHE.getLocalName())
// Capability references should not allow expressions
.setAllowExpression(false)
.setFlags(AttributeAccess.Flag.RESTART_NONE)
// a CapabilityReference to a BinaryRequirement (including a parent attribute)
.setCapabilityReference(new CapabilityReference(()->CLUSTER_PASSIVATION_STORE_CAPABILITY, InfinispanCacheRequirement.CONFIGURATION, ()->CACHE_CONTAINER))
.build()
;
@Deprecated
static final SimpleAttributeDefinition CLIENT_MAPPINGS_CACHE = new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.CLIENT_MAPPINGS_CACHE, ModelType.STRING, true)
.setXmlName(EJB3SubsystemXMLAttribute.CLIENT_MAPPINGS_CACHE.getLocalName())
.setDefaultValue(new ModelNode("remote-connector-client-mappings"))
// Capability references should not allow expressions
.setAllowExpression(false)
.setFlags(AttributeAccess.Flag.RESTART_NONE)
.setDeprecated(DEPRECATED_VERSION)
// TODO: replace this with a Requirement reference when the ejb-spi module for clustering is available
.setCapabilityReference(INFINISPAN_CACHE_CONTAINER_CAPABILITY_NAME, CLUSTER_PASSIVATION_STORE_CAPABILITY)
.build()
;
@Deprecated
static final SimpleAttributeDefinition PASSIVATE_EVENTS_ON_REPLICATE = new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.PASSIVATE_EVENTS_ON_REPLICATE, ModelType.BOOLEAN, true)
.setXmlName(EJB3SubsystemXMLAttribute.PASSIVATE_EVENTS_ON_REPLICATE.getLocalName())
.setDefaultValue(ModelNode.TRUE)
.setAllowExpression(true)
.setFlags(AttributeAccess.Flag.RESTART_NONE)
.setDeprecated(DEPRECATED_VERSION)
.build()
;
private static final AttributeDefinition[] ATTRIBUTES = { MAX_SIZE, IDLE_TIMEOUT, IDLE_TIMEOUT_UNIT, CACHE_CONTAINER, BEAN_CACHE, CLIENT_MAPPINGS_CACHE, PASSIVATE_EVENTS_ON_REPLICATE };
private static final ClusterPassivationStoreAdd ADD_HANDLER = new ClusterPassivationStoreAdd(ATTRIBUTES);
private static final PassivationStoreRemove REMOVE_HANDLER = new PassivationStoreRemove(ADD_HANDLER);
ClusterPassivationStoreResourceDefinition() {
super(EJB3SubsystemModel.CLUSTER_PASSIVATION_STORE, ADD_HANDLER, REMOVE_HANDLER, OperationEntry.Flag.RESTART_NONE, OperationEntry.Flag.RESTART_RESOURCE_SERVICES, CLUSTER_PASSIVATION_STORE_CAPABILITY, ATTRIBUTES);
}
}
| 6,080 | 55.305556 | 220 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/EJB3RemoteServiceAdd.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.ejb3.subsystem;
import static org.jboss.as.ejb3.subsystem.EJB3RemoteResourceDefinition.EJB_REMOTE_CAPABILITY_NAME;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.concurrent.ExecutorService;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.jboss.as.clustering.controller.CapabilityServiceConfigurator;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.AbstractBoottimeAddStepHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.CapabilityServiceBuilder;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.remote.AssociationService;
import org.jboss.as.ejb3.remote.EJBRemoteConnectorService;
import org.jboss.as.ejb3.remote.EJBRemotingConnectorClientMappingsEntryProviderService;
import org.jboss.as.network.ClientMapping;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.remoting3.Endpoint;
import org.jboss.remoting3.RemotingOptions;
import org.wildfly.clustering.ejb.remote.ClientMappingsRegistryProvider;
import org.wildfly.clustering.ejb.remote.RemoteEjbRequirement;
import org.wildfly.clustering.ejb.remote.LegacyClientMappingsRegistryProviderFactory;
import org.wildfly.clustering.service.ChildTargetService;
import org.wildfly.clustering.service.FunctionSupplierDependency;
import org.wildfly.clustering.service.ServiceConfigurator;
import org.wildfly.clustering.service.ServiceSupplierDependency;
import org.wildfly.clustering.service.SimpleSupplierDependency;
import org.wildfly.clustering.service.SupplierDependency;
import org.wildfly.transaction.client.provider.remoting.RemotingTransactionService;
import org.xnio.Option;
import org.xnio.OptionMap;
import org.xnio.Options;
/**
* A {@link AbstractAddStepHandler} to handle the add operation for the Jakarta Enterprise Beans
* remote service, in the Jakarta Enterprise Beans subsystem
*
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
* @author <a href="mailto:[email protected]">Richard Opalka</a>
* @author <a href="mailto:[email protected]">Richard Achmatowicz</a>
*/
public class EJB3RemoteServiceAdd extends AbstractBoottimeAddStepHandler {
private final LegacyClientMappingsRegistryProviderFactory providerFactory;
EJB3RemoteServiceAdd(AttributeDefinition... attributes) {
super(attributes);
Iterator<LegacyClientMappingsRegistryProviderFactory> providerFactories = ServiceLoader.load(LegacyClientMappingsRegistryProviderFactory.class, LegacyClientMappingsRegistryProviderFactory.class.getClassLoader()).iterator();
this.providerFactory = providerFactories.hasNext() ? providerFactories.next() : null;
}
/**
* Override populateModel() to handle case of deprecated attribute connector-ref
* - if connector-ref is present, use it to initialise connectors
* - if connector-ref is not present and connectors is not present, throw an exception
*/
@Override
protected void populateModel(ModelNode operation, ModelNode model) throws OperationFailedException {
if (operation.hasDefined(EJB3RemoteResourceDefinition.CONNECTOR_REF.getName())) {
ModelNode connectorRef = operation.remove(EJB3RemoteResourceDefinition.CONNECTOR_REF.getName());
operation.get(EJB3RemoteResourceDefinition.CONNECTORS.getName()).set(new ModelNode().add(connectorRef));
}
super.populateModel(operation, model);
}
@Override
protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
installRuntimeServices(context, model);
}
void installRuntimeServices(final OperationContext context, final ModelNode model) throws OperationFailedException {
final String clientMappingsClusterName = EJB3RemoteResourceDefinition.CLIENT_MAPPINGS_CLUSTER_NAME.resolveModelAttribute(context, model).asString();
final List<ModelNode> connectorNameNodes = EJB3RemoteResourceDefinition.CONNECTORS.resolveModelAttribute(context, model).asList();
final String threadPoolName = EJB3RemoteResourceDefinition.THREAD_POOL_NAME.resolveModelAttribute(context, model).asString();
final boolean executeInWorker = EJB3RemoteResourceDefinition.EXECUTE_IN_WORKER.resolveModelAttribute(context, model).asBoolean();
final ServiceTarget target = context.getServiceTarget();
final CapabilityServiceSupport support = context.getCapabilityServiceSupport();
// final ClientMappingsRegistryProvider provider = providerFactory.createClientMappingsRegistryProvider(clientMappingsClusterName);
final SupplierDependency<ClientMappingsRegistryProvider> provider = getClientMappingsRegistryProvider(context, clientMappingsClusterName);
// for each connector specified, we need to set up a client-mappings cache
for (ModelNode connectorNameNode : connectorNameNodes) {
String connectorName = connectorNameNode.asString();
// Install the client-mappings entry provider service for the remoting connector
ServiceConfigurator clientMappingsEntryProviderConfigurator = new EJBRemotingConnectorClientMappingsEntryProviderService(clientMappingsClusterName, connectorName).configure(context);
clientMappingsEntryProviderConfigurator.build(target).setInitialMode(ServiceController.Mode.ON_DEMAND).install();
// Install the cache-based abstractions to support the registries
if (provider != null) {
// Install the registry for the remoting connector's client mappings
SupplierDependency<Map.Entry<String, List<ClientMapping>>> registryEntryDependency = new ServiceSupplierDependency<>(clientMappingsEntryProviderConfigurator.getServiceName());
// use a ChildTargetService so that the provider may be resolved
Consumer<ServiceTarget> installer = new Consumer<ServiceTarget>() {
@Override
public void accept(ServiceTarget serviceTarget) {
for (CapabilityServiceConfigurator configurator : provider.get().getServiceConfigurators(connectorName, new FunctionSupplierDependency<>(registryEntryDependency, Map.Entry::getValue))) {
configurator.configure(support).build(target).install();
}
}
};
ServiceName name = ServiceName.JBOSS.append("ejb", "remote", "client-mappings-registry", "installer", "connector", connectorName);
provider.register(target.addService(name)).setInstance(new ChildTargetService(installer)).install();
}
}
final OptionMap channelCreationOptions = this.getChannelCreationOptions(context);
// Install the Jakarta Enterprise Beans remoting connector service which will listen for client connections on the remoting channel
// TODO: Externalize (expose via management API if needed) the version and the marshalling strategy
final CapabilityServiceBuilder<?> builder = context.getCapabilityServiceTarget().addCapability(EJB3RemoteResourceDefinition.EJB_REMOTE_CAPABILITY);
final Consumer<EJBRemoteConnectorService> serviceConsumer = builder.provides(EJB3RemoteResourceDefinition.EJB_REMOTE_CAPABILITY);
final Supplier<Endpoint> endpointSupplier = builder.requiresCapability(EJB3RemoteResourceDefinition.REMOTING_ENDPOINT_CAPABILITY_NAME, Endpoint.class);
Supplier<ExecutorService> executorServiceSupplier = null;
if (!executeInWorker) {
executorServiceSupplier = builder.requiresCapability(EJB3RemoteResourceDefinition.THREAD_POOL_CAPABILITY_NAME, ExecutorService.class, threadPoolName);
}
// add rest of the dependencies
final Supplier<AssociationService> associationServiceSupplier = builder.requires(AssociationService.SERVICE_NAME);
final Supplier<RemotingTransactionService> remotingTransactionServiceSupplier = builder.requiresCapability(EJB3RemoteResourceDefinition.REMOTE_TRANSACTION_SERVICE_CAPABILITY_NAME, RemotingTransactionService.class);
builder.addAliases(EJBRemoteConnectorService.SERVICE_NAME).setInitialMode(ServiceController.Mode.LAZY);
final EJBRemoteConnectorService ejbRemoteConnectorService = new EJBRemoteConnectorService(serviceConsumer, endpointSupplier, executorServiceSupplier, associationServiceSupplier, remotingTransactionServiceSupplier, channelCreationOptions,
FilterSpecClassResolverFilter.getFilterForOperationContext(context));
builder.setInstance(ejbRemoteConnectorService);
builder.install();
}
private OptionMap getChannelCreationOptions(final OperationContext context) throws OperationFailedException {
// read the full model of the current resource
final ModelNode fullModel = Resource.Tools.readModel(context.readResource(PathAddress.EMPTY_ADDRESS));
final ModelNode channelCreationOptions = fullModel.get(EJB3SubsystemModel.CHANNEL_CREATION_OPTIONS);
if (channelCreationOptions.isDefined() && channelCreationOptions.asInt() > 0) {
final ClassLoader loader = this.getClass().getClassLoader();
final OptionMap.Builder builder = OptionMap.builder();
for (final Property optionProperty : channelCreationOptions.asPropertyList()) {
final String name = optionProperty.getName();
final ModelNode propValueModel = optionProperty.getValue();
final String type = RemoteConnectorChannelCreationOptionResource.CHANNEL_CREATION_OPTION_TYPE.resolveModelAttribute(context,propValueModel).asString();
final String optionClassName = getClassNameForChannelOptionType(type);
final String fullyQualifiedOptionName = optionClassName + "." + name;
final Option option = Option.fromString(fullyQualifiedOptionName, loader);
final String value = RemoteConnectorChannelCreationOptionResource.CHANNEL_CREATION_OPTION_VALUE.resolveModelAttribute(context, propValueModel).asString();
builder.set(option, option.parseValue(value, loader));
}
return builder.getMap();
}
return OptionMap.EMPTY;
}
private static String getClassNameForChannelOptionType(final String optionType) {
if ("remoting".equals(optionType)) {
return RemotingOptions.class.getName();
}
if ("xnio".equals(optionType)) {
return Options.class.getName();
}
throw EjbLogger.ROOT_LOGGER.unknownChannelCreationOptionType(optionType);
}
/*
* Return a client mappings registry provider, used to provide base clustering abstractions for the client mappings registries.
* The preference for obtaining the provider is:
* - use a client mappings registry provider defined in the distributable-ejb subsystem and installed as a service
* - otherwise, use the legacy provider loaded from the classpath
*/
private SupplierDependency<ClientMappingsRegistryProvider> getClientMappingsRegistryProvider(OperationContext context, String clusterName) {
if (context.hasOptionalCapability(RemoteEjbRequirement.CLIENT_MAPPINGS_REGISTRY_PROVIDER.getName(), EJB_REMOTE_CAPABILITY_NAME, null)) {
return new ServiceSupplierDependency<>(RemoteEjbRequirement.CLIENT_MAPPINGS_REGISTRY_PROVIDER.getServiceName(context));
}
EjbLogger.ROOT_LOGGER.legacyClientMappingsRegistryProviderInUse(clusterName);
return new SimpleSupplierDependency<>(this.providerFactory.createClientMappingsRegistryProvider(clusterName));
}
}
| 13,267 | 61.29108 | 245 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/PassivationStoreResourceDefinition.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.jboss.as.ejb3.subsystem;
import org.jboss.as.clustering.controller.CapabilityReference;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathElement;
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.capability.RuntimeCapability;
import org.jboss.as.controller.operations.validation.LongRangeValidator;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.OperationEntry;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.wildfly.clustering.ejb.bean.LegacyBeanManagementConfiguration;
import org.wildfly.clustering.infinispan.service.InfinispanCacheRequirement;
import org.wildfly.clustering.infinispan.service.InfinispanDefaultCacheRequirement;
/**
* Definies a CacheFactoryBuilder instance which, during deployment, is used to configure, build and install a CacheFactory for the SFSB being deployed.
* The CacheFactory produces bean caches which are distributable and have passivation enabled. Used to support CacheFactoryResourceDefinition.
*
* @author Paul Ferraro
*/
@Deprecated
public class PassivationStoreResourceDefinition extends SimpleResourceDefinition {
public static final String PASSIVATION_STORE_CAPABILITY_NAME = "org.wildfly.ejb.passivation-store";
// use these to avoid pulling in ISPN SPI module
protected static final String INFINISPAN_DEFAULT_CACHE_CONFIGURATION_CAPABILITY_NAME = "org.wildfly.clustering.infinispan.default-cache-configuration";
protected static final String INFINISPAN_CACHE_CONFIGURATION_CAPABILITY_NAME = "org.wildfly.clustering.infinispan.cache-configuration";
static final RuntimeCapability<Void> PASSIVATION_STORE_CAPABILITY = RuntimeCapability.Builder.of(PASSIVATION_STORE_CAPABILITY_NAME, true)
.setServiceType(Void.class)
.build();
static final SimpleAttributeDefinition MAX_SIZE = new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.MAX_SIZE, ModelType.INT, true)
.setXmlName(EJB3SubsystemXMLAttribute.MAX_SIZE.getLocalName())
.setDefaultValue(new ModelNode(10000))
.setAllowExpression(true)
.setValidator(new LongRangeValidator(0, Integer.MAX_VALUE, true, true))
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.build();
static final SimpleAttributeDefinition CACHE_CONTAINER = new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.CACHE_CONTAINER, ModelType.STRING, true)
.setXmlName(EJB3SubsystemXMLAttribute.CACHE_CONTAINER.getLocalName())
.setDefaultValue(new ModelNode(LegacyBeanManagementConfiguration.DEFAULT_CONTAINER_NAME))
// Capability references should not allow expressions
.setAllowExpression(false)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
// a CapabilityReference to a UnaryRequirement
.setCapabilityReference(new CapabilityReference(()->PASSIVATION_STORE_CAPABILITY, InfinispanDefaultCacheRequirement.CONFIGURATION))
.build();
static final SimpleAttributeDefinition BEAN_CACHE = new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.BEAN_CACHE, ModelType.STRING, true)
.setXmlName(EJB3SubsystemXMLAttribute.BEAN_CACHE.getLocalName())
// Capability references should not allow expressions
.setAllowExpression(false)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
// a CapabilityReference to a BinaryRequirement (including a parent attribute)
.setCapabilityReference(new CapabilityReference(()->PASSIVATION_STORE_CAPABILITY, InfinispanCacheRequirement.CONFIGURATION, ()->CACHE_CONTAINER))
.build();
static final AttributeDefinition[] ATTRIBUTES = { MAX_SIZE, CACHE_CONTAINER, BEAN_CACHE };
static final PassivationStoreAdd ADD_HANDLER = new PassivationStoreAdd(ATTRIBUTES);
PassivationStoreResourceDefinition() {
super(new Parameters(PathElement.pathElement(EJB3SubsystemModel.PASSIVATION_STORE), EJB3Extension.getResourceDescriptionResolver(EJB3SubsystemModel.PASSIVATION_STORE))
.setAddHandler(ADD_HANDLER)
.setRemoveHandler(new PassivationStoreRemove(ADD_HANDLER))
.setRemoveRestartLevel(OperationEntry.Flag.RESTART_RESOURCE_SERVICES)
.setCapabilities(PASSIVATION_STORE_CAPABILITY));
this.setDeprecated(EJB3Model.VERSION_10_0_0.getVersion());
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
OperationStepHandler writeHandler = new ReloadRequiredWriteAttributeHandler(ATTRIBUTES);
for (AttributeDefinition definition: ATTRIBUTES) {
resourceRegistration.registerReadWriteAttribute(definition, null, writeHandler);
}
}
}
| 5,320 | 56.215054 | 175 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/RemotingProfileChildResourceAddHandler.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ejb3.subsystem;
import java.util.Arrays;
import java.util.Collection;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationDescriptor;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
/**
*
* @author <a href="mailto:[email protected]">Tomasz Adamski</a>
*/
public class RemotingProfileChildResourceAddHandler extends RemotingProfileChildResourceHandlerBase implements OperationDescriptor {
private final Collection<AttributeDefinition> attributes;
protected RemotingProfileChildResourceAddHandler(AttributeDefinition... attributes) {
this.attributes = Arrays.asList(attributes);
}
@Override
public Collection<? extends AttributeDefinition> getAttributes() {
return this.attributes;
}
@Override
public String toString() {
return super.toString();
}
@Override
protected void updateModel(final OperationContext context,final ModelNode operation) throws OperationFailedException {
final Resource resource = context.createResource(PathAddress.EMPTY_ADDRESS);
populateModel(operation, resource.getModel());
}
protected void populateModel(final ModelNode operation,final ModelNode model) throws OperationFailedException {
for (final AttributeDefinition attr : this.attributes) {
attr.validateAndSet(operation, model);
}
}
}
| 2,623 | 35.957746 | 132 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/DefaultResourceAdapterWriteHandler.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.ejb3.subsystem;
import org.jboss.as.controller.AbstractWriteAttributeHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.ejb3.component.messagedriven.DefaultResourceAdapterService;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceRegistry;
/**
* User: jpai
*/
public class DefaultResourceAdapterWriteHandler extends AbstractWriteAttributeHandler<Void> {
public static final DefaultResourceAdapterWriteHandler INSTANCE = new DefaultResourceAdapterWriteHandler();
private DefaultResourceAdapterWriteHandler() {
super(EJB3SubsystemRootResourceDefinition.DEFAULT_RESOURCE_ADAPTER_NAME);
}
@Override
protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName,
ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<Void> handbackHolder) throws OperationFailedException {
final ModelNode model = context.readResource(PathAddress.EMPTY_ADDRESS).getModel();
updateDefaultAdapterService(context, model);
return false;
}
@Override
protected void revertUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName,
ModelNode valueToRestore, ModelNode valueToRevert, Void handback) throws OperationFailedException {
final ModelNode restored = context.readResource(PathAddress.EMPTY_ADDRESS).getModel().clone();
restored.get(attributeName).set(valueToRestore);
updateDefaultAdapterService(context, restored);
}
void updateDefaultAdapterService(final OperationContext context, final ModelNode model) throws OperationFailedException {
final ModelNode adapterNameNode = EJB3SubsystemRootResourceDefinition.DEFAULT_RESOURCE_ADAPTER_NAME.resolveModelAttribute(context, model);
final String adapterName = adapterNameNode.isDefined() ? adapterNameNode.asString() : null;
final ServiceRegistry serviceRegistry = context.getServiceRegistry(true);
ServiceController<DefaultResourceAdapterService> existingDefaultRANameService = (ServiceController<DefaultResourceAdapterService>) serviceRegistry.getService(DefaultResourceAdapterService.DEFAULT_RA_NAME_SERVICE_NAME);
// if a default RA name service is already installed then just update the resource adapter name
if (existingDefaultRANameService != null) {
existingDefaultRANameService.getValue().setResourceAdapterName(adapterName);
} else if (adapterName != null) {
// create a new one and install
final DefaultResourceAdapterService defaultResourceAdapterService = new DefaultResourceAdapterService(adapterName);
ServiceController<?> newController =
context.getServiceTarget().addService(DefaultResourceAdapterService.DEFAULT_RA_NAME_SERVICE_NAME, defaultResourceAdapterService)
.install();
}
}
}
| 4,192 | 50.134146 | 226 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/RemotingEjbReceiverDefinition.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ejb3.subsystem;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
/**
* {@link org.jboss.as.controller.ResourceDefinition} for remoting Jakarta Enterprise Beans receiver in remoting profile.
*
* This is deprecated, but is still required for domain most support for older servers.
*
* @author <a href="mailto:[email protected]">Tomasz Adamski</a>
*/
public class RemotingEjbReceiverDefinition extends SimpleResourceDefinition {
public static final SimpleAttributeDefinition OUTBOUND_CONNECTION_REF = new SimpleAttributeDefinitionBuilder(
EJB3SubsystemModel.OUTBOUND_CONNECTION_REF, ModelType.STRING).setRequired(true).setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition CONNECT_TIMEOUT = new SimpleAttributeDefinitionBuilder(
EJB3SubsystemModel.CONNECT_TIMEOUT, ModelType.LONG, true).setDefaultValue(new ModelNode(5000L))
.setAllowExpression(true).build();
private static final AttributeDefinition[] ATTRIBUTES = new AttributeDefinition[] { OUTBOUND_CONNECTION_REF, CONNECT_TIMEOUT };
RemotingEjbReceiverDefinition() {
super(PathElement.pathElement(EJB3SubsystemModel.REMOTING_EJB_RECEIVER), EJB3Extension
.getResourceDescriptionResolver(EJB3SubsystemModel.REMOTING_EJB_RECEIVER), new RemotingProfileChildResourceAddHandler(
ATTRIBUTES), new RemotingProfileChildResourceRemoveHandler());
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
for (final AttributeDefinition attr : ATTRIBUTES) {
resourceRegistration.registerReadWriteAttribute(attr, null, new RemotingProfileResourceChildWriteAttributeHandler(attr));
}
}
@Override
public void registerChildren(ManagementResourceRegistration resourceRegistration) {
super.registerChildren(resourceRegistration);
resourceRegistration.registerSubModel(new RemotingEjbReceiverChannelCreationOptionResource());
}
}
| 3,430 | 46.652778 | 134 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/EJB3SubsystemRootResourceDefinition.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.ejb3.subsystem;
import static org.jboss.as.controller.SimpleAttributeDefinitionBuilder.create;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.AbstractWriteAttributeHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.ObjectListAttributeDefinition;
import org.jboss.as.controller.ObjectTypeAttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationDefinition;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.ReloadRequiredWriteAttributeHandler;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleOperationDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler;
import org.jboss.as.controller.operations.global.ReadAttributeHandler;
import org.jboss.as.controller.operations.global.WriteAttributeHandler;
import org.jboss.as.controller.operations.validation.LongRangeValidator;
import org.jboss.as.controller.operations.validation.StringLengthValidator;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.OperationEntry;
import org.jboss.as.controller.services.path.PathManager;
import org.jboss.as.ejb3.component.pool.PoolConfig;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.security.ApplicationSecurityDomainConfig;
import org.jboss.as.threads.EnhancedQueueExecutorResourceDefinition;
import org.jboss.as.threads.ThreadFactoryResolver;
import org.jboss.as.threads.ThreadsServices;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
/**
* {@link org.jboss.as.controller.ResourceDefinition} for the EJB3 subsystem's root management resource.
*
* NOTE: References in this file to Enterprise JavaBeans (EJB) refer to the Jakarta Enterprise Beans unless otherwise noted.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class EJB3SubsystemRootResourceDefinition extends SimpleResourceDefinition {
// TODO: put capability definitions up here
public static final String DEFAULT_SLSB_POOL_CONFIG_CAPABILITY_NAME = "org.wildfly.ejb3.pool-config.slsb-default";
public static final String DEFAULT_MDB_POOL_CONFIG_CAPABILITY_NAME = "org.wildfly.ejb3.pool-config.mdb-default";
public static final String DEFAULT_ENTITY_POOL_CONFIG_CAPABILITY_NAME = "org.wildfly.ejb3.pool-config.entity-default";
private static final String EJB_CAPABILITY_NAME = "org.wildfly.ejb3";
private static final String EJB_CLIENT_CONFIGURATOR_CAPABILITY_NAME = "org.wildfly.ejb3.remote.client-configurator";
private static final String CLUSTERED_SINGLETON_CAPABILITY_NAME = "org.wildfly.ejb3.clustered.singleton";
private static final String TRANSACTION_GLOBAL_DEFAULT_LOCAL_PROVIDER_CAPABILITY_NAME = "org.wildfly.transactions.global-default-local-provider";
static final SimpleAttributeDefinition DEFAULT_SLSB_INSTANCE_POOL =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.DEFAULT_SLSB_INSTANCE_POOL, ModelType.STRING, true)
.setAllowExpression(true).build();
static final SimpleAttributeDefinition DEFAULT_MDB_INSTANCE_POOL =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.DEFAULT_MDB_INSTANCE_POOL, ModelType.STRING, true)
.setAllowExpression(true).build();
static final SimpleAttributeDefinition DEFAULT_RESOURCE_ADAPTER_NAME =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.DEFAULT_RESOURCE_ADAPTER_NAME, ModelType.STRING, true)
.setDefaultValue(new ModelNode("activemq-ra"))
.setAllowExpression(true).build();
@Deprecated
static final SimpleAttributeDefinition DEFAULT_ENTITY_BEAN_INSTANCE_POOL =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.DEFAULT_ENTITY_BEAN_INSTANCE_POOL, ModelType.STRING, true)
.setDeprecated(EJB3Model.VERSION_10_0_0.getVersion())
.setAllowExpression(true).build();
@Deprecated
static final SimpleAttributeDefinition DEFAULT_ENTITY_BEAN_OPTIMISTIC_LOCKING =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.DEFAULT_ENTITY_BEAN_OPTIMISTIC_LOCKING, ModelType.BOOLEAN, true)
.setDeprecated(EJB3Model.VERSION_10_0_0.getVersion())
.setAllowExpression(true).build();
static final SimpleAttributeDefinition DEFAULT_STATEFUL_BEAN_ACCESS_TIMEOUT =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.DEFAULT_STATEFUL_BEAN_ACCESS_TIMEOUT, ModelType.LONG, true)
.setXmlName(EJB3SubsystemXMLAttribute.DEFAULT_ACCESS_TIMEOUT.getLocalName())
.setDefaultValue(new ModelNode().set(5000)) // TODO: this should come from component description
.setAllowExpression(true) // we allow expression for setting a timeout value
.setValidator(new LongRangeValidator(1, Integer.MAX_VALUE, true, true))
.setFlags(AttributeAccess.Flag.RESTART_NONE)
.build();
static final SimpleAttributeDefinition DEFAULT_STATEFUL_BEAN_SESSION_TIMEOUT =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.DEFAULT_STATEFUL_BEAN_SESSION_TIMEOUT, ModelType.LONG, true)
.setXmlName(EJB3SubsystemXMLAttribute.DEFAULT_SESSION_TIMEOUT.getLocalName())
.setAllowExpression(true) // we allow expression for setting a timeout value
.setValidator(new LongRangeValidator(-1, Integer.MAX_VALUE, true, true))
.setFlags(AttributeAccess.Flag.RESTART_NONE)
.build();
static final SimpleAttributeDefinition DEFAULT_SINGLETON_BEAN_ACCESS_TIMEOUT =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.DEFAULT_SINGLETON_BEAN_ACCESS_TIMEOUT, ModelType.LONG, true)
.setXmlName(EJB3SubsystemXMLAttribute.DEFAULT_ACCESS_TIMEOUT.getLocalName())
.setDefaultValue(new ModelNode().set(5000)) // TODO: this should come from component description
.setAllowExpression(true) // we allow expression for setting a timeout value
.setValidator(new LongRangeValidator(1, Integer.MAX_VALUE, true, true))
.setFlags(AttributeAccess.Flag.RESTART_NONE)
.build();
static final SimpleAttributeDefinition DEFAULT_SFSB_CACHE =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.DEFAULT_SFSB_CACHE, ModelType.STRING, true)
.setAllowExpression(true)
.build();
static final SimpleAttributeDefinition DEFAULT_SFSB_PASSIVATION_DISABLED_CACHE =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.DEFAULT_SFSB_PASSIVATION_DISABLED_CACHE, ModelType.STRING, true)
.setXmlName(EJB3SubsystemXMLAttribute.PASSIVATION_DISABLED_CACHE_REF.getLocalName())
.setAllowExpression(true)
.build();
static final SimpleAttributeDefinition DEFAULT_CLUSTERED_SFSB_CACHE =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.DEFAULT_CLUSTERED_SFSB_CACHE, ModelType.STRING, true)
.setAllowExpression(true)
.setRequired(false)
.setDeprecated(ModelVersion.create(2))
.build();
static final SimpleAttributeDefinition ENABLE_STATISTICS =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.ENABLE_STATISTICS, ModelType.BOOLEAN, true)
.setAllowExpression(true)
.setDeprecated(ModelVersion.create(5))
.setFlags(AttributeAccess.Flag.ALIAS)
.build();
static final SimpleAttributeDefinition STATISTICS_ENABLED =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.STATISTICS_ENABLED, ModelType.BOOLEAN, true)
.setAllowExpression(true)
.setDefaultValue(ModelNode.FALSE)
.build();
static final SimpleAttributeDefinition DEFAULT_DISTINCT_NAME =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.DEFAULT_DISTINCT_NAME, ModelType.STRING, true)
.setAllowExpression(true)
.setValidator(new StringLengthValidator(0, true))
.build();
public static final SimpleAttributeDefinition DEFAULT_SECURITY_DOMAIN =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.DEFAULT_SECURITY_DOMAIN, ModelType.STRING, true)
.setAllowExpression(true)
.addAccessConstraint(SensitiveTargetAccessConstraintDefinition.SECURITY_DOMAIN_REF)
.setNullSignificant(true)
.build();
public static final SimpleAttributeDefinition PASS_BY_VALUE =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.IN_VM_REMOTE_INTERFACE_INVOCATION_PASS_BY_VALUE, ModelType.BOOLEAN, true)
.setAllowExpression(true)
.setDefaultValue(ModelNode.TRUE)
.build();
public static final SimpleAttributeDefinition DEFAULT_MISSING_METHOD_PERMISSIONS_DENY_ACCESS =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.DEFAULT_MISSING_METHOD_PERMISSIONS_DENY_ACCESS, ModelType.BOOLEAN, true)
.setAllowExpression(true)
.setDefaultValue(ModelNode.FALSE)
.build();
public static final SimpleAttributeDefinition DISABLE_DEFAULT_EJB_PERMISSIONS =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.DISABLE_DEFAULT_EJB_PERMISSIONS, ModelType.BOOLEAN, true)
.setDeprecated(ModelVersion.create(3, 0, 0))
.setAllowExpression(true)
.setDefaultValue(ModelNode.TRUE)
.build();
public static final SimpleAttributeDefinition ENABLE_GRACEFUL_TXN_SHUTDOWN =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.ENABLE_GRACEFUL_TXN_SHUTDOWN, ModelType.BOOLEAN, true)
.setAllowExpression(true)
.setDefaultValue(ModelNode.FALSE)
.build();
public static final SimpleAttributeDefinition LOG_EJB_EXCEPTIONS =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.LOG_SYSTEM_EXCEPTIONS, ModelType.BOOLEAN, true)
.setAllowExpression(true)
.setDefaultValue(ModelNode.TRUE)
.build();
public static final SimpleAttributeDefinition ALLOW_EJB_NAME_REGEX =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.ALLOW_EJB_NAME_REGEX, ModelType.BOOLEAN, true)
.setDefaultValue(ModelNode.FALSE)
.setAllowExpression(true)
.build();
private static final ObjectTypeAttributeDefinition SERVER_INTERCEPTOR = ObjectTypeAttributeDefinition.Builder.of(EJB3SubsystemModel.SERVER_INTERCEPTOR,
create(EJB3SubsystemModel.CLASS, ModelType.STRING, false)
.setAllowExpression(false)
.build(),
create(EJB3SubsystemModel.MODULE, ModelType.STRING, false)
.setAllowExpression(false)
.build())
.build();
public static final ObjectListAttributeDefinition SERVER_INTERCEPTORS = ObjectListAttributeDefinition.Builder.of(EJB3SubsystemModel.SERVER_INTERCEPTORS, SERVER_INTERCEPTOR)
.setRequired(false)
.setAllowExpression(false)
.setMinSize(1)
.setMaxSize(Integer.MAX_VALUE)
.build();
private static final ObjectTypeAttributeDefinition CLIENT_INTERCEPTOR = ObjectTypeAttributeDefinition.Builder.of(EJB3SubsystemModel.CLIENT_INTERCEPTOR,
create(EJB3SubsystemModel.CLASS, ModelType.STRING, false)
.setAllowExpression(false)
.build(),
create(EJB3SubsystemModel.MODULE, ModelType.STRING, false)
.setAllowExpression(false)
.build())
.build();
public static final ObjectListAttributeDefinition CLIENT_INTERCEPTORS = ObjectListAttributeDefinition.Builder.of(EJB3SubsystemModel.CLIENT_INTERCEPTORS, CLIENT_INTERCEPTOR)
.setRequired(false)
.setAllowExpression(false)
.setMinSize(1)
.setMaxSize(Integer.MAX_VALUE)
.build();
public static final RuntimeCapability<Void> CLUSTERED_SINGLETON_CAPABILITY = RuntimeCapability.Builder.of(
CLUSTERED_SINGLETON_CAPABILITY_NAME, Void.class).build();
public static final RuntimeCapability<Void> EJB_CAPABILITY = RuntimeCapability.Builder.of(EJB_CAPABILITY_NAME, Void.class)
// EJBComponentDescription adds a create dependency on the local tx provider to all components,
// so in the absence of relevant finer grained EJB capabilities, we'll say that EJB overall requires the local provider
.addRequirements(TRANSACTION_GLOBAL_DEFAULT_LOCAL_PROVIDER_CAPABILITY_NAME)
.build();
//We don't want to actually expose the service, we just want to use optional deps
public static final RuntimeCapability<Void> EJB_CLIENT_CONFIGURATOR_CAPABILITY = RuntimeCapability.Builder.of(EJB_CLIENT_CONFIGURATOR_CAPABILITY_NAME, Void.class)
.build();
// default pool capabilities, defined here but registered conditionally
// TODO: these are not guaranteed to be defined but their use as dependants is guarded by predicate which knows if the pool is available or not
public static final RuntimeCapability<Void> DEFAULT_SLSB_POOL_CONFIG_CAPABILITY =
RuntimeCapability.Builder.of(DEFAULT_SLSB_POOL_CONFIG_CAPABILITY_NAME, PoolConfig.class)
.build();
public static final RuntimeCapability<Void> DEFAULT_MDB_POOL_CONFIG_CAPABILITY =
RuntimeCapability.Builder.of(DEFAULT_MDB_POOL_CONFIG_CAPABILITY_NAME, PoolConfig.class)
.build();
public static final RuntimeCapability<Void> DEFAULT_ENTITY_POOL_CONFIG_CAPABILITY =
RuntimeCapability.Builder.of(DEFAULT_ENTITY_POOL_CONFIG_CAPABILITY_NAME, PoolConfig.class)
.build();
private final boolean registerRuntimeOnly;
private final PathManager pathManager;
private final AtomicReference<String> defaultSecurityDomainName;
private final Set<ApplicationSecurityDomainConfig> knownApplicationSecurityDomains;
private final List<String> outflowSecurityDomains;
private final AtomicBoolean denyAccessByDefault;
EJB3SubsystemRootResourceDefinition(boolean registerRuntimeOnly, PathManager pathManager) {
this(registerRuntimeOnly, pathManager, new AtomicReference<>(), new CopyOnWriteArraySet<>(), new CopyOnWriteArrayList<>(), new AtomicBoolean(false));
}
private EJB3SubsystemRootResourceDefinition(boolean registerRuntimeOnly, PathManager pathManager, AtomicReference<String> defaultSecurityDomainName, Set<ApplicationSecurityDomainConfig> knownApplicationSecurityDomains, List<String> outflowSecurityDomains, AtomicBoolean denyAccessByDefault) {
super(new Parameters(PathElement.pathElement(SUBSYSTEM, EJB3Extension.SUBSYSTEM_NAME), EJB3Extension.getResourceDescriptionResolver(EJB3Extension.SUBSYSTEM_NAME))
.setAddHandler(new EJB3SubsystemAdd(defaultSecurityDomainName, knownApplicationSecurityDomains, outflowSecurityDomains, denyAccessByDefault, ATTRIBUTES))
.setRemoveHandler(EJB3SubsystemRemove.INSTANCE)
.setAddRestartLevel(OperationEntry.Flag.RESTART_ALL_SERVICES)
.setRemoveRestartLevel(OperationEntry.Flag.RESTART_ALL_SERVICES)
.setCapabilities(CLUSTERED_SINGLETON_CAPABILITY, EJB_CLIENT_CONFIGURATOR_CAPABILITY, EJB_CAPABILITY)
);
this.registerRuntimeOnly = registerRuntimeOnly;
this.pathManager = pathManager;
this.defaultSecurityDomainName = defaultSecurityDomainName;
this.knownApplicationSecurityDomains = knownApplicationSecurityDomains;
this.outflowSecurityDomains = outflowSecurityDomains;
this.denyAccessByDefault = denyAccessByDefault;
}
static final AttributeDefinition[] ATTRIBUTES = {
DEFAULT_ENTITY_BEAN_INSTANCE_POOL,
DEFAULT_ENTITY_BEAN_OPTIMISTIC_LOCKING,
DEFAULT_MDB_INSTANCE_POOL,
DEFAULT_RESOURCE_ADAPTER_NAME,
DEFAULT_SFSB_CACHE,
DEFAULT_SINGLETON_BEAN_ACCESS_TIMEOUT,
DEFAULT_SLSB_INSTANCE_POOL,
DEFAULT_STATEFUL_BEAN_ACCESS_TIMEOUT,
DEFAULT_STATEFUL_BEAN_SESSION_TIMEOUT,
STATISTICS_ENABLED,
ENABLE_STATISTICS,
PASS_BY_VALUE,
DEFAULT_DISTINCT_NAME,
DEFAULT_SECURITY_DOMAIN,
DEFAULT_MISSING_METHOD_PERMISSIONS_DENY_ACCESS,
DEFAULT_SFSB_PASSIVATION_DISABLED_CACHE,
DISABLE_DEFAULT_EJB_PERMISSIONS,
ENABLE_GRACEFUL_TXN_SHUTDOWN,
LOG_EJB_EXCEPTIONS,
ALLOW_EJB_NAME_REGEX,
SERVER_INTERCEPTORS,
CLIENT_INTERCEPTORS
};
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerReadOnlyAttribute(DEFAULT_CLUSTERED_SFSB_CACHE, new SimpleAliasReadAttributeHandler(DEFAULT_SFSB_CACHE));
resourceRegistration.registerReadWriteAttribute(DEFAULT_SFSB_CACHE, null, EJB3SubsystemDefaultCacheWriteHandler.SFSB_CACHE);
resourceRegistration.registerReadWriteAttribute(DEFAULT_SFSB_PASSIVATION_DISABLED_CACHE, null, EJB3SubsystemDefaultCacheWriteHandler.SFSB_PASSIVATION_DISABLED_CACHE);
resourceRegistration.registerReadWriteAttribute(DEFAULT_SLSB_INSTANCE_POOL, null, EJB3SubsystemDefaultPoolWriteHandler.SLSB_POOL);
resourceRegistration.registerReadWriteAttribute(DEFAULT_MDB_INSTANCE_POOL, null, EJB3SubsystemDefaultPoolWriteHandler.MDB_POOL);
resourceRegistration.registerReadWriteAttribute(DEFAULT_ENTITY_BEAN_INSTANCE_POOL, null, EJB3SubsystemDefaultPoolWriteHandler.ENTITY_BEAN_POOL);
resourceRegistration.registerReadWriteAttribute(DEFAULT_ENTITY_BEAN_OPTIMISTIC_LOCKING, null, EJB3SubsystemDefaultEntityBeanOptimisticLockingWriteHandler.INSTANCE);
resourceRegistration.registerReadWriteAttribute(DEFAULT_RESOURCE_ADAPTER_NAME, null, DefaultResourceAdapterWriteHandler.INSTANCE);
resourceRegistration.registerReadWriteAttribute(DEFAULT_SINGLETON_BEAN_ACCESS_TIMEOUT, null, DefaultSingletonBeanAccessTimeoutWriteHandler.INSTANCE);
resourceRegistration.registerReadWriteAttribute(DEFAULT_STATEFUL_BEAN_ACCESS_TIMEOUT, null, DefaultStatefulBeanAccessTimeoutWriteHandler.INSTANCE);
resourceRegistration.registerReadWriteAttribute(DEFAULT_STATEFUL_BEAN_SESSION_TIMEOUT, null, DefaultStatefulBeanSessionTimeoutWriteHandler.INSTANCE);
resourceRegistration.registerReadWriteAttribute(ENABLE_STATISTICS, (context, operation) -> {
ModelNode aliasOp = operation.clone();
aliasOp.get("name").set(EJB3SubsystemModel.STATISTICS_ENABLED);
context.addStep(aliasOp, ReadAttributeHandler.INSTANCE, OperationContext.Stage.MODEL, true);
}, (context, operation) -> {
ModelNode aliasOp = operation.clone();
aliasOp.get("name").set(EJB3SubsystemModel.STATISTICS_ENABLED);
context.addStep(aliasOp, WriteAttributeHandler.INSTANCE, OperationContext.Stage.MODEL, true);
});
resourceRegistration.registerReadWriteAttribute(STATISTICS_ENABLED, null, StatisticsEnabledWriteHandler.INSTANCE);
resourceRegistration.registerReadWriteAttribute(PASS_BY_VALUE, null, EJBRemoteInvocationPassByValueWriteHandler.INSTANCE);
resourceRegistration.registerReadWriteAttribute(DEFAULT_DISTINCT_NAME, null, EJBDefaultDistinctNameWriteHandler.INSTANCE);
resourceRegistration.registerReadWriteAttribute(LOG_EJB_EXCEPTIONS, null, ExceptionLoggingWriteHandler.INSTANCE);
resourceRegistration.registerReadWriteAttribute(ALLOW_EJB_NAME_REGEX, null, EJBNameRegexWriteHandler.INSTANCE);
final EJBDefaultSecurityDomainWriteHandler defaultSecurityDomainWriteHandler = new EJBDefaultSecurityDomainWriteHandler(DEFAULT_SECURITY_DOMAIN, this.defaultSecurityDomainName);
resourceRegistration.registerReadWriteAttribute(DEFAULT_SECURITY_DOMAIN, null, defaultSecurityDomainWriteHandler);
final EJBDefaultMissingMethodPermissionsWriteHandler defaultMissingMethodPermissionsWriteHandler = new EJBDefaultMissingMethodPermissionsWriteHandler(DEFAULT_MISSING_METHOD_PERMISSIONS_DENY_ACCESS, this.denyAccessByDefault);
resourceRegistration.registerReadWriteAttribute(DEFAULT_MISSING_METHOD_PERMISSIONS_DENY_ACCESS, null, defaultMissingMethodPermissionsWriteHandler);
resourceRegistration.registerReadWriteAttribute(DISABLE_DEFAULT_EJB_PERMISSIONS, null, new AbstractWriteAttributeHandler<Void>(DISABLE_DEFAULT_EJB_PERMISSIONS) {
protected boolean applyUpdateToRuntime(final OperationContext context, final ModelNode operation, final String attributeName, final ModelNode resolvedValue, final ModelNode currentValue, final HandbackHolder<Void> handbackHolder) throws OperationFailedException {
if (resolvedValue.asBoolean()) {
throw EjbLogger.ROOT_LOGGER.disableDefaultEjbPermissionsCannotBeTrue();
}
return false;
}
protected void revertUpdateToRuntime(final OperationContext context, final ModelNode operation, final String attributeName, final ModelNode valueToRestore, final ModelNode valueToRevert, final Void handback) throws OperationFailedException {
}
});
resourceRegistration.registerReadWriteAttribute(ENABLE_GRACEFUL_TXN_SHUTDOWN, null, EnableGracefulTxnShutdownWriteHandler.INSTANCE);
resourceRegistration.registerReadWriteAttribute(SERVER_INTERCEPTORS, null, new ReloadRequiredWriteAttributeHandler(SERVER_INTERCEPTORS));
resourceRegistration.registerReadWriteAttribute(CLIENT_INTERCEPTORS, null, new ReloadRequiredWriteAttributeHandler(CLIENT_INTERCEPTORS));
}
@Override
public void registerOperations(ManagementResourceRegistration subsystemRegistration) {
super.registerOperations(subsystemRegistration);
subsystemRegistration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE);
}
/**
* Overrides the default impl to use a special definition of the add op that includes additional parameter
* {@link #DEFAULT_CLUSTERED_SFSB_CACHE}
* {@inheritDoc}
*/
@Override
protected void registerAddOperation(ManagementResourceRegistration registration, AbstractAddStepHandler handler, OperationEntry.Flag... flags) {
OperationDefinition od = new SimpleOperationDefinitionBuilder(ADD, getResourceDescriptionResolver())
.setParameters(ATTRIBUTES)
.addParameter(DEFAULT_CLUSTERED_SFSB_CACHE)
.withFlags(flags)
.build();
registration.registerOperationHandler(od, handler);
}
@Override
public void registerChildren(ManagementResourceRegistration subsystemRegistration) {
// subsystem=ejb3/service=remote
subsystemRegistration.registerSubModel(new EJB3RemoteResourceDefinition());
// subsystem=ejb3/service=async
subsystemRegistration.registerSubModel(new EJB3AsyncResourceDefinition());
// subsystem=ejb3/strict-max-bean-instance-pool=*
subsystemRegistration.registerSubModel(new StrictMaxPoolResourceDefinition());
// subsystem=ejb3/{cache=*, simple-cache=*, distributable-cache=*}
subsystemRegistration.registerSubModel(new LegacyCacheFactoryResourceDefinition());
new SimpleStatefulSessionBeanCacheProviderResourceDefinition().register(subsystemRegistration);
new DistributableStatefulSessionBeanCacheProviderResourceDefinition().register(subsystemRegistration);
subsystemRegistration.registerSubModel(new PassivationStoreResourceDefinition());
subsystemRegistration.registerSubModel(new FilePassivationStoreResourceDefinition());
subsystemRegistration.registerSubModel(new ClusterPassivationStoreResourceDefinition());
// subsystem=ejb3/service=timerservice
subsystemRegistration.registerSubModel(new TimerServiceResourceDefinition(pathManager));
// subsystem=ejb3/thread-pool=*
subsystemRegistration.registerSubModel(EnhancedQueueExecutorResourceDefinition.create(
PathElement.pathElement(EJB3SubsystemModel.THREAD_POOL),
new EJB3ThreadFactoryResolver(),
EJB3SubsystemModel.BASE_THREAD_POOL_SERVICE_NAME,
registerRuntimeOnly,
ThreadsServices.createCapability(EJB3SubsystemModel.BASE_EJB_THREAD_POOL_NAME, ExecutorService.class),
false));
// subsystem=ejb3/service=iiop
subsystemRegistration.registerSubModel(new EJB3IIOPResourceDefinition());
subsystemRegistration.registerSubModel(new RemotingProfileResourceDefinition());
// subsystem=ejb3/mdb-delivery-group=*
subsystemRegistration.registerSubModel(new MdbDeliveryGroupResourceDefinition());
// subsystem=ejb3/application-security-domain=*
subsystemRegistration.registerSubModel(new ApplicationSecurityDomainDefinition(this.knownApplicationSecurityDomains));
subsystemRegistration.registerSubModel(new IdentityResourceDefinition(this.outflowSecurityDomains));
}
private static class EJB3ThreadFactoryResolver extends ThreadFactoryResolver.SimpleResolver {
private EJB3ThreadFactoryResolver() {
super(ThreadsServices.FACTORY);
}
@Override
protected String getThreadGroupName(String threadPoolName) {
return "EJB " + threadPoolName;
}
}
}
| 28,202 | 60.444444 | 296 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/EJB3Subsystem70Parser.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2019, 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.ejb3.subsystem;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLExtendedStreamReader;
import javax.xml.stream.XMLStreamException;
import java.util.EnumSet;
import java.util.List;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequired;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoContent;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoNamespaceAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute;
/**
* Parser for ejb3:7.0 namespace.
*
*/
public class EJB3Subsystem70Parser extends EJB3Subsystem60Parser {
EJB3Subsystem70Parser() {
}
@Override
protected EJB3SubsystemNamespace getExpectedNamespace() {
return EJB3SubsystemNamespace.EJB3_7_0;
}
@Override
protected void parseStatefulBean(final XMLExtendedStreamReader reader, final List<ModelNode> operations, final ModelNode ejb3SubsystemAddOperation) throws XMLStreamException {
final int count = reader.getAttributeCount();
final EnumSet<EJB3SubsystemXMLAttribute> missingRequiredAttributes = EnumSet.of(EJB3SubsystemXMLAttribute.DEFAULT_ACCESS_TIMEOUT, EJB3SubsystemXMLAttribute.CACHE_REF);
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final EJB3SubsystemXMLAttribute attribute = EJB3SubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case DEFAULT_ACCESS_TIMEOUT: {
EJB3SubsystemRootResourceDefinition.DEFAULT_STATEFUL_BEAN_ACCESS_TIMEOUT.parseAndSetParameter(value, ejb3SubsystemAddOperation, reader);
break;
}
case DEFAULT_SESSION_TIMEOUT: {
EJB3SubsystemRootResourceDefinition.DEFAULT_STATEFUL_BEAN_SESSION_TIMEOUT.parseAndSetParameter(value, ejb3SubsystemAddOperation, reader);
break;
}
case CACHE_REF: {
EJB3SubsystemRootResourceDefinition.DEFAULT_SFSB_CACHE.parseAndSetParameter(value, ejb3SubsystemAddOperation, reader);
break;
}
case CLUSTERED_CACHE_REF: {
EJB3SubsystemRootResourceDefinition.DEFAULT_CLUSTERED_SFSB_CACHE.parseAndSetParameter(value, ejb3SubsystemAddOperation, reader);
break;
}
case PASSIVATION_DISABLED_CACHE_REF: {
EJB3SubsystemRootResourceDefinition.DEFAULT_SFSB_PASSIVATION_DISABLED_CACHE.parseAndSetParameter(value, ejb3SubsystemAddOperation, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
// found the mandatory attribute
missingRequiredAttributes.remove(attribute);
}
requireNoContent(reader);
if (!missingRequiredAttributes.isEmpty()) {
throw missingRequired(reader, missingRequiredAttributes);
}
}
}
| 4,195 | 43.168421 | 179 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/EJB3Subsystem12Parser.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.ejb3.subsystem;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequired;
import static org.jboss.as.controller.parsing.ParseUtils.readStringAttributeElement;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoAttributes;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoContent;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoNamespaceAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
import static org.jboss.as.ejb3.subsystem.EJB3SubsystemModel.ASYNC;
import static org.jboss.as.ejb3.subsystem.EJB3SubsystemModel.CACHE;
import static org.jboss.as.ejb3.subsystem.EJB3SubsystemModel.CLUSTER_PASSIVATION_STORE;
import static org.jboss.as.ejb3.subsystem.EJB3SubsystemModel.DEFAULT_DATA_STORE;
import static org.jboss.as.ejb3.subsystem.EJB3SubsystemModel.FILE_DATA_STORE;
import static org.jboss.as.ejb3.subsystem.EJB3SubsystemModel.FILE_PASSIVATION_STORE;
import static org.jboss.as.ejb3.subsystem.EJB3SubsystemModel.IIOP;
import static org.jboss.as.ejb3.subsystem.EJB3SubsystemModel.PATH;
import static org.jboss.as.ejb3.subsystem.EJB3SubsystemModel.RELATIVE_TO;
import static org.jboss.as.ejb3.subsystem.EJB3SubsystemModel.REMOTE;
import static org.jboss.as.ejb3.subsystem.EJB3SubsystemModel.SERVICE;
import static org.jboss.as.ejb3.subsystem.EJB3SubsystemModel.STRICT_MAX_BEAN_INSTANCE_POOL;
import static org.jboss.as.ejb3.subsystem.EJB3SubsystemModel.THREAD_POOL;
import static org.jboss.as.ejb3.subsystem.EJB3SubsystemModel.TIMER_SERVICE;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.parsing.ParseUtils;
import org.jboss.as.threads.Namespace;
import org.jboss.as.threads.ThreadsParser;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* @author Jaikiran Pai
*/
public class EJB3Subsystem12Parser implements XMLElementReader<List<ModelNode>> {
protected static final PathAddress SUBSYSTEM_PATH = PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM, EJB3Extension.SUBSYSTEM_NAME));
protected EJB3Subsystem12Parser() {
}
protected void readAttributes(final XMLExtendedStreamReader reader) throws XMLStreamException {
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
/**
* {@inheritDoc}
*/
@Override
public void readElement(final XMLExtendedStreamReader reader, final List<ModelNode> operations) throws XMLStreamException {
final ModelNode ejb3SubsystemAddOperation = Util.createAddOperation(SUBSYSTEM_PATH);
operations.add(ejb3SubsystemAddOperation);
readAttributes(reader);
// elements
final EnumSet<EJB3SubsystemXMLElement> encountered = EnumSet.noneOf(EJB3SubsystemXMLElement.class);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
if (EJB3SubsystemNamespace.forUri(reader.getNamespaceURI()) != getExpectedNamespace()) {
throw unexpectedElement(reader);
}
final EJB3SubsystemXMLElement element = EJB3SubsystemXMLElement.forName(reader.getLocalName());
if (!encountered.add(element)) {
throw unexpectedElement(reader);
}
readElement(reader, element, operations, ejb3SubsystemAddOperation);
}
}
protected void readElement(final XMLExtendedStreamReader reader, final EJB3SubsystemXMLElement element, final List<ModelNode> operations, final ModelNode ejb3SubsystemAddOperation) throws XMLStreamException {
switch (element) {
case CACHES: {
this.parseCaches(reader, operations);
break;
}
case PASSIVATION_STORES: {
this.parsePassivationStores(reader, operations);
break;
}
case MDB: {
// read <mdb>
this.parseMDB(reader, operations, ejb3SubsystemAddOperation);
break;
}
case ENTITY_BEAN: {
// read <entity-bean>
this.parseEntityBean(reader, operations, ejb3SubsystemAddOperation);
break;
}
case POOLS: {
// read <pools>
this.parsePools(reader, operations);
break;
}
case REMOTE: {
// read <remote>
parseRemote(reader, operations);
break;
}
case ASYNC: {
// read <remote>
parseAsync(reader, operations);
break;
}
case SESSION_BEAN: {
// read <session-bean>
this.parseSessionBean(reader, operations, ejb3SubsystemAddOperation);
break;
}
case TIMER_SERVICE: {
parseTimerService(reader, operations);
break;
}
case THREAD_POOLS: {
parseThreadPools(reader, operations);
break;
}
case IIOP: {
parseIIOP(reader, operations);
break;
}
case IN_VM_REMOTE_INTERFACE_INVOCATION:
parseInVMRemoteInterfaceInvocation(reader, ejb3SubsystemAddOperation);
break;
default: {
throw unexpectedElement(reader);
}
}
}
protected void parseRemote(final XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
final int count = reader.getAttributeCount();
ModelNode operation = Util.createAddOperation(SUBSYSTEM_PATH.append(SERVICE, REMOTE));
final EnumSet<EJB3SubsystemXMLAttribute> required = EnumSet.of(EJB3SubsystemXMLAttribute.CONNECTOR_REF, EJB3SubsystemXMLAttribute.THREAD_POOL_NAME);
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final EJB3SubsystemXMLAttribute attribute = EJB3SubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case CONNECTOR_REF:
EJB3RemoteResourceDefinition.CONNECTOR_REF.parseAndSetParameter(value, operation, reader);
break;
case THREAD_POOL_NAME:
EJB3RemoteResourceDefinition.THREAD_POOL_NAME.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
operation.get(EJB3SubsystemModel.EXECUTE_IN_WORKER).set(ModelNode.FALSE);
requireNoContent(reader);
operations.add(operation);
}
private void parseAsync(final XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
final int count = reader.getAttributeCount();
//String threadPoolName = null;
ModelNode operation = Util.createAddOperation(SUBSYSTEM_PATH.append(SERVICE, ASYNC));
final EnumSet<EJB3SubsystemXMLAttribute> required = EnumSet.of(EJB3SubsystemXMLAttribute.THREAD_POOL_NAME);
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final EJB3SubsystemXMLAttribute attribute = EJB3SubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case THREAD_POOL_NAME:
EJB3AsyncResourceDefinition.THREAD_POOL_NAME.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
requireNoContent(reader);
operations.add(operation);
}
private void parseIIOP(final XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
ModelNode operation = Util.createAddOperation(SUBSYSTEM_PATH.append(SERVICE, IIOP));
final int count = reader.getAttributeCount();
final EnumSet<EJB3SubsystemXMLAttribute> required = EnumSet.of(EJB3SubsystemXMLAttribute.ENABLE_BY_DEFAULT, EJB3SubsystemXMLAttribute.USE_QUALIFIED_NAME);
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final EJB3SubsystemXMLAttribute attribute = EJB3SubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case ENABLE_BY_DEFAULT:
EJB3IIOPResourceDefinition.ENABLE_BY_DEFAULT.parseAndSetParameter(value,operation,reader);
break;
case USE_QUALIFIED_NAME:
EJB3IIOPResourceDefinition.USE_QUALIFIED_NAME.parseAndSetParameter(value,operation,reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
requireNoContent(reader);
operations.add(operation);
}
protected void parseMDB(final XMLExtendedStreamReader reader, List<ModelNode> operations, final ModelNode ejb3SubsystemAddOperation) throws XMLStreamException {
// no attributes expected
requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (EJB3SubsystemXMLElement.forName(reader.getLocalName())) {
case BEAN_INSTANCE_POOL_REF: {
final String poolName = readStringAttributeElement(reader, EJB3SubsystemXMLAttribute.POOL_NAME.getLocalName());
EJB3SubsystemRootResourceDefinition.DEFAULT_MDB_INSTANCE_POOL.parseAndSetParameter(poolName, ejb3SubsystemAddOperation, reader);
break;
}
case RESOURCE_ADAPTER_REF: {
final String resourceAdapterName = readStringAttributeElement(reader, EJB3SubsystemXMLAttribute.RESOURCE_ADAPTER_NAME.getLocalName());
EJB3SubsystemRootResourceDefinition.DEFAULT_RESOURCE_ADAPTER_NAME.parseAndSetParameter(resourceAdapterName, ejb3SubsystemAddOperation, reader);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private void parseEntityBean(final XMLExtendedStreamReader reader, List<ModelNode> operations, final ModelNode ejb3SubsystemAddOperation) throws XMLStreamException {
// no attributes expected
requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (EJB3SubsystemXMLElement.forName(reader.getLocalName())) {
case BEAN_INSTANCE_POOL_REF: {
final String poolName = readStringAttributeElement(reader, EJB3SubsystemXMLAttribute.POOL_NAME.getLocalName());
EJB3SubsystemRootResourceDefinition.DEFAULT_ENTITY_BEAN_INSTANCE_POOL.parseAndSetParameter(poolName, ejb3SubsystemAddOperation, reader);
break;
}
case OPTIMISTIC_LOCKING: {
final String enabled = readStringAttributeElement(reader, EJB3SubsystemXMLAttribute.ENABLED.getLocalName());
EJB3SubsystemRootResourceDefinition.DEFAULT_ENTITY_BEAN_OPTIMISTIC_LOCKING.parseAndSetParameter(enabled, ejb3SubsystemAddOperation, reader);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private void parseSessionBean(final XMLExtendedStreamReader reader, final List<ModelNode> operations, ModelNode ejb3SubsystemAddOperation) throws XMLStreamException {
// no attributes expected
requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (EJB3SubsystemXMLElement.forName(reader.getLocalName())) {
case STATELESS: {
this.parseStatelessBean(reader, operations, ejb3SubsystemAddOperation);
break;
}
case STATEFUL: {
this.parseStatefulBean(reader, operations, ejb3SubsystemAddOperation);
break;
}
case SINGLETON: {
this.parseSingletonBean(reader, operations, ejb3SubsystemAddOperation);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private void parseStatelessBean(final XMLExtendedStreamReader reader, final List<ModelNode> operations, ModelNode ejb3SubsystemAddOperation) throws XMLStreamException {
// no attributes expected
requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (EJB3SubsystemXMLElement.forName(reader.getLocalName())) {
case BEAN_INSTANCE_POOL_REF: {
final String poolName = readStringAttributeElement(reader, EJB3SubsystemXMLAttribute.POOL_NAME.getLocalName());
EJB3SubsystemRootResourceDefinition.DEFAULT_SLSB_INSTANCE_POOL.parseAndSetParameter(poolName, ejb3SubsystemAddOperation, reader);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
protected void parseStatefulBean(final XMLExtendedStreamReader reader, final List<ModelNode> operations, final ModelNode ejb3SubsystemAddOperation) throws XMLStreamException {
final int count = reader.getAttributeCount();
final EnumSet<EJB3SubsystemXMLAttribute> missingRequiredAttributes = EnumSet.of(EJB3SubsystemXMLAttribute.DEFAULT_ACCESS_TIMEOUT, EJB3SubsystemXMLAttribute.CACHE_REF);
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final EJB3SubsystemXMLAttribute attribute = EJB3SubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case DEFAULT_ACCESS_TIMEOUT: {
EJB3SubsystemRootResourceDefinition.DEFAULT_STATEFUL_BEAN_ACCESS_TIMEOUT.parseAndSetParameter(value, ejb3SubsystemAddOperation, reader);
break;
}
case CACHE_REF: {
EJB3SubsystemRootResourceDefinition.DEFAULT_SFSB_CACHE.parseAndSetParameter(value, ejb3SubsystemAddOperation, reader);
break;
}
case CLUSTERED_CACHE_REF: {
EJB3SubsystemRootResourceDefinition.DEFAULT_CLUSTERED_SFSB_CACHE.parseAndSetParameter(value, ejb3SubsystemAddOperation, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
// found the mandatory attribute
missingRequiredAttributes.remove(attribute);
}
requireNoContent(reader);
if (!missingRequiredAttributes.isEmpty()) {
throw missingRequired(reader, missingRequiredAttributes);
}
}
private void parseSingletonBean(final XMLExtendedStreamReader reader, final List<ModelNode> operations, final ModelNode ejb3SubsystemAddOperation) throws XMLStreamException {
final int count = reader.getAttributeCount();
final EnumSet<EJB3SubsystemXMLAttribute> missingRequiredAttributes = EnumSet.of(EJB3SubsystemXMLAttribute.DEFAULT_ACCESS_TIMEOUT);
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final EJB3SubsystemXMLAttribute attribute = EJB3SubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case DEFAULT_ACCESS_TIMEOUT:
EJB3SubsystemRootResourceDefinition.DEFAULT_SINGLETON_BEAN_ACCESS_TIMEOUT.parseAndSetParameter(value, ejb3SubsystemAddOperation, reader);
// found the mandatory attribute
missingRequiredAttributes.remove(EJB3SubsystemXMLAttribute.DEFAULT_ACCESS_TIMEOUT);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
requireNoContent(reader);
if (!missingRequiredAttributes.isEmpty()) {
throw missingRequired(reader, missingRequiredAttributes);
}
}
private void parsePools(final XMLExtendedStreamReader reader, final List<ModelNode> operations) throws XMLStreamException {
// no attributes expected
requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (EJB3SubsystemXMLElement.forName(reader.getLocalName())) {
case BEAN_INSTANCE_POOLS: {
this.parseBeanInstancePools(reader, operations);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private void parseBeanInstancePools(final XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
// no attributes expected
requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (EJB3SubsystemXMLElement.forName(reader.getLocalName())) {
case STRICT_MAX_POOL: {
this.parseStrictMaxPool(reader, operations);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
void parseStrictMaxPool(final XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
final int count = reader.getAttributeCount();
String poolName = null;
final ModelNode operation = Util.createAddOperation();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final EJB3SubsystemXMLAttribute attribute = EJB3SubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NAME:
poolName = value;
break;
case MAX_POOL_SIZE:
StrictMaxPoolResourceDefinition.MAX_POOL_SIZE.parseAndSetParameter(value, operation, reader);
break;
case INSTANCE_ACQUISITION_TIMEOUT:
StrictMaxPoolResourceDefinition.INSTANCE_ACQUISITION_TIMEOUT.parseAndSetParameter(value, operation, reader);
break;
case INSTANCE_ACQUISITION_TIMEOUT_UNIT:
StrictMaxPoolResourceDefinition.INSTANCE_ACQUISITION_TIMEOUT_UNIT.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
requireNoContent(reader);
if (poolName == null) {
throw missingRequired(reader, Collections.singleton(EJB3SubsystemXMLAttribute.NAME.getLocalName()));
}
// create and add the operation
// create /subsystem=ejb3/strict-max-bean-instance-pool=name:add(...)
final PathAddress address = this.getEJB3SubsystemAddress().append(STRICT_MAX_BEAN_INSTANCE_POOL, poolName);
operation.get(OP_ADDR).set(address.toModelNode());
operations.add(operation);
}
protected void parseCaches(final XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
// no attributes expected
requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (EJB3SubsystemXMLElement.forName(reader.getLocalName())) {
case CACHE: {
this.parseCache(reader, operations);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
protected void parseCache(final XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
String name = null;
ModelNode operation = Util.createAddOperation();
//Set<String> aliases = new LinkedHashSet<String>();
for (int i = 0; i < reader.getAttributeCount(); i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
switch (EJB3SubsystemXMLAttribute.forName(reader.getAttributeLocalName(i))) {
case NAME: {
name = value;
break;
}
case PASSIVATION_STORE_REF: {
LegacyCacheFactoryResourceDefinition.PASSIVATION_STORE.parseAndSetParameter(value, operation, reader);
break;
}
case ALIASES: {
LegacyCacheFactoryResourceDefinition.ALIASES.getParser().parseAndSetParameter(LegacyCacheFactoryResourceDefinition.ALIASES, value, operation, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
requireNoContent(reader);
if (name == null) {
throw missingRequired(reader, Collections.singleton(EJB3SubsystemXMLAttribute.NAME.getLocalName()));
}
final PathAddress address = this.getEJB3SubsystemAddress().append(PathElement.pathElement(CACHE, name));
operation.get(OP_ADDR).set(address.toModelNode());
operations.add(operation);
}
@SuppressWarnings("deprecation")
protected void parsePassivationStores(final XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
// no attributes expected
requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (EJB3SubsystemXMLElement.forName(reader.getLocalName())) {
case FILE_PASSIVATION_STORE: {
this.parseFilePassivationStore(reader, operations);
break;
}
case CLUSTER_PASSIVATION_STORE: {
this.parseClusterPassivationStore(reader, operations);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
@SuppressWarnings("deprecation")
protected void parseFilePassivationStore(final XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
String name = null;
ModelNode operation = Util.createAddOperation();
for (int i = 0; i < reader.getAttributeCount(); i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
switch (EJB3SubsystemXMLAttribute.forName(reader.getAttributeLocalName(i))) {
case NAME: {
name = value;
break;
}
case MAX_SIZE: {
FilePassivationStoreResourceDefinition.MAX_SIZE.parseAndSetParameter(value, operation, reader);
break;
}
case IDLE_TIMEOUT: {
LegacyPassivationStoreResourceDefinition.IDLE_TIMEOUT.parseAndSetParameter(value, operation, reader);
break;
}
case IDLE_TIMEOUT_UNIT: {
LegacyPassivationStoreResourceDefinition.IDLE_TIMEOUT_UNIT.parseAndSetParameter(value, operation, reader);
break;
}
case RELATIVE_TO: {
FilePassivationStoreResourceDefinition.RELATIVE_TO.parseAndSetParameter(value, operation, reader);
break;
}
case GROUPS_PATH: {
FilePassivationStoreResourceDefinition.GROUPS_PATH.parseAndSetParameter(value, operation, reader);
break;
}
case SESSIONS_PATH: {
FilePassivationStoreResourceDefinition.SESSIONS_PATH.parseAndSetParameter(value, operation, reader);
break;
}
case SUBDIRECTORY_COUNT: {
FilePassivationStoreResourceDefinition.SUBDIRECTORY_COUNT.parseAndSetParameter(value, operation, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
requireNoContent(reader);
if (name == null) {
throw missingRequired(reader, Collections.singleton(EJB3SubsystemXMLAttribute.NAME.getLocalName()));
}
// create and add the operation
operation.get(OP_ADDR).set(SUBSYSTEM_PATH.append(FILE_PASSIVATION_STORE, name).toModelNode());
operations.add(operation);
}
@SuppressWarnings("deprecation")
protected void parseClusterPassivationStore(final XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
String name = null;
ModelNode operation = Util.createAddOperation();
for (int i = 0; i < reader.getAttributeCount(); i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
switch (EJB3SubsystemXMLAttribute.forName(reader.getAttributeLocalName(i))) {
case NAME: {
name = value;
break;
}
case MAX_SIZE: {
ClusterPassivationStoreResourceDefinition.MAX_SIZE.parseAndSetParameter(value, operation, reader);
break;
}
case IDLE_TIMEOUT: {
LegacyPassivationStoreResourceDefinition.IDLE_TIMEOUT.parseAndSetParameter(value, operation, reader);
break;
}
case IDLE_TIMEOUT_UNIT: {
LegacyPassivationStoreResourceDefinition.IDLE_TIMEOUT_UNIT.parseAndSetParameter(value, operation, reader);
break;
}
case CACHE_CONTAINER: {
ClusterPassivationStoreResourceDefinition.CACHE_CONTAINER.parseAndSetParameter(value, operation, reader);
break;
}
case BEAN_CACHE: {
ClusterPassivationStoreResourceDefinition.BEAN_CACHE.parseAndSetParameter(value, operation, reader);
break;
}
case CLIENT_MAPPINGS_CACHE: {
ClusterPassivationStoreResourceDefinition.CLIENT_MAPPINGS_CACHE.parseAndSetParameter(value, operation, reader);
break;
}
case PASSIVATE_EVENTS_ON_REPLICATE: {
ClusterPassivationStoreResourceDefinition.PASSIVATE_EVENTS_ON_REPLICATE.parseAndSetParameter(value, operation, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
requireNoContent(reader);
if (name == null) {
throw missingRequired(reader, Collections.singleton(EJB3SubsystemXMLAttribute.NAME.getLocalName()));
}
// create and add the operation
operation.get(OP_ADDR).set(SUBSYSTEM_PATH.append(CLUSTER_PASSIVATION_STORE, name).toModelNode());
operations.add(operation);
}
protected void parseTimerService(final XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
ModelNode fileDataStoreAdd = null;
final ModelNode address = new ModelNode();
address.add(SUBSYSTEM, EJB3Extension.SUBSYSTEM_NAME);
address.add(SERVICE, TIMER_SERVICE);
final ModelNode timerServiceAdd = new ModelNode();
timerServiceAdd.get(OP).set(ADD);
timerServiceAdd.get(OP_ADDR).set(address);
ModelNode dataStorePath = null;
ModelNode dataStorePathRelativeTo = null;
final int attCount = reader.getAttributeCount();
final EnumSet<EJB3SubsystemXMLAttribute> required = EnumSet.of(EJB3SubsystemXMLAttribute.THREAD_POOL_NAME);
for (int i = 0; i < attCount; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final EJB3SubsystemXMLAttribute attribute = EJB3SubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case THREAD_POOL_NAME:
TimerServiceResourceDefinition.THREAD_POOL_NAME.parseAndSetParameter(value, timerServiceAdd, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (EJB3SubsystemXMLElement.forName(reader.getLocalName())) {
case DATA_STORE: {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final EJB3SubsystemXMLAttribute attribute = EJB3SubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case PATH:
if (dataStorePath != null) {
throw unexpectedAttribute(reader, i);
}
dataStorePath = parse(FileDataStoreResourceDefinition.PATH, value, reader);
break;
case RELATIVE_TO:
if (dataStorePathRelativeTo != null) {
throw unexpectedAttribute(reader, i);
}
dataStorePathRelativeTo = parse(FileDataStoreResourceDefinition.RELATIVE_TO, value, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (dataStorePath == null) {
throw missingRequired(reader, Collections.singleton(EJB3SubsystemXMLAttribute.PATH));
}
timerServiceAdd.get(DEFAULT_DATA_STORE).set("default-file-store");
fileDataStoreAdd = new ModelNode();
final ModelNode fileDataAddress = address.clone();
fileDataAddress.add(FILE_DATA_STORE, "default-file-store");
fileDataStoreAdd.get(OP).set(ADD);
fileDataStoreAdd.get(OP_ADDR).set(fileDataAddress);
fileDataStoreAdd.get(PATH).set(dataStorePath);
if (dataStorePathRelativeTo != null) {
fileDataStoreAdd.get(RELATIVE_TO).set(dataStorePathRelativeTo);
}
requireNoContent(reader);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
operations.add(timerServiceAdd);
if(fileDataStoreAdd != null) {
operations.add(fileDataStoreAdd);
}
}
private void parseThreadPools(final XMLExtendedStreamReader reader, final List<ModelNode> operations) throws XMLStreamException {
// no attributes expected
requireNoAttributes(reader);
final ModelNode parentAddress = SUBSYSTEM_PATH.toModelNode();
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
EJB3SubsystemNamespace readerNS = EJB3SubsystemNamespace.forUri(reader.getNamespaceURI());
switch (EJB3SubsystemXMLElement.forName(reader.getLocalName())) {
case THREAD_POOL: {
ThreadsParser.getInstance().parseEnhancedQueueThreadPool(reader, readerNS.getUriString(),
Namespace.THREADS_1_1, parentAddress, operations, THREAD_POOL, null);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
protected EJB3SubsystemNamespace getExpectedNamespace() {
return EJB3SubsystemNamespace.EJB3_1_2;
}
PathAddress getEJB3SubsystemAddress() {
return SUBSYSTEM_PATH;
}
private void parseInVMRemoteInterfaceInvocation(final XMLExtendedStreamReader reader, final ModelNode ejb3SubsystemAddOperation) throws XMLStreamException {
final int count = reader.getAttributeCount();
final EnumSet<EJB3SubsystemXMLAttribute> missingRequiredAttributes = EnumSet.of(EJB3SubsystemXMLAttribute.PASS_BY_VALUE);
//String passByValue = null;
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final EJB3SubsystemXMLAttribute attribute = EJB3SubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case PASS_BY_VALUE:
EJB3SubsystemRootResourceDefinition.PASS_BY_VALUE.parseAndSetParameter(value, ejb3SubsystemAddOperation, reader);
// found the mandatory attribute
missingRequiredAttributes.remove(EJB3SubsystemXMLAttribute.PASS_BY_VALUE);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
requireNoContent(reader);
if (!missingRequiredAttributes.isEmpty()) {
throw missingRequired(reader, missingRequiredAttributes);
}
}
protected static ModelNode parse(AttributeDefinition ad, String value, XMLStreamReader reader) throws XMLStreamException {
return ad.getParser().parse(ad, value, reader);
}
}
| 37,832 | 46.889873 | 212 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/RemotingProfileResourceChildWriteAttributeHandler.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ejb3.subsystem;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.RestartParentWriteAttributeHandler;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceName;
/**
* A write handler for the "value" attribute of the channel creation option
*
* @author <a href="mailto:[email protected]">Tomasz Adamski</a>
*/
public class RemotingProfileResourceChildWriteAttributeHandler extends RestartParentWriteAttributeHandler {
public RemotingProfileResourceChildWriteAttributeHandler(final AttributeDefinition attributeDefinition) {
super(EJB3SubsystemModel.REMOTING_PROFILE, attributeDefinition);
}
@Override
protected void recreateParentService(OperationContext context, PathAddress parentAddress, ModelNode parentModel) throws OperationFailedException {
RemotingProfileResourceDefinition.ADD_HANDLER.installServices(context, parentAddress, parentModel);
}
@Override
protected ServiceName getParentServiceName(PathAddress parentAddress) {
return RemotingProfileResourceDefinition.REMOTING_PROFILE_CAPABILITY.getCapabilityServiceName(parentAddress);
}
}
| 2,355 | 42.62963 | 150 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/TimerServiceResourceDefinition.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.ejb3.subsystem;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.ReloadRequiredRemoveStepHandler;
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.capability.RuntimeCapability;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.OperationEntry;
import org.jboss.as.controller.services.path.PathManager;
import org.jboss.as.ejb3.timerservice.persistence.TimerPersistence;
import org.jboss.as.threads.ThreadsServices;
import org.jboss.dmr.ModelType;
import org.wildfly.clustering.ejb.timer.TimerServiceRequirement;
import java.util.Timer;
import java.util.concurrent.ExecutorService;
/**
* {@link org.jboss.as.controller.ResourceDefinition} for the timer-service resource.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class TimerServiceResourceDefinition extends SimpleResourceDefinition {
// this is an unregistered copy of the capability defined and registered in /subsystem=ejb3/thread-pool=*
// needed due to the unorthodox way in which the thread pools are defined in ejb3 subsystem
public static final String THREAD_POOL_CAPABILITY_NAME = ThreadsServices.createCapability(EJB3SubsystemModel.BASE_EJB_THREAD_POOL_NAME, ExecutorService.class).getName();
public static final String TIMER_PERSISTENCE_CAPABILITY_NAME = "org.wildfly.ejb3.timer-service.timer-persistence-service";
public static final RuntimeCapability<Void> TIMER_PERSISTENCE_CAPABILITY =
RuntimeCapability.Builder.of(TIMER_PERSISTENCE_CAPABILITY_NAME, true, TimerPersistence.class)
.setAllowMultipleRegistrations(true)
.build();
public static final String TIMER_SERVICE_CAPABILITY_NAME = "org.wildfly.ejb3.timer-service";
public static final RuntimeCapability<Void> TIMER_SERVICE_CAPABILITY = RuntimeCapability.Builder.of(TIMER_SERVICE_CAPABILITY_NAME, Timer.class).build();
static final SimpleAttributeDefinition THREAD_POOL_NAME =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.THREAD_POOL_NAME, ModelType.STRING)
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.setRequired(true)
.setAlternatives(EJB3SubsystemModel.DEFAULT_TRANSIENT_TIMER_MANAGEMENT)
.setCapabilityReference(THREAD_POOL_CAPABILITY_NAME, TIMER_SERVICE_CAPABILITY)
.build();
static final SimpleAttributeDefinition DEFAULT_DATA_STORE =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.DEFAULT_DATA_STORE, ModelType.STRING)
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.setRequired(true)
.setAlternatives(EJB3SubsystemModel.DEFAULT_PERSISTENT_TIMER_MANAGEMENT)
.setRequires(EJB3SubsystemModel.THREAD_POOL_NAME)
.setCapabilityReference(TIMER_PERSISTENCE_CAPABILITY_NAME, TIMER_SERVICE_CAPABILITY)
.build();
static final SimpleAttributeDefinition DEFAULT_PERSISTENT_TIMER_MANAGEMENT =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.DEFAULT_PERSISTENT_TIMER_MANAGEMENT, ModelType.STRING)
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.setRequired(true)
.setAlternatives(EJB3SubsystemModel.DEFAULT_DATA_STORE)
.setCapabilityReference(TimerServiceRequirement.TIMER_MANAGEMENT_PROVIDER.getName(), TIMER_SERVICE_CAPABILITY)
.build();
static final SimpleAttributeDefinition DEFAULT_TRANSIENT_TIMER_MANAGEMENT =
new SimpleAttributeDefinitionBuilder(EJB3SubsystemModel.DEFAULT_TRANSIENT_TIMER_MANAGEMENT, ModelType.STRING)
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.setRequired(true)
.setAlternatives(EJB3SubsystemModel.THREAD_POOL_NAME)
.setCapabilityReference(TimerServiceRequirement.TIMER_MANAGEMENT_PROVIDER.getName(), TIMER_SERVICE_CAPABILITY)
.build();
static final AttributeDefinition[] ATTRIBUTES = new AttributeDefinition[] { THREAD_POOL_NAME, DEFAULT_DATA_STORE, DEFAULT_PERSISTENT_TIMER_MANAGEMENT, DEFAULT_TRANSIENT_TIMER_MANAGEMENT };
private final PathManager pathManager;
public TimerServiceResourceDefinition(final PathManager pathManager) {
super(new SimpleResourceDefinition.Parameters(EJB3SubsystemModel.TIMER_SERVICE_PATH, EJB3Extension.getResourceDescriptionResolver(EJB3SubsystemModel.TIMER_SERVICE))
.setAddHandler(TimerServiceAdd.INSTANCE)
.setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE)
.setAddRestartLevel(OperationEntry.Flag.RESTART_ALL_SERVICES)
.setRemoveRestartLevel(OperationEntry.Flag.RESTART_ALL_SERVICES)
.setCapabilities(TIMER_SERVICE_CAPABILITY));
this.pathManager = pathManager;
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
for (AttributeDefinition attr : ATTRIBUTES) {
resourceRegistration.registerReadWriteAttribute(attr, null, new ReloadRequiredWriteAttributeHandler(attr));
}
}
@Override
public void registerChildren(final ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerSubModel(new FileDataStoreResourceDefinition(pathManager));
resourceRegistration.registerSubModel(new DatabaseDataStoreResourceDefinition());
}
}
| 6,945 | 54.126984 | 192 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/RemotingEjbReceiverChannelCreationOptionResource.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ejb3.subsystem;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelType;
/**
* {@link SimpleResourceDefinition} for the channel creation option(s) that are configured for the remoting Jakarta Enterprise Beans receivers
*
* @author Jaikiran Pai
* @author <a href="mailto:[email protected]">Tomasz Adamski</a>
*/
class RemotingEjbReceiverChannelCreationOptionResource extends SimpleResourceDefinition {
/**
* Attribute definition of the channel creation option "value"
*/
static final SimpleAttributeDefinition CHANNEL_CREATION_OPTION_VALUE = new SimpleAttributeDefinitionBuilder(
EJB3SubsystemModel.VALUE, ModelType.STRING, true).setAllowExpression(true)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES).build();
/**
* Attribute definition of the channel creation option "type"
*/
static final SimpleAttributeDefinition CHANNEL_CREATION_OPTION_TYPE = new SimpleAttributeDefinitionBuilder(
EJB3SubsystemModel.TYPE, ModelType.STRING).setRequired(true)
.setValidator(AllowedChannelOptionTypesValidator.INSTANCE).build();
private static final AttributeDefinition[] ATTRIBUTES = new AttributeDefinition[] { CHANNEL_CREATION_OPTION_VALUE, CHANNEL_CREATION_OPTION_TYPE };
static final RemotingEjbReceiverChannelCreationOptionResource INSTANCE = new RemotingEjbReceiverChannelCreationOptionResource();
RemotingEjbReceiverChannelCreationOptionResource() {
super(PathElement.pathElement(EJB3SubsystemModel.CHANNEL_CREATION_OPTIONS),
EJB3Extension.getResourceDescriptionResolver(EJB3SubsystemModel.CHANNEL_CREATION_OPTIONS),
new RemotingProfileChildResourceAddHandler(ATTRIBUTES),
new RemotingProfileChildResourceRemoveHandler());
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerReadWriteAttribute(CHANNEL_CREATION_OPTION_VALUE, null, new RemotingProfileResourceChildWriteAttributeHandler(CHANNEL_CREATION_OPTION_VALUE));
resourceRegistration.registerReadWriteAttribute(CHANNEL_CREATION_OPTION_TYPE, null, new RemotingProfileResourceChildWriteAttributeHandler(CHANNEL_CREATION_OPTION_TYPE));
}
}
| 3,696 | 49.643836 | 179 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/RemoteHttpConnectionDefinition.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ejb3.subsystem;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelType;
/**
* @author <a href="mailto:[email protected]">Tomasz Adamski</a>
*/
public class RemoteHttpConnectionDefinition extends SimpleResourceDefinition {
public static final SimpleAttributeDefinition URI = new SimpleAttributeDefinitionBuilder(
EJB3SubsystemModel.URI, ModelType.STRING).setRequired(true).setAllowExpression(true)
.build();
private static final AttributeDefinition[] ATTRIBUTES = new AttributeDefinition[]{URI};
RemoteHttpConnectionDefinition() {
super(PathElement.pathElement(EJB3SubsystemModel.REMOTE_HTTP_CONNECTION), EJB3Extension
.getResourceDescriptionResolver(EJB3SubsystemModel.REMOTE_HTTP_CONNECTION), new RemotingProfileChildResourceAddHandler(
ATTRIBUTES), new RemotingProfileChildResourceRemoveHandler());
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
for (final AttributeDefinition attr : ATTRIBUTES) {
resourceRegistration.registerReadWriteAttribute(attr, null, new RemotingProfileResourceChildWriteAttributeHandler(attr));
}
}
}
| 2,579 | 43.482759 | 135 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/FileDataStoreAdd.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.ejb3.subsystem;
import java.util.function.Consumer;
import java.util.function.Supplier;
import jakarta.transaction.TransactionSynchronizationRegistry;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.CapabilityServiceBuilder;
import org.jboss.as.controller.CapabilityServiceTarget;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.services.path.PathManager;
import org.jboss.as.ejb3.timerservice.persistence.filestore.FileTimerPersistence;
import org.jboss.as.server.Services;
import org.jboss.dmr.ModelNode;
import org.jboss.modules.ModuleLoader;
/**
* Adds the timer service file based data store
*
* @author Stuart Douglas
*/
public class FileDataStoreAdd extends AbstractAddStepHandler {
private static final String TRANSACTION_SYNCHRONIZATION_REGISTRY_CAPABILITY_NAME = "org.wildfly.transactions.transaction-synchronization-registry";
private static final String TRANSACTION_GLOBAL_DEFAULT_LOCAL_PROVIDER_CAPABILITY_NAME = "org.wildfly.transactions.global-default-local-provider";
private static final String PATH_MANAGER_CAPABILITY_NAME = "org.wildfly.management.path-manager";
FileDataStoreAdd(AttributeDefinition... attributes) {
super(attributes);
}
protected void performRuntime(final OperationContext context, ModelNode operation, final ModelNode model) throws OperationFailedException {
final ModelNode pathNode = FileDataStoreResourceDefinition.PATH.resolveModelAttribute(context, model);
final String path = pathNode.isDefined() ? pathNode.asString() : null;
final ModelNode relativeToNode = FileDataStoreResourceDefinition.RELATIVE_TO.resolveModelAttribute(context, model);
final String relativeTo = relativeToNode.isDefined() ? relativeToNode.asString() : null;
// add the TimerPersistence instance
final CapabilityServiceTarget serviceTarget = context.getCapabilityServiceTarget();
final CapabilityServiceBuilder<?> builder = serviceTarget.addCapability(TimerServiceResourceDefinition.TIMER_PERSISTENCE_CAPABILITY);
final Consumer<FileTimerPersistence> consumer = builder.provides(TimerServiceResourceDefinition.TIMER_PERSISTENCE_CAPABILITY);
builder.requiresCapability(TRANSACTION_GLOBAL_DEFAULT_LOCAL_PROVIDER_CAPABILITY_NAME, Void.class);
final Supplier<TransactionSynchronizationRegistry> txnRegistrySupplier = builder.requiresCapability(TRANSACTION_SYNCHRONIZATION_REGISTRY_CAPABILITY_NAME, TransactionSynchronizationRegistry.class);
final Supplier<ModuleLoader> moduleLoaderSupplier = builder.requires(Services.JBOSS_SERVICE_MODULE_LOADER);
final Supplier<PathManager> pathManagerSupplier = builder.requiresCapability(PATH_MANAGER_CAPABILITY_NAME, PathManager.class);
final FileTimerPersistence fileTimerPersistence = new FileTimerPersistence(consumer, txnRegistrySupplier, moduleLoaderSupplier, pathManagerSupplier, true, path, relativeTo);
builder.setInstance(fileTimerPersistence);
builder.install();
}
}
| 4,221 | 54.552632 | 204 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/EJB3Model.java | package org.jboss.as.ejb3.subsystem;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.SubsystemModel;
/**
* Enumerates the supported model versions.
* @author Paul Ferraro
* @author Richard Achmatowicz
*/
public enum EJB3Model implements SubsystemModel {
VERSION_1_2_0(1, 2, 0),
VERSION_1_2_1(1, 2, 1), // EAP 6.4.0
VERSION_1_3_0(1, 3, 0), // EAP 6.4.7
VERSION_3_0_0(3, 0, 0), //
VERSION_4_0_0(4, 0, 0), // EAP 7.0.0
VERSION_5_0_0(5, 0, 0), // EAP 7.2.0, EAP 7.1.0
VERSION_6_0_0(6, 0, 0),
VERSION_7_0_0(7, 0, 0),
VERSION_8_0_0(8, 0, 0),
VERSION_9_0_0(9, 0, 0),
VERSION_10_0_0(10, 0, 0),
;
static final EJB3Model CURRENT = VERSION_10_0_0;
private final ModelVersion version;
EJB3Model(int major, int minor, int micro) {
this.version = ModelVersion.create(major, minor, micro);
}
@Override
public ModelVersion getVersion() {
return this.version;
}
}
| 978 | 24.102564 | 64 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/EJBDefaultSecurityDomainWriteHandler.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.ejb3.subsystem;
import java.util.concurrent.atomic.AtomicReference;
import org.jboss.as.controller.AbstractWriteAttributeHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.dmr.ModelNode;
/**
* Write handler for default security domain attribute of EJB3 subsystem
*
* @author Jaikiran Pai
*/
class EJBDefaultSecurityDomainWriteHandler extends AbstractWriteAttributeHandler<Void> {
private final AttributeDefinition attributeDefinition;
private final AtomicReference<String> defaultSecurityDomainName;
EJBDefaultSecurityDomainWriteHandler(final AttributeDefinition attributeDefinition, final AtomicReference<String> defaultSecurityDomainName) {
super(attributeDefinition);
this.attributeDefinition = attributeDefinition;
this.defaultSecurityDomainName = defaultSecurityDomainName;
}
@Override
protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName,
ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<Void> handbackHolder) throws OperationFailedException {
final ModelNode model = context.readResource(PathAddress.EMPTY_ADDRESS).getModel();
updateDefaultSecurityDomainDeploymentProcessor(context, model);
return false;
}
@Override
protected void revertUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName,
ModelNode valueToRestore, ModelNode valueToRevert, Void handback) throws OperationFailedException {
final ModelNode restored = context.readResource(PathAddress.EMPTY_ADDRESS).getModel().clone();
restored.get(attributeName).set(valueToRestore);
updateDefaultSecurityDomainDeploymentProcessor(context, restored);
}
private void updateDefaultSecurityDomainDeploymentProcessor(final OperationContext context, final ModelNode model) throws OperationFailedException {
final ModelNode defaultSecurityDomainModelNode = this.attributeDefinition.resolveModelAttribute(context, model);
final String defaultSecurityDomainName = defaultSecurityDomainModelNode.isDefined() ? defaultSecurityDomainModelNode.asString() : null;
this.defaultSecurityDomainName.set(defaultSecurityDomainName);
}
}
| 3,542 | 46.24 | 162 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/EJB3Subsystem80Parser.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2019, 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.ejb3.subsystem;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequired;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoNamespaceAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
import static org.jboss.as.ejb3.subsystem.EJB3SubsystemModel.REMOTE;
import static org.jboss.as.ejb3.subsystem.EJB3SubsystemModel.SERVICE;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.dmr.ModelNode;
import org.jboss.ejb.client.EJBClientContext;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* Parser for ejb3:8.0 namespace.
*/
public class EJB3Subsystem80Parser extends EJB3Subsystem70Parser {
EJB3Subsystem80Parser() {
}
@Override
protected EJB3SubsystemNamespace getExpectedNamespace() {
return EJB3SubsystemNamespace.EJB3_8_0;
}
protected void parseRemote(final XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
final int count = reader.getAttributeCount();
final PathAddress ejb3RemoteServiceAddress = SUBSYSTEM_PATH.append(SERVICE, REMOTE);
ModelNode operation = Util.createAddOperation(ejb3RemoteServiceAddress);
final EnumSet<EJB3SubsystemXMLAttribute> required = EnumSet.of(EJB3SubsystemXMLAttribute.CONNECTORS, EJB3SubsystemXMLAttribute.THREAD_POOL_NAME);
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final EJB3SubsystemXMLAttribute attribute = EJB3SubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case CLIENT_MAPPINGS_CLUSTER_NAME:
EJB3RemoteResourceDefinition.CLIENT_MAPPINGS_CLUSTER_NAME.parseAndSetParameter(value, operation, reader);
break;
case CONNECTORS:
// can't use the obvious: EJB3RemoteResourceDefinition.CONNECTORS.parseAndSetParameter(value, operation, reader);
EJB3RemoteResourceDefinition.CONNECTORS.getParser().parseAndSetParameter(EJB3RemoteResourceDefinition.CONNECTORS, value, operation, reader);
break;
case THREAD_POOL_NAME:
EJB3RemoteResourceDefinition.THREAD_POOL_NAME.parseAndSetParameter(value, operation, reader);
break;
case EXECUTE_IN_WORKER:
EJB3RemoteResourceDefinition.EXECUTE_IN_WORKER.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
// each profile adds it's own operation
operations.add(operation);
final Set<EJB3SubsystemXMLElement> parsedElements = new HashSet<EJB3SubsystemXMLElement>();
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
EJB3SubsystemXMLElement element = EJB3SubsystemXMLElement.forName(reader.getLocalName());
switch (element) {
case CHANNEL_CREATION_OPTIONS: {
if (parsedElements.contains(EJB3SubsystemXMLElement.CHANNEL_CREATION_OPTIONS)) {
throw unexpectedElement(reader);
}
parsedElements.add(EJB3SubsystemXMLElement.CHANNEL_CREATION_OPTIONS);
this.parseChannelCreationOptions(reader, ejb3RemoteServiceAddress, operations);
break;
}
case PROFILES: {
parseProfiles(reader, operations);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
protected void parseProfile(final XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
final int count = reader.getAttributeCount();
String profileName = null;
final EJBClientContext.Builder builder = new EJBClientContext.Builder();
final ModelNode operation = Util.createAddOperation();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final EJB3SubsystemXMLAttribute attribute = EJB3SubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NAME:
profileName = value;
break;
case EXCLUDE_LOCAL_RECEIVER:
RemotingProfileResourceDefinition.EXCLUDE_LOCAL_RECEIVER.parseAndSetParameter(value, operation, reader);
break;
case LOCAL_RECEIVER_PASS_BY_VALUE:
RemotingProfileResourceDefinition.LOCAL_RECEIVER_PASS_BY_VALUE.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (profileName == null) {
throw missingRequired(reader, Collections.singleton(EJB3SubsystemXMLAttribute.NAME.getLocalName()));
}
final PathAddress address = SUBSYSTEM_PATH.append(EJB3SubsystemModel.REMOTING_PROFILE, profileName);
operation.get(OP_ADDR).set(address.toModelNode());
operations.add(operation);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (EJB3SubsystemXMLElement.forName(reader.getLocalName())) {
case STATIC_EJB_DISCOVERY:
final ModelNode staticEjb = parseStaticEjbDiscoveryType(reader);
operation.get(StaticEJBDiscoveryDefinition.STATIC_EJB_DISCOVERY).set(staticEjb);
break;
case REMOTING_EJB_RECEIVER: {
parseRemotingReceiver(reader, address, operations);
break;
}
case REMOTE_HTTP_CONNECTION:
parseRemoteHttpConnection(reader, address, operations);
break;
default: {
throw unexpectedElement(reader);
}
}
}
}
protected void parseRemoteHttpConnection(final XMLExtendedStreamReader reader, final PathAddress profileAddress,
final List<ModelNode> operations) throws XMLStreamException {
final ModelNode operation = Util.createAddOperation();
String name = null;
final Set<EJB3SubsystemXMLAttribute> required = EnumSet.of(EJB3SubsystemXMLAttribute.URI);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
final EJB3SubsystemXMLAttribute attribute = EJB3SubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME:
name = value;
break;
case URI:
RemoteHttpConnectionDefinition.URI.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
final PathAddress receiverAddress = profileAddress.append(EJB3SubsystemModel.REMOTE_HTTP_CONNECTION, name);
operation.get(OP_ADDR).set(receiverAddress.toModelNode());
operations.add(operation);
while (reader.hasNext() && reader.nextTag() != XMLStreamConstants.END_ELEMENT) {
switch (EJB3SubsystemXMLElement.forName(reader.getLocalName())) {
case CHANNEL_CREATION_OPTIONS:
parseChannelCreationOptions(reader, receiverAddress, operations);
break;
default:
throw unexpectedElement(reader);
}
}
}
}
| 9,835 | 44.327189 | 160 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/EJB3AsyncServiceAdd.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.ejb3.subsystem;
import static org.jboss.as.ejb3.logging.EjbLogger.ROOT_LOGGER;
import org.jboss.as.controller.AbstractBoottimeAddStepHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.ejb3.deployment.processors.merging.AsynchronousMergingProcessor;
import org.jboss.as.server.AbstractDeploymentChainStep;
import org.jboss.as.server.DeploymentProcessorTarget;
import org.jboss.as.server.deployment.Phase;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceName;
import java.util.concurrent.Executor;
/**
* A {@link org.jboss.as.controller.AbstractBoottimeAddStepHandler} to handle the add operation for the Jakarta Enterprise Beans
* remote service, in the Jakarta Enterprise Beans subsystem
* <p/>
*
* @author Stuart Douglas
*/
public class EJB3AsyncServiceAdd extends AbstractBoottimeAddStepHandler {
EJB3AsyncServiceAdd(AttributeDefinition... attributes) {
super(attributes);
}
@Override
protected void performBoottime(final OperationContext context, final ModelNode operation, final ModelNode model) throws OperationFailedException {
final String threadPoolName = EJB3AsyncResourceDefinition.THREAD_POOL_NAME.resolveModelAttribute(context, model).asString();
final ServiceName threadPoolServiceName = context.getCapabilityServiceName(EJB3AsyncResourceDefinition.THREAD_POOL_CAPABILITY_NAME, threadPoolName, Executor.class);
context.addStep(new AbstractDeploymentChainStep() {
protected void execute(DeploymentProcessorTarget processorTarget) {
ROOT_LOGGER.debug("Adding Jakarta Enterprise Beans @Asynchronous support");
processorTarget.addDeploymentProcessor(EJB3Extension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_EJB_ASYNCHRONOUS_MERGE, new AsynchronousMergingProcessor(threadPoolServiceName));
}
}, OperationContext.Stage.RUNTIME);
}
}
| 3,081 | 45 | 203 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/TimerServiceAdd.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.ejb3.subsystem;
import static org.jboss.as.ejb3.logging.EjbLogger.ROOT_LOGGER;
import java.util.Timer;
import org.jboss.as.controller.AbstractBoottimeAddStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.ejb3.deployment.processors.AroundTimeoutAnnotationParsingProcessor;
import org.jboss.as.ejb3.deployment.processors.TimerServiceDeploymentProcessor;
import org.jboss.as.ejb3.deployment.processors.annotation.TimerServiceAnnotationProcessor;
import org.jboss.as.ejb3.deployment.processors.merging.TimerMethodMergingProcessor;
import org.jboss.as.ejb3.timerservice.TimerServiceMetaData;
import org.jboss.as.server.AbstractDeploymentChainStep;
import org.jboss.as.server.DeploymentProcessorTarget;
import org.jboss.as.server.deployment.Phase;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* Adds the timer service
*
* @author Stuart Douglas
*/
public class TimerServiceAdd extends AbstractBoottimeAddStepHandler {
public static final TimerServiceAdd INSTANCE = new TimerServiceAdd();
private TimerServiceAdd() {
super(TimerServiceResourceDefinition.ATTRIBUTES);
}
@Override
protected void performBoottime(final OperationContext context, ModelNode operation, final ModelNode model) throws OperationFailedException {
final String threadPoolName = TimerServiceResourceDefinition.THREAD_POOL_NAME.resolveModelAttribute(context, model).asStringOrNull();
TimerServiceMetaData defaultMetaData = new TimerServiceMetaData();
defaultMetaData.setDataStoreName(TimerServiceResourceDefinition.DEFAULT_DATA_STORE.resolveModelAttribute(context, model).asStringOrNull());
defaultMetaData.setPersistentTimerManagementProvider(TimerServiceResourceDefinition.DEFAULT_PERSISTENT_TIMER_MANAGEMENT.resolveModelAttribute(context, model).asStringOrNull());
defaultMetaData.setTransientTimerManagementProvider(TimerServiceResourceDefinition.DEFAULT_TRANSIENT_TIMER_MANAGEMENT.resolveModelAttribute(context, model).asStringOrNull());
context.addStep(new AbstractDeploymentChainStep() {
@Override
protected void execute(DeploymentProcessorTarget processorTarget) {
ROOT_LOGGER.debug("Configuring timers");
//we only add the timer service DUP's when the timer service in enabled in XML
processorTarget.addDeploymentProcessor(EJB3Extension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_TIMEOUT_ANNOTATION, new TimerServiceAnnotationProcessor());
processorTarget.addDeploymentProcessor(EJB3Extension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_AROUNDTIMEOUT_ANNOTATION, new AroundTimeoutAnnotationParsingProcessor());
processorTarget.addDeploymentProcessor(EJB3Extension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_EJB_TIMER_METADATA_MERGE, new TimerMethodMergingProcessor());
processorTarget.addDeploymentProcessor(EJB3Extension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_EJB_TIMER_SERVICE, new TimerServiceDeploymentProcessor(threadPoolName, defaultMetaData));
}
}, OperationContext.Stage.RUNTIME);
if (threadPoolName != null) {
context.getCapabilityServiceTarget().addCapability(TimerServiceResourceDefinition.TIMER_SERVICE_CAPABILITY).setInstance(new TimerValueService()).install();
}
}
private static final class TimerValueService implements Service<Timer> {
private Timer timer;
@Override
public synchronized void start(final StartContext context) throws StartException {
timer = new Timer();
}
@Override
public synchronized void stop(final StopContext context) {
timer.cancel();
timer = null;
}
@Override
public synchronized Timer getValue() throws IllegalStateException, IllegalArgumentException {
return timer;
}
}
}
| 5,201 | 47.616822 | 211 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/SimpleStatefulSessionBeanCacheProviderResourceDefinition.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2022, 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.ejb3.subsystem;
import java.util.function.UnaryOperator;
import org.jboss.as.ejb3.component.stateful.cache.simple.SimpleStatefulSessionBeanCacheProviderServiceConfigurator;
/**
* Defines a CacheFactoryBuilder instance which, during deployment, is used to configure, build and install a CacheFactory for the SFSB being deployed.
* The CacheFactory resource instances defined here produce bean caches which are non distributed and do not have passivation-enabled.
*
* @author Paul Ferraro
* @author Richard Achmatowicz
*/
public class SimpleStatefulSessionBeanCacheProviderResourceDefinition extends StatefulSessionBeanCacheProviderResourceDefinition {
public SimpleStatefulSessionBeanCacheProviderResourceDefinition() {
super(EJB3SubsystemModel.SIMPLE_CACHE_PATH, UnaryOperator.identity(), SimpleStatefulSessionBeanCacheProviderServiceConfigurator::new);
}
}
| 1,928 | 46.04878 | 151 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/EJBClientConfiguratorService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ejb3.subsystem;
import java.util.function.Consumer;
import org.jboss.ejb.client.EJBClientContext;
import org.jboss.ejb.client.EJBTransportProvider;
import org.jboss.ejb.protocol.remote.RemoteTransportProvider;
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.jboss.remoting3.Endpoint;
import org.wildfly.httpclient.ejb.HttpClientProvider;
/**
* A service to configure an {@code EJBClientContext} with any information defined in the subsystem model.
*
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
public final class EJBClientConfiguratorService implements Consumer<EJBClientContext.Builder>, Service<EJBClientConfiguratorService> {
public static final ServiceName SERVICE_NAME = ServiceName.JBOSS.append("ejb", "client", "configurator");
private final InjectedValue<Endpoint> endpointInjector = new InjectedValue<>();
private volatile EJBTransportProvider remoteTransportProvider;
private volatile EJBTransportProvider remoteHttpTransportProvider;
public void start(final StartContext context) throws StartException {
remoteTransportProvider = new RemoteTransportProvider();
remoteHttpTransportProvider = new HttpClientProvider();
}
public void stop(final StopContext context) {
remoteTransportProvider = null;
remoteHttpTransportProvider = null;
}
public EJBClientConfiguratorService getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
/**
* Perform the configuration of the transport provider.
*
* @param builder the EJB client context builder (not {@code null})
*/
public void accept(final EJBClientContext.Builder builder) {
final EJBTransportProvider remoteTransportProvider = this.remoteTransportProvider;
if (remoteTransportProvider != null) {
builder.addTransportProvider(remoteTransportProvider);
builder.addTransportProvider(remoteHttpTransportProvider);
}
}
/**
* Get the endpoint injector. This is populated only when the Remoting subsystem is present.
*
* @return the endpoint injector
*/
public InjectedValue<Endpoint> getEndpointInjector() {
return endpointInjector;
}
}
| 3,518 | 38.539326 | 134 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/EJB3Subsystem90Parser.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.ejb3.subsystem;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequired;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoContent;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoNamespaceAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute;
import static org.jboss.as.ejb3.subsystem.EJB3SubsystemModel.APPLICATION_SECURITY_DOMAIN;
import java.util.Collections;
import java.util.List;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* Parser for ejb3:9.0 namespace.
*/
public class EJB3Subsystem90Parser extends EJB3Subsystem80Parser {
EJB3Subsystem90Parser() {
}
@Override
protected EJB3SubsystemNamespace getExpectedNamespace() {
return EJB3SubsystemNamespace.EJB3_9_0;
}
@Override
protected void parseApplicationSecurityDomain(final XMLExtendedStreamReader reader, final List<ModelNode> operations) throws XMLStreamException {
String applicationSecurityDomain = null;
ModelNode operation = Util.createAddOperation();
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String attributeValue = reader.getAttributeValue(i);
final EJB3SubsystemXMLAttribute attribute = EJB3SubsystemXMLAttribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NAME:
applicationSecurityDomain = attributeValue;
break;
case SECURITY_DOMAIN:
ApplicationSecurityDomainDefinition.SECURITY_DOMAIN.parseAndSetParameter(attributeValue, operation, reader);
break;
case ENABLE_JACC:
ApplicationSecurityDomainDefinition.ENABLE_JACC.parseAndSetParameter(attributeValue, operation, reader);
break;
case LEGACY_COMPLIANT_PRINCIPAL_PROPAGATION:
ApplicationSecurityDomainDefinition.LEGACY_COMPLIANT_PRINCIPAL_PROPAGATION.parseAndSetParameter(attributeValue, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (applicationSecurityDomain == null) {
throw missingRequired(reader, Collections.singleton(EJB3SubsystemXMLAttribute.NAME.getLocalName()));
}
requireNoContent(reader);
final PathAddress address = this.getEJB3SubsystemAddress().append(PathElement.pathElement(APPLICATION_SECURITY_DOMAIN, applicationSecurityDomain));
operation.get(OP_ADDR).set(address.toModelNode());
operations.add(operation);
}
}
| 4,112 | 44.7 | 155 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/deployment/TimerResourceDefinition.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.ejb3.subsystem.deployment;
import java.io.Serializable;
import java.util.Date;
import jakarta.ejb.NoMoreTimeoutsException;
import jakarta.ejb.NoSuchObjectLocalException;
import jakarta.ejb.ScheduleExpression;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.ObjectListAttributeDefinition;
import org.jboss.as.controller.ObjectTypeAttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationDefinition;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleOperationDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.descriptions.ResourceDescriptionResolver;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.OperationEntry;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.subsystem.EJB3Extension;
import org.jboss.as.ejb3.subsystem.EJB3SubsystemModel;
import org.jboss.as.ejb3.timerservice.spi.ManagedTimer;
import org.jboss.as.ejb3.timerservice.spi.ManagedTimerService;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
/**
* {@link org.jboss.as.controller.ResourceDefinition} for the timer resource for runtime Jakarta Enterprise Beans deployment. This definition declares operations and
* attributes of single timer.
*
* @author baranowb
*/
public class TimerResourceDefinition<T extends EJBComponent> extends SimpleResourceDefinition {
private static final ResourceDescriptionResolver RESOURCE_DESCRIPTION_RESOLVER = EJB3Extension
.getResourceDescriptionResolver(EJB3SubsystemModel.TIMER);
// attributes, copy of TimerAttributeDefinition
private static final SimpleAttributeDefinition TIME_REMAINING = new SimpleAttributeDefinitionBuilder("time-remaining",
ModelType.LONG, true).setStorageRuntime().build();
private static final SimpleAttributeDefinition NEXT_TIMEOUT = new SimpleAttributeDefinitionBuilder("next-timeout",
ModelType.LONG, true).setStorageRuntime().build();
private static final SimpleAttributeDefinition CALENDAR_TIMER = new SimpleAttributeDefinitionBuilder("calendar-timer",
ModelType.BOOLEAN, true).setStorageRuntime().build();
private static final SimpleAttributeDefinition PERSISTENT = new SimpleAttributeDefinitionBuilder("persistent",
ModelType.BOOLEAN, true).setStorageRuntime().build();
private static final SimpleAttributeDefinition ACTIVE = new SimpleAttributeDefinitionBuilder("active", ModelType.BOOLEAN,
true).setStorageRuntime().build();
// schedule and its children
static final SimpleAttributeDefinition DAY_OF_MONTH = new SimpleAttributeDefinitionBuilder("day-of-month",
ModelType.STRING, true).setStorageRuntime().build();
static final SimpleAttributeDefinition DAY_OF_WEEK = new SimpleAttributeDefinitionBuilder("day-of-week",
ModelType.STRING, true).setStorageRuntime().build();
static final SimpleAttributeDefinition HOUR = new SimpleAttributeDefinitionBuilder("hour", ModelType.STRING, true)
.setStorageRuntime().build();
static final SimpleAttributeDefinition MINUTE = new SimpleAttributeDefinitionBuilder("minute", ModelType.STRING,
true).setStorageRuntime().build();
static final SimpleAttributeDefinition SECOND = new SimpleAttributeDefinitionBuilder("second", ModelType.STRING,
true).setStorageRuntime().build();
static final SimpleAttributeDefinition MONTH = new SimpleAttributeDefinitionBuilder("month", ModelType.STRING, true)
.setStorageRuntime().build();
static final SimpleAttributeDefinition YEAR = new SimpleAttributeDefinitionBuilder("year", ModelType.STRING, true)
.setStorageRuntime().build();
static final SimpleAttributeDefinition TIMEZONE = new SimpleAttributeDefinitionBuilder("timezone",
ModelType.STRING, true).setStorageRuntime().build();
static final SimpleAttributeDefinition START = new SimpleAttributeDefinitionBuilder("start", ModelType.LONG, true)
.setStorageRuntime().build();
static final SimpleAttributeDefinition END = new SimpleAttributeDefinitionBuilder("end", ModelType.LONG, true)
.setStorageRuntime().build();
public static final ObjectListAttributeDefinition SCHEDULE = ObjectListAttributeDefinition.Builder.of(
"schedule",
ObjectTypeAttributeDefinition.Builder.of("schedule", YEAR, MONTH, DAY_OF_MONTH, DAY_OF_WEEK, HOUR, MINUTE, SECOND,
TIMEZONE, START, END).build()).build();
// TimerConfig.info
private static final SimpleAttributeDefinition INFO = new SimpleAttributeDefinitionBuilder("info", ModelType.STRING, true)
.setStorageRuntime().build();
@Deprecated
private static final SimpleAttributeDefinition PRIMARY_KEY = new SimpleAttributeDefinitionBuilder("primary-key",
ModelType.STRING, true).setStorageRuntime().setDeprecated(ModelVersion.create(9)).build();
// operations
private static final OperationDefinition SUSPEND = new SimpleOperationDefinitionBuilder("suspend",
RESOURCE_DESCRIPTION_RESOLVER).setRuntimeOnly().build();
private static final OperationDefinition ACTIVATE = new SimpleOperationDefinitionBuilder("activate",
RESOURCE_DESCRIPTION_RESOLVER).setRuntimeOnly().build();
private static final OperationDefinition CANCEL = new SimpleOperationDefinitionBuilder("cancel",
RESOURCE_DESCRIPTION_RESOLVER).setRuntimeOnly().build();
private static final OperationDefinition TRIGGER = new SimpleOperationDefinitionBuilder("trigger",
RESOURCE_DESCRIPTION_RESOLVER).setRuntimeOnly().build();
private final AbstractEJBComponentRuntimeHandler<T> parentHandler;
TimerResourceDefinition(AbstractEJBComponentRuntimeHandler<T> parentHandler) {
super(new SimpleResourceDefinition.Parameters(EJB3SubsystemModel.TIMER_PATH, RESOURCE_DESCRIPTION_RESOLVER)
.setRemoveRestartLevel(OperationEntry.Flag.RESTART_RESOURCE_SERVICES));
this.parentHandler = parentHandler;
}
@Override
public void registerChildren(ManagementResourceRegistration resourceRegistration) {
super.registerChildren(resourceRegistration);
}
@Override
public void registerOperations(ManagementResourceRegistration resourceRegistration) {
super.registerOperations(resourceRegistration);
resourceRegistration.registerOperationHandler(SUSPEND, new AbstractTimerHandler() {
@Override
void executeRuntime(OperationContext context, ModelNode operation) throws OperationFailedException {
final ManagedTimer timer = getTimer(context, operation, true);
timer.suspend();
context.completeStep(new OperationContext.RollbackHandler() {
@Override
public void handleRollback(OperationContext context, ModelNode operation) {
timer.activate();
}
});
}
});
resourceRegistration.registerOperationHandler(ACTIVATE, new AbstractTimerHandler() {
@Override
void executeRuntime(OperationContext context, ModelNode operation) throws OperationFailedException {
final ManagedTimer timer = getTimer(context, operation, true);
if (!timer.isActive()) {
timer.activate();
context.completeStep(new OperationContext.RollbackHandler() {
@Override
public void handleRollback(OperationContext context, ModelNode operation) {
timer.suspend();
}
});
} else {
throw EjbLogger.ROOT_LOGGER.timerIsActive(timer);
}
}
});
resourceRegistration.registerOperationHandler(CANCEL, new AbstractTimerHandler() {
@Override
void executeRuntime(OperationContext context, ModelNode operation) throws OperationFailedException {
final ManagedTimer timer = getTimer(context, operation, true);
// this is TX aware
timer.cancel();
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
});
resourceRegistration.registerOperationHandler(TRIGGER, new AbstractTimerHandler() {
@Override
void executeRuntime(OperationContext context, ModelNode operation) throws OperationFailedException {
// This will invoke timer in 'management-handler-thread'
final ManagedTimer timer = getTimer(context, operation, true);
try {
timer.invoke();
} catch (Exception e) {
throw EjbLogger.ROOT_LOGGER.timerInvocationFailed(e);
}
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
});
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerReadOnlyAttribute(TIME_REMAINING, new AbstractReadAttributeHandler() {
@Override
protected void readAttribute(ManagedTimer timer, ModelNode toSet) {
if (timer.isCanceled()) {
return;
}
try {
final long time = timer.getTimeRemaining();
toSet.set(time);
} catch (NoMoreTimeoutsException nmte) {
// leave undefined
// the same will occur for next-timeout attribute, but let's log it only once
if (EjbLogger.ROOT_LOGGER.isDebugEnabled())
EjbLogger.ROOT_LOGGER.debug("No more timeouts for timer " + timer);
} catch (NoSuchObjectLocalException e) {
// Ignore
}
}
});
resourceRegistration.registerReadOnlyAttribute(NEXT_TIMEOUT, new AbstractReadAttributeHandler() {
@Override
protected void readAttribute(ManagedTimer timer, ModelNode toSet) {
if (timer.isCanceled()) {
return;
}
try {
final Date d = timer.getNextTimeout();
if (d != null) {
toSet.set(d.getTime());
}
} catch (NoMoreTimeoutsException ignored) {
// leave undefined
} catch (NoSuchObjectLocalException e) {
// Ignore
}
}
});
resourceRegistration.registerReadOnlyAttribute(CALENDAR_TIMER, new AbstractReadAttributeHandler() {
@Override
protected void readAttribute(ManagedTimer timer, ModelNode toSet) {
if (timer.isCanceled()) {
return;
}
try {
final boolean calendarTimer = timer.isCalendarTimer();
toSet.set(calendarTimer);
} catch (NoSuchObjectLocalException e) {
// Ignore
}
}
});
resourceRegistration.registerReadOnlyAttribute(PERSISTENT, new AbstractReadAttributeHandler() {
@Override
protected void readAttribute(ManagedTimer timer, ModelNode toSet) {
if (timer.isCanceled()) {
return;
}
try {
final boolean persistent = timer.isPersistent();
toSet.set(persistent);
} catch (NoSuchObjectLocalException e) {
// Ignore
}
}
});
resourceRegistration.registerReadOnlyAttribute(ACTIVE, new AbstractReadAttributeHandler() {
@Override
protected void readAttribute(ManagedTimer timer, ModelNode toSet) {
final boolean active = timer.isActive();
toSet.set(active);
}
});
resourceRegistration.registerReadOnlyAttribute(SCHEDULE, new AbstractReadAttributeHandler() {
@Override
protected void readAttribute(ManagedTimer timer, ModelNode toSet) {
if (timer.isCanceled() || !timer.isCalendarTimer()) {
return;
}
try {
ScheduleExpression sched = timer.getSchedule();
addString(toSet, sched.getYear(), YEAR.getName());
addString(toSet, sched.getMonth(), MONTH.getName());
addString(toSet, sched.getDayOfMonth(), DAY_OF_MONTH.getName());
addString(toSet, sched.getDayOfWeek(), DAY_OF_WEEK.getName());
addString(toSet, sched.getHour(), HOUR.getName());
addString(toSet, sched.getMinute(), MINUTE.getName());
addString(toSet, sched.getSecond(), SECOND.getName());
addString(toSet, sched.getTimezone(), TIMEZONE.getName());
addDate(toSet, sched.getStart(), START.getName());
addDate(toSet, sched.getEnd(), END.getName());
} catch (NoSuchObjectLocalException e) {
// Ignore
}
}
private void addString(ModelNode schedNode, String value, String name) {
final ModelNode node = schedNode.get(name);
if (value != null) {
node.set(value);
}
}
private void addDate(ModelNode schedNode, Date value, String name) {
final ModelNode node = schedNode.get(name);
if (value != null) {
node.set(value.getTime());
}
}
});
resourceRegistration.registerReadOnlyAttribute(PRIMARY_KEY, new AbstractReadAttributeHandler() {
@Override
protected void readAttribute(ManagedTimer timer, ModelNode toSet) {
}
});
resourceRegistration.registerReadOnlyAttribute(INFO, new AbstractReadAttributeHandler() {
@Override
protected void readAttribute(ManagedTimer timer, ModelNode toSet) {
if (timer.isCanceled()) {
return;
}
try {
final Serializable info = timer.getInfo();
if (info != null) {
toSet.set(info.toString());
}
} catch (NoSuchObjectLocalException e) {
// Ignore
}
}
});
}
abstract class AbstractTimerHandler implements OperationStepHandler {
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
if (context.isNormalServer()) {
context.addStep(new OperationStepHandler() {
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
executeRuntime(context, operation);
}
}, OperationContext.Stage.RUNTIME);
}
}
protected ManagedTimer getTimer(final OperationContext context, final ModelNode operation) throws OperationFailedException {
return getTimer(context, operation, false);
}
protected ManagedTimer getTimer(final OperationContext context, final ModelNode operation, final boolean notNull) throws OperationFailedException {
final T ejbcomponent = parentHandler.getComponent(context, operation);
final ManagedTimerService timerService = ejbcomponent.getTimerService();
final PathAddress address = PathAddress.pathAddress(operation.require(ModelDescriptionConstants.OP_ADDR));
final String timerId = address.getLastElement().getValue();
ManagedTimer timer = timerService.findTimer(timerId);
if (timer == null && notNull) {
throw EjbLogger.ROOT_LOGGER.timerNotFound(timerId);
}
return timer;
}
abstract void executeRuntime(OperationContext context, ModelNode operation) throws OperationFailedException;
}
abstract class AbstractReadAttributeHandler extends AbstractTimerHandler {
@Override
void executeRuntime(final OperationContext context, final ModelNode operation) throws OperationFailedException {
final String opName = operation.require(ModelDescriptionConstants.OP).asString();
if (!opName.equals(ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION)) {
throw EjbLogger.ROOT_LOGGER.unknownOperations(opName);
}
final ManagedTimer timer = getTimer(context, operation);
if (timer != null) {
//the timer can expire at any point, so protect against an NPE
readAttribute(timer, context.getResult());
}
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
protected abstract void readAttribute(final ManagedTimer timer, final ModelNode toSet);
}
}
| 19,091 | 44.134752 | 165 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/deployment/AbstractEJBComponentResourceDefinition.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.ejb3.subsystem.deployment;
import java.util.Map;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.ObjectMapAttributeDefinition;
import org.jboss.as.controller.ObjectTypeAttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.StringListAttributeDefinition;
import org.jboss.as.controller.operations.validation.StringLengthValidator;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.as.ejb3.component.invocationmetrics.InvocationMetrics;
import org.jboss.as.ejb3.component.stateful.StatefulSessionComponent;
import org.jboss.as.ejb3.component.stateful.StatefulSessionComponentInstance;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanCache;
import org.jboss.as.ejb3.subsystem.EJB3Extension;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.ejb.client.SessionID;
/**
* Base class for {@link org.jboss.as.controller.ResourceDefinition}s describing runtime {@link EJBComponent}s.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public abstract class AbstractEJBComponentResourceDefinition extends SimpleResourceDefinition {
static final SimpleAttributeDefinition COMPONENT_CLASS_NAME = new SimpleAttributeDefinitionBuilder("component-class-name", ModelType.STRING)
.setValidator(new StringLengthValidator(1))
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
static final StringListAttributeDefinition JNDI_NAMES = StringListAttributeDefinition.Builder.of("jndi-names")
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
static final StringListAttributeDefinition BUSINESS_LOCAL = StringListAttributeDefinition.Builder.of("business-local")
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
static final StringListAttributeDefinition BUSINESS_REMOTE = StringListAttributeDefinition.Builder.of("business-remote")
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
static final SimpleAttributeDefinition TIMEOUT_METHOD = new SimpleAttributeDefinitionBuilder("timeout-method", ModelType.STRING)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
static final StringListAttributeDefinition ASYNC_METHODS = StringListAttributeDefinition.Builder.of("async-methods")
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
static final SimpleAttributeDefinition TRANSACTION_TYPE = new SimpleAttributeDefinitionBuilder("transaction-type", ModelType.STRING)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
private static final AttributeDefinition EXECUTION_TIME = new SimpleAttributeDefinitionBuilder("execution-time", ModelType.LONG)
.setUndefinedMetricValue(ModelNode.ZERO)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME, AttributeAccess.Flag.COUNTER_METRIC)
.build();
private static final AttributeDefinition INVOCATIONS = new SimpleAttributeDefinitionBuilder("invocations", ModelType.LONG)
.setUndefinedMetricValue(ModelNode.ZERO)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME, AttributeAccess.Flag.COUNTER_METRIC)
.build();
private static final AttributeDefinition PEAK_CONCURRENT_INVOCATIONS = new SimpleAttributeDefinitionBuilder("peak-concurrent-invocations", ModelType.LONG)
.setUndefinedMetricValue(ModelNode.ZERO)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
public static final SimpleAttributeDefinition SECURITY_DOMAIN = new SimpleAttributeDefinitionBuilder("security-domain", ModelType.STRING, true)
.setValidator(new StringLengthValidator(1, true))
.build();
private static final AttributeDefinition WAIT_TIME = new SimpleAttributeDefinitionBuilder("wait-time", ModelType.LONG)
.setUndefinedMetricValue(ModelNode.ZERO)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME, AttributeAccess.Flag.COUNTER_METRIC)
.build();
private static final AttributeDefinition METHODS = ObjectMapAttributeDefinition.Builder.of(
"methods",
ObjectTypeAttributeDefinition.Builder.of("complex", EXECUTION_TIME, INVOCATIONS, WAIT_TIME)
.build())
.setRequired(false)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
public static final SimpleAttributeDefinition RUN_AS_ROLE = new SimpleAttributeDefinitionBuilder("run-as-role", ModelType.STRING, true)
.setValidator(new StringLengthValidator(1, true))
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
public static final StringListAttributeDefinition DECLARED_ROLES = StringListAttributeDefinition.Builder.of("declared-roles")
.setRequired(false)
.setElementValidator(new StringLengthValidator(1))
.setStorageRuntime()
.build();
private static final AttributeDefinition CACHE_SIZE = new SimpleAttributeDefinitionBuilder("cache-size", ModelType.LONG)
.setUndefinedMetricValue(ModelNode.ZERO)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
private static final AttributeDefinition PASSIVATED_SIZE = new SimpleAttributeDefinitionBuilder("passivated-count",
ModelType.LONG)
.setUndefinedMetricValue(ModelNode.ZERO)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
private static final AttributeDefinition TOTAL_SIZE = new SimpleAttributeDefinitionBuilder("total-size", ModelType.LONG)
.setUndefinedMetricValue(ModelNode.ZERO)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
// Pool attributes
public static final SimpleAttributeDefinition POOL_AVAILABLE_COUNT = new SimpleAttributeDefinitionBuilder("pool-available-count", ModelType.INT, false)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
public static final SimpleAttributeDefinition POOL_CREATE_COUNT = new SimpleAttributeDefinitionBuilder("pool-create-count", ModelType.INT, false)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME, AttributeAccess.Flag.COUNTER_METRIC).build();
public static final SimpleAttributeDefinition POOL_CURRENT_SIZE = new SimpleAttributeDefinitionBuilder("pool-current-size", ModelType.INT, false)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME).build();
public static final SimpleAttributeDefinition POOL_NAME = new SimpleAttributeDefinitionBuilder("pool-name", ModelType.STRING, true)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME).build();
public static final SimpleAttributeDefinition POOL_REMOVE_COUNT = new SimpleAttributeDefinitionBuilder("pool-remove-count", ModelType.INT, false)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME, AttributeAccess.Flag.COUNTER_METRIC).build();
public static final SimpleAttributeDefinition POOL_MAX_SIZE = new SimpleAttributeDefinitionBuilder("pool-max-size", ModelType.INT, false)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME).build();
final EJBComponentType componentType;
public AbstractEJBComponentResourceDefinition(final EJBComponentType componentType) {
super(PathElement.pathElement(componentType.getResourceType()),
EJB3Extension.getResourceDescriptionResolver(componentType.getResourceType()));
this.componentType = componentType;
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
final AbstractEJBComponentRuntimeHandler<?> handler = componentType.getRuntimeHandler();
resourceRegistration.registerReadOnlyAttribute(COMPONENT_CLASS_NAME, handler);
resourceRegistration.registerReadOnlyAttribute(SECURITY_DOMAIN, handler);
resourceRegistration.registerReadOnlyAttribute(RUN_AS_ROLE, handler);
resourceRegistration.registerReadOnlyAttribute(DECLARED_ROLES, handler);
resourceRegistration.registerReadOnlyAttribute(TRANSACTION_TYPE, handler);
if (!componentType.equals(EJBComponentType.MESSAGE_DRIVEN)) {
resourceRegistration.registerReadOnlyAttribute(JNDI_NAMES, handler);
resourceRegistration.registerReadOnlyAttribute(BUSINESS_LOCAL, handler);
resourceRegistration.registerReadOnlyAttribute(BUSINESS_REMOTE, handler);
resourceRegistration.registerReadOnlyAttribute(ASYNC_METHODS, handler);
}
if (componentType.hasTimer()) {
resourceRegistration.registerReadOnlyAttribute(TimerAttributeDefinition.INSTANCE, handler);
resourceRegistration.registerReadOnlyAttribute(TIMEOUT_METHOD, handler);
}
if (componentType.hasPool()) {
resourceRegistration.registerReadOnlyAttribute(POOL_AVAILABLE_COUNT, handler);
resourceRegistration.registerReadOnlyAttribute(POOL_CREATE_COUNT, handler);
resourceRegistration.registerReadOnlyAttribute(POOL_NAME, handler);
resourceRegistration.registerReadOnlyAttribute(POOL_REMOVE_COUNT, handler);
resourceRegistration.registerReadOnlyAttribute(POOL_CURRENT_SIZE, handler);
resourceRegistration.registerReadWriteAttribute(POOL_MAX_SIZE, handler, handler);
}
if (componentType.equals(EJBComponentType.STATEFUL)) {
resourceRegistration.registerMetric(CACHE_SIZE, new AbstractRuntimeMetricsHandler() {
@Override
protected void executeReadMetricStep(final OperationContext context, final ModelNode operation, final EJBComponent component) {
StatefulSessionBeanCache<SessionID, StatefulSessionComponentInstance> cache = ((StatefulSessionComponent) component).getCache();
context.getResult().set(cache.getActiveCount());
}
});
resourceRegistration.registerMetric(PASSIVATED_SIZE, new AbstractRuntimeMetricsHandler() {
@Override
protected void executeReadMetricStep(final OperationContext context, final ModelNode operation, final EJBComponent component) {
StatefulSessionBeanCache<SessionID, StatefulSessionComponentInstance> cache = ((StatefulSessionComponent) component).getCache();
context.getResult().set(cache.getPassiveCount());
}
});
resourceRegistration.registerMetric(TOTAL_SIZE, new AbstractRuntimeMetricsHandler() {
@Override
protected void executeReadMetricStep(final OperationContext context, final ModelNode operation, final EJBComponent component) {
StatefulSessionBeanCache<SessionID, StatefulSessionComponentInstance> cache = ((StatefulSessionComponent) component).getCache();
context.getResult().set(cache.getActiveCount() + cache.getPassiveCount());
}
});
}
resourceRegistration.registerMetric(EXECUTION_TIME, new AbstractRuntimeMetricsHandler() {
@Override
protected void executeReadMetricStep(final OperationContext context, final ModelNode operation, final EJBComponent component) {
context.getResult().set(component.getInvocationMetrics().getExecutionTime());
}
});
resourceRegistration.registerMetric(INVOCATIONS, new AbstractRuntimeMetricsHandler() {
@Override
protected void executeReadMetricStep(final OperationContext context, final ModelNode operation, final EJBComponent component) {
context.getResult().set(component.getInvocationMetrics().getInvocations());
}
});
resourceRegistration.registerMetric(PEAK_CONCURRENT_INVOCATIONS, new AbstractRuntimeMetricsHandler() {
@Override
protected void executeReadMetricStep(final OperationContext context, final ModelNode operation, final EJBComponent component) {
context.getResult().set(component.getInvocationMetrics().getPeakConcurrent());
}
});
resourceRegistration.registerMetric(WAIT_TIME, new AbstractRuntimeMetricsHandler() {
@Override
protected void executeReadMetricStep(final OperationContext context, final ModelNode operation, final EJBComponent component) {
context.getResult().set(component.getInvocationMetrics().getWaitTime());
}
});
resourceRegistration.registerMetric(METHODS, new AbstractRuntimeMetricsHandler() {
@Override
protected void executeReadMetricStep(final OperationContext context, final ModelNode operation, final EJBComponent component) {
context.getResult().setEmptyObject();
for (final Map.Entry<String, InvocationMetrics.Values> entry : component.getInvocationMetrics().getMethods().entrySet()) {
final InvocationMetrics.Values values = entry.getValue();
final ModelNode result = new ModelNode();
result.get("execution-time").set(values.getExecutionTime());
result.get("invocations").set(values.getInvocations());
result.get("wait-time").set(values.getWaitTime());
context.getResult().get(entry.getKey()).set(result);
}
}
});
}
/* (non-Javadoc)
* @see org.jboss.as.controller.SimpleResourceDefinition#registerChildren(org.jboss.as.controller.registry.ManagementResourceRegistration)
*/
@Override
public void registerChildren(ManagementResourceRegistration resourceRegistration) {
super.registerChildren(resourceRegistration);
if (componentType.hasTimer()) {
// /deployment=DU/**/subsystem=ejb3/*=EJBName/service=timer-service
final AbstractEJBComponentRuntimeHandler<?> handler = componentType.getRuntimeHandler();
resourceRegistration.registerSubModel(new TimerServiceResourceDefinition(handler));
}
}
}
| 15,683 | 55.826087 | 158 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/deployment/TimerAttributeDefinition.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.ejb3.subsystem.deployment;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DESCRIPTION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NILLABLE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.TYPE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.UNIT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE_TYPE;
import static org.jboss.as.ejb3.logging.EjbLogger.ROOT_LOGGER;
import java.io.Serializable;
import java.util.Date;
import java.util.Locale;
import java.util.ResourceBundle;
import jakarta.ejb.EJBException;
import jakarta.ejb.NoSuchObjectLocalException;
import jakarta.ejb.ScheduleExpression;
import jakarta.ejb.Timer;
import jakarta.ejb.TimerService;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.jboss.as.controller.ListAttributeDefinition;
import org.jboss.as.controller.ObjectListAttributeDefinition;
import org.jboss.as.controller.client.helpers.MeasurementUnit;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.descriptions.ResourceDescriptionResolver;
import org.jboss.as.controller.operations.validation.ModelTypeValidator;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.timerservice.TimerImpl;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
/**
* Attribute definition for the list of timers associated with an Jakarta Enterprise Beans.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
// TODO Convert to ObjectListAttributeDefinition
public class TimerAttributeDefinition extends ListAttributeDefinition {
public static final TimerAttributeDefinition INSTANCE = new TimerAttributeDefinition.Builder().build();
public static final String TIME_REMAINING = "time-remaining";
public static final String NEXT_TIMEOUT = "next-timeout";
public static final String CALENDAR_TIMER = "calendar-timer";
public static final String PERSISTENT = "persistent";
public static final String INFO = "info";
public static final String SCHEDULE = "schedule";
public static final String DAY_OF_MONTH = "day-of-month";
public static final String DAY_OF_WEEK = "day-of-week";
public static final String HOUR = "hour";
public static final String MINUTE = "minute";
public static final String SECOND = "second";
public static final String MONTH = "month";
public static final String YEAR = "year";
public static final String TIMEZONE = "timezone";
public static final String START = "start";
public static final String END = "end";
private TimerAttributeDefinition(Builder builder) {
super(builder);
}
public static final class Builder extends ListAttributeDefinition.Builder<ObjectListAttributeDefinition.Builder, TimerAttributeDefinition>{
public Builder() {
super("timers", false);
}
@Override
public TimerAttributeDefinition build() {
setValidator(new ModelTypeValidator(ModelType.OBJECT));
setStorageRuntime();
return new TimerAttributeDefinition(this);
}
}
@Override
protected void addValueTypeDescription(ModelNode node, ResourceBundle bundle) {
throw EjbLogger.ROOT_LOGGER.resourceBundleDescriptionsNotSupported(getName());
}
@Override
protected void addAttributeValueTypeDescription(ModelNode node, ResourceDescriptionResolver resolver, Locale locale, ResourceBundle bundle) {
addValueTypeDescription(node, resolver, locale, bundle);
}
@Override
protected void addOperationParameterValueTypeDescription(ModelNode node, String operationName, ResourceDescriptionResolver resolver, Locale locale, ResourceBundle bundle) {
addValueTypeDescription(node, resolver, locale, bundle);
}
@Override
public void marshallAsElement(ModelNode resourceModel, final boolean marshalDefault, XMLStreamWriter writer) throws XMLStreamException {
throw EjbLogger.ROOT_LOGGER.runtimeAttributeNotMarshallable(getName());
}
private void addValueTypeDescription(ModelNode node, ResourceDescriptionResolver resolver, Locale locale, ResourceBundle bundle) {
final ModelNode valueTypeNode = node.get(ModelDescriptionConstants.VALUE_TYPE);
addAttributeDescription(resolver, locale, bundle, valueTypeNode, ModelType.LONG, true, MeasurementUnit.MILLISECONDS, TIME_REMAINING);
addAttributeDescription(resolver, locale, bundle, valueTypeNode, ModelType.LONG, true, MeasurementUnit.EPOCH_MILLISECONDS, NEXT_TIMEOUT);
addAttributeDescription(resolver, locale, bundle, valueTypeNode, ModelType.BOOLEAN, true, null, CALENDAR_TIMER);
addAttributeDescription(resolver, locale, bundle, valueTypeNode, ModelType.BOOLEAN, true, null, PERSISTENT);
addAttributeDescription(resolver, locale, bundle, valueTypeNode, ModelType.STRING, true, null, INFO);
final ModelNode sched = addAttributeDescription(resolver, locale, bundle, valueTypeNode, ModelType.OBJECT, true, null, SCHEDULE);
final ModelNode schedValType = sched.get(VALUE_TYPE);
addAttributeDescription(resolver, locale, bundle, schedValType, ModelType.STRING, true, null, SCHEDULE, YEAR);
addAttributeDescription(resolver, locale, bundle, schedValType, ModelType.STRING, true, null, SCHEDULE, MONTH);
addAttributeDescription(resolver, locale, bundle, schedValType, ModelType.STRING, true, null, SCHEDULE, DAY_OF_MONTH);
addAttributeDescription(resolver, locale, bundle, schedValType, ModelType.STRING, true, null, SCHEDULE, DAY_OF_WEEK);
addAttributeDescription(resolver, locale, bundle, schedValType, ModelType.STRING, true, null, SCHEDULE, HOUR);
addAttributeDescription(resolver, locale, bundle, schedValType, ModelType.STRING, true, null, SCHEDULE, MINUTE);
addAttributeDescription(resolver, locale, bundle, schedValType, ModelType.STRING, true, null, SCHEDULE, SECOND);
addAttributeDescription(resolver, locale, bundle, schedValType, ModelType.STRING, true, null, SCHEDULE, TIMEZONE);
addAttributeDescription(resolver, locale, bundle, schedValType, ModelType.LONG, true, MeasurementUnit.EPOCH_MILLISECONDS, SCHEDULE, START);
addAttributeDescription(resolver, locale, bundle, schedValType, ModelType.LONG, true, MeasurementUnit.EPOCH_MILLISECONDS, SCHEDULE, END);
}
private ModelNode addAttributeDescription(final ResourceDescriptionResolver resolver, final Locale locale, final ResourceBundle bundle,
final ModelNode node, final ModelType type, final boolean nillable,
final MeasurementUnit measurementUnit, final String... suffixes) {
final ModelNode valNode = node.get(suffixes[suffixes.length -1]);
valNode.get(DESCRIPTION).set(resolver.getResourceAttributeValueTypeDescription(getName(), locale, bundle, suffixes));
valNode.get(TYPE).set(type);
valNode.get(NILLABLE).set(nillable);
if (measurementUnit != null) {
valNode.get(UNIT).set(measurementUnit.getName());
}
return valNode;
}
public static void addTimers(final EJBComponent ejb, final ModelNode response) {
response.setEmptyList();
final String name = ejb.getComponentName();
TimerService ts = ejb.getTimerService();
if (ts != null) {
for (Timer timer : ts.getTimers()) {
ModelNode timerNode = response.add();
addTimeRemaining(timer, timerNode, name);
addNextTimeout(timer, timerNode, name);
addCalendarTimer(timer, timerNode, name);
addPersistent(timer, timerNode, name);
addInfo(timer, timerNode, name);
addSchedule(timer, timerNode, name);
}
}
}
private static void addTimeRemaining(Timer timer, ModelNode timerNode, final String componentName) {
try {
final ModelNode detailNode = timerNode.get(TIME_REMAINING);
long time = timer.getTimeRemaining();
detailNode.set(time);
} catch (IllegalStateException e) {
// ignore
} catch (NoSuchObjectLocalException e) {
// ignore
} catch (EJBException e) {
logTimerFailure(componentName, e);
}
}
private static void addNextTimeout(Timer timer, ModelNode timerNode, final String componentName) {
try {
final ModelNode detailNode = timerNode.get(NEXT_TIMEOUT);
Date d = timer.getNextTimeout();
if (d != null) {
detailNode.set(d.getTime());
}
} catch (IllegalStateException e) {
// ignore
} catch (NoSuchObjectLocalException e) {
// ignore
} catch (EJBException e) {
logTimerFailure(componentName, e);
}
}
private static void addSchedule(Timer timer, ModelNode timerNode, final String componentName) {
try {
final ModelNode schedNode = timerNode.get(SCHEDULE);
ScheduleExpression sched = timer.getSchedule();
addScheduleDetailString(schedNode, sched.getYear(), YEAR);
addScheduleDetailString(schedNode, sched.getMonth(), MONTH);
addScheduleDetailString(schedNode, sched.getDayOfMonth(), DAY_OF_MONTH);
addScheduleDetailString(schedNode, sched.getDayOfWeek(), DAY_OF_WEEK);
addScheduleDetailString(schedNode, sched.getHour(), HOUR);
addScheduleDetailString(schedNode, sched.getMinute(), MINUTE);
addScheduleDetailString(schedNode, sched.getSecond(), SECOND);
addScheduleDetailString(schedNode, sched.getTimezone(), TIMEZONE);
addScheduleDetailDate(schedNode, sched.getStart(), START);
addScheduleDetailDate(schedNode, sched.getEnd(), END);
} catch (IllegalStateException e) {
// ignore
} catch (NoSuchObjectLocalException e) {
// ignore
} catch (EJBException e) {
logTimerFailure(componentName, e);
}
}
private static void addCalendarTimer(Timer timer, ModelNode timerNode, final String componentName) {
try {
final ModelNode detailNode = timerNode.get(CALENDAR_TIMER);
boolean b = timer.isCalendarTimer();
detailNode.set(b);
} catch (IllegalStateException e) {
// ignore
} catch (NoSuchObjectLocalException e) {
// ignore
} catch (EJBException e) {
logTimerFailure(componentName, e);
}
}
private static void addPersistent(Timer timer, ModelNode timerNode, final String componentName) {
try {
final ModelNode detailNode = timerNode.get(PERSISTENT);
boolean b = timer.isPersistent();
detailNode.set(b);
} catch (IllegalStateException e) {
// ignore
} catch (NoSuchObjectLocalException e) {
// ignore
} catch (EJBException e) {
logTimerFailure(componentName, e);
}
}
private static void addInfo(Timer timer, ModelNode timerNode, final String componentName) {
try {
final Serializable info = (timer instanceof TimerImpl) ? ((TimerImpl) timer).getCachedTimerInfo() : timer.getInfo();
if (info != null) {
final ModelNode detailNode = timerNode.get(INFO);
detailNode.set(info.toString());
}
} catch (IllegalStateException e) {
// ignore
} catch (NoSuchObjectLocalException e) {
// ignore
} catch (EJBException e) {
logTimerFailure(componentName, e);
}
}
private static void addScheduleDetailString(ModelNode schedNode, String value, String detailName) {
final ModelNode node = schedNode.get(detailName);
if (value != null) {
node.set(value);
}
}
private static void addScheduleDetailDate(ModelNode schedNode, Date value, String detailName) {
final ModelNode node = schedNode.get(detailName);
if (value != null) {
node.set(value.getTime());
}
}
private static void logTimerFailure(final String componentName, final EJBException e) {
ROOT_LOGGER.failToReadTimerInformation(componentName);
}
}
| 13,679 | 46.665505 | 176 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/deployment/StatefulSessionBeanDeploymentResourceDefinition.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.ejb3.subsystem.deployment;
import org.jboss.as.controller.ObjectListAttributeDefinition;
import org.jboss.as.controller.ObjectTypeAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelType;
/**
* {@link org.jboss.as.controller.ResourceDefinition} for a {@link org.jboss.as.ejb3.component.stateful.StatefulSessionComponent}.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class StatefulSessionBeanDeploymentResourceDefinition extends AbstractEJBComponentResourceDefinition {
static final SimpleAttributeDefinition STATEFUL_TIMEOUT = new SimpleAttributeDefinitionBuilder("stateful-timeout", ModelType.STRING)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
static final SimpleAttributeDefinition AFTER_BEGIN_METHOD = new SimpleAttributeDefinitionBuilder("after-begin-method", ModelType.STRING)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
static final SimpleAttributeDefinition BEFORE_COMPLETION_METHOD = new SimpleAttributeDefinitionBuilder("before-completion-method", ModelType.STRING)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
static final SimpleAttributeDefinition AFTER_COMPLETION_METHOD = new SimpleAttributeDefinitionBuilder("after-completion-method", ModelType.STRING)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
static final SimpleAttributeDefinition PASSIVATION_CAPABLE = new SimpleAttributeDefinitionBuilder("passivation-capable", ModelType.BOOLEAN)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
static final SimpleAttributeDefinition BEAN_METHOD = new SimpleAttributeDefinitionBuilder("bean-method", ModelType.STRING)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
static final SimpleAttributeDefinition RETAIN_IF_EXCEPTION = new SimpleAttributeDefinitionBuilder("retain-if-exception", ModelType.BOOLEAN)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
static final ObjectTypeAttributeDefinition REMOVE_METHOD = new ObjectTypeAttributeDefinition.Builder("remove-method", BEAN_METHOD, RETAIN_IF_EXCEPTION)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
static final ObjectListAttributeDefinition REMOVE_METHODS = new ObjectListAttributeDefinition.Builder("remove-methods", REMOVE_METHOD)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
public StatefulSessionBeanDeploymentResourceDefinition() {
super(EJBComponentType.STATEFUL);
}
@Override
public void registerAttributes(final ManagementResourceRegistration resourceRegistration) {
super.registerAttributes(resourceRegistration);
final AbstractEJBComponentRuntimeHandler<?> handler = componentType.getRuntimeHandler();
resourceRegistration.registerReadOnlyAttribute(STATEFUL_TIMEOUT, handler);
resourceRegistration.registerReadOnlyAttribute(AFTER_BEGIN_METHOD, handler);
resourceRegistration.registerReadOnlyAttribute(BEFORE_COMPLETION_METHOD, handler);
resourceRegistration.registerReadOnlyAttribute(AFTER_COMPLETION_METHOD, handler);
resourceRegistration.registerReadOnlyAttribute(PASSIVATION_CAPABLE, handler);
resourceRegistration.registerReadOnlyAttribute(REMOVE_METHODS, handler);
}
}
| 4,717 | 53.860465 | 155 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/deployment/InstalledComponent.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.ejb3.subsystem.deployment;
import org.jboss.as.controller.PathAddress;
/**
* utility class that tracks components registered with the management API
*
* @author Stuart Douglas
*/
public class InstalledComponent {
private final EJBComponentType type;
private final PathAddress address;
public InstalledComponent(final EJBComponentType type, final PathAddress address) {
this.type = type;
this.address = address;
}
public EJBComponentType getType() {
return type;
}
public PathAddress getAddress() {
return address;
}
}
| 1,636 | 32.408163 | 87 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/deployment/StatelessSessionBeanRuntimeHandler.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.ejb3.subsystem.deployment;
import org.jboss.as.ejb3.component.stateless.StatelessSessionComponent;
/**
* Handles operations that provide runtime management of a {@link StatelessSessionComponent}.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class StatelessSessionBeanRuntimeHandler extends AbstractEJBComponentRuntimeHandler<StatelessSessionComponent> {
public static final StatelessSessionBeanRuntimeHandler INSTANCE = new StatelessSessionBeanRuntimeHandler();
private StatelessSessionBeanRuntimeHandler() {
super(EJBComponentType.STATELESS, StatelessSessionComponent.class);
}
}
| 1,670 | 40.775 | 119 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/deployment/AbstractEJBComponentRuntimeHandler.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.ejb3.subsystem.deployment;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE;
import static org.jboss.as.ejb3.subsystem.deployment.AbstractEJBComponentResourceDefinition.ASYNC_METHODS;
import static org.jboss.as.ejb3.subsystem.deployment.AbstractEJBComponentResourceDefinition.BUSINESS_LOCAL;
import static org.jboss.as.ejb3.subsystem.deployment.AbstractEJBComponentResourceDefinition.BUSINESS_REMOTE;
import static org.jboss.as.ejb3.subsystem.deployment.AbstractEJBComponentResourceDefinition.COMPONENT_CLASS_NAME;
import static org.jboss.as.ejb3.subsystem.deployment.AbstractEJBComponentResourceDefinition.DECLARED_ROLES;
import static org.jboss.as.ejb3.subsystem.deployment.AbstractEJBComponentResourceDefinition.JNDI_NAMES;
import static org.jboss.as.ejb3.subsystem.deployment.AbstractEJBComponentResourceDefinition.POOL_AVAILABLE_COUNT;
import static org.jboss.as.ejb3.subsystem.deployment.AbstractEJBComponentResourceDefinition.POOL_CREATE_COUNT;
import static org.jboss.as.ejb3.subsystem.deployment.AbstractEJBComponentResourceDefinition.POOL_CURRENT_SIZE;
import static org.jboss.as.ejb3.subsystem.deployment.AbstractEJBComponentResourceDefinition.POOL_MAX_SIZE;
import static org.jboss.as.ejb3.subsystem.deployment.AbstractEJBComponentResourceDefinition.POOL_NAME;
import static org.jboss.as.ejb3.subsystem.deployment.AbstractEJBComponentResourceDefinition.POOL_REMOVE_COUNT;
import static org.jboss.as.ejb3.subsystem.deployment.AbstractEJBComponentResourceDefinition.RUN_AS_ROLE;
import static org.jboss.as.ejb3.subsystem.deployment.AbstractEJBComponentResourceDefinition.SECURITY_DOMAIN;
import static org.jboss.as.ejb3.subsystem.deployment.AbstractEJBComponentResourceDefinition.TIMEOUT_METHOD;
import static org.jboss.as.ejb3.subsystem.deployment.AbstractEJBComponentResourceDefinition.TRANSACTION_TYPE;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import jakarta.ejb.TransactionManagementType;
import org.jboss.as.controller.AbstractRuntimeOnlyHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.ee.component.ViewDescription;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.as.ejb3.component.EJBComponentDescription;
import org.jboss.as.ejb3.component.EJBViewDescription;
import org.jboss.as.ejb3.component.session.SessionBeanComponentDescription;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.pool.Pool;
import org.jboss.as.ejb3.security.EJBSecurityMetaData;
import org.jboss.dmr.ModelNode;
import org.jboss.invocation.proxy.MethodIdentifier;
import org.jboss.metadata.ejb.spec.MethodInterfaceType;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceRegistry;
/**
* Base class for operation handlers that provide runtime management for {@link EJBComponent}s.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public abstract class AbstractEJBComponentRuntimeHandler<T extends EJBComponent> extends AbstractRuntimeOnlyHandler {
private final Map<PathAddress, ServiceName> componentConfigs = Collections.synchronizedMap(new HashMap<PathAddress, ServiceName>());
private final Class<T> componentClass;
private final EJBComponentType componentType;
protected AbstractEJBComponentRuntimeHandler(final EJBComponentType componentType, final Class<T> componentClass) {
this.componentType = componentType;
this.componentClass = componentClass;
}
@Override
protected void executeRuntimeStep(OperationContext context, ModelNode operation) throws OperationFailedException {
String opName = operation.require(ModelDescriptionConstants.OP).asString();
boolean forWrite = isForWrite(opName);
PathAddress address = PathAddress.pathAddress(operation.require(ModelDescriptionConstants.OP_ADDR));
final ServiceName serviceName = getComponentConfiguration(context,address);
T component = getComponent(serviceName, address, context, forWrite);
if (ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION.equals(opName)) {
final String attributeName = operation.require(ModelDescriptionConstants.NAME).asString();
executeReadAttribute(attributeName, context, component, address);
} else if (ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION.equals(opName)) {
final String attributeName = operation.require(ModelDescriptionConstants.NAME).asString();
executeWriteAttribute(attributeName, context, operation, component, address);
} else {
executeAgainstComponent(context, operation, component, opName, address);
}
}
public void registerComponent(final PathAddress address, final ServiceName serviceName) {
componentConfigs.put(address, serviceName);
}
public void unregisterComponent(final PathAddress address) {
componentConfigs.remove(address);
}
protected void executeReadAttribute(final String attributeName, final OperationContext context, final T component, final PathAddress address) {
final boolean hasPool = componentType.hasPool();
final ModelNode result = context.getResult();
final EJBComponentDescription componentDescription = component.getComponentDescription();
if (COMPONENT_CLASS_NAME.getName().equals(attributeName)) {
result.set(component.getComponentClass().getName());
} else if (JNDI_NAMES.getName().equals(attributeName)) {
for (ViewDescription view : componentDescription.getViews()) {
for (String binding : view.getBindingNames()) {
result.add(binding);
}
}
} else if (BUSINESS_LOCAL.getName().equals(attributeName)) {
for (final ViewDescription view : componentDescription.getViews()) {
final EJBViewDescription ejbViewDescription = (EJBViewDescription) view;
if (!ejbViewDescription.isEjb2xView() && ejbViewDescription.getMethodIntf() == MethodInterfaceType.Local) {
result.add(ejbViewDescription.getViewClassName());
}
}
} else if (BUSINESS_REMOTE.getName().equals(attributeName)) {
for (final ViewDescription view : componentDescription.getViews()) {
final EJBViewDescription ejbViewDescription = (EJBViewDescription) view;
if (!ejbViewDescription.isEjb2xView() && ejbViewDescription.getMethodIntf() == MethodInterfaceType.Remote) {
result.add(ejbViewDescription.getViewClassName());
}
}
} else if (TIMEOUT_METHOD.getName().equals(attributeName)) {
final Method timeoutMethod = component.getTimeoutMethod();
if (timeoutMethod != null) {
result.set(timeoutMethod.toString());
}
} else if (ASYNC_METHODS.getName().equals(attributeName)) {
final SessionBeanComponentDescription sessionBeanComponentDescription = (SessionBeanComponentDescription) componentDescription;
final Set<MethodIdentifier> asynchronousMethods = sessionBeanComponentDescription.getAsynchronousMethods();
for (MethodIdentifier m : asynchronousMethods) {
result.add(m.getReturnType() + ' ' + m.getName() + '(' + String.join(", ", m.getParameterTypes()) + ')');
}
} else if (TRANSACTION_TYPE.getName().equals(attributeName)) {
result.set(component.isBeanManagedTransaction() ? TransactionManagementType.BEAN.name() : TransactionManagementType.CONTAINER.name());
} else if (SECURITY_DOMAIN.getName().equals(attributeName)) {
EJBSecurityMetaData md = component.getSecurityMetaData();
if (md != null && md.getSecurityDomainName() != null) {
result.set(md.getSecurityDomainName());
}
} else if (RUN_AS_ROLE.getName().equals(attributeName)) {
EJBSecurityMetaData md = component.getSecurityMetaData();
if (md != null && md.getRunAs() != null) {
result.set(md.getRunAs());
}
} else if (DECLARED_ROLES.getName().equals(attributeName)) {
EJBSecurityMetaData md = component.getSecurityMetaData();
if (md != null) {
result.setEmptyList();
Set<String> roles = md.getDeclaredRoles();
if (roles != null) {
for (String role : roles) {
result.add(role);
}
}
}
} else if (componentType.hasTimer() && TimerAttributeDefinition.INSTANCE.getName().equals(attributeName)) {
TimerAttributeDefinition.addTimers(component, result);
} else if (hasPool && POOL_AVAILABLE_COUNT.getName().equals(attributeName)) {
final Pool<?> pool = componentType.getPool(component);
if (pool != null) {
result.set(pool.getAvailableCount());
}
} else if (hasPool && POOL_CREATE_COUNT.getName().equals(attributeName)) {
final Pool<?> pool = componentType.getPool(component);
if (pool != null) {
result.set(pool.getCreateCount());
}
} else if (hasPool && POOL_NAME.getName().equals(attributeName)) {
final String poolName = componentType.pooledComponent(component).getPoolName();
if (poolName != null) {
result.set(poolName);
}
} else if (hasPool && POOL_REMOVE_COUNT.getName().equals(attributeName)) {
final Pool<?> pool = componentType.getPool(component);
if (pool != null) {
result.set(pool.getRemoveCount());
}
} else if (hasPool && POOL_CURRENT_SIZE.getName().equals(attributeName)) {
final Pool<?> pool = componentType.getPool(component);
if (pool != null) {
result.set(pool.getCurrentSize());
}
} else if (hasPool && POOL_MAX_SIZE.getName().equals(attributeName)) {
final Pool<?> pool = componentType.getPool(component);
if (pool != null) {
result.set(pool.getMaxSize());
}
} else {
// Bug; we were registered for an attribute but there is no code for handling it
throw EjbLogger.ROOT_LOGGER.unknownAttribute(attributeName);
}
}
protected void executeWriteAttribute(String attributeName, OperationContext context, ModelNode operation, T component,
PathAddress address) throws OperationFailedException {
if (componentType.hasPool() && POOL_MAX_SIZE.getName().equals(attributeName)) {
int newSize = POOL_MAX_SIZE.resolveValue(context, operation.get(VALUE)).asInt();
final Pool<?> pool = componentType.getPool(component);
final int oldSize = pool.getMaxSize();
componentType.getPool(component).setMaxSize(newSize);
context.completeStep(new OperationContext.RollbackHandler() {
@Override
public void handleRollback(OperationContext context, ModelNode operation) {
pool.setMaxSize(oldSize);
}
});
} else {
// Bug; we were registered for an attribute but there is no code for handling it
throw EjbLogger.ROOT_LOGGER.unknownAttribute(attributeName);
}
}
protected void executeAgainstComponent(OperationContext context, ModelNode operation, T component, String opName, PathAddress address) throws OperationFailedException {
throw unknownOperation(opName);
}
protected boolean isOperationReadOnly(String opName) {
throw unknownOperation(opName);
}
private static IllegalStateException unknownOperation(String opName) {
throw EjbLogger.ROOT_LOGGER.unknownOperations(opName);
}
private boolean isForWrite(String opName) {
if (ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION.equals(opName)) {
return true;
} else if (ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION.equals(opName)) {
return false;
} else {
return !isOperationReadOnly(opName);
}
}
private ServiceName getComponentConfiguration(final OperationContext context, final PathAddress operationAddress) throws OperationFailedException {
final List<PathElement> relativeAddress = new ArrayList<PathElement>();
final String typeKey = this.componentType.getResourceType();
boolean skip=true;
for (int i = operationAddress.size() - 1; i >= 0; i--) {
PathElement pe = operationAddress.getElement(i);
if(skip && !pe.getKey().equals(typeKey)){
continue;
} else {
skip = false;
}
if (ModelDescriptionConstants.DEPLOYMENT.equals(pe.getKey())) {
final String runtimName = resolveRuntimeName(context,pe);
PathElement realPe = PathElement.pathElement(pe.getKey(), runtimName);
relativeAddress.add(0, realPe);
break;
} else {
relativeAddress.add(0, pe);
}
}
final PathAddress pa = PathAddress.pathAddress(relativeAddress);
final ServiceName config = componentConfigs.get(pa);
if (config == null) {
String exceptionMessage = EjbLogger.ROOT_LOGGER.noComponentRegisteredForAddress(operationAddress);
throw new OperationFailedException(exceptionMessage);
}
return config;
}
private T getComponent(final ServiceName serviceName, final PathAddress operationAddress,
final OperationContext context, final boolean forWrite) throws OperationFailedException {
ServiceRegistry registry = context.getServiceRegistry(forWrite);
ServiceController<?> controller = registry.getService(serviceName);
if (controller == null) {
String exceptionMessage = EjbLogger.ROOT_LOGGER.noComponentAvailableForAddress(operationAddress);
throw new OperationFailedException(exceptionMessage);
}
ServiceController.State controllerState = controller.getState();
if (controllerState != ServiceController.State.UP) {
String exceptionMessage = EjbLogger.ROOT_LOGGER.invalidComponentState(operationAddress, controllerState, ServiceController.State.UP);
throw new OperationFailedException(exceptionMessage);
}
return componentClass.cast(controller.getValue());
}
T getComponent(OperationContext context, ModelNode operation) throws OperationFailedException{
PathAddress address = PathAddress.pathAddress(operation.require(ModelDescriptionConstants.OP_ADDR));
final ServiceName serviceName = getComponentConfiguration(context,address);
T component = getComponent(serviceName, address, context, false);
return component;
}
/**
* Resolves runtime name of model resource.
* @param context - operation context in which handler is invoked
* @param address - deployment address
* @return runtime name of module. Value which is returned is never null.
*/
protected String resolveRuntimeName(final OperationContext context, final PathElement address){
final ModelNode runtimeName = context.readResourceFromRoot(PathAddress.pathAddress(address),false).getModel()
.get(ModelDescriptionConstants.RUNTIME_NAME);
return runtimeName.asString();
}
}
| 17,078 | 51.550769 | 172 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/deployment/EJBComponentType.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.ejb3.subsystem.deployment;
import java.util.HashMap;
import java.util.Map;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.as.ejb3.component.EJBComponentDescription;
import org.jboss.as.ejb3.component.messagedriven.MessageDrivenComponent;
import org.jboss.as.ejb3.component.messagedriven.MessageDrivenComponentDescription;
import org.jboss.as.ejb3.component.pool.PooledComponent;
import org.jboss.as.ejb3.component.singleton.SingletonComponent;
import org.jboss.as.ejb3.component.singleton.SingletonComponentDescription;
import org.jboss.as.ejb3.component.stateful.StatefulComponentDescription;
import org.jboss.as.ejb3.component.stateful.StatefulSessionComponent;
import org.jboss.as.ejb3.component.stateless.StatelessComponentDescription;
import org.jboss.as.ejb3.component.stateless.StatelessSessionComponent;
import org.jboss.as.ejb3.pool.Pool;
/**
* Enumeration of types of manageable Jakarta Enterprise Beans components.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public enum EJBComponentType {
MESSAGE_DRIVEN("message-driven-bean", MessageDrivenComponent.class, MessageDrivenComponentDescription.class),
SINGLETON("singleton-bean", SingletonComponent.class, SingletonComponentDescription.class),
STATELESS("stateless-session-bean", StatelessSessionComponent.class, StatelessComponentDescription.class),
STATEFUL("stateful-session-bean", StatefulSessionComponent.class, StatefulComponentDescription.class);
private static final Map<Class<?>, EJBComponentType> typeByDescriptionClass;
static {
typeByDescriptionClass = new HashMap<Class<?>, EJBComponentType>();
for (EJBComponentType type : values()) {
typeByDescriptionClass.put(type.componentDescriptionClass, type);
}
}
private final String resourceType;
private final Class<? extends EJBComponent> componentClass;
private final Class<? extends EJBComponentDescription> componentDescriptionClass;
private EJBComponentType(final String resourceType, final Class<? extends EJBComponent> componentClass,
final Class<? extends EJBComponentDescription> componentDescriptionClass) {
this.resourceType = resourceType;
this.componentClass = componentClass;
this.componentDescriptionClass = componentDescriptionClass;
}
public String getResourceType() {
return resourceType;
}
public Class<? extends EJBComponent> getComponentClass() {
return componentClass;
}
public Class<? extends EJBComponentDescription> getComponentDescriptionClass() {
return componentDescriptionClass;
}
public boolean hasPool() {
switch (this) {
case STATEFUL:
case SINGLETON:
return false;
default:
return true;
}
}
public boolean hasTimer() {
switch (this) {
case STATELESS:
case SINGLETON:
case MESSAGE_DRIVEN:
return true;
default:
return false;
}
}
public Pool<?> getPool(EJBComponent component) {
return pooledComponent(component).getPool();
}
public AbstractEJBComponentRuntimeHandler<?> getRuntimeHandler() {
switch (this) {
case MESSAGE_DRIVEN:
return MessageDrivenBeanRuntimeHandler.INSTANCE;
case SINGLETON:
return SingletonBeanRuntimeHandler.INSTANCE;
case STATELESS:
return StatelessSessionBeanRuntimeHandler.INSTANCE;
case STATEFUL:
return StatefulSessionBeanRuntimeHandler.INSTANCE;
default:
// Bug
throw EjbLogger.ROOT_LOGGER.unknownComponentType(this);
}
}
public static EJBComponentType getComponentType(ComponentConfiguration componentConfiguration) {
final ComponentDescription description = componentConfiguration.getComponentDescription();
EJBComponentType type = typeByDescriptionClass.get(description.getClass());
if (type != null) {
return type;
}
// Check for subclass
for(Map.Entry<Class<?>, EJBComponentType> entry : typeByDescriptionClass.entrySet()) {
if(entry.getKey().isAssignableFrom(description.getClass())) {
return entry.getValue();
}
}
throw EjbLogger.ROOT_LOGGER.unknownComponentDescriptionType(description.getClass());
}
protected PooledComponent<?> pooledComponent(final EJBComponent component) {
switch (this) {
case MESSAGE_DRIVEN:
return MessageDrivenComponent.class.cast(component);
case STATELESS:
return StatelessSessionComponent.class.cast(component);
case SINGLETON:
case STATEFUL:
throw EjbLogger.ROOT_LOGGER.invalidComponentType(this.getComponentClass().getSimpleName());
default:
// Bug
throw EjbLogger.ROOT_LOGGER.unknownComponentType(this);
}
}
}
| 6,341 | 38.886792 | 113 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/deployment/MessageDrivenBeanRuntimeHandler.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.ejb3.subsystem.deployment;
import static org.jboss.as.ejb3.subsystem.deployment.MessageDrivenBeanResourceDefinition.ACTIVATION_CONFIG;
import static org.jboss.as.ejb3.subsystem.deployment.MessageDrivenBeanResourceDefinition.DELIVERY_ACTIVE;
import static org.jboss.as.ejb3.subsystem.deployment.MessageDrivenBeanResourceDefinition.MESSAGE_DESTINATION_LINK;
import static org.jboss.as.ejb3.subsystem.deployment.MessageDrivenBeanResourceDefinition.MESSAGE_DESTINATION_TYPE;
import static org.jboss.as.ejb3.subsystem.deployment.MessageDrivenBeanResourceDefinition.MESSAGING_TYPE;
import static org.jboss.as.ejb3.subsystem.deployment.MessageDrivenBeanResourceDefinition.START_DELIVERY;
import static org.jboss.as.ejb3.subsystem.deployment.MessageDrivenBeanResourceDefinition.STOP_DELIVERY;
import java.util.Properties;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.ejb3.component.messagedriven.MessageDrivenComponent;
import org.jboss.as.ejb3.component.messagedriven.MessageDrivenComponentDescription;
import org.jboss.dmr.ModelNode;
import org.jboss.metadata.ejb.spec.MessageDrivenBeanMetaData;
import org.jboss.msc.service.ServiceController;
/**
* Handles operations that provide runtime management of a {@link MessageDrivenComponent}.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
* @author Flavia Rainone
*/
public class MessageDrivenBeanRuntimeHandler extends AbstractEJBComponentRuntimeHandler<MessageDrivenComponent> {
public static final MessageDrivenBeanRuntimeHandler INSTANCE = new MessageDrivenBeanRuntimeHandler();
private MessageDrivenBeanRuntimeHandler() {
super(EJBComponentType.MESSAGE_DRIVEN, MessageDrivenComponent.class);
}
@Override
protected void executeReadAttribute(String attributeName, OperationContext context, MessageDrivenComponent component, PathAddress address) {
final MessageDrivenComponentDescription componentDescription = (MessageDrivenComponentDescription) component.getComponentDescription();
final ModelNode result = context.getResult();
if (DELIVERY_ACTIVE.getName().equals(attributeName)) {
result.set(component.isDeliveryActive());
} else if (MESSAGING_TYPE.getName().equals(attributeName)) {
result.set(componentDescription.getMessageListenerInterfaceName());
} else if (MESSAGE_DESTINATION_TYPE.getName().equals(attributeName)) {
final MessageDrivenBeanMetaData descriptorData = componentDescription.getDescriptorData();
if (descriptorData != null) {
final String destinationType = descriptorData.getMessageDestinationType();
if (destinationType != null) {
result.set(destinationType);
}
}
} else if (MESSAGE_DESTINATION_LINK.getName().equals(attributeName)) {
final MessageDrivenBeanMetaData descriptorData = componentDescription.getDescriptorData();
if (descriptorData != null) {
final String messageDestinationLink = descriptorData.getMessageDestinationLink();
if (messageDestinationLink != null) {
result.set(messageDestinationLink);
}
}
} else if (ACTIVATION_CONFIG.getName().equals(attributeName)) {
final Properties activationProps = componentDescription.getActivationProps();
for (String k : activationProps.stringPropertyNames()) {
result.add(k, activationProps.getProperty(k));
}
} else {
super.executeReadAttribute(attributeName, context, component, address);
}
}
protected boolean isOperationReadOnly(String opName) {
if (START_DELIVERY.equals(opName) ||
STOP_DELIVERY.equals(opName)) {
return false;
}
return super.isOperationReadOnly(opName);
}
@Override
protected void executeAgainstComponent(OperationContext context, ModelNode operation, MessageDrivenComponent component, String opName, PathAddress address) throws OperationFailedException {
if (START_DELIVERY.equals(opName)) {
if (component.isDeliveryControlled()) {
context.getServiceRegistry(true).getRequiredService(component.getDeliveryControllerName()).setMode(ServiceController.Mode.PASSIVE);
} else {
component.startDelivery();
}
} else if (STOP_DELIVERY.equals(opName)) {
if (component.isDeliveryControlled()) {
context.getServiceRegistry(true).getRequiredService(component.getDeliveryControllerName()).setMode(
ServiceController.Mode.NEVER);
} else {
component.stopDelivery();
}
} else {
super.executeAgainstComponent(context, operation, component, opName, address);
}
}
}
| 6,055 | 49.049587 | 193 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/deployment/MessageDrivenBeanResourceDefinition.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.ejb3.subsystem.deployment;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PropertiesAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleOperationDefinition;
import org.jboss.as.controller.SimpleOperationDefinitionBuilder;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
/**
* {@link org.jboss.as.controller.ResourceDefinition} for a {@link org.jboss.as.ejb3.component.messagedriven.MessageDrivenComponent}.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class MessageDrivenBeanResourceDefinition extends AbstractEJBComponentResourceDefinition {
static final AttributeDefinition DELIVERY_ACTIVE = new SimpleAttributeDefinitionBuilder("delivery-active", ModelType.BOOLEAN, true)
.setDefaultValue(ModelNode.TRUE)
.setStorageRuntime()
.build();
static final SimpleAttributeDefinition MESSAGING_TYPE = new SimpleAttributeDefinitionBuilder("messaging-type", ModelType.STRING)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
static final SimpleAttributeDefinition MESSAGE_DESTINATION_TYPE = new SimpleAttributeDefinitionBuilder("message-destination-type", ModelType.STRING)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
static final SimpleAttributeDefinition MESSAGE_DESTINATION_LINK = new SimpleAttributeDefinitionBuilder("message-destination-link", ModelType.STRING)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
static final PropertiesAttributeDefinition ACTIVATION_CONFIG = new PropertiesAttributeDefinition.Builder("activation-config", true)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
static final String START_DELIVERY = "start-delivery";
static final String STOP_DELIVERY = "stop-delivery";
public MessageDrivenBeanResourceDefinition() {
super(EJBComponentType.MESSAGE_DRIVEN);
}
@Override
public void registerAttributes(ManagementResourceRegistration registry) {
super.registerAttributes(registry);
registry.registerReadOnlyAttribute(DELIVERY_ACTIVE, MessageDrivenBeanRuntimeHandler.INSTANCE);
registry.registerReadOnlyAttribute(MESSAGING_TYPE, MessageDrivenBeanRuntimeHandler.INSTANCE);
registry.registerReadOnlyAttribute(MESSAGE_DESTINATION_TYPE, MessageDrivenBeanRuntimeHandler.INSTANCE);
registry.registerReadOnlyAttribute(MESSAGE_DESTINATION_LINK, MessageDrivenBeanRuntimeHandler.INSTANCE);
registry.registerReadOnlyAttribute(ACTIVATION_CONFIG, MessageDrivenBeanRuntimeHandler.INSTANCE);
}
@Override
public void registerOperations(ManagementResourceRegistration registry) {
super.registerOperations(registry);
final SimpleOperationDefinition startDelivery = new SimpleOperationDefinitionBuilder(START_DELIVERY, getResourceDescriptionResolver())
.setRuntimeOnly()
.build();
registry.registerOperationHandler(startDelivery, MessageDrivenBeanRuntimeHandler.INSTANCE);
final SimpleOperationDefinition stopDelivery = new SimpleOperationDefinitionBuilder(STOP_DELIVERY, getResourceDescriptionResolver())
.setRuntimeOnly()
.build();
registry.registerOperationHandler(stopDelivery, MessageDrivenBeanRuntimeHandler.INSTANCE);
}
}
| 4,714 | 48.114583 | 152 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/deployment/TimerServiceResource.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.ejb3.subsystem.deployment;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.jboss.as.clustering.controller.ChildResourceProvider;
import org.jboss.as.clustering.controller.ComplexResource;
import org.jboss.as.clustering.controller.SimpleChildResourceProvider;
import org.jboss.as.controller.registry.PlaceholderResource;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.ejb3.subsystem.EJB3SubsystemModel;
import org.jboss.as.ejb3.timerservice.spi.TimerListener;
/**
* Dynamic management resource for a timer service.
* @author baranowb
* @author Paul Ferraro
*/
public class TimerServiceResource extends ComplexResource implements TimerListener {
private static final String CHILD_TYPE = EJB3SubsystemModel.TIMER_PATH.getKey();
public TimerServiceResource() {
this(PlaceholderResource.INSTANCE, Collections.singletonMap(CHILD_TYPE, new SimpleChildResourceProvider(ConcurrentHashMap.newKeySet())));
}
private TimerServiceResource(Resource resource, Map<String, ChildResourceProvider> providers) {
super(resource, providers, TimerServiceResource::new);
}
@Override
public void timerAdded(String id) {
ChildResourceProvider handler = this.apply(CHILD_TYPE);
handler.getChildren().add(id);
}
@Override
public void timerRemoved(String id) {
ChildResourceProvider handler = this.apply(CHILD_TYPE);
handler.getChildren().remove(id);
}
}
| 2,561 | 37.818182 | 145 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/deployment/SingletonBeanRuntimeHandler.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.ejb3.subsystem.deployment;
import static org.jboss.as.ejb3.subsystem.deployment.SingletonBeanDeploymentResourceDefinition.DEPENDS_ON;
import static org.jboss.as.ejb3.subsystem.deployment.SingletonBeanDeploymentResourceDefinition.INIT_ON_STARTUP;
import java.util.List;
import jakarta.ejb.ConcurrencyManagementType;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.ejb3.component.singleton.SingletonComponent;
import org.jboss.as.ejb3.component.singleton.SingletonComponentDescription;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceName;
/**
* Handles operations that provide runtime management of a {@link SingletonComponent}.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class SingletonBeanRuntimeHandler extends AbstractEJBComponentRuntimeHandler<SingletonComponent> {
public static final SingletonBeanRuntimeHandler INSTANCE = new SingletonBeanRuntimeHandler();
private SingletonBeanRuntimeHandler() {
super(EJBComponentType.SINGLETON, SingletonComponent.class);
}
@Override
protected void executeReadAttribute(final String attributeName, final OperationContext context, final SingletonComponent component, final PathAddress address) {
final SingletonComponentDescription componentDescription = (SingletonComponentDescription) component.getComponentDescription();
final ModelNode result = context.getResult();
if (INIT_ON_STARTUP.getName().equals(attributeName)) {
result.set(componentDescription.isInitOnStartup());
} else if (SingletonBeanDeploymentResourceDefinition.CONCURRENCY_MANAGEMENT_TYPE.getName().equals(attributeName)) {
final ConcurrencyManagementType concurrencyManagementType = componentDescription.getConcurrencyManagementType();
if (concurrencyManagementType != null) {
result.set(concurrencyManagementType.toString());
}
} else if (DEPENDS_ON.getName().equals(attributeName)) {
final List<ServiceName> dependsOn = componentDescription.getDependsOn();
for (final ServiceName dep : dependsOn) {
final String[] nameArray = dep.toArray();
result.add(nameArray[nameArray.length - 2]);
}
} else {
super.executeReadAttribute(attributeName, context, component, address);
}
}
}
| 3,480 | 46.684932 | 164 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/deployment/StatefulSessionBeanRuntimeHandler.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.ejb3.subsystem.deployment;
import static org.jboss.as.ejb3.subsystem.deployment.StatefulSessionBeanDeploymentResourceDefinition.AFTER_BEGIN_METHOD;
import static org.jboss.as.ejb3.subsystem.deployment.StatefulSessionBeanDeploymentResourceDefinition.AFTER_COMPLETION_METHOD;
import static org.jboss.as.ejb3.subsystem.deployment.StatefulSessionBeanDeploymentResourceDefinition.BEAN_METHOD;
import static org.jboss.as.ejb3.subsystem.deployment.StatefulSessionBeanDeploymentResourceDefinition.BEFORE_COMPLETION_METHOD;
import static org.jboss.as.ejb3.subsystem.deployment.StatefulSessionBeanDeploymentResourceDefinition.PASSIVATION_CAPABLE;
import static org.jboss.as.ejb3.subsystem.deployment.StatefulSessionBeanDeploymentResourceDefinition.REMOVE_METHODS;
import static org.jboss.as.ejb3.subsystem.deployment.StatefulSessionBeanDeploymentResourceDefinition.RETAIN_IF_EXCEPTION;
import static org.jboss.as.ejb3.subsystem.deployment.StatefulSessionBeanDeploymentResourceDefinition.STATEFUL_TIMEOUT;
import java.lang.reflect.Method;
import java.util.Collection;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.ejb3.component.stateful.StatefulComponentDescription;
import org.jboss.as.ejb3.component.stateful.StatefulSessionComponent;
import org.jboss.as.ejb3.component.stateful.StatefulTimeoutInfo;
import org.jboss.dmr.ModelNode;
import org.jboss.invocation.proxy.MethodIdentifier;
/**
* Handles operations that provide runtime management of a {@link StatefulSessionComponent}.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class StatefulSessionBeanRuntimeHandler extends AbstractEJBComponentRuntimeHandler<StatefulSessionComponent> {
public static final StatefulSessionBeanRuntimeHandler INSTANCE = new StatefulSessionBeanRuntimeHandler();
private StatefulSessionBeanRuntimeHandler() {
super(EJBComponentType.STATEFUL, StatefulSessionComponent.class);
}
@Override
protected void executeReadAttribute(String attributeName, OperationContext context, StatefulSessionComponent component, PathAddress address) {
final StatefulComponentDescription componentDescription = (StatefulComponentDescription) component.getComponentDescription();
final ModelNode result = context.getResult();
if (STATEFUL_TIMEOUT.getName().equals(attributeName)) {
final StatefulTimeoutInfo statefulTimeout = componentDescription.getStatefulTimeout();
if (statefulTimeout != null) {
result.set(statefulTimeout.getValue() + ' ' + statefulTimeout.getTimeUnit().toString());
}
} else if (AFTER_BEGIN_METHOD.getName().equals(attributeName)) {
final Method afterBeginMethod = component.getAfterBeginMethod();
if (afterBeginMethod != null) {
result.set(afterBeginMethod.toString());
}
} else if (BEFORE_COMPLETION_METHOD.getName().equals(attributeName)) {
final Method beforeCompletionMethod = component.getBeforeCompletionMethod();
if (beforeCompletionMethod != null) {
result.set(beforeCompletionMethod.toString());
}
} else if (AFTER_COMPLETION_METHOD.getName().equals(attributeName)) {
final Method afterCompletionMethod = component.getAfterCompletionMethod();
if (afterCompletionMethod != null) {
result.set(afterCompletionMethod.toString());
}
} else if (PASSIVATION_CAPABLE.getName().equals(attributeName)) {
result.set(componentDescription.isPassivationApplicable());
} else if (REMOVE_METHODS.getName().equals(attributeName)) {
final Collection<StatefulComponentDescription.StatefulRemoveMethod> removeMethods = componentDescription.getRemoveMethods();
for (StatefulComponentDescription.StatefulRemoveMethod removeMethod : removeMethods) {
ModelNode removeMethodNode = result.add();
final ModelNode beanMethodNode = removeMethodNode.get(BEAN_METHOD.getName());
final MethodIdentifier methodIdentifier = removeMethod.getMethodIdentifier();
beanMethodNode.set(methodIdentifier.getReturnType() + ' ' + methodIdentifier.getName() + '(' + String.join(", ", methodIdentifier.getParameterTypes()) + ')');
final ModelNode retainIfExceptionNode = removeMethodNode.get(RETAIN_IF_EXCEPTION.getName());
retainIfExceptionNode.set(removeMethod.getRetainIfException());
}
} else {
super.executeReadAttribute(attributeName, context, component, address);
}
//TODO expose the cache
}
}
| 5,759 | 56.029703 | 174 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/deployment/StatelessSessionBeanDeploymentResourceDefinition.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.ejb3.subsystem.deployment;
/**
* {@link org.jboss.as.controller.ResourceDefinition} for a {@link org.jboss.as.ejb3.component.stateless.StatelessSessionComponent}.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class StatelessSessionBeanDeploymentResourceDefinition extends AbstractEJBComponentResourceDefinition {
public StatelessSessionBeanDeploymentResourceDefinition() {
super(EJBComponentType.STATELESS);
}
}
| 1,494 | 40.527778 | 132 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/deployment/TimerServiceResourceDefinition.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.ejb3.subsystem.deployment;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.OperationEntry;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.as.ejb3.subsystem.EJB3Extension;
import org.jboss.as.ejb3.subsystem.EJB3SubsystemModel;
/**
* {@link ResourceDefinition} for the timer-service resource for runtime ejb deployment.
* As of now this is dummy path impl, since mgmt ops are supported by top level service=timer-service
* @author baranowb
*/
public class TimerServiceResourceDefinition<T extends EJBComponent> extends SimpleResourceDefinition {
private final AbstractEJBComponentRuntimeHandler<T> parentHandler;
TimerServiceResourceDefinition(AbstractEJBComponentRuntimeHandler<T> parentHandler) {
super(new SimpleResourceDefinition.Parameters(EJB3SubsystemModel.TIMER_SERVICE_PATH, EJB3Extension.getResourceDescriptionResolver(EJB3SubsystemModel.TIMER_SERVICE))
.setRemoveRestartLevel(OperationEntry.Flag.RESTART_RESOURCE_SERVICES));
this.parentHandler = parentHandler;
}
@Override
public void registerChildren(ManagementResourceRegistration resourceRegistration) {
super.registerChildren(resourceRegistration);
resourceRegistration.registerSubModel(new TimerResourceDefinition<T>(this.parentHandler));
}
}
| 2,472 | 46.557692 | 172 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/deployment/SingletonBeanDeploymentResourceDefinition.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.ejb3.subsystem.deployment;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.StringListAttributeDefinition;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelType;
/**
* {@link org.jboss.as.controller.ResourceDefinition} for a {@link org.jboss.as.ejb3.component.singleton.SingletonComponent}.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class SingletonBeanDeploymentResourceDefinition extends AbstractEJBComponentResourceDefinition {
static final SimpleAttributeDefinition INIT_ON_STARTUP = new SimpleAttributeDefinitionBuilder("init-on-startup", ModelType.BOOLEAN)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
static final StringListAttributeDefinition DEPENDS_ON = StringListAttributeDefinition.Builder.of("depends-on")
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
static final SimpleAttributeDefinition CONCURRENCY_MANAGEMENT_TYPE = new SimpleAttributeDefinitionBuilder("concurrency-management-type", ModelType.STRING)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
public SingletonBeanDeploymentResourceDefinition() {
super(EJBComponentType.SINGLETON);
}
@Override
public void registerAttributes(final ManagementResourceRegistration resourceRegistration) {
super.registerAttributes(resourceRegistration);
final AbstractEJBComponentRuntimeHandler<?> handler = componentType.getRuntimeHandler();
resourceRegistration.registerReadOnlyAttribute(CONCURRENCY_MANAGEMENT_TYPE, handler);
resourceRegistration.registerReadOnlyAttribute(INIT_ON_STARTUP, handler);
resourceRegistration.registerReadOnlyAttribute(DEPENDS_ON, handler);
}
}
| 3,003 | 45.215385 | 158 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/subsystem/deployment/AbstractRuntimeMetricsHandler.java | /*
* JBoss, Home of Professional Open Source.
* Copyright (c) 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.ejb3.subsystem.deployment;
import org.jboss.as.controller.AbstractRuntimeOnlyHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.ee.component.BasicComponent;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.as.server.deployment.Services;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceName;
/**
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
*/
public abstract class AbstractRuntimeMetricsHandler extends AbstractRuntimeOnlyHandler {
private static ServiceName componentServiceName(final OperationContext context, final ModelNode operation) {
final PathAddress address = PathAddress.pathAddress(operation.require(ModelDescriptionConstants.OP_ADDR));
final String parent;
final String module;
int i = 2;
if (address.getElement(1).getKey().equals(ModelDescriptionConstants.SUBDEPLOYMENT)) {
parent = resolveRuntimeName(context,address.getElement(0));
module = address.getElement(1).getValue();
i++;
} else {
parent = null;
module = resolveRuntimeName(context,address.getElement(0));
}
final String component = address.getElement(i).getValue();
final ServiceName deploymentUnitServiceName;
if (parent == null) {
deploymentUnitServiceName = Services.deploymentUnitName(module);
}
else {
deploymentUnitServiceName = Services.deploymentUnitName(parent, module);
}
// Hmm, don't like the START bit
return BasicComponent.serviceNameOf(deploymentUnitServiceName, component).append("START");
}
protected abstract void executeReadMetricStep(final OperationContext context, final ModelNode operation, final EJBComponent component) throws OperationFailedException;
@Override
protected void executeRuntimeStep(final OperationContext context, final ModelNode operation) throws OperationFailedException {
final ServiceName componentServiceName = componentServiceName(context,operation);
final EJBComponent component = (EJBComponent) context.getServiceRegistry(false).getRequiredService(componentServiceName).getValue();
executeReadMetricStep(context, operation, component);
}
/**
* Resolves runtime name of model resource.
* @param context - operation context in which handler is invoked
* @param address - deployment address
* @return runtime name of module. Value which is returned is never null.
*/
protected static String resolveRuntimeName(final OperationContext context, final PathElement address){
final ModelNode runtimeName = context.readResourceFromRoot(PathAddress.pathAddress(address),false).getModel()
.get(ModelDescriptionConstants.RUNTIME_NAME);
return runtimeName.asString();
}
}
| 4,156 | 47.905882 | 171 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/util/MethodInfoHelper.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.ejb3.util;
import java.lang.reflect.Method;
/**
* This helper class contains helper methods that are used
* to resolve method-params in deployment descriptors and method level annotations
* in Jakarta Enterprise Beans implementation classes.
*
* @author [email protected]
*
*/
public final class MethodInfoHelper {
public static final String[] EMPTY_STRING_ARRAY = new String[0];
private MethodInfoHelper() {}
/**
* This method returns the class names of the parameters of the given method
* in canonical form. In case of a method without parameters it will return an empty
* array.
*
* <p>The canonical form is the one that is used in deployment descriptors.
*
* <p>Example: For the method <code>f(String[] arg0, String arg1, int)</code> this method will return
* <code>{"java.lang.String[]", "java.lang.String", "int"}</code>
*
* @param viewMethod the method to extract its parameter types
* @return string array of parameter types
*/
public static String[] getCanonicalParameterTypes(Method viewMethod) {
Class<?>[] parameterTypes = viewMethod.getParameterTypes();
if (parameterTypes.length == 0) {
return EMPTY_STRING_ARRAY;
}
String[] canonicalNames = new String[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
canonicalNames[i] = parameterTypes[i].getCanonicalName();
}
return canonicalNames;
}
}
| 2,549 | 37.636364 | 105 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/util/MdbValidityStatus.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.ejb3.util;
/**
* @author Romain Pelisse - [email protected]
*/
public enum MdbValidityStatus {
MDB_CANNOT_BE_AN_INTERFACE, MDB_CLASS_CANNOT_BE_PRIVATE_ABSTRACT_OR_FINAL, MDB_ON_MESSAGE_METHOD_CANT_BE_FINAL, MDB_ON_MESSAGE_METHOD_CANT_BE_STATIC, MDB_ON_MESSAGE_METHOD_CANT_BE_PRIVATE, MDB_SHOULD_NOT_HAVE_FINALIZE_METHOD, MDB_IS_VALID;
}
| 1,390 | 42.46875 | 243 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/util/EjbValidationsUtil.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2018, 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.ejb3.util;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.MethodInfo;
/**
* @author Romain Pelisse - [email protected]
*/
public final class EjbValidationsUtil {
private EjbValidationsUtil() {
}
/**
* Verifies that the passed <code>mdbClass</code> meets the requirements set by the Enterprise Beans 3 spec about bean implementation
* classes. The passed <code>mdbClass</code> must not be an interface and must be public and not final and not abstract. If
* it fails any of these requirements then one of the {@code MdbValidityStatus} value is added to the returned collection.
* An empty collection is returned if no violation is found.
*
* @param mdbClass The MDB class
* @return a collection of violations represented by {@code MdbValidityStatus}
*/
public static Collection<MdbValidityStatus> assertEjbClassValidity(final ClassInfo mdbClass) {
Collection<MdbValidityStatus> mdbComplianceIssueList = new ArrayList<>(MdbValidityStatus.values().length);
final String className = mdbClass.name().toString();
verifyModifiers(className, mdbClass.flags(), mdbComplianceIssueList);
for (MethodInfo method : mdbClass.methods()) {
if ("onMessage".equals(method.name())) {
verifyOnMessageMethod(className, method.flags(), mdbComplianceIssueList);
}
if ("finalize".equals(method.name())) {
EjbLogger.DEPLOYMENT_LOGGER.mdbCantHaveFinalizeMethod(className);
mdbComplianceIssueList.add(MdbValidityStatus.MDB_SHOULD_NOT_HAVE_FINALIZE_METHOD);
}
}
return mdbComplianceIssueList;
}
private static void verifyModifiers(final String className, final short flags,
final Collection<MdbValidityStatus> mdbComplianceIssueList) {
// must *not* be an interface
if (Modifier.isInterface(flags)) {
EjbLogger.DEPLOYMENT_LOGGER.mdbClassCannotBeAnInterface(className);
mdbComplianceIssueList.add(MdbValidityStatus.MDB_CANNOT_BE_AN_INTERFACE);
}
// bean class must be public, must *not* be abstract or final
if (!Modifier.isPublic(flags) || Modifier.isAbstract(flags) || Modifier.isFinal(flags)) {
EjbLogger.DEPLOYMENT_LOGGER.mdbClassMustBePublicNonAbstractNonFinal(className);
mdbComplianceIssueList.add(MdbValidityStatus.MDB_CLASS_CANNOT_BE_PRIVATE_ABSTRACT_OR_FINAL);
}
}
private static void verifyOnMessageMethod(final String className, final short methodsFlags,
final Collection<MdbValidityStatus> mdbComplianceIssueList) {
if (Modifier.isFinal(methodsFlags)) {
EjbLogger.DEPLOYMENT_LOGGER.mdbOnMessageMethodCantBeFinal(className);
mdbComplianceIssueList.add(MdbValidityStatus.MDB_ON_MESSAGE_METHOD_CANT_BE_FINAL);
}
if (Modifier.isStatic(methodsFlags)) {
EjbLogger.DEPLOYMENT_LOGGER.mdbOnMessageMethodCantBeStatic(className);
mdbComplianceIssueList.add(MdbValidityStatus.MDB_ON_MESSAGE_METHOD_CANT_BE_STATIC);
}
if (Modifier.isPrivate(methodsFlags)) {
EjbLogger.DEPLOYMENT_LOGGER.mdbOnMessageMethodCantBePrivate(className);
mdbComplianceIssueList.add(MdbValidityStatus.MDB_ON_MESSAGE_METHOD_CANT_BE_PRIVATE);
}
}
public static void verifyEjbClassAndDefaultConstructor(final Constructor<?> ctor, Class<?> enclosingClass,
boolean noInterface, String componentName, String componentClassname, int modifiers)
throws DeploymentUnitProcessingException {
if (ctor == null && noInterface) {
// we only validate this for no interface views
throw EjbLogger.ROOT_LOGGER.ejbMustHavePublicDefaultConstructor(componentName, componentClassname);
}
if (enclosingClass != null) {
throw EjbLogger.ROOT_LOGGER.ejbMustNotBeInnerClass(componentName, componentClassname);
}
if (!Modifier.isPublic(modifiers)) {
throw EjbLogger.ROOT_LOGGER.ejbMustBePublicClass(componentName, componentClassname);
}
if (Modifier.isFinal(modifiers)) {
throw EjbLogger.ROOT_LOGGER.ejbMustNotBeFinalClass(componentName, componentClassname);
}
}
public static boolean verifyEjbPublicMethodAreNotFinalNorStatic(Method[] methods, String classname) {
boolean isEjbCompliant = true;
for (Method method : methods) {
if (Object.class != method.getDeclaringClass() && !EjbValidationsUtil.verifyMethodIsNotFinalNorStatic(method, classname))
isEjbCompliant = false;
}
return isEjbCompliant;
}
public static boolean verifyMethodIsNotFinalNorStatic(Method method, String classname) {
boolean isMethodCompliant = true;
if (Modifier.isStatic(method.getModifiers()) || Modifier.isFinal(method.getModifiers())) {
EjbLogger.ROOT_LOGGER.ejbMethodMustNotBeFinalNorStatic(classname, method.getName());
isMethodCompliant = false;
}
return isMethodCompliant;
}
}
| 6,474 | 46.262774 | 137 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/concurrency/AccessTimeoutDetails.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, 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.ejb3.concurrency;
import java.util.concurrent.TimeUnit;
/**
* @author Stuart Douglas
*/
public class AccessTimeoutDetails {
private final long value;
private final TimeUnit timeUnit;
public AccessTimeoutDetails(final long value, final TimeUnit timeUnit) {
this.value = value;
this.timeUnit = timeUnit;
}
public TimeUnit getTimeUnit() {
return timeUnit;
}
public long getValue() {
return value;
}
}
| 1,508 | 30.4375 | 76 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/iiop/POARegistry.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ejb3.iiop;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
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.omg.CORBA.Policy;
import org.omg.CORBA.SetOverrideType;
import org.omg.PortableServer.IdAssignmentPolicyValue;
import org.omg.PortableServer.IdUniquenessPolicyValue;
import org.omg.PortableServer.LifespanPolicyValue;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.RequestProcessingPolicyValue;
import org.omg.PortableServer.Servant;
import org.omg.PortableServer.ServantRetentionPolicyValue;
/**
* Registry that maintains 2 different servant registries
* <p/>
* <ul>
* <li>a <code>ServantRegistry</code> with a transient POA per servant;</li>
* <li>a <code>ServantRegistry</code> with persistent POA per servant.</li>
* </ul>
* <p/>
* CORBA servants registered with any of these
* <code>ServantRegistry</code> instances will receive IIOP invocations.
*
* @author <a href="mailto:[email protected]">Francisco Reverbel</a>
*/
public class POARegistry implements Service<POARegistry> {
public static final ServiceName SERVICE_NAME = ServiceName.JBOSS.append("ejb", "iiop", "POARegistry");
public static final byte[] EMPTY_BYTES = {};
/**
* The root POA. *
*/
private final InjectedValue<POA> rootPOA = new InjectedValue<POA>();
/**
* A ServantRegistry with a transient POA per servant.
*/
private ServantRegistry registryWithTransientPOAPerServant;
/**
* The transient POA map used by the ServantRegistry above.
*/
private Map<String, POA> transientPoaMap;
/**
* POA policies used by the ServantRegistry above.
*/
private Policy[] transientPoaPolicies;
/**
* A ServantRegistry with a persistent POA per servant.
*/
private ServantRegistry registryWithPersistentPOAPerServant;
/**
* The persistent POA map used by the ServantRegistry above.
*/
private Map<String, POA> persistentPoaMap;
/**
* POA policies used by the ServantRegistry above.
*/
private Policy[] persistentPoaPolicies;
public synchronized void start(final StartContext startContext) throws StartException {
transientPoaMap = Collections.synchronizedMap(new HashMap<String, POA>());
persistentPoaMap = Collections.synchronizedMap(new HashMap<String, POA>());
final POA rootPOA = this.rootPOA.getValue();
// Policies for per-servant transient POAs
transientPoaPolicies = new Policy[]{rootPOA.create_lifespan_policy(
LifespanPolicyValue.TRANSIENT),
rootPOA.create_id_assignment_policy(IdAssignmentPolicyValue.SYSTEM_ID),
rootPOA.create_servant_retention_policy(ServantRetentionPolicyValue.NON_RETAIN),
rootPOA.create_request_processing_policy(RequestProcessingPolicyValue.USE_DEFAULT_SERVANT),
rootPOA.create_id_uniqueness_policy( IdUniquenessPolicyValue.MULTIPLE_ID),
};
// Policies for per-servant persistent POAs
persistentPoaPolicies = new Policy[]{
rootPOA.create_lifespan_policy(
LifespanPolicyValue.PERSISTENT),
rootPOA.create_id_assignment_policy(
IdAssignmentPolicyValue.USER_ID),
rootPOA.create_servant_retention_policy(
ServantRetentionPolicyValue.NON_RETAIN),
rootPOA.create_request_processing_policy(
RequestProcessingPolicyValue.USE_DEFAULT_SERVANT),
rootPOA.create_id_uniqueness_policy(
IdUniquenessPolicyValue.MULTIPLE_ID),
};
// Create this POARegistry's ServantRegistry implementations
registryWithTransientPOAPerServant = new ServantRegistryWithTransientPOAPerServant();
registryWithPersistentPOAPerServant = new ServantRegistryWithPersistentPOAPerServant();
}
public synchronized void stop(final StopContext context) {
transientPoaMap = null;
persistentPoaMap = null;
transientPoaPolicies = null;
persistentPoaPolicies = null;
}
private static Policy[] concatPolicies(Policy[] policies1, Policy[] policies2) {
Policy[] policies = new Policy[policies1.length + policies2.length];
int j = 0;
for (int i = 0; i < policies1.length; i++, j++) {
policies[j] = policies1[i];
}
for (int i = 0; i < policies2.length; i++, j++) {
policies[j] = policies2[i];
}
return policies;
}
@Override
public synchronized POARegistry getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
static class PoaReferenceFactory implements ReferenceFactory {
private final POA poa;
private final Policy[] policies;
PoaReferenceFactory(final POA poa, final Policy[] policies) {
this.poa = poa;
this.policies = policies;
}
PoaReferenceFactory(final POA poa) {
this(poa, null);
}
public org.omg.CORBA.Object createReference(final String interfId) throws Exception {
final org.omg.CORBA.Object corbaRef = poa.create_reference_with_id(EMPTY_BYTES, interfId);
if (policies != null) {
return corbaRef._set_policy_override(policies, SetOverrideType.ADD_OVERRIDE);
} else {
return corbaRef;
}
}
public org.omg.CORBA.Object createReferenceWithId(final byte[] id, final String interfId) throws Exception {
final org.omg.CORBA.Object corbaRef = poa.create_reference_with_id(id, interfId);
if (policies != null) {
return corbaRef._set_policy_override(policies, SetOverrideType.ADD_OVERRIDE);
} else {
return corbaRef;
}
}
public POA getPOA() {
return poa;
}
}
/**
* ServantRegistry with a transient POA per servant
*/
class ServantRegistryWithTransientPOAPerServant implements ServantRegistry {
public ReferenceFactory bind(final String name, final Servant servant, final Policy[] policies) throws Exception {
final Policy[] poaPolicies = concatPolicies(transientPoaPolicies, policies);
final POA poa = rootPOA.getValue().create_POA(name, null, poaPolicies);
transientPoaMap.put(name, poa);
poa.set_servant(servant);
poa.the_POAManager().activate();
return new PoaReferenceFactory(poa); // no servantName: in this case
// name is the POA name
}
public ReferenceFactory bind(final String name, final Servant servant) throws Exception {
final POA poa = rootPOA.getValue().create_POA(name, null, transientPoaPolicies);
transientPoaMap.put(name, poa);
poa.set_servant(servant);
poa.the_POAManager().activate();
return new PoaReferenceFactory(poa); // no servantName: in this case
// name is the POA name
}
public void unbind(final String name) throws Exception {
final POA poa = transientPoaMap.remove(name);
if (poa != null) {
poa.the_POAManager().deactivate(false, true);
poa.destroy(false, true);
}
}
}
/**
* ServantRegistry with a persistent POA per servant
*/
class ServantRegistryWithPersistentPOAPerServant implements ServantRegistry {
public ReferenceFactory bind(final String name, final Servant servant, final Policy[] policies) throws Exception {
final Policy[] poaPolicies = concatPolicies(persistentPoaPolicies, policies);
final POA poa = rootPOA.getValue().create_POA(name, null, poaPolicies);
persistentPoaMap.put(name, poa);
poa.set_servant(servant);
poa.the_POAManager().activate();
return new PoaReferenceFactory(poa); // no servantName: in this case
// name is the POA name
}
public ReferenceFactory bind(final String name, final Servant servant) throws Exception {
final POA poa = rootPOA.getValue().create_POA(name, null, persistentPoaPolicies);
persistentPoaMap.put(name, poa);
poa.set_servant(servant);
poa.the_POAManager().activate();
return new PoaReferenceFactory(poa); // no servantName: in this case
// name is the POA name
}
public void unbind(final String name) throws Exception {
final POA poa = persistentPoaMap.remove(name);
if (poa != null) {
poa.the_POAManager().deactivate(false, true);
poa.destroy(false, true);
}
}
}
public ServantRegistry getRegistryWithTransientPOAPerServant() {
return registryWithTransientPOAPerServant;
}
public ServantRegistry getRegistryWithPersistentPOAPerServant() {
return registryWithPersistentPOAPerServant;
}
public InjectedValue<POA> getRootPOA() {
return rootPOA;
}
}
| 10,486 | 37.697417 | 122 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/iiop/LocalIIOPInvoker.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ejb3.iiop;
import jakarta.transaction.Transaction;
import java.security.Principal;
/**
* Interface used by local IIOP invocations.
*
* @author <a href="mailto:[email protected]">Francisco Reverbel</a>
*/
public interface LocalIIOPInvoker {
Object invoke(String opName, Object[] arguments, Transaction tx, Principal identity, Object credential) throws Exception;
}
| 1,429 | 39.857143 | 125 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/iiop/EjbCorbaServant.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ejb3.iiop;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.rmi.RemoteException;
import java.security.Principal;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.HashMap;
import java.util.Map;
import javax.management.MBeanException;
import jakarta.ejb.EJBMetaData;
import jakarta.ejb.HomeHandle;
import jakarta.transaction.Status;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import org.jboss.as.ee.component.Component;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.as.ee.component.interceptors.InvocationType;
import org.jboss.as.ejb3.component.stateful.StatefulSessionComponent;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.naming.context.NamespaceContextSelector;
import org.jboss.ejb.client.SessionID;
import org.jboss.ejb.iiop.HandleImplIIOP;
import org.jboss.iiop.csiv2.SASCurrent;
import org.jboss.invocation.InterceptorContext;
import org.jboss.marshalling.InputStreamByteInput;
import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.MarshallingConfiguration;
import org.jboss.marshalling.Unmarshaller;
import org.omg.CORBA.BAD_OPERATION;
import org.omg.CORBA.InterfaceDef;
import org.omg.CORBA.ORB;
import org.omg.CORBA.ORBPackage.InvalidName;
import org.omg.CORBA.portable.InputStream;
import org.omg.CORBA.portable.InvokeHandler;
import org.omg.CORBA.portable.OutputStream;
import org.omg.CORBA.portable.ResponseHandler;
import org.omg.PortableServer.Current;
import org.omg.PortableServer.CurrentPackage.NoContext;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.Servant;
import org.wildfly.iiop.openjdk.rmi.RmiIdlUtil;
import org.wildfly.iiop.openjdk.rmi.marshal.strategy.SkeletonStrategy;
import org.wildfly.security.auth.client.AuthenticationConfiguration;
import org.wildfly.security.auth.client.AuthenticationContext;
import org.wildfly.security.auth.client.MatchRule;
import org.wildfly.security.auth.principal.NamePrincipal;
import org.wildfly.security.auth.server.RealmUnavailableException;
import org.wildfly.security.auth.server.SecurityDomain;
import org.wildfly.security.auth.server.SecurityIdentity;
import org.wildfly.security.auth.server.ServerAuthenticationContext;
import org.wildfly.security.evidence.PasswordGuessEvidence;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* CORBA servant class for the <code>EJBObject</code>s of a given bean. An
* instance of this class "implements" the bean's set of <code>EJBObject</code>
* instances by forwarding to the bean container all IIOP invocations on any
* of the bean's <code>EJBObject</code>s.
*
* @author <a href="mailto:[email protected]">Francisco Reverbel</a>
* @author Stuart Douglas
*/
public class EjbCorbaServant extends Servant implements InvokeHandler, LocalIIOPInvoker {
/**
* The injected component view
*/
private final ComponentView componentView;
/**
* The ORB
*/
private final ORB orb;
/**
* Thread-local <code>Current</code> object from which we get the target oid
* in an incoming IIOP request.
*/
private final Current poaCurrent;
/**
* Mapping from bean methods to <code>SkeletonStrategy</code> instances.
*/
private final Map<String, SkeletonStrategy> methodInvokerMap;
/**
* CORBA repository ids of the RMI-IDL interfaces implemented by the bean
* (<code>EJBObject</code> instance).
*/
private final String[] repositoryIds;
/**
* CORBA reference to an IR object representing the bean's remote interface.
*/
private final InterfaceDef interfaceDef;
/**
* The security domain for CORBA invocations
*/
private final String legacySecurityDomain;
/**
* The Elytron security domain for CORBA invocations
*/
private final SecurityDomain securityDomain;
/**
* If true this is the servant for an EJBHome object
*/
private final boolean home;
/**
* <code>HomeHandle</code> for the <code>EJBHome</code>
* implemented by this servant.
*/
private volatile HomeHandle homeHandle = null;
/**
* The metadata for this
*/
private volatile EJBMetaData ejbMetaData;
/**
* A reference to the SASCurrent, or null if the SAS interceptors are not
* installed.
*/
private final SASCurrent sasCurrent;
/**
* A reference to the InboundTransactionCurrent, or null if OTS interceptors
* are not installed.
*/
private final org.jboss.iiop.tm.InboundTransactionCurrent inboundTxCurrent;
/**
* The transaction manager
*/
private final TransactionManager transactionManager;
/**
* Used for serializing EJB id's
*/
private final MarshallerFactory factory;
private final MarshallingConfiguration configuration;
/**
* The EJB's deployment class loader
*/
private final ClassLoader classLoader;
/**
* Constructs an <code>EjbObjectCorbaServant></code>.
*/
public EjbCorbaServant(final Current poaCurrent, final Map<String, SkeletonStrategy> methodInvokerMap, final String[] repositoryIds,
final InterfaceDef interfaceDef, final ORB orb, final ComponentView componentView, final MarshallerFactory factory,
final MarshallingConfiguration configuration, final TransactionManager transactionManager, final ClassLoader classLoader,
final boolean home, final String legacySecurityDomain, final SecurityDomain securityDomain) {
this.poaCurrent = poaCurrent;
this.methodInvokerMap = methodInvokerMap;
this.repositoryIds = repositoryIds;
this.interfaceDef = interfaceDef;
this.orb = orb;
this.componentView = componentView;
this.factory = factory;
this.configuration = configuration;
this.transactionManager = transactionManager;
this.classLoader = classLoader;
this.home = home;
this.legacySecurityDomain = legacySecurityDomain;
this.securityDomain = securityDomain;
SASCurrent sasCurrent;
try {
sasCurrent = (SASCurrent) this.orb.resolve_initial_references("SASCurrent");
} catch (InvalidName invalidName) {
sasCurrent = null;
}
this.sasCurrent = sasCurrent;
org.jboss.iiop.tm.InboundTransactionCurrent inboundTxCurrent;
try {
inboundTxCurrent = (org.jboss.iiop.tm.InboundTransactionCurrent) this.orb.resolve_initial_references(org.jboss.iiop.tm.InboundTransactionCurrent.NAME);
} catch (InvalidName invalidName) {
inboundTxCurrent = null;
}
this.inboundTxCurrent = inboundTxCurrent;
}
/**
* Returns an IR object describing the bean's remote interface.
*/
public org.omg.CORBA.Object _get_interface_def() {
if (interfaceDef != null)
return interfaceDef;
else
return super._get_interface_def();
}
/**
* Returns an array with the CORBA repository ids of the RMI-IDL interfaces
* implemented by this servant's <code>EJBObject</code>s.
*/
public String[] _all_interfaces(POA poa, byte[] objectId) {
return repositoryIds.clone();
}
/**
* Receives IIOP requests to this servant's <code>EJBObject</code>s
* and forwards them to the bean container, through the JBoss
* <code>MBean</code> server.
*/
public OutputStream _invoke(final String opName, final InputStream in, final ResponseHandler handler) {
EjbLogger.ROOT_LOGGER.tracef("EJBObject invocation: %s", opName);
SkeletonStrategy op = methodInvokerMap.get(opName);
if (op == null) {
EjbLogger.ROOT_LOGGER.debugf("Unable to find opname '%s' valid operations:%s", opName, methodInvokerMap.keySet());
throw new BAD_OPERATION(opName);
}
final NamespaceContextSelector selector = componentView.getComponent().getNamespaceContextSelector();
final ClassLoader oldCl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
NamespaceContextSelector.pushCurrentSelector(selector);
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader);
org.omg.CORBA_2_3.portable.OutputStream out;
try {
Object retVal;
if (!home && opName.equals("_get_handle")) {
retVal = new HandleImplIIOP(orb.object_to_string(_this_object()));
} else if (home && opName.equals("_get_homeHandle")) {
retVal = homeHandle;
} else if (home && opName.equals("_get_EJBMetaData")) {
retVal = ejbMetaData;
} else {
Principal identityPrincipal = null;
Principal principal = null;
Object credential = null;
if (this.sasCurrent != null) {
final byte[] incomingIdentity = this.sasCurrent.get_incoming_principal_name();
//we have an identity token, which is a trust based mechanism
if (incomingIdentity != null && incomingIdentity.length > 0) {
String name = new String(incomingIdentity, StandardCharsets.UTF_8);
int domainIndex = name.indexOf('@');
if (domainIndex > 0)
name = name.substring(0, domainIndex);
identityPrincipal = new NamePrincipal(name);
}
final byte[] incomingUsername = this.sasCurrent.get_incoming_username();
if (incomingUsername != null && incomingUsername.length > 0) {
final byte[] incomingPassword = this.sasCurrent.get_incoming_password();
String name = new String(incomingUsername, StandardCharsets.UTF_8);
int domainIndex = name.indexOf('@');
if (domainIndex > 0) {
name = name.substring(0, domainIndex);
}
principal = new NamePrincipal(name);
credential = new String(incomingPassword, StandardCharsets.UTF_8).toCharArray();
}
}
final Object[] params = op.readParams((org.omg.CORBA_2_3.portable.InputStream) in);
if (!this.home && opName.equals("isIdentical") && params.length == 1) {
//handle isIdentical specially
Object val = params[0];
retVal = val instanceof org.omg.CORBA.Object && handleIsIdentical((org.omg.CORBA.Object) val);
} else {
if (this.securityDomain != null) {
// an elytron security domain is available: authenticate and authorize the client before invoking the component.
SecurityIdentity identity = this.securityDomain.getAnonymousSecurityIdentity();
AuthenticationConfiguration authenticationConfiguration = AuthenticationConfiguration.empty();
if (identityPrincipal != null) {
// we have an identity token principal - check if the TLS identity, if available,
// has permission to run as the identity token principal.
// TODO use the TLS identity when that becomes available to us.
// no TLS identity found, check if an initial context token was also sent. If it was,
// authenticate the incoming username/password and check if the resulting identity has
// permission to run as the identity token principal.
if (principal != null) {
char[] password = (char[]) credential;
authenticationConfiguration = authenticationConfiguration.useName(principal.getName())
.usePassword(password);
SecurityIdentity authenticatedIdentity = this.authenticate(principal, password);
identity = authenticatedIdentity.createRunAsIdentity(identityPrincipal.getName(), true);
} else {
// no TLS nor initial context token found - check if the anonymous identity has
// permission to run as the identity principal.
identity = this.securityDomain.getAnonymousSecurityIdentity().createRunAsIdentity(identityPrincipal.getName(), true);
}
} else if (principal != null) {
char[] password = (char[]) credential;
// we have an initial context token containing a username/password pair.
authenticationConfiguration = authenticationConfiguration.useName(principal.getName())
.usePassword(password);
identity = this.authenticate(principal, password);
}
final InterceptorContext interceptorContext = new InterceptorContext();
this.prepareInterceptorContext(op, params, interceptorContext);
try {
final AuthenticationContext context = AuthenticationContext.captureCurrent().with(MatchRule.ALL.matchProtocol("iiop"), authenticationConfiguration);
retVal = identity.runAs((PrivilegedExceptionAction<Object>) () -> context.run((PrivilegedExceptionAction<Object>) () -> this.componentView.invoke(interceptorContext)));
} catch (PrivilegedActionException e) {
throw e.getCause();
}
} else {
// legacy security behavior: setup the security context if a SASCurrent is available and invoke the component.
// One of the EJB security interceptors will authenticate and authorize the client.
final InterceptorContext interceptorContext = new InterceptorContext();
prepareInterceptorContext(op, params, interceptorContext);
retVal = this.componentView.invoke(interceptorContext);
}
}
}
out = (org.omg.CORBA_2_3.portable.OutputStream)
handler.createReply();
if (op.isNonVoid()) {
op.writeRetval(out, retVal);
}
} catch (Throwable e) {
EjbLogger.ROOT_LOGGER.trace("Exception in EJBObject invocation", e);
if (e instanceof MBeanException) {
e = ((MBeanException) e).getTargetException();
}
RmiIdlUtil.rethrowIfCorbaSystemException(e);
out = (org.omg.CORBA_2_3.portable.OutputStream)
handler.createExceptionReply();
op.writeException(out, e);
}
return out;
} finally {
NamespaceContextSelector.popCurrentSelector();
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldCl);
}
}
private void prepareInterceptorContext(final SkeletonStrategy op, final Object[] params, final InterceptorContext interceptorContext) throws IOException, ClassNotFoundException {
if (!home && componentView.getComponent() instanceof StatefulSessionComponent) {
final SessionID sessionID = (SessionID) unmarshalIdentifier();
interceptorContext.putPrivateData(SessionID.class, sessionID);
}
interceptorContext.setContextData(new HashMap<>());
interceptorContext.setParameters(params);
interceptorContext.setMethod(op.getMethod());
interceptorContext.putPrivateData(ComponentView.class, componentView);
interceptorContext.putPrivateData(Component.class, componentView.getComponent());
interceptorContext.putPrivateData(InvocationType.class, InvocationType.REMOTE);
interceptorContext.setTransaction(inboundTxCurrent == null ? null : inboundTxCurrent.getCurrentTransaction());
}
private boolean handleIsIdentical(final org.omg.CORBA.Object val) throws RemoteException {
//TODO: is this correct?
return orb.object_to_string(_this_object()).equals(orb.object_to_string(val));
}
private Object unmarshalIdentifier() throws IOException, ClassNotFoundException {
final Object id;
try (final Unmarshaller unmarshaller = factory.createUnmarshaller(configuration)) {
final byte[] idData = poaCurrent.get_object_id();
unmarshaller.start(new InputStreamByteInput(new ByteArrayInputStream(idData)));
id = unmarshaller.readObject();
} catch (NoContext noContext) {
throw new RuntimeException(noContext);
}
return id;
}
// Implementation of the interface LocalIIOPInvoker ------------------------
/**
* Receives intra-VM invocations on this servant's <code>EJBObject</code>s
* and forwards them to the bean container, through the JBoss
* <code>MBean</code>
* server.
*/
public Object invoke(String opName,
Object[] arguments,
Transaction tx,
Principal identity,
Object credential)
throws Exception {
EjbLogger.ROOT_LOGGER.tracef("EJBObject local invocation: %s", opName);
SkeletonStrategy op = methodInvokerMap.get(opName);
if (op == null) {
throw new BAD_OPERATION(opName);
}
if (tx != null) {
transactionManager.resume(tx);
}
try {
final InterceptorContext interceptorContext = new InterceptorContext();
prepareInterceptorContext(op, arguments, interceptorContext);
return componentView.invoke(interceptorContext);
} finally {
if (tx != null
&& transactionManager.getStatus() != Status.STATUS_NO_TRANSACTION) {
transactionManager.suspend();
}
}
}
public void setHomeHandle(final HomeHandle homeHandle) {
this.homeHandle = homeHandle;
}
public void setEjbMetaData(final EJBMetaData ejbMetaData) {
this.ejbMetaData = ejbMetaData;
}
/**
* Authenticate the user with the given credential against the configured Elytron security domain.
*
* @param principal the principal representing the user being authenticated.
* @param credential the credential used as evidence to verify the user's identity.
* @return the authenticated and authorized {@link SecurityIdentity}.
* @throws Exception if an error occurs while authenticating the user.
*/
private SecurityIdentity authenticate(final Principal principal, final char[] credential) throws Exception {
final ServerAuthenticationContext context = this.securityDomain.createNewAuthenticationContext();
final PasswordGuessEvidence evidence = new PasswordGuessEvidence(credential != null ? credential : null);
try {
context.setAuthenticationPrincipal(principal);
if (context.verifyEvidence(evidence)) {
if (context.authorize()) {
context.succeed();
return context.getAuthorizedIdentity();
} else {
context.fail();
throw new SecurityException("Authorization failed");
}
} else {
context.fail();
throw new SecurityException("Authentication failed");
}
} catch (IllegalArgumentException | IllegalStateException | RealmUnavailableException e) {
context.fail();
throw e;
} finally {
evidence.destroy();
}
}
}
| 21,846 | 45.090717 | 200 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/iiop/EjbIIOPService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ejb3.iiop;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InvalidClassException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import jakarta.ejb.EJBHome;
import jakarta.ejb.EJBMetaData;
import javax.rmi.PortableRemoteObject;
import jakarta.transaction.TransactionManager;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.as.ejb3.component.stateless.StatelessSessionComponent;
import org.jboss.as.ejb3.iiop.stub.DynamicStubFactoryFactory;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.server.moduleservice.ServiceModuleLoader;
import org.jboss.ejb.client.EJBHomeLocator;
import org.jboss.ejb.client.EJBLocator;
import org.jboss.ejb.client.EntityEJBLocator;
import org.jboss.ejb.client.StatefulEJBLocator;
import org.jboss.ejb.client.StatelessEJBLocator;
import org.jboss.ejb.iiop.EJBMetaDataImplIIOP;
import org.jboss.ejb.iiop.HandleImplIIOP;
import org.jboss.ejb.iiop.HomeHandleImplIIOP;
import org.jboss.marshalling.ClassResolver;
import org.jboss.marshalling.Marshaller;
import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.MarshallingConfiguration;
import org.jboss.marshalling.ModularClassResolver;
import org.jboss.marshalling.OutputStreamByteOutput;
import org.jboss.marshalling.Unmarshaller;
import org.jboss.marshalling.river.RiverMarshallerFactory;
import org.jboss.metadata.ejb.jboss.IIOPMetaData;
import org.jboss.metadata.ejb.jboss.IORSecurityConfigMetaData;
import org.jboss.metadata.ejb.jboss.IORTransportConfigMetaData;
import org.jboss.modules.Module;
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.omg.CORBA.Any;
import org.omg.CORBA.InterfaceDef;
import org.omg.CORBA.InterfaceDefHelper;
import org.omg.CORBA.ORB;
import org.omg.CORBA.Policy;
import org.omg.CORBA.Repository;
import org.omg.CosNaming.NameComponent;
import org.omg.CosNaming.NamingContext;
import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextHelper;
import org.omg.CosNaming.NamingContextPackage.CannotProceed;
import org.omg.CosNaming.NamingContextPackage.InvalidName;
import org.omg.CosNaming.NamingContextPackage.NotFound;
import org.omg.PortableServer.Current;
import org.omg.PortableServer.CurrentHelper;
import org.omg.PortableServer.POA;
import org.wildfly.iiop.openjdk.csiv2.CSIv2Policy;
import org.wildfly.iiop.openjdk.rmi.ir.InterfaceRepository;
import org.wildfly.iiop.openjdk.rmi.marshal.strategy.SkeletonStrategy;
import org.wildfly.security.manager.WildFlySecurityManager;
import org.wildfly.transaction.client.ContextTransactionManager;
import com.arjuna.ats.jbossatx.jta.TransactionManagerService;
import com.sun.corba.se.spi.extension.ZeroPortPolicy;
/**
* This is an IIOP "proxy factory" for <code>EJBHome</code>s and
* <code>EJBObject</code>s. Rather than creating Java proxies (as the JRMP
* proxy factory does), this factory creates CORBA IORs.
* <p/>
* An <code>EjbIIOPService</code> is associated to a given enterprise bean. It
* registers with the IIOP invoker two CORBA servants: an
* <code>EjbHomeCorbaServant</code> for the bean's
* <code>EJBHome</code> and an <code>EjbObjectCorbaServant</code> for the
* bean's <code>EJBObject</code>s.
*
* NOTE: References in this document to Enterprise JavaBeans (EJB) refer to the Jakarta Enterprise Beans unless otherwise noted.
*
*/
public class EjbIIOPService implements Service<EjbIIOPService> {
/**
* The service name
*/
public static final ServiceName SERVICE_NAME = ServiceName.of("EjbIIOPService");
/**
* The component
*/
private final InjectedValue<EJBComponent> ejbComponentInjectedValue = new InjectedValue<EJBComponent>();
/**
* The home view
*/
private final InjectedValue<ComponentView> homeView = new InjectedValue<ComponentView>();
/**
* the ejbObject view
*/
private final InjectedValue<ComponentView> remoteView = new InjectedValue<ComponentView>();
private final InjectedValue<POARegistry> poaRegistry = new InjectedValue<POARegistry>();
/**
* The corba naming context
*/
private final InjectedValue<NamingContextExt> corbaNamingContext = new InjectedValue<NamingContextExt>();
/**
* A reference for the ORB.
*/
private final InjectedValue<ORB> orb = new InjectedValue<ORB>();
/**
* The module loader
*/
private final InjectedValue<ServiceModuleLoader> serviceModuleLoaderInjectedValue = new InjectedValue<ServiceModuleLoader>();
/**
* The JTS underlying transaction manager service (not ContextTransactionManager)
*/
private final InjectedValue<TransactionManagerService> transactionManagerInjectedValue = new InjectedValue<>();
/**
* Used for serializing EJB id's
*/
private MarshallerFactory factory;
private MarshallingConfiguration configuration;
/**
* <code>EJBMetaData</code> the enterprise bean in the container.
*/
private EJBMetaData ejbMetaData;
/**
* Mapping from bean methods to <code>SkeletonStrategy</code> instances.
*/
private final Map<String, SkeletonStrategy> beanMethodMap;
/**
* Mapping from home methods to <code>SkeletonStrategy</code> instances.
*/
private final Map<String, SkeletonStrategy> homeMethodMap;
/**
* CORBA repository ids of the RMI-IDL interfaces implemented by the bean
* (<code>EJBObject</code> instance).
*/
private final String[] beanRepositoryIds;
/**
* CORBA repository ids of the RMI-IDL interfaces implemented by the bean's
* home (<code>EJBHome</code> instance).
*/
private final String[] homeRepositoryIds;
private final boolean useQualifiedName;
private final Module module;
/**
* <code>ServantRegistry</code> for the container's <code>EJBHome</code>.
*/
private ServantRegistry homeServantRegistry;
/**
* <code>ServantRegistry</code> for the container's <code>EJBObject</code>s.
*/
private ServantRegistry beanServantRegistry;
/**
* <code>ReferenceFactory</code> for <code>EJBObject</code>s.
*/
private ReferenceFactory beanReferenceFactory;
/**
* The container's <code>EJBHome</code>.
*/
private EJBHome ejbHome;
/**
* The enterprise bean's interface repository implementation, or null
* if the enterprise bean does not have its own interface repository.
*/
private InterfaceRepository iri;
/**
* POA for the enterprise bean's interface repository.
*/
private final InjectedValue<POA> irPoa = new InjectedValue<POA>();
/**
* Default IOR security config metadata (defined in the iiop subsystem).
*/
private final InjectedValue<IORSecurityConfigMetaData> iorSecConfigMetaData = new InjectedValue<IORSecurityConfigMetaData>();
/**
* The IIOP metadata, configured in the assembly descriptor.
*/
private IIOPMetaData iiopMetaData;
/**
* The fully qualified name
*/
private String name = null;
public EjbIIOPService(final Map<String, SkeletonStrategy> beanMethodMap, final String[] beanRepositoryIds,
final Map<String, SkeletonStrategy> homeMethodMap, final String[] homeRepositoryIds,
final boolean useQualifiedName, final IIOPMetaData iiopMetaData, final Module module) {
this.useQualifiedName = useQualifiedName;
this.module = module;
this.beanMethodMap = Collections.unmodifiableMap(beanMethodMap);
this.beanRepositoryIds = beanRepositoryIds;
this.homeMethodMap = Collections.unmodifiableMap(homeMethodMap);
this.homeRepositoryIds = homeRepositoryIds;
this.iiopMetaData = iiopMetaData;
}
@Override
public synchronized void start(final StartContext startContext) throws StartException {
try {
final RiverMarshallerFactory factory = new RiverMarshallerFactory();
final MarshallingConfiguration configuration = new MarshallingConfiguration();
configuration.setClassResolver(new FilteringClassResolver(ModularClassResolver.getInstance(serviceModuleLoaderInjectedValue.getValue())));
this.configuration = configuration;
this.factory = factory;
final TransactionManager jtsTransactionManager = transactionManagerInjectedValue.getValue().getTransactionManager();
assert ! (jtsTransactionManager instanceof ContextTransactionManager);
// Should create a CORBA interface repository?
final boolean interfaceRepositorySupported = false;
// Build binding name of the bean.
final EJBComponent component = ejbComponentInjectedValue.getValue();
final String earApplicationName = component.getEarApplicationName();
if (iiopMetaData != null && iiopMetaData.getBindingName() != null) {
name = iiopMetaData.getBindingName();
} else if (useQualifiedName) {
if (component.getDistinctName() == null || component.getDistinctName().isEmpty()) {
name = earApplicationName == null || earApplicationName.isEmpty() ? "" : earApplicationName + "/";
name = name + component.getModuleName() + "/" + component.getComponentName();
} else {
name = earApplicationName == null || earApplicationName.isEmpty() ? "" : earApplicationName + "/";
name = name + component.getModuleName() + "/" + component.getDistinctName() + "/" + component.getComponentName();
}
} else {
name = component.getComponentName();
}
name = name.replace(".", "_");
EjbLogger.DEPLOYMENT_LOGGER.iiopBindings(component.getComponentName(), component.getModuleName(),
name);
final ORB orb = this.orb.getValue();
if (interfaceRepositorySupported) {
// Create a CORBA interface repository for the enterprise bean
iri = new InterfaceRepository(orb, irPoa.getValue(), name);
// Add bean interface info to the interface repository
iri.mapClass(remoteView.getValue().getViewClass());
iri.mapClass(homeView.getValue().getViewClass());
iri.finishBuild();
EjbLogger.ROOT_LOGGER.cobraInterfaceRepository(name, orb.object_to_string(iri.getReference()));
}
IORSecurityConfigMetaData iorSecurityConfigMetaData = this.iorSecConfigMetaData.getOptionalValue();
if (this.iiopMetaData != null && this.iiopMetaData.getIorSecurityConfigMetaData() != null)
iorSecurityConfigMetaData = this.iiopMetaData.getIorSecurityConfigMetaData();
// Create security policies if security metadata has been provided.
List<Policy> policyList = new ArrayList<Policy>();
if (iorSecurityConfigMetaData != null) {
// Create csiv2Policy for both home and remote containing IorSecurityConfigMetadata.
final Any secPolicy = orb.create_any();
secPolicy.insert_Value(iorSecurityConfigMetaData);
Policy csiv2Policy = orb.create_policy(CSIv2Policy.TYPE, secPolicy);
policyList.add(csiv2Policy);
// Add ZeroPortPolicy if ssl is required (it ensures home and remote IORs will have port 0 in the primary address).
boolean sslRequired = false;
if (iorSecurityConfigMetaData != null && iorSecurityConfigMetaData.getTransportConfig() != null) {
IORTransportConfigMetaData tc = iorSecurityConfigMetaData.getTransportConfig();
sslRequired = IORTransportConfigMetaData.INTEGRITY_REQUIRED.equals(tc.getIntegrity())
|| IORTransportConfigMetaData.CONFIDENTIALITY_REQUIRED.equals(tc.getConfidentiality())
|| IORTransportConfigMetaData.ESTABLISH_TRUST_IN_CLIENT_REQUIRED.equals(tc.getEstablishTrustInClient());
}
if(sslRequired){
policyList.add(ZeroPortPolicy.getPolicy());
}
}
String securityDomainName = "CORBA_REMOTE"; //TODO: what should this default to
if (component.getSecurityMetaData() != null) {
securityDomainName = component.getSecurityMetaData().getSecurityDomainName();
}
Policy[] policies = policyList.toArray(new Policy[policyList.size()]);
// If there is an interface repository, then get the homeInterfaceDef from the IR
InterfaceDef homeInterfaceDef = null;
if (iri != null) {
Repository ir = iri.getReference();
homeInterfaceDef = InterfaceDefHelper.narrow(ir.lookup_id(homeRepositoryIds[0]));
}
// Get the POACurrent object
Current poaCurrent = CurrentHelper.narrow(orb.resolve_initial_references("POACurrent"));
// Instantiate home servant, bind it to the servant registry, and create CORBA reference to the EJBHome.
final EjbCorbaServant homeServant = new EjbCorbaServant(poaCurrent, homeMethodMap, homeRepositoryIds, homeInterfaceDef,
orb, homeView.getValue(), factory, configuration, jtsTransactionManager, module.getClassLoader(), true, securityDomainName,
component.getSecurityDomain());
homeServantRegistry = poaRegistry.getValue().getRegistryWithPersistentPOAPerServant();
ReferenceFactory homeReferenceFactory = homeServantRegistry.bind(homeServantName(name), homeServant, policies);
final org.omg.CORBA.Object corbaRef = homeReferenceFactory.createReference(homeRepositoryIds[0]);
//we do this twice to force eager dynamic stub creation
ejbHome = (EJBHome) PortableRemoteObject.narrow(corbaRef, EJBHome.class);
final HomeHandleImplIIOP homeHandle = new HomeHandleImplIIOP(orb.object_to_string(corbaRef));
homeServant.setHomeHandle(homeHandle);
// Initialize beanPOA and create metadata
// This is a session bean (lifespan: transient)
beanServantRegistry = poaRegistry.getValue().getRegistryWithTransientPOAPerServant();
if (component instanceof StatelessSessionComponent) {
// Stateless session bean
ejbMetaData = new EJBMetaDataImplIIOP(remoteView.getValue().getViewClass(), homeView.getValue().getViewClass(), null, true, true, homeHandle);
} else {
// Stateful session bean
ejbMetaData = new EJBMetaDataImplIIOP(remoteView.getValue().getViewClass(), homeView.getValue().getViewClass(), null, true, false, homeHandle);
}
homeServant.setEjbMetaData(ejbMetaData);
// If there is an interface repository, then get the beanInterfaceDef from the IR
InterfaceDef beanInterfaceDef = null;
if (iri != null) {
final Repository ir = iri.getReference();
beanInterfaceDef = InterfaceDefHelper.narrow(ir.lookup_id(beanRepositoryIds[0]));
}
// Instantiate the ejb object servant and bind it to the servant registry.
final EjbCorbaServant beanServant = new EjbCorbaServant(poaCurrent, beanMethodMap, beanRepositoryIds,
beanInterfaceDef, orb, remoteView.getValue(), factory, configuration, jtsTransactionManager,
module.getClassLoader(), false, securityDomainName, component.getSecurityDomain());
beanReferenceFactory = beanServantRegistry.bind(beanServantName(name), beanServant, policies);
// Register bean home in local CORBA naming context
rebind(corbaNamingContext.getValue(), name, corbaRef);
EjbLogger.ROOT_LOGGER.debugf("Home IOR for %s bound to %s in CORBA naming service", component.getComponentName(), this.name);
//now eagerly force stub creation, so de-serialization of stubs will work correctly
final ClassLoader cl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(module.getClassLoader());
try {
DynamicStubFactoryFactory.makeStubClass(homeView.getValue().getViewClass());
} catch (Exception e) {
EjbLogger.ROOT_LOGGER.dynamicStubCreationFailed(homeView.getValue().getViewClass().getName(), e);
}
try {
DynamicStubFactoryFactory.makeStubClass(remoteView.getValue().getViewClass());
} catch (Exception e) {
EjbLogger.ROOT_LOGGER.dynamicStubCreationFailed(remoteView.getValue().getViewClass().getName(), e);
}
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(cl);
}
} catch (Exception e) {
throw new StartException(e);
}
}
@Override
public synchronized void stop(final StopContext context) {
// Get local (in-VM) CORBA naming context
final NamingContextExt corbaContext = corbaNamingContext.getValue();
// Unregister bean home from local CORBA naming context
try {
NameComponent[] name = corbaContext.to_name(this.name);
corbaContext.unbind(name);
} catch (InvalidName invalidName) {
EjbLogger.ROOT_LOGGER.cannotUnregisterEJBHomeFromCobra(invalidName);
} catch (NotFound notFound) {
EjbLogger.ROOT_LOGGER.cannotUnregisterEJBHomeFromCobra(notFound);
} catch (CannotProceed cannotProceed) {
EjbLogger.ROOT_LOGGER.cannotUnregisterEJBHomeFromCobra(cannotProceed);
}
// Deactivate the home servant and the bean servant
try {
homeServantRegistry.unbind(homeServantName(this.name));
} catch (Exception e) {
EjbLogger.ROOT_LOGGER.cannotDeactivateHomeServant(e);
}
try {
beanServantRegistry.unbind(beanServantName(this.name));
} catch (Exception e) {
EjbLogger.ROOT_LOGGER.cannotDeactivateBeanServant(e);
}
if (iri != null) {
// Deactivate the interface repository
iri.shutdown();
}
this.name = null;
}
/**
* Returns a corba reference for the given locator
*
* @param locator The locator
* @return The corba reference
*/
public org.omg.CORBA.Object referenceForLocator(final EJBLocator<?> locator) {
final EJBComponent ejbComponent = ejbComponentInjectedValue.getValue();
try {
final String earApplicationName = ejbComponent.getEarApplicationName() == null ? "" : ejbComponent.getEarApplicationName();
if (locator.getBeanName().equals(ejbComponent.getComponentName()) &&
locator.getAppName().equals(earApplicationName) &&
locator.getModuleName().equals(ejbComponent.getModuleName()) &&
locator.getDistinctName().equals(ejbComponent.getDistinctName())) {
if (locator instanceof EJBHomeLocator) {
return (org.omg.CORBA.Object) ejbHome;
} else if (locator instanceof StatelessEJBLocator) {
return beanReferenceFactory.createReference(beanRepositoryIds[0]);
} else if (locator instanceof StatefulEJBLocator) {
try (final Marshaller marshaller = factory.createMarshaller(configuration)) {
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
marshaller.start(new OutputStreamByteOutput(stream));
marshaller.writeObject(((StatefulEJBLocator<?>) locator).getSessionId());
marshaller.flush();
return beanReferenceFactory.createReferenceWithId(stream.toByteArray(), beanRepositoryIds[0]);
}
} else if (locator instanceof EntityEJBLocator) {
try (final Marshaller marshaller = factory.createMarshaller(configuration)) {
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
marshaller.start(new OutputStreamByteOutput(stream));
marshaller.writeObject(((EntityEJBLocator<?>) locator).getPrimaryKey());
marshaller.flush();
return beanReferenceFactory.createReferenceWithId(stream.toByteArray(), beanRepositoryIds[0]);
}
}
throw EjbLogger.ROOT_LOGGER.unknownEJBLocatorType(locator);
} else {
throw EjbLogger.ROOT_LOGGER.incorrectEJBLocatorForBean(locator, ejbComponent.getComponentName());
}
} catch (Exception e) {
throw EjbLogger.ROOT_LOGGER.couldNotCreateCorbaObject(e, locator);
}
}
/**
* Gets a handle for the given ejb locator.
*
* @param locator The locator to get the handle for
* @return The {@link org.jboss.ejb.client.EJBHandle} or {@link org.jboss.ejb.client.EJBHomeHandle}
*/
public Object handleForLocator(final EJBLocator<?> locator) {
final org.omg.CORBA.Object reference = referenceForLocator(locator);
if(locator instanceof EJBHomeLocator) {
return new HomeHandleImplIIOP(orb.getValue().object_to_string(reference));
}
return new HandleImplIIOP(orb.getValue().object_to_string(reference));
}
/**
* (Re)binds an object to a name in a given CORBA naming context, creating
* any non-existent intermediate contexts along the way.
* <p/>
* This method is synchronized on the class object, if multiple services attempt to bind the
* same context name at once it will fail
*
* @param ctx a reference to the COSNaming service.
* @param strName the name under which the CORBA object is to be bound.
* @param obj the CORBA object to be bound.
* @throws Exception if an error occurs while binding the object.
*/
public static synchronized void rebind(final NamingContextExt ctx, final String strName, final org.omg.CORBA.Object obj) throws Exception {
final NameComponent[] name = ctx.to_name(strName);
NamingContext intermediateCtx = ctx;
for (int i = 0; i < name.length - 1; i++) {
final NameComponent[] relativeName = new NameComponent[]{name[i]};
try {
intermediateCtx = NamingContextHelper.narrow(
intermediateCtx.resolve(relativeName));
} catch (NotFound e) {
intermediateCtx = intermediateCtx.bind_new_context(relativeName);
}
}
intermediateCtx.rebind(new NameComponent[]{name[name.length - 1]}, obj);
}
/**
* Returns the name of a home servant for an EJB with the given jndiName.
* The home servant will be bound to this name in a ServantRegistry.
*/
private static String homeServantName(final String jndiName) {
return jndiName + "/home";
}
/**
* Returns the name of a bean servant for an EJB with the given jndiName.
* The bean servant will be bound to this name in a ServantRegistry.
*/
private static String beanServantName(final String jndiName) {
return jndiName + "/remote";
}
@Override
public EjbIIOPService getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
public InjectedValue<ComponentView> getRemoteView() {
return remoteView;
}
public InjectedValue<ComponentView> getHomeView() {
return homeView;
}
public InjectedValue<EJBComponent> getEjbComponentInjectedValue() {
return ejbComponentInjectedValue;
}
public InjectedValue<ORB> getOrb() {
return orb;
}
public InjectedValue<NamingContextExt> getCorbaNamingContext() {
return corbaNamingContext;
}
public InjectedValue<POARegistry> getPoaRegistry() {
return poaRegistry;
}
public InjectedValue<POA> getIrPoa() {
return irPoa;
}
public InjectedValue<ServiceModuleLoader> getServiceModuleLoaderInjectedValue() {
return serviceModuleLoaderInjectedValue;
}
public InjectedValue<IORSecurityConfigMetaData> getIORSecConfigMetaDataInjectedValue() {
return iorSecConfigMetaData;
}
public InjectedValue<TransactionManagerService> getTransactionManagerInjectedValue() {
return transactionManagerInjectedValue;
}
// ModularClassResolver is final so we have to wrap it
private static final class FilteringClassResolver implements ClassResolver {
private final ClassResolver delegate;
private FilteringClassResolver(ClassResolver delegate) {
this.delegate = delegate;
}
@Override
public void annotateClass(Marshaller marshaller, Class<?> clazz) throws IOException {
delegate.annotateClass(marshaller, clazz);
}
@Override
public void annotateProxyClass(Marshaller marshaller, Class<?> proxyClass) throws IOException {
delegate.annotateProxyClass(marshaller, proxyClass);
}
@Override
public String getClassName(Class<?> clazz) throws IOException {
return delegate.getClassName(clazz);
}
@Override
public String[] getProxyInterfaces(Class<?> proxyClass) throws IOException {
return delegate.getProxyInterfaces(proxyClass);
}
@Override
public Class<?> resolveClass(Unmarshaller unmarshaller, String name, long serialVersionUID) throws IOException, ClassNotFoundException {
checkFilter(name);
return delegate.resolveClass(unmarshaller, name, serialVersionUID);
}
@Override
public Class<?> resolveProxyClass(Unmarshaller unmarshaller, String[] interfaces) throws IOException, ClassNotFoundException {
for (String name : interfaces) {
checkFilter(name);
}
return delegate.resolveProxyClass(unmarshaller, interfaces);
}
private void checkFilter(String className) throws InvalidClassException {
// We only resolve org.jboss.ejb.client.SessionId impls in its package.
// The SessionId abstract class is public but its constructor is package
// protected, so the only valid impls are in that package.
// The JBoss Marshalling 'Configuration' object instances that use this
// ClassResolver are only meant to marshal/unmarshal SessionId objects.
if (!className.startsWith("org.jboss.ejb.client.")) {
throw EjbLogger.REMOTE_LOGGER.cannotResolveFilteredClass(className);
}
}
}
}
| 28,588 | 42.983077 | 159 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/iiop/ServantRegistry.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ejb3.iiop;
import org.omg.CORBA.Policy;
import org.omg.PortableServer.Servant;
/**
* Interface of a registry for CORBA servants.
*
* @author <a href="mailto:[email protected]">Francisco Reverbel</a>
* @version $Revision: 81018 $
*/
public interface ServantRegistry {
/**
* Binds <code>name</code> to <code>servant</code>, with the given
* <code>policies</code>. Returns a <code>ReferenceFactory</code>
* that should be used to create CORBA references to the object(s)
* implemented by <code>servant</code>. A CORBA reference created by this
* factory will contain <code>name</code> as the servant id embedded in the
* reference. If the servant implements more than one CORBA object,
* references for such objects should be created by the
* <code>ReferenceFactory</code> method
* <code>createReferenceWithId()</code>, which takes an <code>id</code>
* parameter to distinguish among the objects implemented by the same
* servant. Otherwise (if the servant implements a single CORBA object)
* the method <code>createReference()</code> should be used.
*/
ReferenceFactory bind(String name, Servant servant, Policy[] policies) throws Exception;
/**
* Binds <code>name</code> to <code>servant</code>. Returns a
* <code>ReferenceFactory</code> that should be used to create CORBA
* references to the object(s) implemented by <code>servant</code>.
* For the usage of this <code>ReferenceFactory</code>, see method
* above.
*/
ReferenceFactory bind(String name, Servant servant) throws Exception;
/**
* Unbinds the servant bound to <code>name</code>.
*/
void unbind(String name) throws Exception;
}
| 2,786 | 41.227273 | 92 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/iiop/EjbIIOPTransactionInterceptor.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.ejb3.iiop;
import jakarta.ejb.TransactionAttributeType;
import jakarta.transaction.Transaction;
import org.jboss.as.ee.component.Component;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.metadata.ejb.spec.MethodInterfaceType;
import org.wildfly.iiop.openjdk.tm.ForeignTransaction;
import org.wildfly.iiop.openjdk.tm.TxServerInterceptor;
/**
* @author Stuart Douglas
*/
public class EjbIIOPTransactionInterceptor implements Interceptor {
public static final InterceptorFactory FACTORY = new ImmediateInterceptorFactory(new EjbIIOPTransactionInterceptor());
@Override
public Object processInvocation(final InterceptorContext invocation) throws Exception {
// Do we have a foreign transaction context?
Transaction tx = TxServerInterceptor.getCurrentTransaction();
if (tx instanceof ForeignTransaction) {
final EJBComponent component = (EJBComponent) invocation.getPrivateData(Component.class);
//for timer invocations there is no view, so the methodInf is attached directly
//to the context. Otherwise we retrieve it from the invoked view
MethodInterfaceType methodIntf = invocation.getPrivateData(MethodInterfaceType.class);
if (methodIntf == null) {
final ComponentView componentView = invocation.getPrivateData(ComponentView.class);
if (componentView != null) {
methodIntf = componentView.getPrivateData(MethodInterfaceType.class);
} else {
methodIntf = MethodInterfaceType.Bean;
}
}
final TransactionAttributeType attr = component.getTransactionAttributeType(methodIntf, invocation.getMethod());
if (attr != TransactionAttributeType.NOT_SUPPORTED && attr != TransactionAttributeType.REQUIRES_NEW) {
throw EjbLogger.ROOT_LOGGER.transactionPropagationNotSupported();
}
}
return invocation.proceed();
}
}
| 3,346 | 44.22973 | 124 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/iiop/ReferenceFactory.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ejb3.iiop;
import org.omg.PortableServer.POA;
/**
* Interface of a CORBA reference factory. Such a factory encapsulates a POA
* and provides reference creation methods.
*
* @author <a href="mailto:[email protected]">Francisco Reverbel</a>
*/
public interface ReferenceFactory {
/**
* Creates a reference with a null id in its "reference data" and
* with object type information given by the <code>interfId</code>
* parameter.
*/
org.omg.CORBA.Object createReference(String inferfId) throws Exception;
/**
* Creates a reference with the specified <code>id</code> in its
* "reference data" and with object type information given by the
* <code>interfId</code> parameter.
*/
org.omg.CORBA.Object createReferenceWithId(final byte[] id, String interfId)
throws Exception;
/**
* Returns a reference to the POA encapsulated by this
* <code>ReferenceFactory</code>.
*/
POA getPOA();
}
| 2,034 | 35.339286 | 80 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/iiop/RemoteObjectSubstitutionService.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.ejb3.iiop;
import org.jboss.as.ejb3.deployment.DeploymentRepository;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.deployment.DeploymentModuleIdentifier;
import org.jboss.as.ejb3.deployment.EjbDeploymentInformation;
import org.jboss.as.ejb3.deployment.ModuleDeployment;
import org.jboss.ejb.client.AbstractEJBMetaData;
import org.jboss.ejb.client.EJBHomeLocator;
import org.jboss.ejb.client.EntityEJBMetaData;
import org.jboss.javax.rmi.RemoteObjectSubstitution;
import org.jboss.ejb.client.EJBClient;
import org.jboss.ejb.client.EJBHandle;
import org.jboss.ejb.client.EJBHomeHandle;
import org.jboss.ejb.client.EJBLocator;
import org.jboss.ejb.client.EJBMetaDataImpl;
import org.jboss.ejb.iiop.EJBMetaDataImplIIOP;
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 jakarta.ejb.HomeHandle;
/**
* @author Stuart Douglas
*/
public class RemoteObjectSubstitutionService implements RemoteObjectSubstitution, Service<RemoteObjectSubstitution> {
private final InjectedValue<DeploymentRepository> deploymentRepositoryInjectedValue = new InjectedValue<DeploymentRepository>();
public static final ServiceName SERVICE_NAME = ServiceName.JBOSS.append("ejb3", "iiop", "remoteObjectSubstitution");
@Override
public Object writeReplaceRemote(final Object object) {
final DeploymentRepository deploymentRepository = deploymentRepositoryInjectedValue.getOptionalValue();
//if we are not started yet just return
if (deploymentRepository == null) {
return object;
}
if (EJBClient.isEJBProxy(object)) {
return createIIOPReferenceForBean(object, deploymentRepository);
} else if (object instanceof EJBHandle) {
final EJBHandle<?> handle = (EJBHandle<?>) object;
final EJBLocator<?> locator = handle.getLocator();
final EjbIIOPService factory = serviceForLocator(locator, deploymentRepository);
if (factory != null) {
return factory.handleForLocator(locator);
}
} else if (object instanceof EJBHomeHandle) {
final EJBHomeHandle<?> handle = (EJBHomeHandle<?>) object;
final EJBLocator<?> locator = handle.getLocator();
final EjbIIOPService factory = serviceForLocator(locator, deploymentRepository);
if (factory != null) {
return factory.handleForLocator(locator);
}
} else if (object instanceof EJBMetaDataImpl) {
final EJBMetaDataImpl metadata = (EJBMetaDataImpl) object;
Class<?> pk = null;
if (!metadata.isSession()) {
pk = metadata.getPrimaryKeyClass();
}
final EJBLocator<?> locator = EJBClient.getLocatorFor(metadata.getEJBHome());
final EjbIIOPService factory = serviceForLocator(locator, deploymentRepository);
if(factory != null) {
return new EJBMetaDataImplIIOP(metadata.getRemoteInterfaceClass(), metadata.getHomeInterfaceClass(), pk, metadata.isSession(), metadata.isStatelessSession(), (HomeHandle) factory.handleForLocator(locator));
}
} else if (object instanceof AbstractEJBMetaData) {
final AbstractEJBMetaData<?, ?> metadata = (AbstractEJBMetaData<?, ?>) object;
final EJBHomeLocator<?> locator = metadata.getHomeLocator();
final EjbIIOPService factory = serviceForLocator(locator, deploymentRepository);
Class<?> pk = metadata instanceof EntityEJBMetaData ? metadata.getPrimaryKeyClass() : null;
if(factory != null) {
return new EJBMetaDataImplIIOP(metadata.getRemoteInterfaceClass(), metadata.getHomeInterfaceClass(), pk, metadata.isSession(), metadata.isStatelessSession(), (HomeHandle) factory.handleForLocator(locator));
}
}
return object;
}
private Object createIIOPReferenceForBean(Object object, DeploymentRepository deploymentRepository) {
EJBLocator<? extends Object> locator;
try {
locator = EJBClient.getLocatorFor(object);
} catch (Exception e) {
//not an Jakarta Enterprise Beans proxy
locator = null;
}
if (locator != null) {
final EjbIIOPService factory = serviceForLocator(locator, deploymentRepository);
if (factory != null) {
return factory.referenceForLocator(locator);
}
}
return object;
}
private EjbIIOPService serviceForLocator(final EJBLocator<?> locator, DeploymentRepository deploymentRepository) {
final ModuleDeployment module = deploymentRepository.getModules().get(new DeploymentModuleIdentifier(locator.getAppName(), locator.getModuleName(), locator.getDistinctName()));
if (module == null) {
EjbLogger.ROOT_LOGGER.couldNotFindEjbForLocatorIIOP(locator);
return null;
}
final EjbDeploymentInformation ejb = module.getEjbs().get(locator.getBeanName());
if (ejb == null) {
EjbLogger.ROOT_LOGGER.couldNotFindEjbForLocatorIIOP(locator);
return null;
}
final EjbIIOPService factory = ejb.getIorFactory();
if (factory == null) {
EjbLogger.ROOT_LOGGER.ejbNotExposedOverIIOP(locator);
return null;
}
return factory;
}
@Override
public void start(final StartContext context) throws StartException {
}
@Override
public void stop(final StopContext context) {
}
@Override
public RemoteObjectSubstitution getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
public InjectedValue<DeploymentRepository> getDeploymentRepositoryInjectedValue() {
return deploymentRepositoryInjectedValue;
}
}
| 7,103 | 42.851852 | 222 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/iiop/stub/IIOPStubCompiler.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ejb3.iiop.stub;
// because it calls some ProxyAssembler
// methods that currently are package
// accessible
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.rmi.RemoteException;
import org.jboss.as.server.deployment.ModuleClassFactory;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.classfilewriter.ClassFile;
import org.jboss.classfilewriter.ClassMethod;
import org.jboss.classfilewriter.code.CodeAttribute;
import org.jboss.classfilewriter.util.Boxing;
import org.jboss.classfilewriter.util.DescriptorUtils;
import org.wildfly.iiop.openjdk.rmi.AttributeAnalysis;
import org.wildfly.iiop.openjdk.rmi.ExceptionAnalysis;
import org.wildfly.iiop.openjdk.rmi.InterfaceAnalysis;
import org.wildfly.iiop.openjdk.rmi.OperationAnalysis;
import org.wildfly.iiop.openjdk.rmi.RMIIIOPViolationException;
import org.wildfly.iiop.openjdk.rmi.marshal.CDRStream;
import org.wildfly.iiop.openjdk.rmi.marshal.strategy.StubStrategy;
/**
* Utility class responsible for the dynamic generation of bytecodes of
* IIOP stub classes.
*
* @author Stuart Douglas
* @author <a href="mailto:[email protected]">Francisco Reverbel</a>
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class IIOPStubCompiler {
public static final String ID_FIELD_NAME = "$ids";
/**
* Returns the name of the stub strategy field associated with the method
* whose index is <code>methodIndex</code>.
*/
private static String strategy(int methodIndex) {
return "$s" + methodIndex;
}
/**
* Returns the name of static initializer method associated with the method
* whose index is <code>methodIndex</code>.
*/
private static String init(int methodIndex) {
return "$i" + methodIndex;
}
/**
* Generates the code of a given method within a stub class.
*
* @param asm the <code>ProxyAssembler</code> used to assemble
* the method code
* @param superclass the superclass of the stub class within which the
* method will be generated
* @param m a <code>Method</code> instance describing the
* method declaration by an RMI/IDL interface
* @param idlName a string with the method name mapped to IDL
* @param strategyField a string with the name of the strategy field that
* will be associated with the generated method
* @param initMethod a string with the name of the static initialization
* method that will be associated with the generated
* method.
*/
private static void generateMethodCode(ClassFile asm,
Class<?> superclass,
Method m,
String idlName,
String strategyField,
String initMethod) {
Class<?> returnType = m.getReturnType();
Class<?>[] paramTypes = m.getParameterTypes();
Class<?>[] exceptions = m.getExceptionTypes();
// Generate a static field with the StubStrategy for the method
asm.addField(Modifier.PRIVATE + Modifier.STATIC, strategyField, StubStrategy.class);
// Generate the method code
final CodeAttribute ca = asm.addMethod(m).getCodeAttribute();
// The method code issues a call
// super.invoke*(idlName, strategyField, args)
ca.aload(0);
ca.ldc(idlName);
ca.getstatic(asm.getName(), strategyField, StubStrategy.class);
// Push args
if (paramTypes.length == 0) {
ca.iconst(0);
ca.anewarray(Object.class.getName());
//asm.pushField(Util.class, "NOARGS");
} else {
ca.iconst(paramTypes.length);
ca.anewarray(Object.class.getName());
int index = 1;
for (int j = 0; j < paramTypes.length; j++) {
Class<?> type = paramTypes[j];
ca.dup();
ca.iconst(j);
if (!type.isPrimitive()) {
// object or array
ca.aload(index);
} else if (type.equals(double.class)) {
ca.dload(index);
Boxing.boxDouble(ca);
index++;
} else if (type.equals(long.class)) {
ca.lload(index);
Boxing.boxLong(ca);
index++;
} else if (type.equals(float.class)) {
ca.fload(index);
Boxing.boxFloat(ca);
} else {
ca.iload(index);
Boxing.boxIfNessesary(ca, DescriptorUtils.makeDescriptor(type));
}
index++;
ca.aastore();
}
}
// Generate the call to an invoke* method ot the superclass
String invoke = "invoke";
String ret = "Ljava/lang/Object;";
if (returnType.isPrimitive() && returnType != Void.TYPE) {
String typeName = returnType.getName();
invoke += (Character.toUpperCase(typeName.charAt(0))
+ typeName.substring(1));
ret = DescriptorUtils.makeDescriptor(returnType);
}
ca.invokevirtual(superclass.getName(), invoke, "(Ljava/lang/String;Lorg/wildfly/iiop/openjdk/rmi/marshal/strategy/StubStrategy;[Ljava/lang/Object;)" + ret);
if (!returnType.isPrimitive() && returnType != Object.class) {
ca.checkcast(returnType);
}
ca.returnInstruction();
// Generate a static method that initializes the method's strategy field
final CodeAttribute init = asm.addMethod(Modifier.PRIVATE + Modifier.STATIC,initMethod, "V").getCodeAttribute();
int i;
int len;
// Push first argument for StubStrategy constructor:
// array with abbreviated names of the param marshallers
len = paramTypes.length;
init.iconst(len);
init.anewarray(String.class.getName());
for (i = 0; i < len; i++) {
init.dup();
init.iconst(i);
init.ldc(CDRStream.abbrevFor(paramTypes[i]));
init.aastore();
}
// Push second argument for StubStrategy constructor:
// array with exception repository ids
len = exceptions.length;
int n = 0;
for (i = 0; i < len; i++) {
if (!RemoteException.class.isAssignableFrom(exceptions[i])) {
n++;
}
}
init.iconst(n);
init.anewarray(String.class.getName());
try {
int j = 0;
for (i = 0; i < len; i++) {
if (!RemoteException.class.isAssignableFrom(exceptions[i])) {
init.dup();
init.iconst(j);
init.ldc(
ExceptionAnalysis.getExceptionAnalysis(exceptions[i])
.getExceptionRepositoryId());
init.aastore();
j++;
}
}
} catch (RMIIIOPViolationException e) {
throw EjbLogger.ROOT_LOGGER.exceptionRepositoryNotFound(exceptions[i].getName(), e.getLocalizedMessage());
}
// Push third argument for StubStrategy constructor:
// array with exception class names
init.iconst(n);
init.anewarray(String.class.getName());
int j = 0;
for (i = 0; i < len; i++) {
if (!RemoteException.class.isAssignableFrom(exceptions[i])) {
init.dup();
init.iconst(j);
init.ldc(exceptions[i].getName());
init.aastore();
j++;
}
}
// Push fourth argument for StubStrategy constructor:
// abbreviated name of the return value marshaller
init.ldc(CDRStream.abbrevFor(returnType));
// Push fifth argument for StubStrategy constructor:
// null (no ClassLoader specified)
init.aconstNull();
// Constructs the StubStrategy
init.invokestatic(StubStrategy.class.getName(), "forMethod", "([Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;Ljava/lang/ClassLoader;)Lorg/wildfly/iiop/openjdk/rmi/marshal/strategy/StubStrategy;");
// Set the strategy field of this stub class
init.putstatic(asm.getName(), strategyField, StubStrategy.class);
init.returnInstruction();
}
/**
* Generates the bytecodes of a stub class for a given interface.
*
* @param interfaceAnalysis an <code>InterfaceAnalysis</code> instance
* describing the RMI/IIOP interface to be
* implemented by the stub class
* @param superclass the superclass of the stub class
* @param stubClassName the name of the stub class
* @return a byte array with the generated bytecodes.
*/
private static ClassFile generateCode(InterfaceAnalysis interfaceAnalysis,
Class<?> superclass, String stubClassName) {
final ClassFile asm =
new ClassFile(stubClassName, superclass.getName(), null, ModuleClassFactory.INSTANCE, interfaceAnalysis.getCls().getName());
int methodIndex = 0;
AttributeAnalysis[] attrs = interfaceAnalysis.getAttributes();
for (int i = 0; i < attrs.length; i++) {
OperationAnalysis op = attrs[i].getAccessorAnalysis();
generateMethodCode(asm, superclass, op.getMethod(), op.getIDLName(),
strategy(methodIndex), init(methodIndex));
methodIndex++;
op = attrs[i].getMutatorAnalysis();
if (op != null) {
generateMethodCode(asm, superclass,
op.getMethod(), op.getIDLName(),
strategy(methodIndex), init(methodIndex));
methodIndex++;
}
}
final OperationAnalysis[] ops = interfaceAnalysis.getOperations();
for (int i = 0; i < ops.length; i++) {
generateMethodCode(asm, superclass,
ops[i].getMethod(), ops[i].getIDLName(),
strategy(methodIndex), init(methodIndex));
methodIndex++;
}
// Generate the constructor
final ClassMethod ctor = asm.addMethod(Modifier.PUBLIC, "<init>", "V");
ctor.getCodeAttribute().aload(0);
ctor.getCodeAttribute().invokespecial(superclass.getName(), "<init>", "()V");
ctor.getCodeAttribute().returnInstruction();
// Generate the method _ids(), declared as abstract in ObjectImpl
final String[] ids = interfaceAnalysis.getAllTypeIds();
asm.addField(Modifier.PRIVATE + Modifier.STATIC, ID_FIELD_NAME, String[].class);
final CodeAttribute idMethod = asm.addMethod(Modifier.PUBLIC + Modifier.FINAL, "_ids", "[Ljava/lang/String;").getCodeAttribute();
idMethod.getstatic(stubClassName, ID_FIELD_NAME, "[Ljava/lang/String;");
idMethod.returnInstruction();
// Generate the static initializer
final CodeAttribute clinit = asm.addMethod(Modifier.STATIC, "<clinit>", "V").getCodeAttribute();
clinit.iconst(ids.length);
clinit.anewarray(String.class.getName());
for (int i = 0; i < ids.length; i++) {
clinit.dup();
clinit.iconst(i);
clinit.ldc(ids[i]);
clinit.aastore();
}
clinit.putstatic(stubClassName, ID_FIELD_NAME, "[Ljava/lang/String;");
int n = methodIndex; // last methodIndex + 1
for (methodIndex = 0; methodIndex < n; methodIndex++) {
clinit.invokestatic(stubClassName, init(methodIndex), "()V");
}
clinit.returnInstruction();
return asm;
}
/**
* Generates the bytecodes of a stub class for a given interface.
*
* @param interfaceAnalysis an <code>InterfaceAnalysis</code> instance
* describing the RMI/IIOP interface to be
* implemented by the stub class
* @param superclass the superclass of the stub class
* @param stubClassName the name of the stub class
* @return a byte array with the generated bytecodes.
*/
private static ClassFile makeCode(InterfaceAnalysis interfaceAnalysis,
Class<?> superclass, String stubClassName) {
ClassFile code = generateCode(interfaceAnalysis, superclass, stubClassName);
//try {
// String fname = stubClassName;
// fname = fname.substring(1 + fname.lastIndexOf('.')) + ".class";
// fname = "/tmp/" + fname;
// java.io.OutputStream cf = new java.io.FileOutputStream(fname);
// cf.write(code);
// cf.close();
// System.err.println("wrote " + fname);
//}
//catch(java.io.IOException ee) {
//}
return code;
}
// Public method ----------------------------------------------------------
/**
* Generates the bytecodes of a stub class for a given interface.
*
* @param intf RMI/IIOP interface to be implemented by the
* stub class
* @param stubClassName the name of the stub class
* @return a byte array with the generated bytecodes;
*/
public static ClassFile compile(Class<?> intf, String stubClassName) {
InterfaceAnalysis interfaceAnalysis = null;
try {
interfaceAnalysis = InterfaceAnalysis.getInterfaceAnalysis(intf);
} catch (RMIIIOPViolationException e) {
throw EjbLogger.ROOT_LOGGER.rmiIiopVoliation(e.getLocalizedMessage());
}
return makeCode(interfaceAnalysis, DynamicIIOPStub.class, stubClassName);
}
public Class<?> compileToClass(Class<?> intf, String stubClassName) {
return compile(intf, stubClassName).define(intf.getClassLoader(), intf.getProtectionDomain());
}
}
| 15,631 | 41.248649 | 237 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/iiop/stub/DynamicStubFactoryFactory.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.ejb3.iiop.stub;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.classfilewriter.ClassFile;
import com.sun.corba.se.impl.presentation.rmi.StubFactoryBase;
import com.sun.corba.se.impl.presentation.rmi.StubFactoryFactoryDynamicBase;
import com.sun.corba.se.spi.presentation.rmi.PresentationManager;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* @author Stuart Douglas
*/
public class DynamicStubFactoryFactory extends StubFactoryFactoryDynamicBase {
@Override
public PresentationManager.StubFactory makeDynamicStubFactory(final PresentationManager pm, final PresentationManager.ClassData classData, final ClassLoader classLoader) {
final Class<?> myClass = classData.getMyClass();
Class<?> theClass = makeStubClass(myClass);
return new StubFactory(classData, theClass);
}
/**
* Makes a dynamic stub class, if it does not already exist.
* @param myClass The class to create a stub for
* @return The dynamic stub class
*/
public static Class<?> makeStubClass(final Class<?> myClass) {
final String stubClassName = myClass + "_Stub";
ClassLoader cl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
if (cl == null) {
cl = myClass.getClassLoader();
}
if (cl == null) {
throw EjbLogger.ROOT_LOGGER.couldNotFindClassLoaderForStub(stubClassName);
}
Class<?> theClass;
try {
theClass = cl.loadClass(stubClassName);
} catch (ClassNotFoundException e) {
try {
final ClassFile clazz = IIOPStubCompiler.compile(myClass, stubClassName);
theClass = clazz.define(cl, myClass.getProtectionDomain());
} catch (Throwable ex) {
//there is a possibility that another thread may have defined the same class in the meantime
try {
theClass = cl.loadClass(stubClassName);
} catch (ClassNotFoundException e1) {
EjbLogger.ROOT_LOGGER.dynamicStubCreationFailed(stubClassName, ex);
throw ex;
}
}
}
return theClass;
}
private static final class StubFactory extends StubFactoryBase {
private final Class<?> clazz;
protected StubFactory(PresentationManager.ClassData classData, final Class<?> clazz) {
super(classData);
this.clazz = clazz;
}
@Override
public org.omg.CORBA.Object makeStub() {
try {
return (org.omg.CORBA.Object) clazz.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
}
| 3,927 | 38.28 | 175 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/iiop/stub/DynamicIIOPStub.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2006, 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.ejb3.iiop.stub;
import static java.security.AccessController.doPrivileged;
import java.security.PrivilegedAction;
import org.jboss.as.ejb3.logging.EjbLogger;
import javax.rmi.CORBA.Util;
import org.jboss.ejb.iiop.HandleImplIIOP;
import org.jboss.ejb.iiop.HomeHandleImplIIOP;
import org.omg.CORBA.BAD_OPERATION;
import org.omg.CORBA.SystemException;
import org.omg.CORBA.portable.ApplicationException;
import org.omg.CORBA.portable.RemarshalException;
import org.omg.CORBA_2_3.portable.InputStream;
import org.omg.CORBA_2_3.portable.OutputStream;
import org.wildfly.iiop.openjdk.rmi.marshal.strategy.StubStrategy;
/**
* Dynamically generated IIOP stub classes extend this abstract superclass,
* which extends <code>javax.rmi.CORBA.Stub</code>.
* <p/>
* A <code>DynamicIIOPStub</code> is a local proxy of a remote object. It has
* methods (<code>invoke()</code>, <code>invokeBoolean()</code>,
* <code>invokeByte()</code>, and so on) that send an IIOP request to the
* server that implements the remote object, receive the reply from the
* server, and return the results to the caller. All of these methods take
* the IDL name of the operation, a <code>StubStrategy</code> instance to
* be used for marshalling parameters and unmarshalling the result, plus an
* array of operation parameters.
*
* @author <a href="mailto:[email protected]">Francisco Reverbel</a>
* @author Stuart Douglas
*/
public abstract class DynamicIIOPStub
extends javax.rmi.CORBA.Stub {
/**
* @since 4.2.0
*/
static final long serialVersionUID = 3283717238950231589L;
/**
* My handle (either a HandleImplIIOP or a HomeHandleImplIIOP).
*/
private Object handle = null;
private static void trace(final String msg) {
if (EjbLogger.EJB3_INVOCATION_LOGGER.isTraceEnabled())
EjbLogger.EJB3_INVOCATION_LOGGER.trace(msg);
}
private static void tracef(final String format, final Object... params) {
if (EjbLogger.EJB3_INVOCATION_LOGGER.isTraceEnabled())
EjbLogger.EJB3_INVOCATION_LOGGER.tracef(format, params);
}
/**
* Constructs a <code>DynamicIIOPStub</code>.
*/
public DynamicIIOPStub() {
super();
}
/**
* Sends a request message to the server, receives the reply from the
* server, and returns an <code>Object</code> result to the caller.
*/
public Object invoke(String operationName, final StubStrategy stubStrategy, Object[] params) throws Throwable {
if (operationName.equals("_get_handle")
&& this instanceof jakarta.ejb.EJBObject) {
if (handle == null) {
handle = new HandleImplIIOP(this);
}
return handle;
} else if (operationName.equals("_get_homeHandle")
&& this instanceof jakarta.ejb.EJBHome) {
if (handle == null) {
handle = new HomeHandleImplIIOP(this);
}
return handle;
} else {
//FIXME
// all invocations are now made using remote invocation
// local invocations between two different applications cause
// ClassCastException between Stub and Interface
// (two different modules are loading the classes)
// problem was unnoticeable with JacORB because it uses
// remote invocations to all stubs to which interceptors are
// registered and a result all that JacORB always used
// remote invocations
// remote call path
// To check whether this is a local stub or not we must call
// org.omg.CORBA.portable.ObjectImpl._is_local(), and _not_
// javax.rmi.CORBA.Util.isLocal(Stub s), which in Sun's JDK
// always return false.
InputStream in = null;
try {
try {
OutputStream out =
(OutputStream) _request(operationName, true);
stubStrategy.writeParams(out, params);
tracef("sent request: %s", operationName);
in = (InputStream) _invoke(out);
if (stubStrategy.isNonVoid()) {
trace("received reply");
final InputStream finalIn = in;
return doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
return stubStrategy.readRetval(finalIn);
}
});
} else {
return null;
}
} catch (final ApplicationException ex) {
trace("got application exception");
in = (InputStream) ex.getInputStream();
final InputStream finalIn1 = in;
throw doPrivileged(new PrivilegedAction<Exception>() {
public Exception run() {
return stubStrategy.readException(ex.getId(), finalIn1);
}
});
} catch (RemarshalException ex) {
trace("got remarshal exception");
return invoke(operationName, stubStrategy, params);
}
} catch (SystemException ex) {
if (EjbLogger.EJB3_INVOCATION_LOGGER.isTraceEnabled()) {
EjbLogger.EJB3_INVOCATION_LOGGER.trace("CORBA system exception in IIOP stub", ex);
}
throw Util.mapSystemException(ex);
} finally {
_releaseReply(in);
}
}
}
/**
* Sends a request message to the server, receives the reply from the
* server, and returns a <code>boolean</code> result to the caller.
*/
public boolean invokeBoolean(String operationName, StubStrategy stubStrategy, Object[] params) throws Throwable {
return (Boolean) invoke(operationName,
stubStrategy, params);
}
/**
* Sends a request message to the server, receives the reply from the
* server, and returns a <code>byte</code> result to the caller.
*/
public byte invokeByte(String operationName, StubStrategy stubStrategy, Object[] params) throws Throwable {
return (byte) invoke(operationName,
stubStrategy, params);
}
/**
* Sends a request message to the server, receives the reply from the
* server, and returns a <code>char</code> result to the caller.
*/
public char invokeChar(String operationName, StubStrategy stubStrategy, Object[] params) throws Throwable {
return (char) invoke(operationName,
stubStrategy, params);
}
/**
* Sends a request message to the server, receives the reply from the
* server, and returns a <code>short</code> result to the caller.
*/
public short invokeShort(String operationName, StubStrategy stubStrategy, Object[] params) throws Throwable {
return (short) invoke(operationName,
stubStrategy, params);
}
/**
* Sends a request message to the server, receives the reply from the
* server, and returns an <code>int</code> result to the caller.
*/
public int invokeInt(String operationName, StubStrategy stubStrategy, Object[] params) throws Throwable {
return (int) invoke(operationName, stubStrategy, params);
}
/**
* Sends a request message to the server, receives the reply from the
* server, and returns a <code>long</code> result to the caller.
*/
public long invokeLong(String operationName, StubStrategy stubStrategy, Object[] params) throws Throwable {
return (long) invoke(operationName, stubStrategy, params);
}
/**
* Sends a request message to the server, receives the reply from the
* server, and returns a <code>float</code> result to the caller.
*/
public float invokeFloat(String operationName, StubStrategy stubStrategy, Object[] params) throws Throwable {
return (float) invoke(operationName, stubStrategy, params);
}
/**
* Sends a request message to the server, receives the reply from the
* server, and returns a <code>double</code> result to the caller.
*/
public double invokeDouble(String operationName, StubStrategy stubStrategy, Object[] params) throws Throwable {
return (double) invoke(operationName,
stubStrategy, params);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("JBossDynStub[").append(getClass().getName()).append(", ");
try {
builder.append(_orb().object_to_string(this));
} catch (BAD_OPERATION ignored) {
builder.append("*DISCONNECTED*");
}
builder.append("]");
return builder.toString();
}
}
| 10,078 | 40.138776 | 117 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/iiop/handle/SerializationHackProxy.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.ejb3.iiop.handle;
import java.io.ObjectInputStream;
import java.lang.reflect.Modifier;
import org.jboss.as.server.deployment.ModuleClassFactory;
import org.jboss.classfilewriter.ClassFile;
import org.jboss.classfilewriter.ClassMethod;
import org.jboss.classfilewriter.code.CodeAttribute;
/**
* As ObjectInputStream is broken it looks for the class loader of the last non JDK object on the stack.
* <p/>
* As this would normally be from the ejb3 module which can't see deployment modules, we instead define a proxy
* in the deployment class loader, that simply calls readObject.
*
* @author Stuart Douglas
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public abstract class SerializationHackProxy {
public static final String NAME = "org.jboss.as.ejb3.SerializationProxyHackImplementation";
public Object read(ObjectInputStream stream) {
return null;
}
public static final SerializationHackProxy proxy(final ClassLoader loader) {
Class<?> clazz;
try {
clazz = loader.loadClass(NAME);
} catch (ClassNotFoundException e) {
try {
final ClassFile file = new ClassFile(NAME, SerializationHackProxy.class.getName(), null, ModuleClassFactory.INSTANCE);
final ClassMethod method = file.addMethod(Modifier.PUBLIC, "read", "Ljava/lang/Object;", "Ljava/io/ObjectInputStream;");
final CodeAttribute codeAttribute = method.getCodeAttribute();
codeAttribute.aload(1);
codeAttribute.invokevirtual("java/io/ObjectInputStream", "readObject", "()Ljava/lang/Object;");
codeAttribute.returnInstruction();
ClassMethod ctor = file.addMethod(Modifier.PUBLIC, "<init>", "V");
ctor.getCodeAttribute().aload(0);
ctor.getCodeAttribute().invokespecial(SerializationHackProxy.class.getName(), "<init>", "()V");
ctor.getCodeAttribute().returnInstruction();
clazz = file.define(loader);
} catch (RuntimeException ex) {
try {
clazz = loader.loadClass(NAME);
} catch (ClassNotFoundException e1) {
throw ex;
}
}
}
try {
return (SerializationHackProxy) clazz.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
| 3,606 | 39.52809 | 136 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/iiop/handle/HandleDelegateImpl.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ejb3.iiop.handle;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import jakarta.ejb.EJBHome;
import jakarta.ejb.EJBObject;
import jakarta.ejb.spi.HandleDelegate;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.CORBA.Stub;
import javax.rmi.PortableRemoteObject;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.omg.CORBA.BAD_OPERATION;
import org.omg.CORBA.ORB;
import org.omg.CORBA.portable.ObjectImpl;
/**
* <P>Implementation of the jakarta.ejb.spi.HandleDelegate interface</P>
* <p/>
* <P>The HandleDelegate interface is implemented by the Jakarta Enterprise Beans container.
* It is used by portable implementations of jakarta.ejb.Handle and
* jakarta.ejb.HomeHandle. It is not used by Jakarta Enterprise Beans components or by client components.
* It provides methods to serialize and deserialize Jakarta Enterprise Beans Object and Jakarta Enterprise Beans Home
* references to streams.</P>
* <p/>
* <P>The HandleDelegate object is obtained by JNDI lookup at the reserved name
* "java:comp/HandleDelegate".</P>
*
* @author [email protected]
* @author [email protected]
*/
public class HandleDelegateImpl implements HandleDelegate {
public HandleDelegateImpl(final ClassLoader classLoader) {
proxy = SerializationHackProxy.proxy(classLoader);
}
private final SerializationHackProxy proxy;
public void writeEJBObject(final EJBObject ejbObject, final ObjectOutputStream oostream)
throws IOException {
oostream.writeObject(ejbObject);
}
public EJBObject readEJBObject(final ObjectInputStream oistream)
throws IOException, ClassNotFoundException {
final Object ejbObject = proxy.read(oistream);
reconnect(ejbObject);
return (EJBObject) PortableRemoteObject.narrow(ejbObject, EJBObject.class);
}
public void writeEJBHome(final EJBHome ejbHome, final ObjectOutputStream oostream)
throws IOException {
oostream.writeObject(ejbHome);
}
public EJBHome readEJBHome(final ObjectInputStream oistream)
throws IOException, ClassNotFoundException {
final Object ejbHome = proxy.read(oistream);
reconnect(ejbHome);
return (EJBHome) PortableRemoteObject.narrow(ejbHome, EJBHome.class);
}
protected void reconnect(Object object) throws IOException {
if (object instanceof ObjectImpl) {
try {
// Check we are still connected
ObjectImpl objectImpl = (ObjectImpl) object;
objectImpl._get_delegate();
} catch (BAD_OPERATION e) {
try {
// Reconnect
final Stub stub = (Stub) object;
final ORB orb = (ORB) new InitialContext().lookup("java:comp/ORB");
stub.connect(orb);
} catch (NamingException ne) {
throw EjbLogger.ROOT_LOGGER.failedToLookupORB();
}
}
} else {
throw EjbLogger.ROOT_LOGGER.notAnObjectImpl(object.getClass());
}
}
public static HandleDelegate getDelegate() {
try {
final InitialContext ctx = new InitialContext();
return (HandleDelegate) ctx.lookup("java:comp/HandleDelegate");
} catch (NamingException e) {
throw new RuntimeException(e);
}
}
}
| 4,536 | 37.777778 | 117 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/tx/BMTInterceptor.java | /*
* JBoss, Home of Professional Open Source
* Copyright (c) 2010, JBoss 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.ejb3.tx;
import jakarta.ejb.EJBException;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.wildfly.transaction.client.ContextTransactionManager;
/**
* Suspend an incoming tx.
*
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @author <a href="mailto:[email protected]">Ole Husgaard</a>
* @author <a href="[email protected]">Carlo de Wolf</a>
*/
public abstract class BMTInterceptor implements Interceptor {
private final EJBComponent component;
public BMTInterceptor(final EJBComponent component) {
this.component = component;
}
protected abstract Object handleInvocation(InterceptorContext invocation) throws Exception;
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
final ContextTransactionManager tm = ContextTransactionManager.getInstance();
final int oldTimeout = tm.getTransactionTimeout();
try {
Transaction oldTx = tm.suspend();
try {
return handleInvocation(context);
} finally {
if (oldTx != null) tm.resume(oldTx);
}
} finally {
// See also https://issues.jboss.org/browse/WFTC-44
tm.setTransactionTimeout(oldTimeout == ContextTransactionManager.getGlobalDefaultTransactionTimeout() ? 0 : oldTimeout);
}
}
/**
* Checks if the passed exception is an application exception. If yes, then throws back the
* exception as-is. Else, wraps the exception in a {@link jakarta.ejb.EJBException} and throws the EJBException
*
* @param ex The exception to handle
* @throws Exception Either the passed exception or an EJBException
*/
protected Exception handleException(final InterceptorContext invocation, Throwable ex) throws Exception {
ApplicationExceptionDetails ae = component.getApplicationException(ex.getClass(), invocation.getMethod());
// it's an application exception, so just throw it back as-is
if (ae != null) {
throw (Exception)ex;
}
if (ex instanceof EJBException) {
throw (EJBException) ex;
} else if(ex instanceof Exception){
throw new EJBException((Exception)ex);
} else {
throw new EJBException(new RuntimeException(ex));
}
}
protected int getCurrentTransactionTimeout(final EJBComponent component) throws SystemException {
return ContextTransactionManager.getInstance().getTransactionTimeout();
}
public EJBComponent getComponent() {
return component;
}
}
| 3,835 | 38.546392 | 132 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/tx/TimerCMTTxInterceptor.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.ejb3.tx;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.InterceptorFactory;
/**
* CMT interceptor for timer invocations. An exception is thrown if the transaction is rolled back, so the timer
* service knows to retry the timeout.
*
* @author Stuart Douglas
*/
public class TimerCMTTxInterceptor extends CMTTxInterceptor {
public static final InterceptorFactory FACTORY = new ImmediateInterceptorFactory(new TimerCMTTxInterceptor());
protected void ourTxRolledBack() {
throw EjbLogger.ROOT_LOGGER.timerInvocationRolledBack();
}
}
| 1,688 | 39.214286 | 114 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/tx/OwnableReentrantLock.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2009 Red Hat Inc. and/or its affiliates and other
* contributors as indicated by the @author tags. All rights reserved.
* 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.ejb3.tx;
import org.wildfly.common.Assert;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
* A lock that supports reentrancy based on owner (and not on current thread).
*
* @author Stuart Douglas
*/
public class OwnableReentrantLock {
private static final long serialVersionUID = 493297473462848792L;
/**
* Current owner
*/
private Object owner;
private final Object lock = new Object();
private int lockCount = 0;
private int waiters = 0;
/**
* Creates a new lock instance.
*/
public OwnableReentrantLock() {
}
public void lock(Object owner) {
Assert.checkNotNullParam("owner", owner);
synchronized (this.lock) {
if (Objects.equals(owner, this.owner)) {
lockCount++;
} else if (this.owner == null) {
this.owner = owner;
lockCount ++;
} else {
while (this.owner != null) {
try {
waiters++;
try {
lock.wait();
} finally {
--waiters;
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
this.owner = owner;
lockCount ++;
}
}
}
public boolean tryLock(long timeValue, TimeUnit timeUnit, Object owner) {
Assert.checkNotNullParam("owner", owner);
synchronized (this.lock) {
if (Objects.equals(owner, this.owner)) {
lockCount++;
return true;
} else if (this.owner == null) {
this.owner = owner;
lockCount ++;
return true;
} else {
long endTime = System.currentTimeMillis() + timeUnit.toMillis(timeValue);
while (this.owner != null && System.currentTimeMillis() < endTime) {
try {
waiters++;
try {
lock.wait(endTime - System.currentTimeMillis());
} finally {
waiters--;
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
if(this.owner == null) {
this.owner = owner;
lockCount++;
return true;
} else {
return false;
}
}
}
}
public void unlock(Object owner) {
Assert.checkNotNullParam("owner", owner);
synchronized (this.lock) {
if (!Objects.equals(owner,this.owner)) {
throw new IllegalMonitorStateException();
} else {
if (--lockCount == 0) {
this.owner = null;
if (waiters > 0) {
lock.notifyAll();
}
}
}
}
}
/**
* Returns a string identifying this lock, as well as its lock state. The state, in brackets, includes either the
* String "Unlocked" or the String "Locked by" followed by the String representation of the lock
* owner.
*
* @return a string identifying this lock, as well as its lock state.
*/
public String toString() {
return super.toString() + ((owner == null) ?
"[Unlocked]" :
"[Locked by " + owner + "]");
}
}
| 4,834 | 31.019868 | 120 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/tx/LifecycleCMTTxInterceptor.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.ejb3.tx;
import jakarta.ejb.TransactionAttributeType;
import jakarta.transaction.Status;
import jakarta.transaction.Transaction;
import org.jboss.as.ee.component.Component;
import org.jboss.as.ee.component.ComponentInterceptorFactory;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactoryContext;
import org.jboss.invocation.proxy.MethodIdentifier;
import org.jboss.metadata.ejb.spec.MethodInterfaceType;
import org.wildfly.transaction.client.ContextTransactionManager;
/**
* Transaction interceptor for Singleton and Stateless beans,
*
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
*/
public class LifecycleCMTTxInterceptor extends CMTTxInterceptor {
private final TransactionAttributeType transactionAttributeType;
private final int transactionTimeout;
public LifecycleCMTTxInterceptor(final TransactionAttributeType transactionAttributeType, final int transactionTimeout) {
this.transactionAttributeType = transactionAttributeType;
this.transactionTimeout = transactionTimeout;
}
@Override
public Object processInvocation(InterceptorContext invocation) throws Exception {
final EJBComponent component = (EJBComponent) invocation.getPrivateData(Component.class);
switch (transactionAttributeType) {
case MANDATORY:
return mandatory(invocation, component);
case NEVER:
return never(invocation, component);
case NOT_SUPPORTED:
return notSupported(invocation, component);
case REQUIRED:
return required(invocation, component, transactionTimeout);
case REQUIRES_NEW:
return requiresNew(invocation, component, transactionTimeout);
case SUPPORTS:
return supports(invocation, component);
default:
throw EjbLogger.ROOT_LOGGER.unknownTxAttributeOnInvocation(transactionAttributeType, invocation);
}
}
@Override
protected Object notSupported(InterceptorContext invocation, EJBComponent component) throws Exception {
Transaction tx = ContextTransactionManager.getInstance().getTransaction();
int status = (tx != null) ? tx.getStatus() : Status.STATUS_NO_TRANSACTION;
// If invocation was triggered from Synchronization.afterCompletion(...)
// then skip suspend/resume of associated tx since JTS refuses to resume a completed tx
switch (status) {
case Status.STATUS_NO_TRANSACTION:
case Status.STATUS_COMMITTED:
case Status.STATUS_ROLLEDBACK: {
return invokeInNoTx(invocation, component);
}
default: {
return super.notSupported(invocation, component);
}
}
}
/**
* @author Stuart Douglas
*/
public static class Factory extends ComponentInterceptorFactory {
private final MethodIdentifier methodIdentifier;
/**
* If this is false it means the bean is a SFSB, and can only be NOT_SUPPORTED or REQUIRES_NEW
*/
private final boolean treatRequiredAsRequiresNew;
public Factory(final MethodIdentifier methodIdentifier, final boolean treatRequiredAsRequiresNew) {
this.methodIdentifier = methodIdentifier;
this.treatRequiredAsRequiresNew = treatRequiredAsRequiresNew;
}
@Override
protected Interceptor create(Component component, InterceptorFactoryContext context) {
final EJBComponent ejb = (EJBComponent) component;
TransactionAttributeType txAttr;
if (methodIdentifier == null) {
if(treatRequiredAsRequiresNew) {
txAttr = TransactionAttributeType.REQUIRED;
} else {
//for stateful beans we default to NOT_SUPPORTED
txAttr = TransactionAttributeType.NOT_SUPPORTED;
}
} else {
txAttr = ejb.getTransactionAttributeType(MethodInterfaceType.Bean, methodIdentifier, treatRequiredAsRequiresNew ? TransactionAttributeType.REQUIRES_NEW : TransactionAttributeType.NOT_SUPPORTED);
}
final int txTimeout;
if(methodIdentifier == null) {
txTimeout = -1;
} else {
txTimeout = ejb.getTransactionTimeout(MethodInterfaceType.Bean, methodIdentifier);
}
if (treatRequiredAsRequiresNew && txAttr == TransactionAttributeType.REQUIRED) {
txAttr = TransactionAttributeType.REQUIRES_NEW;
}
if (!treatRequiredAsRequiresNew
&& txAttr != TransactionAttributeType.NOT_SUPPORTED
&& txAttr != TransactionAttributeType.REQUIRES_NEW) {
if (ejb.isTransactionAttributeTypeExplicit(MethodInterfaceType.Bean, methodIdentifier)) {
EjbLogger.ROOT_LOGGER.invalidTransactionTypeForSfsbLifecycleMethod(txAttr, methodIdentifier,
ejb.getComponentClass());
}
txAttr = TransactionAttributeType.NOT_SUPPORTED;
}
return new LifecycleCMTTxInterceptor(txAttr, txTimeout);
}
}
}
| 6,503 | 43.244898 | 210 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/tx/ApplicationExceptionDetails.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, 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.ejb3.tx;
/**
* Class that stores details about application exceptions
*
* @author Stuart Douglas
*/
public class ApplicationExceptionDetails {
private final String exceptionClass;
private final boolean inherited;
private final boolean rollback;
public ApplicationExceptionDetails(final String exceptionClass, final boolean inherited, final boolean rollback) {
this.exceptionClass = exceptionClass;
this.inherited = inherited;
this.rollback = rollback;
}
public String getExceptionClass() {
return exceptionClass;
}
public boolean isInherited() {
return inherited;
}
public boolean isRollback() {
return rollback;
}
}
| 1,757 | 31.555556 | 118 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/tx/CMTTxInterceptor.java | /*
* JBoss, Home of Professional Open Source
* Copyright (c) 2010, JBoss 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.ejb3.tx;
import static org.jboss.as.ejb3.tx.util.StatusHelper.statusAsString;
import java.lang.reflect.Method;
import java.lang.reflect.UndeclaredThrowableException;
import java.rmi.RemoteException;
import jakarta.ejb.EJBException;
import jakarta.ejb.EJBTransactionRolledbackException;
import jakarta.ejb.NoSuchEJBException;
import jakarta.ejb.NoSuchEntityException;
import jakarta.ejb.TransactionAttributeType;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Status;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import org.jboss.as.ee.component.Component;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.as.ejb3.component.MethodIntfHelper;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.metadata.ejb.spec.MethodInterfaceType;
import org.wildfly.transaction.client.AbstractTransaction;
import org.wildfly.transaction.client.ContextTransactionManager;
/**
* NOTE: References in this file to Enterprise JavaBeans (EJB) refer to the Jakarta Enterprise Beans unless otherwise noted.
*
* Ensure the correct exceptions are thrown based on both caller
* transactional context and supported Transaction Attribute Type
* <p/>
* EJB3 13.6.2.6
* EJB3 Core Specification 14.3.1 Table 14
*
* @author <a href="mailto:[email protected]">ALR</a>
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
* @author Scott Marlow
*/
public class CMTTxInterceptor implements Interceptor {
public static final InterceptorFactory FACTORY = new ImmediateInterceptorFactory(new CMTTxInterceptor());
/**
* The <code>endTransaction</code> method ends a transaction and
* translates any exceptions into
* TransactionRolledBack[Local]Exception or SystemException.
*
* @param tx a <code>Transaction</code> value
*/
protected void endTransaction(final Transaction tx) {
ContextTransactionManager tm = ContextTransactionManager.getInstance();
try {
if (! tx.equals(tm.getTransaction())) {
throw EjbLogger.ROOT_LOGGER.wrongTxOnThread(tx, tm.getTransaction());
}
final int txStatus = tx.getStatus();
if (txStatus == Status.STATUS_ACTIVE) {
// Commit tx
// This will happen if
// a) everything goes well
// b) app. exception was thrown
tm.commit();
} else if (txStatus == Status.STATUS_MARKED_ROLLBACK) {
tm.rollback();
} else if (txStatus == Status.STATUS_ROLLEDBACK || txStatus == Status.STATUS_ROLLING_BACK) {
// handle reaper canceled (rolled back) tx case (see WFLY-1346)
// clear current tx state and throw RollbackException (EJBTransactionRolledbackException)
tm.rollback();
throw EjbLogger.ROOT_LOGGER.transactionAlreadyRolledBack(tx);
} else if (txStatus == Status.STATUS_UNKNOWN) {
// STATUS_UNKNOWN isn't expected to be reached here but if it does, we need to clear current thread tx.
// It is possible that calling tm.commit() could succeed but we call tm.rollback, since this is an unexpected
// tx state that are are handling.
tm.rollback();
// if the tm.rollback doesn't fail, we throw an EJBException to reflect the unexpected tx state.
throw EjbLogger.ROOT_LOGGER.transactionInUnexpectedState(tx, statusAsString(txStatus));
} else {
// logically, all of the following (unexpected) tx states are handled here:
// Status.STATUS_PREPARED
// Status.STATUS_PREPARING
// Status.STATUS_COMMITTING
// Status.STATUS_NO_TRANSACTION
// Status.STATUS_COMMITTED
tm.suspend(); // clear current tx state and throw EJBException
throw EjbLogger.ROOT_LOGGER.transactionInUnexpectedState(tx, statusAsString(txStatus));
}
} catch (RollbackException e) {
throw new EJBTransactionRolledbackException(e.toString(), e);
} catch (HeuristicMixedException | SystemException | HeuristicRollbackException e) {
throw new EJBException(e);
}
}
private void endTransaction(final Transaction tx, final Throwable outerEx) {
try {
endTransaction(tx);
} catch (Throwable t) {
outerEx.addSuppressed(t);
}
}
public Object processInvocation(InterceptorContext invocation) throws Exception {
final EJBComponent component = (EJBComponent) invocation.getPrivateData(Component.class);
final ContextTransactionManager tm = ContextTransactionManager.getInstance();
final int oldTimeout = tm.getTransactionTimeout();
try {
final MethodInterfaceType methodIntf = MethodIntfHelper.of(invocation);
final Method method = invocation.getMethod();
final TransactionAttributeType attr = component.getTransactionAttributeType(methodIntf, method);
final int timeoutInSeconds = component.getTransactionTimeout(methodIntf, method);
switch (attr) {
case MANDATORY:
return mandatory(invocation, component);
case NEVER:
return never(invocation, component);
case NOT_SUPPORTED:
return notSupported(invocation, component);
case REQUIRED:
final ComponentView view = invocation.getPrivateData(ComponentView.class);
if (view != null && view.isAsynchronous(method)) {
// EJB 3.2 4.5.3 Transactions
// The client’s transaction context does not propagate with an asynchronous method invocation. From the
// Bean Provider’s point of view, there is never a transaction context flowing in from the client. This
// means, for example, that the semantics of the REQUIRED transaction attribute on an asynchronous
// method are exactly the same as REQUIRES_NEW.
return requiresNew(invocation, component, timeoutInSeconds);
}
return required(invocation, component, timeoutInSeconds);
case REQUIRES_NEW:
return requiresNew(invocation, component, timeoutInSeconds);
case SUPPORTS:
return supports(invocation, component);
default:
throw EjbLogger.ROOT_LOGGER.unknownTxAttributeOnInvocation(attr, invocation);
}
} finally {
// See also https://issues.jboss.org/browse/WFTC-44
tm.setTransactionTimeout(oldTimeout == ContextTransactionManager.getGlobalDefaultTransactionTimeout() ? 0 : oldTimeout);
}
}
protected Object invokeInImportedTx(InterceptorContext invocation, EJBComponent component) throws Exception {
Transaction tx;
try {
tx = invocation.getTransaction();
} catch (SystemException ex) {
// SystemException + server suspended equals the transaction is new and the request
// for new transaction is being rejected
if (component != null && component.getEjbSuspendHandlerService().isSuspended()) {
throw EjbLogger.ROOT_LOGGER.cannotBeginUserTransaction();
} else {
throw new EJBException(ex);
}
}
safeResume(tx);
final Object result;
try {
result = invokeInCallerTx(invocation, tx, component);
} catch (Throwable t) {
safeSuspend(t);
throw t;
}
safeSuspend();
return result;
}
protected Object invokeInCallerTx(InterceptorContext invocation, Transaction tx, final EJBComponent component) throws Exception {
try {
return invocation.proceed();
} catch (Error e) {
final EJBTransactionRolledbackException e2 = EjbLogger.ROOT_LOGGER.unexpectedErrorRolledBack(e);
setRollbackOnly(tx, e2);
throw e2;
} catch (Exception e) {
ApplicationExceptionDetails ae = component.getApplicationException(e.getClass(), invocation.getMethod());
if (ae != null) {
if (ae.isRollback()) setRollbackOnly(tx, e);
throw e;
}
try {
throw e;
} catch (EJBTransactionRolledbackException | NoSuchEJBException | NoSuchEntityException e2) {
setRollbackOnly(tx, e2);
throw e2;
} catch (RuntimeException e2) {
final EJBTransactionRolledbackException e3 = new EJBTransactionRolledbackException(e2.getMessage(), e2);
setRollbackOnly(tx, e3);
throw e3;
}
} catch (Throwable t) {
final EJBException e = new EJBException(new UndeclaredThrowableException(t));
setRollbackOnly(tx, e);
throw e;
}
}
protected Object invokeInNoTx(InterceptorContext invocation, final EJBComponent component) throws Exception {
try {
return invocation.proceed();
} catch (Error e) {
throw EjbLogger.ROOT_LOGGER.unexpectedError(e);
} catch (EJBException e) {
throw e;
} catch (RuntimeException e) {
ApplicationExceptionDetails ae = component.getApplicationException(e.getClass(), invocation.getMethod());
throw ae != null ? e : new EJBException(e);
} catch (Exception e) {
throw e;
} catch (Throwable t) {
throw new EJBException(new UndeclaredThrowableException(t));
}
}
protected Object invokeInOurTx(InterceptorContext invocation, final EJBComponent component) throws Exception {
final ContextTransactionManager tm = ContextTransactionManager.getInstance();
tm.begin();
final AbstractTransaction tx = tm.getTransaction();
Object result = null;
Exception except = null;
try {
result = invocation.proceed();
} catch (Throwable t) {
ApplicationExceptionDetails ae = component.getApplicationException(t.getClass(), invocation.getMethod());
try {
try {
throw t;
} catch (EJBException | RemoteException e) {
throw e;
} catch (RuntimeException e) {
if (ae != null && !ae.isRollback()) {
except = e;
} else if(ae != null && ae.isRollback()) {
throw e;
} else {
throw new EJBException(e);
}
} catch (Exception e) {
throw e;
} catch (Error e) {
throw EjbLogger.ROOT_LOGGER.unexpectedError(e);
} catch (Throwable e) {
throw new EJBException(new UndeclaredThrowableException(e));
}
} catch (Throwable t2) {
if (ae == null || ae.isRollback()) setRollbackOnly(tx, t2);
endTransaction(tx, t2);
throw t2;
}
}
boolean rolledBack = safeGetStatus(tx) == Status.STATUS_MARKED_ROLLBACK;
endTransaction(tx);
if (except!=null) {
throw except;
}
if (rolledBack) ourTxRolledBack();
return result;
}
private int safeGetStatus(final AbstractTransaction tx) {
try {
return tx.getStatus();
} catch (SystemException e) {
return Status.STATUS_UNKNOWN;
}
}
private void safeSuspend() {
try {
ContextTransactionManager.getInstance().suspend();
} catch (SystemException e) {
throw new EJBException(e);
}
}
private void safeSuspend(final Throwable t) {
try {
ContextTransactionManager.getInstance().suspend();
} catch (SystemException e) {
t.addSuppressed(e);
}
}
private void safeResume(final Transaction tx) {
try {
ContextTransactionManager.getInstance().resume(tx);
} catch (Exception e) {
throw new EJBException(e);
}
}
private void safeResume(final Transaction tx, final Throwable t) {
try {
ContextTransactionManager.getInstance().resume(tx);
} catch (Exception e) {
t.addSuppressed(e);
}
}
protected void ourTxRolledBack() {
// normally no operation
}
protected Object mandatory(InterceptorContext invocation, final EJBComponent component) throws Exception {
final ContextTransactionManager tm = ContextTransactionManager.getInstance();
Transaction tx = tm.getTransaction();
if (tx == null) {
if (invocation.hasTransaction()) {
return invokeInImportedTx(invocation, component);
}
throw EjbLogger.ROOT_LOGGER.txRequiredForInvocation(invocation);
}
return invokeInCallerTx(invocation, tx, component);
}
protected Object never(InterceptorContext invocation, final EJBComponent component) throws Exception {
final ContextTransactionManager tm = ContextTransactionManager.getInstance();
if (tm.getTransaction() != null || invocation.hasTransaction()) {
throw EjbLogger.ROOT_LOGGER.txPresentForNeverTxAttribute();
}
return invokeInNoTx(invocation, component);
}
protected Object notSupported(InterceptorContext invocation, final EJBComponent component) throws Exception {
final ContextTransactionManager tm = ContextTransactionManager.getInstance();
Transaction tx = tm.getTransaction();
if (tx != null) {
safeSuspend();
final Object result;
try {
result = invokeInNoTx(invocation, component);
} catch (Throwable t) {
safeResume(tx, t);
throw t;
}
safeResume(tx);
return result;
} else {
return invokeInNoTx(invocation, component);
}
}
protected Object required(final InterceptorContext invocation, final EJBComponent component, final int timeout) throws Exception {
final ContextTransactionManager tm = ContextTransactionManager.getInstance();
if (timeout != -1) {
tm.setTransactionTimeout(timeout);
}
final Transaction tx = tm.getTransaction();
if (tx == null) {
if (invocation.hasTransaction()) {
return invokeInImportedTx(invocation, component);
}
return invokeInOurTx(invocation, component);
} else {
return invokeInCallerTx(invocation, tx, component);
}
}
protected Object requiresNew(InterceptorContext invocation, final EJBComponent component, final int timeout) throws Exception {
final ContextTransactionManager tm = ContextTransactionManager.getInstance();
if (timeout != -1) {
tm.setTransactionTimeout(timeout);
}
Transaction tx = tm.getTransaction();
if (tx != null) {
safeSuspend();
final Object result;
try {
result = invokeInOurTx(invocation, component);
} catch (Throwable t) {
safeResume(tx, t);
throw t;
}
safeResume(tx);
return result;
} else {
return invokeInOurTx(invocation, component);
}
}
/**
* The <code>setRollbackOnly</code> method calls setRollbackOnly()
* on the invocation's transaction and logs any exceptions than may
* occur.
*
* @param tx the transaction
* @param t the exception to add problems to (may be {@code null})
*/
protected void setRollbackOnly(Transaction tx, final Throwable t) {
try {
tx.setRollbackOnly();
} catch (Throwable t2) {
EjbLogger.ROOT_LOGGER.failedToSetRollbackOnly(t2);
if (t != null) {
t.addSuppressed(t2);
}
}
}
protected Object supports(InterceptorContext invocation, final EJBComponent component) throws Exception {
final ContextTransactionManager tm = ContextTransactionManager.getInstance();
Transaction tx = tm.getTransaction();
if (tx == null) {
if (invocation.hasTransaction()) {
return invokeInImportedTx(invocation, component);
}
return invokeInNoTx(invocation, component);
} else {
return invokeInCallerTx(invocation, tx, component);
}
}
}
| 18,562 | 40.068584 | 134 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/tx/StatefulBMTInterceptor.java | /*
* JBoss, Home of Professional Open Source
* Copyright (c) 2010, JBoss 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.ejb3.tx;
import jakarta.transaction.Status;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.as.ejb3.component.stateful.StatefulSessionComponentInstance;
import org.jboss.invocation.InterceptorContext;
import static org.jboss.as.ejb3.tx.util.StatusHelper.statusAsString;
/**
* A per instance interceptor that keeps an association with the outcoming transaction.
* <p/>
* Enterprise Beans 3 13.6.1:
* In the case of a stateful session bean, it is possible that the business method that started a transaction
* completes without committing or rolling back the transaction. In such a case, the container must retain
* the association between the transaction and the instance across multiple client calls until the instance
* commits or rolls back the transaction. When the client invokes the next business method, the container
* must invoke the business method (and any applicable interceptor methods for the bean) in this transac-
* tion context.
*
* @author <a href="[email protected]">Carlo de Wolf</a>
*/
public class StatefulBMTInterceptor extends BMTInterceptor {
public StatefulBMTInterceptor(final EJBComponent component) {
super(component);
}
private void checkBadStateful() {
int status = Status.STATUS_NO_TRANSACTION;
TransactionManager tm = getComponent().getTransactionManager();
try {
status = tm.getStatus();
} catch (SystemException ex) {
EjbLogger.ROOT_LOGGER.failedToGetStatus(ex);
}
switch (status) {
case Status.STATUS_COMMITTING:
case Status.STATUS_MARKED_ROLLBACK:
case Status.STATUS_PREPARING:
case Status.STATUS_ROLLING_BACK:
try {
tm.rollback();
} catch (Exception ex) {
EjbLogger.ROOT_LOGGER.failedToRollback(ex);
}
EjbLogger.ROOT_LOGGER.transactionNotComplete(getComponent().getComponentName(), statusAsString(status));
}
}
@Override
protected Object handleInvocation(final InterceptorContext invocation) throws Exception {
final StatefulSessionComponentInstance instance = (StatefulSessionComponentInstance) invocation.getPrivateData(ComponentInstance.class);
TransactionManager tm = getComponent().getTransactionManager();
assert tm.getTransaction() == null : "can't handle BMT transaction, there is a transaction active";
// Is the instance already associated with a transaction?
Transaction tx = instance.getTransaction();
if (tx != null) {
// then resume that transaction.
instance.setTransaction(null);
tm.resume(tx);
}
try {
return invocation.proceed();
} catch (Throwable e) {
throw this.handleException(invocation, e);
} finally {
checkBadStateful();
// Is the instance finished with the transaction?
Transaction newTx = tm.getTransaction();
//always set it, even if null
instance.setTransaction(newTx);
if (newTx != null) {
// remember the association
// and suspend it.
tm.suspend();
}
}
}
}
| 4,582 | 40.288288 | 144 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/tx/TimerTransactionRolledBackException.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, 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.ejb3.tx;
/**
* @author Stuart Douglas
*/
public class TimerTransactionRolledBackException extends RuntimeException {
public TimerTransactionRolledBackException() {
}
public TimerTransactionRolledBackException(final Throwable cause) {
super(cause);
}
public TimerTransactionRolledBackException(final String message) {
super(message);
}
public TimerTransactionRolledBackException(final String message, final Throwable cause) {
super(message, cause);
}
}
| 1,552 | 34.295455 | 93 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/tx/EjbBMTInterceptor.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.ejb3.tx;
import jakarta.ejb.EJBException;
import jakarta.transaction.Status;
import jakarta.transaction.SystemException;
import jakarta.transaction.TransactionManager;
import org.jboss.as.ee.component.Component;
import org.jboss.as.ee.component.ComponentInstanceInterceptorFactory;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.invocation.InterceptorFactoryContext;
/**
* EJB 3 13.6.1:
* If a stateless session bean instance starts a transaction in a business method or interceptor method, it
* must commit the transaction before the business method (or all its interceptor methods) returns.
*
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
* @version $Revision: $
*/
public class EjbBMTInterceptor extends BMTInterceptor {
public static final InterceptorFactory FACTORY = new ComponentInstanceInterceptorFactory() {
@Override
protected Interceptor create(final Component component, final InterceptorFactoryContext context) {
return new EjbBMTInterceptor((EJBComponent) component);
}
};
EjbBMTInterceptor(final EJBComponent component) {
super(component);
}
private void checkStatelessDone(final EJBComponent component, final InterceptorContext invocation, final TransactionManager tm, Throwable ex) throws Exception {
int status = Status.STATUS_NO_TRANSACTION;
try {
status = tm.getStatus();
} catch (SystemException sex) {
EjbLogger.ROOT_LOGGER.failedToGetStatus(sex);
}
switch (status) {
case Status.STATUS_ACTIVE:
case Status.STATUS_COMMITTING:
case Status.STATUS_MARKED_ROLLBACK:
case Status.STATUS_PREPARING:
case Status.STATUS_ROLLING_BACK:
try {
tm.rollback();
} catch (Exception sex) {
EjbLogger.ROOT_LOGGER.failedToRollback(sex);
}
// fall through...
case Status.STATUS_PREPARED:
final String msg = EjbLogger.ROOT_LOGGER.transactionNotComplete(component.getComponentName());
EjbLogger.ROOT_LOGGER.error(msg);
if (ex instanceof Exception) {
throw new EJBException(msg, (Exception) ex);
} else {
throw new EJBException(msg, new RuntimeException(ex));
}
}
// the instance interceptor will discard the instance
if (ex != null)
throw this.handleException(invocation, ex);
}
@Override
protected Object handleInvocation(final InterceptorContext invocation) throws Exception {
final EJBComponent ejbComponent = getComponent();
TransactionManager tm = ejbComponent.getTransactionManager();
assert tm.getTransaction() == null : "can't handle BMT transaction, there is a transaction active";
boolean exceptionThrown = false;
try {
return invocation.proceed();
} catch (Throwable ex) {
exceptionThrown = true;
checkStatelessDone(ejbComponent, invocation, tm, ex);
//we should never get here, as checkStatelessDone should re-throw
throw (Exception)ex;
} finally {
try {
if (!exceptionThrown) checkStatelessDone(ejbComponent, invocation, tm, null);
} finally {
tm.suspend();
}
}
}
}
| 4,735 | 38.798319 | 164 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/tx/util/StatusHelper.java | /*
* JBoss, Home of Professional Open Source
* Copyright (c) 2010, JBoss 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.ejb3.tx.util;
import jakarta.transaction.Status;
/**
* @author <a href="[email protected]">Carlo de Wolf</a>
*/
public class StatusHelper {
/**
* Transaction Status Strings
*/
private static final String[] TxStatusStrings =
{
"STATUS_ACTIVE",
"STATUS_MARKED_ROLLBACK",
"STATUS_PREPARED",
"STATUS_COMMITTED",
"STATUS_ROLLEDBACK",
"STATUS_UNKNOWN",
"STATUS_NO_TRANSACTION",
"STATUS_PREPARING",
"STATUS_COMMITTING",
"STATUS_ROLLING_BACK"
};
/**
* Converts a tx Status index to a String
*
* @param status the Status index
* @return status as String or "STATUS_INVALID(value)"
* @see jakarta.transaction.Status
*/
public static String statusAsString(int status) {
if (status >= Status.STATUS_ACTIVE && status <= Status.STATUS_ROLLING_BACK) {
return TxStatusStrings[status];
} else {
return "STATUS_INVALID(" + status + ")";
}
}
}
| 2,202 | 34.532258 | 85 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/context/SessionContextImpl.java | /*
* JBoss, Home of Professional Open Source
* Copyright (c) 2010, JBoss 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.ejb3.context;
import jakarta.ejb.EJBLocalObject;
import jakarta.ejb.EJBObject;
import jakarta.ejb.SessionContext;
import jakarta.ejb.TimerService;
import jakarta.transaction.UserTransaction;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.as.ejb3.component.allowedmethods.AllowedMethodsInformation;
import org.jboss.as.ejb3.component.allowedmethods.MethodType;
import org.jboss.as.ejb3.component.interceptors.CancellationFlag;
import org.jboss.as.ejb3.component.session.SessionBeanComponent;
import org.jboss.as.ejb3.component.session.SessionBeanComponentInstance;
import org.jboss.as.ejb3.component.stateful.StatefulSessionComponent;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.invocation.InterceptorContext;
/**
* Implementation of the SessionContext interface.
* <p/>
*
* @author <a href="[email protected]">Carlo de Wolf</a>
*/
public class SessionContextImpl extends EJBContextImpl implements SessionContext {
private static final long serialVersionUID = 1L;
private final boolean stateful;
public SessionContextImpl(SessionBeanComponentInstance instance) {
super(instance);
stateful = instance.getComponent() instanceof StatefulSessionComponent;
}
public <T> T getBusinessObject(Class<T> businessInterface) throws IllegalStateException {
// to allow override per invocation
final InterceptorContext invocation = CurrentInvocationContext.get();
return getComponent().getBusinessObject(businessInterface, invocation);
}
public EJBLocalObject getEJBLocalObject() throws IllegalStateException {
AllowedMethodsInformation.checkAllowed(MethodType.GET_EJB_LOCAL_OBJECT);
// to allow override per invocation
final InterceptorContext invocation = CurrentInvocationContext.get();
return getComponent().getEJBLocalObject(invocation);
}
public EJBObject getEJBObject() throws IllegalStateException {
AllowedMethodsInformation.checkAllowed(MethodType.GET_EJB_OBJECT);
// to allow override per invocation
final InterceptorContext invocation = CurrentInvocationContext.get();
return getComponent().getEJBObject(invocation);
}
public Class<?> getInvokedBusinessInterface() throws IllegalStateException {
final InterceptorContext invocation = CurrentInvocationContext.get();
final ComponentView view = invocation.getPrivateData(ComponentView.class);
if (view.getViewClass().equals(getComponent().getEjbObjectType()) || view.getViewClass().equals(getComponent().getEjbLocalObjectType())) {
throw EjbLogger.ROOT_LOGGER.cannotCall("getInvokedBusinessInterface", "EjbObject", "EJBLocalObject");
}
return view.getViewClass();
}
public SessionBeanComponent getComponent() {
return (SessionBeanComponent) super.getComponent();
}
public boolean wasCancelCalled() throws IllegalStateException {
final InterceptorContext invocation = CurrentInvocationContext.get();
final CancellationFlag flag = invocation.getPrivateData(CancellationFlag.class);
if (flag == null) {
throw EjbLogger.ROOT_LOGGER.noAsynchronousInvocationInProgress();
}
return flag.isCancelFlagSet();
}
@Override
public TimerService getTimerService() throws IllegalStateException {
AllowedMethodsInformation.checkAllowed(MethodType.GET_TIMER_SERVICE);
if (stateful) {
throw EjbLogger.ROOT_LOGGER.notAllowedFromStatefulBeans("getTimerService()");
}
return super.getTimerService();
}
@Override
public UserTransaction getUserTransaction() throws IllegalStateException {
AllowedMethodsInformation.checkAllowed(MethodType.GET_USER_TRANSACTION);
return getComponent().getUserTransaction();
}
@Override
public void setRollbackOnly() throws IllegalStateException {
AllowedMethodsInformation.checkAllowed(MethodType.SET_ROLLBACK_ONLY);
super.setRollbackOnly();
}
@Override
public boolean getRollbackOnly() throws IllegalStateException {
AllowedMethodsInformation.checkAllowed(MethodType.GET_ROLLBACK_ONLY);
return super.getRollbackOnly();
}
}
| 5,292 | 41.344 | 146 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/context/EjbContextResourceReferenceProcessor.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.ejb3.context;
import jakarta.ejb.EJBContext;
import org.jboss.as.ee.component.InjectionSource;
import org.jboss.as.ee.component.deployers.EEResourceReferenceProcessor;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.ServiceBuilder;
/**
* Handler for EjbContext JNDI bindings
*
* @author Stuart Douglas
*/
public class EjbContextResourceReferenceProcessor implements EEResourceReferenceProcessor {
private final Class<? extends EJBContext> type;
public EjbContextResourceReferenceProcessor(final Class<? extends EJBContext> type) {
this.type = type;
}
@Override
public String getResourceReferenceType() {
return type.getName();
}
@Override
public InjectionSource getResourceReferenceBindingSource() throws DeploymentUnitProcessingException {
return new EjbContextInjectionSource();
}
private static final ManagedReference ejbContextManagedReference = new ManagedReference() {
public void release() {
}
public Object getInstance() {
return CurrentInvocationContext.getEjbContext();
}
};
private static final ManagedReferenceFactory ejbContextManagedReferenceFactory = new ManagedReferenceFactory() {
public ManagedReference getReference() {
return ejbContextManagedReference;
}
};
private static class EjbContextInjectionSource extends InjectionSource {
@Override
public void getResourceValue(final ResolutionContext resolutionContext, final ServiceBuilder<?> serviceBuilder, final DeploymentPhaseContext phaseContext, final Injector<ManagedReferenceFactory> injector) throws DeploymentUnitProcessingException {
injector.inject(ejbContextManagedReferenceFactory);
}
public boolean equals(Object other) {
return other instanceof EjbContextInjectionSource;
}
public int hashCode() {
return 45647;
}
}
}
| 3,261 | 35.244444 | 255 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/context/MessageDrivenContext.java | /*
* JBoss, Home of Professional Open Source
* Copyright (c) 2010, JBoss 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.ejb3.context;
import org.jboss.as.ejb3.component.EjbComponentInstance;
import org.jboss.as.ejb3.component.messagedriven.MessageDrivenComponent;
/**
* @author <a href="[email protected]">Carlo de Wolf</a>
*/
public class MessageDrivenContext extends EJBContextImpl implements jakarta.ejb.MessageDrivenContext{
public MessageDrivenContext(final EjbComponentInstance instance) {
super(instance);
}
@Override
public MessageDrivenComponent getComponent() {
return (MessageDrivenComponent) super.getComponent();
}
}
| 1,593 | 36.952381 | 101 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/context/CurrentInvocationContext.java | /*
* JBoss, Home of Professional Open Source
* Copyright (c) 2010, JBoss 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.ejb3.context;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.as.ejb3.component.EjbComponentInstance;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.invocation.InterceptorContext;
import org.wildfly.common.function.ThreadLocalStack;
/**
* @author <a href="[email protected]">Carlo de Wolf</a>
*/
public class CurrentInvocationContext {
private static final ThreadLocalStack<InterceptorContext> stack = new ThreadLocalStack<InterceptorContext>();
public static InterceptorContext get() {
InterceptorContext current = stack.peek();
return current;
}
public static EJBContextImpl getEjbContext() {
final InterceptorContext context = get();
if(context == null) {
throw EjbLogger.ROOT_LOGGER.noEjbContextAvailable();
}
final ComponentInstance component = context.getPrivateData(ComponentInstance.class);
if(!(component instanceof EjbComponentInstance)) {
throw EjbLogger.ROOT_LOGGER.currentComponentNotAEjb(component);
}
return ((EjbComponentInstance)component).getEjbContext();
}
public static InterceptorContext pop() {
return stack.pop();
}
public static void push(InterceptorContext invocation) {
assert invocation != null : "invocation is null";
stack.push(invocation);
}
}
| 2,414 | 37.333333 | 113 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/context/EJBContextImpl.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.ejb3.context;
import java.io.Serializable;
import java.security.Principal;
import java.util.Map;
import jakarta.ejb.EJBHome;
import jakarta.ejb.EJBLocalHome;
import jakarta.ejb.TimerService;
import jakarta.transaction.UserTransaction;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.as.ejb3.component.EjbComponentInstance;
import org.jboss.as.ejb3.component.allowedmethods.AllowedMethodsInformation;
import org.jboss.as.ejb3.component.allowedmethods.MethodType;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.invocation.InterceptorContext;
/**
* @author <a href="[email protected]">Carlo de Wolf</a>
*/
public abstract class EJBContextImpl implements jakarta.ejb.EJBContext, Serializable {
private final EjbComponentInstance instance;
public EJBContextImpl(final EjbComponentInstance instance) {
this.instance = instance;
}
public Principal getCallerPrincipal() {
AllowedMethodsInformation.checkAllowed(MethodType.GET_CALLER_PRINCIPLE);
// per invocation
return instance.getComponent().getCallerPrincipal();
}
public Map<String, Object> getContextData() {
final InterceptorContext invocation = CurrentInvocationContext.get();
return invocation.getContextData();
}
public EJBHome getEJBHome() {
return getComponent().getEJBHome();
}
public EJBLocalHome getEJBLocalHome() {
return instance.getComponent().getEJBLocalHome();
}
public EJBComponent getComponent() {
return instance.getComponent();
}
public boolean getRollbackOnly() throws IllegalStateException {
// to allow override per invocation
final InterceptorContext context = CurrentInvocationContext.get();
if (context.getMethod() == null) {
throw EjbLogger.ROOT_LOGGER.lifecycleMethodNotAllowed("getRollbackOnly");
}
return instance.getComponent().getRollbackOnly();
}
public Object getTarget() {
return instance.getInstance();
}
public TimerService getTimerService() throws IllegalStateException {
AllowedMethodsInformation.checkAllowed(MethodType.GET_TIMER_SERVICE);
return instance.getComponent().getTimerService();
}
public UserTransaction getUserTransaction() throws IllegalStateException {
AllowedMethodsInformation.checkAllowed(MethodType.GET_USER_TRANSACTION);
return getComponent().getUserTransaction();
}
public boolean isCallerInRole(String roleName) {
AllowedMethodsInformation.checkAllowed(MethodType.IS_CALLER_IN_ROLE);
return instance.getComponent().isCallerInRole(roleName);
}
public Object lookup(String name) throws IllegalArgumentException {
return getComponent().lookup(name);
}
public void setRollbackOnly() throws IllegalStateException {
// to allow override per invocation
final InterceptorContext context = CurrentInvocationContext.get();
if (context.getMethod() == null) {
throw EjbLogger.ROOT_LOGGER.lifecycleMethodNotAllowed("getRollbackOnly");
}
instance.getComponent().setRollbackOnly();
}
}
| 4,222 | 36.04386 | 86 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/deliveryactive/parser/EJBBoundMdbDeliveryMetaDataParser11.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.ejb3.deliveryactive.parser;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.jboss.as.ejb3.deliveryactive.metadata.EJBBoundMdbDeliveryMetaData;
import org.jboss.metadata.ejb.parser.jboss.ejb3.AbstractEJBBoundMetaDataParser;
import org.jboss.metadata.property.PropertyReplacer;
/**
* Parser for EJBBoundMdbDeliveryMetaData components, namespace delivery-active:1.1
*
* @author Flavia Rainone
*/
public class EJBBoundMdbDeliveryMetaDataParser11 extends AbstractEJBBoundMetaDataParser<EJBBoundMdbDeliveryMetaData> {
public static final String NAMESPACE_URI_1_1 = "urn:delivery-active:1.1";
private static final String ROOT_ELEMENT_DELIVERY = "delivery";
private static final String ACTIVE = "active";
private static final String GROUP = "group";
public static final EJBBoundMdbDeliveryMetaDataParser11 INSTANCE = new EJBBoundMdbDeliveryMetaDataParser11();
private EJBBoundMdbDeliveryMetaDataParser11() {}
@Override
public EJBBoundMdbDeliveryMetaData parse(XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException {
// we only parse <delivery> (root) element
if (!ROOT_ELEMENT_DELIVERY.equals(reader.getLocalName())) {
throw unexpectedElement(reader);
}
EJBBoundMdbDeliveryMetaData metaData = new EJBBoundMdbDeliveryMetaData();
processElements(metaData, reader, propertyReplacer);
return metaData;
}
@Override
protected void processElement(EJBBoundMdbDeliveryMetaData metaData, XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException {
final String namespaceURI = reader.getNamespaceURI();
final String localName = reader.getLocalName();
if (NAMESPACE_URI_1_1.equals(namespaceURI)) {
switch (localName) {
case ACTIVE:
final String val = getElementText(reader, propertyReplacer);
metaData.setDeliveryActive(Boolean.parseBoolean(val.trim()));
break;
case GROUP:
metaData.setDeliveryGroups(getElementText(reader, propertyReplacer).trim());
break;
default:
throw unexpectedElement(reader);
}
} else {
super.processElement(metaData, reader, propertyReplacer);
}
}
}
| 3,485 | 41.512195 | 165 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/deliveryactive/parser/EJBBoundMdbDeliveryMetaDataParser12.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2019, 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.ejb3.deliveryactive.parser;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.jboss.as.ejb3.deliveryactive.metadata.EJBBoundMdbDeliveryMetaData;
import org.jboss.metadata.ejb.parser.jboss.ejb3.AbstractEJBBoundMetaDataParser;
import org.jboss.metadata.property.PropertyReplacer;
/**
* Parser for EJBBoundMdbDeliveryMetaData components, namespace delivery-active:1.2
*
* @author Flavia Rainone
*/
public class EJBBoundMdbDeliveryMetaDataParser12 extends AbstractEJBBoundMetaDataParser<EJBBoundMdbDeliveryMetaData> {
public static final String NAMESPACE_URI_1_2 = "urn:delivery-active:1.2";
private static final String ROOT_ELEMENT_DELIVERY = "delivery";
private static final String ACTIVE = "active";
private static final String GROUP = "group";
public static final EJBBoundMdbDeliveryMetaDataParser12 INSTANCE = new EJBBoundMdbDeliveryMetaDataParser12();
private EJBBoundMdbDeliveryMetaDataParser12() {}
@Override
public EJBBoundMdbDeliveryMetaData parse(XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException {
// we only parse <delivery> (root) element
if (!ROOT_ELEMENT_DELIVERY.equals(reader.getLocalName())) {
throw unexpectedElement(reader);
}
EJBBoundMdbDeliveryMetaData metaData = new EJBBoundMdbDeliveryMetaData();
processElements(metaData, reader, propertyReplacer);
return metaData;
}
@Override
protected void processElement(EJBBoundMdbDeliveryMetaData metaData, XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException {
final String namespaceURI = reader.getNamespaceURI();
final String localName = reader.getLocalName();
if (NAMESPACE_URI_1_2.equals(namespaceURI)) {
switch (localName) {
case ACTIVE:
final String val = getElementText(reader, propertyReplacer);
metaData.setDeliveryActive(Boolean.parseBoolean(val.trim()));
break;
case GROUP:
final String deliveryGroup = getElementText(reader, propertyReplacer).trim();
if (metaData.getDeliveryGroups() == null)
metaData.setDeliveryGroups(deliveryGroup);
else {
final List<String> deliveryGroups = new ArrayList<String>(metaData.getDeliveryGroups().length + 1);
Collections.addAll(deliveryGroups, metaData.getDeliveryGroups());
deliveryGroups.add(deliveryGroup);
metaData.setDeliveryGroups(deliveryGroups.toArray(new String[deliveryGroups.size()]));
}
break;
default:
throw unexpectedElement(reader);
}
} else {
super.processElement(metaData, reader, propertyReplacer);
}
}
}
| 4,130 | 42.946809 | 165 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/deliveryactive/parser/EJBBoundMdbDeliveryMetaDataParser.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.ejb3.deliveryactive.parser;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.jboss.as.ejb3.deliveryactive.metadata.EJBBoundMdbDeliveryMetaData;
import org.jboss.metadata.ejb.parser.jboss.ejb3.AbstractEJBBoundMetaDataParser;
import org.jboss.metadata.property.PropertyReplacer;
/**
* Parser for EJBBoundMdbDeliveryMetaData components.
*
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2013 Red Hat inc.
* @author Flavia Rainone
*/
public class EJBBoundMdbDeliveryMetaDataParser extends AbstractEJBBoundMetaDataParser<EJBBoundMdbDeliveryMetaData> {
public static final String NAMESPACE_URI_1_0 = "urn:delivery-active:1.0";
private static final String ROOT_ELEMENT_DELIVERY = "delivery";
private static final String ACTIVE = "active";
public static final EJBBoundMdbDeliveryMetaDataParser INSTANCE = new EJBBoundMdbDeliveryMetaDataParser();
private EJBBoundMdbDeliveryMetaDataParser() {
}
@Override
public EJBBoundMdbDeliveryMetaData parse(XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException {
// we only parse <delivery> (root) element
if (!ROOT_ELEMENT_DELIVERY.equals(reader.getLocalName())) {
throw unexpectedElement(reader);
}
EJBBoundMdbDeliveryMetaData metaData = new EJBBoundMdbDeliveryMetaData();
processElements(metaData, reader, propertyReplacer);
return metaData;
}
@Override
protected void processElement(EJBBoundMdbDeliveryMetaData metaData, XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException {
final String namespaceURI = reader.getNamespaceURI();
final String localName = reader.getLocalName();
if (NAMESPACE_URI_1_0.equals(namespaceURI)) {
if (ACTIVE.equals(localName)) {
final String val = getElementText(reader, propertyReplacer);
metaData.setDeliveryActive(Boolean.parseBoolean(val.trim()));
} else {
throw unexpectedElement(reader);
}
} else {
super.processElement(metaData, reader, propertyReplacer);
}
}
}
| 3,270 | 40.405063 | 165 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/deliveryactive/parser/EJBBoundMdbDeliveryMetaDataParser20.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2022, 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.ejb3.deliveryactive.parser;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.jboss.as.ejb3.deliveryactive.metadata.EJBBoundMdbDeliveryMetaData;
import org.jboss.metadata.ejb.parser.jboss.ejb3.AbstractEJBBoundMetaDataParser;
import org.jboss.metadata.property.PropertyReplacer;
/**
* Parser for EJBBoundMdbDeliveryMetaData components, namespace delivery-active:1.2
*
* @author Flavia Rainone
*/
public class EJBBoundMdbDeliveryMetaDataParser20 extends AbstractEJBBoundMetaDataParser<EJBBoundMdbDeliveryMetaData> {
public static final String NAMESPACE_URI_2_0 = "urn:delivery-active:2.0";
private static final String ROOT_ELEMENT_DELIVERY = "delivery";
private static final String ACTIVE = "active";
private static final String GROUP = "group";
public static final EJBBoundMdbDeliveryMetaDataParser20 INSTANCE = new EJBBoundMdbDeliveryMetaDataParser20();
private EJBBoundMdbDeliveryMetaDataParser20() {}
@Override
public EJBBoundMdbDeliveryMetaData parse(XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException {
// we only parse <delivery> (root) element
if (!ROOT_ELEMENT_DELIVERY.equals(reader.getLocalName())) {
throw unexpectedElement(reader);
}
EJBBoundMdbDeliveryMetaData metaData = new EJBBoundMdbDeliveryMetaData();
processElements(metaData, reader, propertyReplacer);
return metaData;
}
@Override
protected void processElement(EJBBoundMdbDeliveryMetaData metaData, XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException {
final String namespaceURI = reader.getNamespaceURI();
final String localName = reader.getLocalName();
if (NAMESPACE_URI_2_0.equals(namespaceURI)) {
switch (localName) {
case ACTIVE:
final String val = getElementText(reader, propertyReplacer);
metaData.setDeliveryActive(Boolean.parseBoolean(val.trim()));
break;
case GROUP:
final String deliveryGroup = getElementText(reader, propertyReplacer).trim();
if (metaData.getDeliveryGroups() == null) {
metaData.setDeliveryGroups(deliveryGroup);
} else {
final List<String> deliveryGroups = new ArrayList<String>(metaData.getDeliveryGroups().length + 1);
Collections.addAll(deliveryGroups, metaData.getDeliveryGroups());
deliveryGroups.add(deliveryGroup);
metaData.setDeliveryGroups(deliveryGroups.toArray(new String[deliveryGroups.size()]));
}
break;
default:
throw unexpectedElement(reader);
}
} else {
super.processElement(metaData, reader, propertyReplacer);
}
}
}
| 4,134 | 42.989362 | 165 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/deliveryactive/metadata/EJBBoundMdbDeliveryMetaData.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.ejb3.deliveryactive.metadata;
import org.jboss.metadata.ejb.parser.jboss.ejb3.AbstractEJBBoundMetaData;
/**
* Metadata for delivery active property of message-driven beans
*
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2013 Red Hat inc
* @author Flavia Rainone.
*/
public class EJBBoundMdbDeliveryMetaData extends AbstractEJBBoundMetaData {
private boolean deliveryActive;
private String[] deliveryGroups;
public boolean isDeliveryActive() {
return deliveryActive;
}
public void setDeliveryActive(boolean deliveryActive) {
this.deliveryActive = deliveryActive;
}
public String[] getDeliveryGroups() {
return deliveryGroups;
}
public void setDeliveryGroups(String... deliveryGroups) {
this.deliveryGroups = deliveryGroups;
}
}
| 1,870 | 33.648148 | 77 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/pool/EJBBoundPoolMetaData.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.ejb3.pool;
import org.jboss.metadata.ejb.parser.jboss.ejb3.AbstractEJBBoundMetaData;
/**
* Metadata represents the pool name configured for EJBs via the jboss-ejb3.xml deployment descriptor
*
* @author Jaikiran Pai
*/
public class EJBBoundPoolMetaData extends AbstractEJBBoundMetaData {
private String poolName;
public String getPoolName() {
return poolName;
}
public void setPoolName(final String poolName) {
this.poolName = poolName;
}
}
| 1,530 | 33.795455 | 101 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/pool/StatelessObjectFactory.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2007, 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.ejb3.pool;
/**
* Creates and destroys stateless objects.
* <p/>
* The object returned by create has dependencies injected. The PostConstruct
* callback, if defined, has been called.
*
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
* @version $Revision: $
*/
public interface StatelessObjectFactory<T> {
/**
* Creates a new stateless object by calling it's empty constructor,
* do injection and calling post-construct.
*
* @return
*/
T create();
/**
* Perform any cleanup actions on the object, such as
* calling the pre-destroy callback.
*
* @param obj the object
*/
void destroy(T obj);
}
| 1,741 | 33.84 | 77 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/pool/EJBBoundPoolParser.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.ejb3.pool;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.jboss.metadata.ejb.parser.jboss.ejb3.AbstractEJBBoundMetaDataParser;
import org.jboss.metadata.property.PropertyReplacer;
/**
* Parser for <code>urn:ejb-pool</code> namespace. The <code>urn:ejb-pool</code> namespace elements
* can be used to configure pool names for Jakarta Enterprise Beans.
*
* @author Jaikiran Pai
*/
public class EJBBoundPoolParser extends AbstractEJBBoundMetaDataParser<EJBBoundPoolMetaData> {
public static final String NAMESPACE_URI_1_0 = "urn:ejb-pool:1.0";
public static final String NAMESPACE_URI_2_0 = "urn:ejb-pool:2.0";
private static final String ROOT_ELEMENT_POOL = "pool";
private static final String ELEMENT_BEAN_INSTANCE_POOL_REF = "bean-instance-pool-ref";
@Override
public EJBBoundPoolMetaData parse(final XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException {
final String element = reader.getLocalName();
// we only parse <pool> (root) element
if (!ROOT_ELEMENT_POOL.equals(element)) {
throw unexpectedElement(reader);
}
final EJBBoundPoolMetaData ejbBoundPoolMetaData = new EJBBoundPoolMetaData();
this.processElements(ejbBoundPoolMetaData, reader, propertyReplacer);
return ejbBoundPoolMetaData;
}
@Override
protected void processElement(final EJBBoundPoolMetaData poolMetaData, final XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException {
final String namespaceURI = reader.getNamespaceURI();
final String elementName = reader.getLocalName();
// if it doesn't belong to our namespace then let the super handle this
if (!NAMESPACE_URI_1_0.equals(namespaceURI) && !NAMESPACE_URI_2_0.equals(namespaceURI)) {
super.processElement(poolMetaData, reader, propertyReplacer);
return;
}
if (ELEMENT_BEAN_INSTANCE_POOL_REF.equals(elementName)) {
final String poolName = getElementText(reader, propertyReplacer);
// set the pool name in the metadata
poolMetaData.setPoolName(poolName);
} else {
throw unexpectedElement(reader);
}
}
}
| 3,348 | 43.653333 | 173 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/pool/AbstractPool.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2006, 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.ejb3.pool;
import java.util.concurrent.atomic.AtomicInteger;
/**
* The base of all pool implementations.
*
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
* @version $Revision$
*/
public abstract class AbstractPool<T> implements Pool<T> {
private final StatelessObjectFactory<T> factory;
private final AtomicInteger createCount = new AtomicInteger(0);
private final AtomicInteger removeCount = new AtomicInteger(0);
protected AbstractPool(StatelessObjectFactory<T> factory) {
assert factory != null : "factory is null";
this.factory = factory;
}
public int getCreateCount() {
return createCount.get();
}
public int getRemoveCount() {
return removeCount.get();
}
public abstract void setMaxSize(int maxSize);
protected T create() {
T bean = factory.create();
createCount.incrementAndGet();
return bean;
}
@Deprecated
protected void remove(T bean) {
this.doRemove(bean);
}
protected void destroy(T bean) {
doRemove(bean);
}
/**
* Remove the bean context and invoke any callbacks
* and track the remove count
*
* @param bean
*/
protected void doRemove(T bean) {
try {
factory.destroy(bean);
} finally {
removeCount.incrementAndGet();
}
}
}
| 2,512 | 28.22093 | 70 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/pool/Pool.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2007, 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.ejb3.pool;
/**
* A pool of stateless objects.
* <p/>
* A pool is linked to an object factory. How this link is established
* is left beyond scope.
*
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
* @version $Revision: $
*/
public interface Pool<T> {
/**
* Discard an object. This will be called
* in case of a system exception.
*
* @param obj the object
*/
void discard(T obj);
/**
* Get an object from the pool. This will mark
* the object as being in use.
*
* @return the object
*/
T get();
int getAvailableCount();
int getCreateCount();
int getCurrentSize();
int getMaxSize();
int getRemoveCount();
/**
* Release the object from use.
*
* @param obj the object
*/
void release(T obj);
void setMaxSize(int maxSize);
/**
* Start the pool.
*/
void start();
/**
* Stop the pool.
*/
void stop();
}
| 2,042 | 24.860759 | 70 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/pool/strictmax/StrictMaxPool.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2007, 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.ejb3.pool.strictmax;
import static org.jboss.as.ejb3.logging.EjbLogger.ROOT_LOGGER;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.pool.AbstractPool;
import org.jboss.as.ejb3.pool.StatelessObjectFactory;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/**
* A pool with a maximum size.
*
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
* @author <a href="mailto:[email protected]">Kabir Khan</a>
*/
public class StrictMaxPool<T> extends AbstractPool<T> {
/**
* A FIFO semaphore that is set when the strict max size behavior is in effect.
* When set, only maxSize instances may be active and any attempt to get an
* instance will block until an instance is freed.
*/
private final Semaphore semaphore;
/**
* The maximum number of instances allowed in the pool
*/
private final int maxSize;
/**
* The time to wait for the semaphore.
*/
private final long timeout;
private final TimeUnit timeUnit;
/**
* The pool data structure
* Guarded by the implicit lock for "pool"
*/
private final Queue<T> pool = new ConcurrentLinkedQueue<T>();
public StrictMaxPool(StatelessObjectFactory<T> factory, int maxSize, long timeout, TimeUnit timeUnit) {
super(factory);
this.maxSize = maxSize;
this.semaphore = new Semaphore(maxSize, false);
this.timeout = timeout;
this.timeUnit = timeUnit;
}
public void discard(T ctx) {
if (ROOT_LOGGER.isTraceEnabled()) {
ROOT_LOGGER.tracef("Discard instance %s#%s", this, ctx);
}
// If we block when maxSize instances are in use, invoke release on strictMaxSize
semaphore.release();
// Let the super do any other remove stuff
super.doRemove(ctx);
}
public int getCurrentSize() {
return getCreateCount() - getRemoveCount();
}
public int getAvailableCount() {
return semaphore.availablePermits();
}
public int getMaxSize() {
return maxSize;
}
public void setMaxSize(int maxSize) {
throw EjbLogger.ROOT_LOGGER.methodNotImplemented();
}
/**
* Get an instance without identity.
* Can be used by finders,create-methods, and activation
*
* @return Context /w instance
*/
public T get() {
try {
boolean acquired = semaphore.tryAcquire(timeout, timeUnit);
if (!acquired)
throw EjbLogger.ROOT_LOGGER.failedToAcquirePermit(timeout, timeUnit);
} catch (InterruptedException e) {
throw EjbLogger.ROOT_LOGGER.acquireSemaphoreInterrupted();
}
T bean = pool.poll();
if( bean !=null) {
//we found a bean instance in the pool, return it
return bean;
}
try {
// Pool is empty, create an instance
bean = create();
} finally {
if (bean == null) {
semaphore.release();
}
}
return bean;
}
/**
* Return an instance after invocation.
* <p/>
* Called in 2 cases:
* a) Done with finder method
* b) Just removed
*
* @param obj
*/
public void release(T obj) {
if (ROOT_LOGGER.isTraceEnabled()) {
ROOT_LOGGER.tracef("%s/%s Free instance: %s", pool.size(), maxSize, this);
}
pool.add(obj);
semaphore.release();
}
@Override
@Deprecated
public void remove(T ctx) {
if (ROOT_LOGGER.isTraceEnabled()) {
ROOT_LOGGER.tracef("Removing instance: %s#%s", this, ctx);
}
semaphore.release();
// let the super do the other remove stuff
super.doRemove(ctx);
}
public void start() {
// TODO Auto-generated method stub
}
public void stop() {
for (T obj = pool.poll(); obj != null; obj = pool.poll()) {
destroy(obj);
}
}
}
| 5,172 | 28.56 | 107 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/inflow/JBossMessageEndpointFactory.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.ejb3.inflow;
import java.lang.reflect.Method;
import java.security.PrivilegedAction;
import java.util.concurrent.atomic.AtomicInteger;
import jakarta.resource.spi.UnavailableException;
import jakarta.resource.spi.endpoint.MessageEndpoint;
import jakarta.resource.spi.endpoint.MessageEndpointFactory;
import javax.transaction.xa.XAResource;
import org.jboss.as.server.deployment.ModuleClassFactory;
import org.jboss.invocation.proxy.ProxyConfiguration;
import org.jboss.invocation.proxy.ProxyFactory;
import org.wildfly.security.manager.WildFlySecurityManager;
import static java.security.AccessController.doPrivileged;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
/**
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class JBossMessageEndpointFactory implements MessageEndpointFactory {
private static final AtomicInteger PROXY_ID = new AtomicInteger(0);
private final MessageEndpointService<?> service;
private final ProxyFactory<Object> factory;
private final Class<?> endpointClass;
public JBossMessageEndpointFactory(final ClassLoader classLoader, final MessageEndpointService<?> service, final Class<Object> ejbClass, final Class<?> messageListenerInterface) {
// todo: generics bug; only Object.class is a Class<Object>. Everything else is Class<? extends Object> aka Class<?>
this.service = service;
final ProxyConfiguration<Object> configuration = new ProxyConfiguration<Object>()
.setClassLoader(classLoader)
.setProxyName(ejbClass.getName() + "$$$endpoint" + PROXY_ID.incrementAndGet())
.setSuperClass(ejbClass)
.setClassFactory(ModuleClassFactory.INSTANCE)
.setProtectionDomain(ejbClass.getProtectionDomain())
.addAdditionalInterface(MessageEndpoint.class)
.addAdditionalInterface(messageListenerInterface);
this.factory = new ProxyFactory<Object>(configuration);
this.endpointClass = ejbClass;
}
@Override
public MessageEndpoint createEndpoint(XAResource xaResource) throws UnavailableException {
return createEndpoint(xaResource, 0);
}
@Override
public MessageEndpoint createEndpoint(XAResource xaResource, long timeout) throws UnavailableException {
Object delegate = service.obtain(timeout, MILLISECONDS);
MessageEndpointInvocationHandler handler = new MessageEndpointInvocationHandler(service, delegate, xaResource);
// New instance creation leads to component initialization which needs to have the TCCL that corresponds to the
// component classloader. @see https://issues.jboss.org/browse/WFLY-3989
final ClassLoader oldTCCL = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(this.factory.getClassLoader());
if (System.getSecurityManager() == null) {
return createEndpoint(factory, handler);
} else {
return doPrivileged((PrivilegedAction<MessageEndpoint>) () -> {
return createEndpoint(factory, handler);
});
}
} finally {
// reset TCCL
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTCCL);
}
}
@Override
public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException {
return service.isDeliveryTransacted(method);
}
@Override
public String getActivationName() {
return service.getActivationName();
}
@Override
public Class<?> getEndpointClass() {
// The MDB class is the message endpoint class
return this.endpointClass;
}
private MessageEndpoint createEndpoint(ProxyFactory<Object> factory, MessageEndpointInvocationHandler handler) {
try {
return (MessageEndpoint) factory.newInstance(handler);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
| 5,306 | 42.146341 | 183 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/inflow/MessageEndpointService.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.ejb3.inflow;
import jakarta.transaction.TransactionManager;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
/**
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
*/
public interface MessageEndpointService<T> {
Class<T> getMessageListenerInterface();
TransactionManager getTransactionManager();
boolean isDeliveryTransacted(Method method) throws NoSuchMethodException;
T obtain(long timeout, TimeUnit milliseconds);
void release(T obj);
/**
* Returns the classloader that's applicable for the endpoint application.
* This classloader will be used to set the thread context classloader during the beforeDelivery()/afterDelivery()
* callbacks as mandated by the JCA 1.6 spec
*
* @return
*/
ClassLoader getClassLoader();
String getActivationName();
}
| 1,904 | 34.943396 | 118 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/inflow/MessageEndpointInvocationHandler.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.ejb3.inflow;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ApplicationServerInternalException;
import jakarta.resource.spi.LocalTransactionException;
import jakarta.resource.spi.endpoint.MessageEndpoint;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.InvalidTransactionException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Status;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import javax.transaction.xa.XAResource;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicBoolean;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
*/
public class MessageEndpointInvocationHandler extends AbstractInvocationHandler implements MessageEndpoint {
private final MessageEndpointService service;
private final Object delegate;
private final XAResource xaRes;
private final AtomicBoolean released = new AtomicBoolean(false);
private Transaction currentTx;
private ClassLoader previousClassLoader;
private Transaction previousTx;
MessageEndpointInvocationHandler(final MessageEndpointService service, final Object delegate, final XAResource xaResource) {
this.service = service;
this.delegate = delegate;
this.xaRes = xaResource;
}
@Override
public void afterDelivery() throws ResourceException {
final TransactionManager tm = getTransactionManager();
try {
if (currentTx != null) {
if (currentTx.getStatus() == Status.STATUS_MARKED_ROLLBACK)
tm.rollback();
else
tm.commit();
currentTx = null;
}
if (previousTx != null) {
tm.resume(previousTx);
previousTx = null;
}
} catch (InvalidTransactionException e) {
throw new LocalTransactionException(e);
} catch (HeuristicMixedException e) {
throw new LocalTransactionException(e);
} catch (SystemException e) {
throw new LocalTransactionException(e);
} catch (HeuristicRollbackException e) {
throw new LocalTransactionException(e);
} catch (RollbackException e) {
throw new LocalTransactionException(e);
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(previousClassLoader);
previousClassLoader = null;
}
}
@Override
public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException {
// JCA 1.6 FR 13.5.6
// The application server must set the thread context class loader to the endpoint
// application class loader during the beforeDelivery call.
previousClassLoader = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(getApplicationClassLoader());
try {
final TransactionManager tm = getTransactionManager();
// TODO: in violation of JCA 1.6 FR 13.5.9?
previousTx = tm.suspend();
boolean isTransacted = service.isDeliveryTransacted(method);
if (isTransacted) {
tm.begin();
currentTx = tm.getTransaction();
if (xaRes != null)
currentTx.enlistResource(xaRes);
}
} catch (Throwable t) {
throw new ApplicationServerInternalException(t);
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(previousClassLoader);
}
}
@Override
protected boolean doEquals(Object obj) {
if (!(obj instanceof MessageEndpointInvocationHandler))
return false;
return delegate.equals(((MessageEndpointInvocationHandler) obj).delegate);
}
@Override
protected Object doInvoke(Object proxy, Method method, Object[] args) throws Throwable {
// Are we still usable?
if (released.get())
throw EjbLogger.ROOT_LOGGER.messageEndpointAlreadyReleased(this);
// TODO: check for concurrent invocation
if (method.getDeclaringClass().equals(MessageEndpoint.class))
return handle(method, args);
// TODO: Option A
try {
return method.invoke(delegate, args);
}
catch (InvocationTargetException e) {
throw e.getCause();
}
}
@Override
public int hashCode() {
return delegate.hashCode();
}
protected final ClassLoader getApplicationClassLoader() {
return this.service.getClassLoader();
}
protected final TransactionManager getTransactionManager() {
return service.getTransactionManager();
}
@Override
public void release() {
if (released.getAndSet(true))
throw new IllegalStateException("Message endpoint " + this + " has already been released");
// TODO: tidy up outstanding delivery
service.release(delegate);
}
}
| 6,385 | 36.786982 | 128 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/inflow/AbstractInvocationHandler.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.ejb3.inflow;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
*/
abstract class AbstractInvocationHandler implements InvocationHandler {
protected abstract boolean doEquals(Object obj);
protected abstract Object doInvoke(Object proxy, Method method, Object[] args) throws Throwable;
@Override
public final boolean equals(Object obj) {
if (obj == this)
return true;
if (obj == null)
return false;
if (Proxy.isProxyClass(obj.getClass()))
return equals(Proxy.getInvocationHandler(obj));
// It might not be a JDK proxy that's handling this, so here we do a little trick.
// Normally you would do:
// if(!(obj instanceof EndpointInvocationHandler))
// return false;
if (!(obj instanceof AbstractInvocationHandler))
return obj.equals(this);
return doEquals(obj);
}
protected Object handle(Method method, Object[] args) throws Throwable {
try {
return method.invoke(this, args);
}
catch (InvocationTargetException e) {
throw e.getCause();
}
}
public abstract int hashCode();
@Override
public final Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getDeclaringClass().equals(Object.class))
return handle(method, args);
return doInvoke(proxy, method, args);
}
}
| 2,694 | 34.460526 | 100 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/suspend/EJBSuspendHandlerService.java | /*
* Copyright 2017 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.ejb3.suspend;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Synchronization;
import jakarta.transaction.SystemException;
import org.jboss.as.ejb3.deployment.DeploymentRepository;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.server.suspend.ServerActivity;
import org.jboss.as.server.suspend.ServerActivityCallback;
import org.jboss.as.server.suspend.SuspendController;
import org.jboss.invocation.InterceptorContext;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.wildfly.transaction.client.AbstractTransaction;
import org.wildfly.transaction.client.CreationListener;
import org.wildfly.transaction.client.LocalTransactionContext;
/**
* Controls shutdown indicating whether a remote request should be accepted or not.
*
* @author Flavia Rainone
*/
public class EJBSuspendHandlerService implements Service<EJBSuspendHandlerService>, ServerActivity, CreationListener,
Synchronization {
/**
* EJBSuspendHandlerService name
*/
public static final ServiceName SERVICE_NAME = ServiceName.JBOSS.append("ejb").append("suspend-handler");
/**
* Updates activeInvocationCount field
*/
private static final AtomicIntegerFieldUpdater<EJBSuspendHandlerService> activeInvocationCountUpdater = AtomicIntegerFieldUpdater
.newUpdater(EJBSuspendHandlerService.class, "activeInvocationCount");
/**
* Updates activeTransactionCount field
*/
private static final AtomicIntegerFieldUpdater<EJBSuspendHandlerService> activeTransactionCountUpdater = AtomicIntegerFieldUpdater
.newUpdater(EJBSuspendHandlerService.class, "activeTransactionCount");
/**
* Updates listener field
*/
private static final AtomicReferenceFieldUpdater<EJBSuspendHandlerService, ServerActivityCallback> listenerUpdater = AtomicReferenceFieldUpdater
.newUpdater(EJBSuspendHandlerService.class, ServerActivityCallback.class, "listener");
/**
* Model attribute: if gracefulTxnShutdown attribute is true, handler will bypass module unavailability notification
* to clients while there still active transactions, giving those transactions a chance to complete before completing
* suspension.
*/
private boolean gracefulTxnShutdown;
/**
* Injection of suspend controller, for registering server activity
*/
private final InjectedValue<SuspendController> suspendControllerInjectedValue = new InjectedValue<>();
/**
* Injection of local transaction context for keeping track of active transactions
*/
private final InjectedValue<LocalTransactionContext> localTransactionContextInjectedValue = new InjectedValue<>();
/**
* Injection of DeploymentRepository, for suspending and resuming deployments
*/
private final InjectedValue<DeploymentRepository> deploymentRepositoryInjectedValue = new InjectedValue<>();
/**
* The number of active requests that are using this entry point
*/
@SuppressWarnings("unused") private volatile int activeInvocationCount = 0;
/**
* The number of active transactions in the server
*/
@SuppressWarnings("unused") private volatile int activeTransactionCount = 0;
/**
* Keeps track of whether the server shutdown controller has requested suspension
*/
private volatile boolean suspended = false;
/**
* Listener to notify when all active transactions are complete
*/
private volatile ServerActivityCallback listener = null;
/**
* Constructor.
*
* @param gracefulTxnShutdown value of model attribute
*/
public EJBSuspendHandlerService(boolean gracefulTxnShutdown) {
this.gracefulTxnShutdown = gracefulTxnShutdown;
}
/**
* Sets a new value for {@code gracefulTxnShutdown}.
*
* @param gracefulTxnShutdown new value of the model attribute
*/
public void enableGracefulTxnShutdown(boolean gracefulTxnShutdown) {
this.gracefulTxnShutdown = gracefulTxnShutdown;
}
/**
* Returns suspend controller injected value.
*
* @return suspend controller injected value
*/
public InjectedValue<SuspendController> getSuspendControllerInjectedValue() {
return suspendControllerInjectedValue;
}
/**
* Returns local transaction context injected value.
*
* @return local transaction context injected value
*/
public InjectedValue<LocalTransactionContext> getLocalTransactionContextInjectedValue() {
return localTransactionContextInjectedValue;
}
/**
* Returns deployment repository injected value.
*
* @return local transaction context injected value
*/
public InjectedValue<DeploymentRepository> getDeploymentRepositoryInjectedValue() {
return deploymentRepositoryInjectedValue;
}
/**
* Returns service value.
*/
@Override public EJBSuspendHandlerService getValue() {
return this;
}
/**
* Starts the service. Registers server activity, sets transaction listener on local transaction context, and creates and
* installs deployment controller service.
*
* @param context start context
*/
public void start(StartContext context) {
final SuspendController suspendController = suspendControllerInjectedValue.getValue();
suspendController.registerActivity(this);
final LocalTransactionContext localTransactionContext = localTransactionContextInjectedValue.getValue();
localTransactionContext.registerCreationListener(this);
}
/**
* Stops the service. Unregisters service activity and clears transaction listener.
* @param context stop context
*/
public void stop(StopContext context) {
final SuspendController suspendController = suspendControllerInjectedValue.getValue();
suspendController.unRegisterActivity(this);
final LocalTransactionContext localTransactionContext = localTransactionContextInjectedValue.getValue();
localTransactionContext.removeCreationListener(this);
}
/**
* Pre suspend. Do nothing.
* @param listener callback listener
*/
@Override public void preSuspend(ServerActivityCallback listener) {
listener.done();
}
/**
* Notifies local transaction context that server is suspended, and only completes suspension if
* there are no active invocations nor transactions.
*
* @param listener callback listener
*/
@Override public void suspended(ServerActivityCallback listener) {
this.suspended = true;
listenerUpdater.set(this, listener);
localTransactionContextInjectedValue.getValue().suspendRequests();
final int activeInvocationCount = activeInvocationCountUpdater.get(this);
if (activeInvocationCount == 0) {
if (gracefulTxnShutdown) {
final int activeTransactionCountUpdaterAtShutdown = activeTransactionCountUpdater.get(this);
if (activeTransactionCountUpdaterAtShutdown == 0) {
this.doneSuspended();
} else {
EjbLogger.ROOT_LOGGER.suspensionWaitingActiveTransactions(activeTransactionCountUpdaterAtShutdown);
}
} else {
this.doneSuspended();
}
}
}
/**
* Notifies local transaction context that server is resumed, and restarts deployment controller.
*/
@Override public void resume() {
this.suspended = false;
localTransactionContextInjectedValue.getValue().resumeRequests();
ServerActivityCallback listener = listenerUpdater.get(this);
if (listener != null) {
listenerUpdater.compareAndSet(this, listener, null);
}
deploymentRepositoryInjectedValue.getValue().resume();
}
/**
* Indicates if a invocation should be accepted: which will happen only if server is not suspended, or if the invocation
* involves a still active transaction.
*
* @param context interceptor context
* @return {@code true} if invocation can be accepted by invoking interceptor
*/
public boolean acceptInvocation(InterceptorContext context) throws SystemException {
if (suspended) {
if (!gracefulTxnShutdown)
return false;
// a null listener means that we are done suspending;
if (listenerUpdater.get(this) == null || activeTransactionCountUpdater.get(this) == 0)
return false;
// retrieve attachment only when we are not entirely suspended, meaning we are mid-suspension
if (!context.hasTransaction()) {
// all requests with no transaction must be rejected at this point
// we need also to block requests with new transactions, which is not being done here. Instead,
// we are relying on a future call to getTransaction in the same thread, before the invocation is executed;
// this call will throw an exception if the transaction is new, because this suspend handler
// has invoked clientTransactionContext.suspendRequests
return false;
}
}
activeInvocationCountUpdater.incrementAndGet(this);
return true;
}
/**
* Notifies handler that an active invocation is complete.
*/
public void invocationComplete() {
int activeInvocations = activeInvocationCountUpdater.decrementAndGet(this);
if (suspended && activeInvocations == 0 && (!gracefulTxnShutdown || (activeTransactionCountUpdater.get(this) == 0))) {
doneSuspended();
}
}
/**
* Notifies handler that a new transaction has been created.
*/
@Override public void transactionCreated(AbstractTransaction transaction, CreatedBy createdBy) {
activeTransactionCountUpdater.incrementAndGet(this);
try {
transaction.registerSynchronization(this);
} catch (RollbackException | IllegalStateException e) {
// it means the transaction is marked for rollback, or is prepared for commit, at this point we cannot register synchronization
decrementTransactionCount();
} catch (SystemException e) {
decrementTransactionCount();
EjbLogger.ROOT_LOGGER.debug("Unexpected exception", e);
throw new RuntimeException(e);
}
}
/**
* Notifies handler that an active transaction is about to complete.
*/
@Override public void beforeCompletion() {
}
/**
* Notifies handler that an active transaction has completed.
*/
@Override public void afterCompletion(int status) {
decrementTransactionCount();
}
/**
* Indicates if Jakarta Enterprise Beans subsystem is suspended.
*
* @return {@code true} if Jakarta Enterprise Beans susbsystem suspension is started (regardless of whether it completed or not)
*/
public boolean isSuspended() {
return suspended;
}
/**
* Completes suspension: stop deployment controller.
*/
private void doneSuspended() {
final ServerActivityCallback oldListener = listener;
if (oldListener != null && listenerUpdater.compareAndSet(this, oldListener, null)) {
deploymentRepositoryInjectedValue.getValue().suspend();
oldListener.done();
EjbLogger.ROOT_LOGGER.suspensionComplete();
}
}
/**
* Decrements active tranbsaction count and completes suspension if we are suspending and there are no more
* active transactions left.
*/
private void decrementTransactionCount() {
int activeTransactionCount = activeTransactionCountUpdater.decrementAndGet(this);
if (suspended && activeTransactionCount == 0 && activeInvocationCountUpdater.get(this) == 0) {
doneSuspended();
}
}
}
| 12,939 | 37.397626 | 148 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/EjbHomeViewDescription.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, 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.ejb3.component;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.metadata.ejb.spec.MethodInterfaceType;
/**
* @author Stuart Douglas
*/
public class EjbHomeViewDescription extends EJBViewDescription {
public EjbHomeViewDescription(final ComponentDescription componentDescription, final String viewClassName, final MethodInterfaceType methodIntf) {
super(componentDescription, viewClassName, methodIntf, false);
}
}
| 1,497 | 39.486486 | 150 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/EJBComponentCreateServiceFactory.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.ejb3.component;
import org.jboss.as.ee.component.ComponentCreateServiceFactory;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.deployment.ApplicationExceptions;
/**
* User: jpai
*/
public abstract class EJBComponentCreateServiceFactory implements ComponentCreateServiceFactory {
protected ApplicationExceptions ejbJarConfiguration;
public void setEjbJarConfiguration(ApplicationExceptions ejbJarConfiguration) {
if (ejbJarConfiguration == null) {
throw EjbLogger.ROOT_LOGGER.EjbJarConfigurationIsNull();
}
this.ejbJarConfiguration = ejbJarConfiguration;
}
}
| 1,680 | 37.204545 | 97 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/Ejb2xViewType.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.ejb3.component;
/**
* An enum that is used as a marker for Enterprise Beans 2.x views.
*
* {@code MethodInterfaceType} is not sufficient for this, as it cannot differentiate
* between Enterprise Beans 3 business and Enterprise Beans 2 component views
*
* @author Stuart Douglas
*/
public enum Ejb2xViewType {
LOCAL,
LOCAL_HOME,
REMOTE,
HOME,
}
| 1,414 | 34.375 | 85 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/EJBContainerInterceptorsViewConfigurator.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.ejb3.component;
import static org.jboss.as.server.deployment.Attachments.REFLECTION_INDEX;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jboss.as.ee.component.Attachments;
import org.jboss.as.ee.component.ClassDescriptionTraversal;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.EEApplicationClasses;
import org.jboss.as.ee.component.EEModuleClassDescription;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.ee.component.InterceptorDescription;
import org.jboss.as.ee.component.ViewConfiguration;
import org.jboss.as.ee.component.ViewConfigurator;
import org.jboss.as.ee.component.ViewDescription;
import org.jboss.as.ee.component.interceptors.InterceptorClassDescription;
import org.jboss.as.ee.component.interceptors.InterceptorOrder;
import org.jboss.as.ee.component.interceptors.UserInterceptorFactory;
import org.jboss.as.ee.logging.EeLogger;
import org.jboss.as.ee.utils.ClassLoadingUtils;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ValueManagedReference;
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.reflect.ClassReflectionIndex;
import org.jboss.as.server.deployment.reflect.ClassReflectionIndexUtil;
import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.invocation.InterceptorFactoryContext;
import org.jboss.invocation.Interceptors;
import org.jboss.invocation.proxy.MethodIdentifier;
import org.jboss.modules.Module;
/**
* A {@link ViewConfigurator} which sets up the Jakarta Enterprise Beans view with the relevant {@link Interceptor}s
* which will carry out invocation on the container-interceptor(s) applicable for an Jakarta Enterprise Beans, during an Jakarta Enterprise Beans method invocation
*
* @author Jaikiran Pai
*/
public class EJBContainerInterceptorsViewConfigurator implements ViewConfigurator {
private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class[0];
public static final EJBContainerInterceptorsViewConfigurator INSTANCE = new EJBContainerInterceptorsViewConfigurator();
private EJBContainerInterceptorsViewConfigurator() {
}
@Override
public void configure(DeploymentPhaseContext deploymentPhaseContext, ComponentConfiguration componentConfiguration, ViewDescription viewDescription, ViewConfiguration viewConfiguration) throws DeploymentUnitProcessingException {
final ComponentDescription componentDescription = componentConfiguration.getComponentDescription();
// ideally it should always be an EJBComponentDescription when this view configurator is invoked, but let's just make sure
if (!(componentDescription instanceof EJBComponentDescription)) {
return;
}
final EJBComponentDescription ejbComponentDescription = (EJBComponentDescription) componentDescription;
// we don't want to waste time processing if there are no container interceptors applicable for the Jakarta Enterprise Beans
final Set<InterceptorDescription> allContainerInterceptors = ejbComponentDescription.getAllContainerInterceptors();
if (allContainerInterceptors == null || allContainerInterceptors.isEmpty()) {
return;
}
// do the processing
this.doConfigure(deploymentPhaseContext, ejbComponentDescription, viewConfiguration);
}
private void doConfigure(final DeploymentPhaseContext context, final EJBComponentDescription ejbComponentDescription,
final ViewConfiguration viewConfiguration) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = context.getDeploymentUnit();
final EEApplicationClasses applicationClasses = deploymentUnit.getAttachment(Attachments.EE_APPLICATION_CLASSES_DESCRIPTION);
final Module module = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.MODULE);
final Map<String, List<InterceptorFactory>> userAroundInvokesByInterceptorClass = new HashMap<String, List<InterceptorFactory>>();
final Map<String, List<InterceptorFactory>> userAroundTimeoutsByInterceptorClass;
if (ejbComponentDescription.isTimerServiceRequired()) {
userAroundTimeoutsByInterceptorClass = new HashMap<String, List<InterceptorFactory>>();
} else {
userAroundTimeoutsByInterceptorClass = null;
}
// First step - find the applicable @AroundInvoke/@AroundTimeout methods on all the container-interceptors and keep track of that
// info
for (final InterceptorDescription interceptorDescription : ejbComponentDescription.getAllContainerInterceptors()) {
final String interceptorClassName = interceptorDescription.getInterceptorClassName();
final Class<?> intereptorClass;
try {
intereptorClass = ClassLoadingUtils.loadClass(interceptorClassName, module);
} catch (ClassNotFoundException e) {
throw EeLogger.ROOT_LOGGER.cannotLoadInterceptor(e, interceptorClassName);
}
// run the interceptor class (and its super class hierarchy) through the InterceptorClassDescriptionTraversal so that it can
// find the relevant @AroundInvoke/@AroundTimeout methods
final InterceptorClassDescriptionTraversal interceptorClassDescriptionTraversal = new InterceptorClassDescriptionTraversal(intereptorClass, applicationClasses, deploymentUnit, ejbComponentDescription);
interceptorClassDescriptionTraversal.run();
// now that the InterceptorClassDescriptionTraversal has done the relevant processing, keep track of the @AroundInvoke and
// @AroundTimeout methods applicable for this interceptor class, within a map
final List<InterceptorFactory> aroundInvokeInterceptorFactories = interceptorClassDescriptionTraversal.getAroundInvokeInterceptorFactories();
if (aroundInvokeInterceptorFactories != null) {
userAroundInvokesByInterceptorClass.put(interceptorClassName, aroundInvokeInterceptorFactories);
}
if (ejbComponentDescription.isTimerServiceRequired()) {
final List<InterceptorFactory> aroundTimeoutInterceptorFactories = interceptorClassDescriptionTraversal.getAroundTimeoutInterceptorFactories();
if (aroundTimeoutInterceptorFactories != null) {
userAroundTimeoutsByInterceptorClass.put(interceptorClassName, aroundTimeoutInterceptorFactories);
}
}
}
// At this point we have each interceptor class mapped against their corresponding @AroundInvoke/@AroundTimeout InterceptorFactory(s)
// Let's now iterate over all the methods of the Jakarta Enterprise Beans view and apply the relevant InterceptorFactory(s) to that method
final List<InterceptorDescription> classLevelContainerInterceptors = ejbComponentDescription.getClassLevelContainerInterceptors();
final Map<MethodIdentifier, List<InterceptorDescription>> methodLevelContainerInterceptors = ejbComponentDescription.getMethodLevelContainerInterceptors();
final List<Method> viewMethods = viewConfiguration.getProxyFactory().getCachedMethods();
for (final Method method : viewMethods) {
final MethodIdentifier methodIdentifier = MethodIdentifier.getIdentifier(method.getReturnType(), method.getName(), method.getParameterTypes());
final List<InterceptorFactory> aroundInvokesApplicableForMethod = new ArrayList<InterceptorFactory>();
final List<InterceptorFactory> aroundTimeoutsApplicableForMethod = new ArrayList<InterceptorFactory>();
// first add the default interceptors (if not excluded) to the deque
if (!ejbComponentDescription.isExcludeDefaultContainerInterceptors() && !ejbComponentDescription.isExcludeDefaultContainerInterceptors(methodIdentifier)) {
for (final InterceptorDescription interceptorDescription : ejbComponentDescription.getDefaultContainerInterceptors()) {
String interceptorClassName = interceptorDescription.getInterceptorClassName();
final List<InterceptorFactory> aroundInvokesOnInterceptor = userAroundInvokesByInterceptorClass.get(interceptorClassName);
if (aroundInvokesOnInterceptor != null) {
aroundInvokesApplicableForMethod.addAll(aroundInvokesOnInterceptor);
}
if (ejbComponentDescription.isTimerServiceRequired()) {
final List<InterceptorFactory> aroundTimeoutsOnInterceptor = userAroundTimeoutsByInterceptorClass.get(interceptorClassName);
if (aroundTimeoutsOnInterceptor != null) {
aroundTimeoutsApplicableForMethod.addAll(aroundTimeoutsOnInterceptor);
}
}
}
}
// now add class level interceptors (if not excluded) to the deque
if (!ejbComponentDescription.isExcludeClassLevelContainerInterceptors(methodIdentifier)) {
for (final InterceptorDescription interceptorDescription : classLevelContainerInterceptors) {
String interceptorClassName = interceptorDescription.getInterceptorClassName();
final List<InterceptorFactory> aroundInvokesOnInterceptor = userAroundInvokesByInterceptorClass.get(interceptorClassName);
if (aroundInvokesOnInterceptor != null) {
aroundInvokesApplicableForMethod.addAll(aroundInvokesOnInterceptor);
}
if (ejbComponentDescription.isTimerServiceRequired()) {
final List<InterceptorFactory> aroundTimeoutsOnInterceptor = userAroundTimeoutsByInterceptorClass.get(interceptorClassName);
if (aroundTimeoutsOnInterceptor != null) {
aroundTimeoutsApplicableForMethod.addAll(aroundTimeoutsOnInterceptor);
}
}
}
}
// now add method level interceptors for to the deque so that they are triggered after the class interceptors
final List<InterceptorDescription> interceptorsForMethod = methodLevelContainerInterceptors.get(methodIdentifier);
if (interceptorsForMethod != null) {
for (final InterceptorDescription methodLevelInterceptor : interceptorsForMethod) {
String interceptorClassName = methodLevelInterceptor.getInterceptorClassName();
final List<InterceptorFactory> aroundInvokesOnInterceptor = userAroundInvokesByInterceptorClass.get(interceptorClassName);
if (aroundInvokesOnInterceptor != null) {
aroundInvokesApplicableForMethod.addAll(aroundInvokesOnInterceptor);
}
if (ejbComponentDescription.isTimerServiceRequired()) {
final List<InterceptorFactory> aroundTimeoutsOnInterceptor = userAroundTimeoutsByInterceptorClass.get(interceptorClassName);
if (aroundTimeoutsOnInterceptor != null) {
aroundTimeoutsApplicableForMethod.addAll(aroundTimeoutsOnInterceptor);
}
}
}
}
// apply the interceptors to the view's method.
viewConfiguration.addViewInterceptor(method, new UserInterceptorFactory(weaved(aroundInvokesApplicableForMethod), weaved(aroundTimeoutsApplicableForMethod)), InterceptorOrder.View.USER_APP_SPECIFIC_CONTAINER_INTERCEPTORS);
}
}
private static InterceptorFactory weaved(final Collection<InterceptorFactory> interceptorFactories) {
return new InterceptorFactory() {
@Override
public Interceptor create(InterceptorFactoryContext context) {
final Interceptor[] interceptors = new Interceptor[interceptorFactories.size()];
final Iterator<InterceptorFactory> factories = interceptorFactories.iterator();
for (int i = 0; i < interceptors.length; i++) {
interceptors[i] = factories.next().create(context);
}
return Interceptors.getWeavedInterceptor(interceptors);
}
};
}
/**
* Traverses the interceptor class and its class hierarchy to find the around-invoke and around-timeout methods
*/
private static final class InterceptorClassDescriptionTraversal extends ClassDescriptionTraversal {
private final EEModuleDescription moduleDescription;
private final EJBComponentDescription ejbComponentDescription;
private final DeploymentReflectionIndex deploymentReflectionIndex;
private final Class<?> interceptorClass;
private final List<InterceptorFactory> aroundInvokeInterceptorFactories = new ArrayList<InterceptorFactory>();
private final List<InterceptorFactory> aroundTimeoutInterceptorFactories = new ArrayList<InterceptorFactory>();
InterceptorClassDescriptionTraversal(final Class<?> interceptorClass, final EEApplicationClasses applicationClasses,
final DeploymentUnit deploymentUnit, final EJBComponentDescription ejbComponentDescription) {
super(interceptorClass, applicationClasses);
this.ejbComponentDescription = ejbComponentDescription;
this.deploymentReflectionIndex = deploymentUnit.getAttachment(REFLECTION_INDEX);
this.moduleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION);
this.interceptorClass = interceptorClass;
}
@Override
public void handle(final Class<?> clazz, EEModuleClassDescription classDescription) throws DeploymentUnitProcessingException {
final InterceptorClassDescription interceptorConfig;
if (classDescription != null) {
interceptorConfig = InterceptorClassDescription.merge(classDescription.getInterceptorClassDescription(), moduleDescription.getInterceptorClassOverride(clazz.getName()));
} else {
interceptorConfig = InterceptorClassDescription.merge(null, moduleDescription.getInterceptorClassOverride(clazz.getName()));
}
// get the container-interceptor class' constructor
final ClassReflectionIndex interceptorClassReflectionIndex = deploymentReflectionIndex.getClassIndex(interceptorClass);
final Constructor<?> interceptorClassConstructor = interceptorClassReflectionIndex.getConstructor(EMPTY_CLASS_ARRAY);
if (interceptorClassConstructor == null) {
throw EeLogger.ROOT_LOGGER.defaultConstructorNotFound(interceptorClass);
}
final MethodIdentifier aroundInvokeMethodIdentifier = interceptorConfig.getAroundInvoke();
final InterceptorFactory aroundInvokeInterceptorFactory = createInterceptorFactory(clazz, aroundInvokeMethodIdentifier, interceptorClassConstructor);
if (aroundInvokeInterceptorFactory != null) {
this.aroundInvokeInterceptorFactories.add(aroundInvokeInterceptorFactory);
}
if (ejbComponentDescription.isTimerServiceRequired()) {
final MethodIdentifier aroundTimeoutMethodIdentifier = interceptorConfig.getAroundTimeout();
final InterceptorFactory aroundTimeoutInterceptorFactory = createInterceptorFactory(clazz, aroundTimeoutMethodIdentifier, interceptorClassConstructor);
if (aroundTimeoutInterceptorFactory != null) {
this.aroundTimeoutInterceptorFactories.add(aroundTimeoutInterceptorFactory);
}
}
}
private InterceptorFactory createInterceptorFactory(final Class<?> clazz, final MethodIdentifier methodIdentifier, final Constructor<?> interceptorClassConstructor) throws DeploymentUnitProcessingException {
if (methodIdentifier == null) {
return null;
}
final Method method = ClassReflectionIndexUtil.findRequiredMethod(deploymentReflectionIndex, clazz, methodIdentifier);
if (isNotOverriden(clazz, method, this.interceptorClass, deploymentReflectionIndex)) {
return this.createInterceptorFactoryForContainerInterceptor(method, interceptorClassConstructor);
}
return null;
}
private boolean isNotOverriden(final Class<?> clazz, final Method method, final Class<?> actualClass, final DeploymentReflectionIndex deploymentReflectionIndex) throws DeploymentUnitProcessingException {
return Modifier.isPrivate(method.getModifiers()) || ClassReflectionIndexUtil.findRequiredMethod(deploymentReflectionIndex, actualClass, method).getDeclaringClass() == clazz;
}
private List<InterceptorFactory> getAroundInvokeInterceptorFactories() {
return this.aroundInvokeInterceptorFactories;
}
private List<InterceptorFactory> getAroundTimeoutInterceptorFactories() {
return this.aroundTimeoutInterceptorFactories;
}
private InterceptorFactory createInterceptorFactoryForContainerInterceptor(final Method method, final Constructor interceptorConstructor) {
// we *don't* create multiple instances of the container-interceptor class, but we just reuse a single instance and it's *not*
// tied to the Jakarta Enterprise Beans component instance lifecycle.
final ManagedReference interceptorInstanceRef = new ValueManagedReference(newInstance(interceptorConstructor));
// return the ContainerInterceptorMethodInterceptorFactory which is responsible for creating an Interceptor
// which can invoke the container-interceptor's around-invoke/around-timeout methods
return new ContainerInterceptorMethodInterceptorFactory(interceptorInstanceRef, method);
}
}
private static Object newInstance(final Constructor ctor) {
try {
return ctor.newInstance(new Object[] {});
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
| 20,009 | 61.727273 | 234 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/RemoteHomeViewInstanceFactory.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, 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.ejb3.component;
import java.util.Map;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.as.ee.component.ViewInstanceFactory;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ValueManagedReference;
import org.jboss.ejb.client.Affinity;
import org.jboss.ejb.client.EJBClient;
import org.jboss.ejb.client.EJBHomeLocator;
/**
* @author Stuart Douglas
*/
public class RemoteHomeViewInstanceFactory implements ViewInstanceFactory {
private final String applicationName;
private final String moduleName;
private final String distinctName;
private final String beanName;
public RemoteHomeViewInstanceFactory(final String applicationName, final String moduleName, final String distinctName, final String beanName) {
this.applicationName = applicationName == null ? "" : applicationName;
this.moduleName = moduleName;
this.distinctName = distinctName;
this.beanName = beanName;
}
@Override
public ManagedReference createViewInstance(final ComponentView componentView, final Map<Object, Object> contextData) {
Object value = EJBClient.createProxy(new EJBHomeLocator(componentView.getViewClass(), applicationName, moduleName, beanName, distinctName, Affinity.LOCAL));
return new ValueManagedReference(value);
}
}
| 2,369 | 39.862069 | 164 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/EjbComponentInstance.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, 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.ejb3.component;
import java.lang.reflect.Method;
import java.util.Map;
import org.jboss.as.ee.component.BasicComponent;
import org.jboss.as.ee.component.BasicComponentInstance;
import org.jboss.as.ejb3.context.EJBContextImpl;
import org.jboss.invocation.Interceptor;
/**
* @author Stuart Douglas
*/
public abstract class EjbComponentInstance extends BasicComponentInstance {
/**
* Construct a new instance.
*
* @param component the component
*/
protected EjbComponentInstance(final BasicComponent component, final Interceptor preDestroyInterceptor, final Map<Method, Interceptor> methodInterceptors) {
super(component, preDestroyInterceptor, methodInterceptors);
}
@Override
public EJBComponent getComponent() {
return (EJBComponent) super.getComponent();
}
public abstract EJBContextImpl getEjbContext();
}
| 1,916 | 35.865385 | 160 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.