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/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/JMSQueueService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq.jms;
import static org.jboss.as.server.Services.addServerExecutorDependency;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import jakarta.jms.Queue;
import org.apache.activemq.artemis.jms.client.ActiveMQDestination;
import org.apache.activemq.artemis.jms.server.JMSServerManager;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.wildfly.extension.messaging.activemq.ActiveMQActivationService;
import org.wildfly.extension.messaging.activemq.logging.MessagingLogger;
/**
* Service responsible for creating and destroying a {@code jakarta.jms.Queue}.
*
* @author Emanuel Muckenhuber
*/
public class JMSQueueService implements Service<Queue> {
static final String JMS_QUEUE_PREFIX = "jms.queue.";
private final InjectedValue<JMSServerManager> jmsServer = new InjectedValue<JMSServerManager>();
private final InjectedValue<ExecutorService> executorInjector = new InjectedValue<ExecutorService>();
private final String queueName;
private final String selectorString;
private final boolean durable;
private Queue queue;
public JMSQueueService(final String name, String selectorString, boolean durable) {
if (name.startsWith(JMS_QUEUE_PREFIX)) {
this.queueName = name.substring(JMS_QUEUE_PREFIX.length());
} else {
this.queueName = name;
}
this.selectorString = selectorString;
this.durable = durable;
}
@Override
public synchronized void start(final StartContext context) throws StartException {
final JMSServerManager jmsManager = jmsServer.getValue();
final Runnable task = new Runnable() {
@Override
public void run() {
try {
// add back the jms.queue. prefix to be consistent with ActiveMQ Artemis 1.x addressing scheme
jmsManager.createQueue(false, JMS_QUEUE_PREFIX + queueName, queueName, selectorString, durable);
JMSQueueService.this.queue = ActiveMQDestination.createQueue(JMS_QUEUE_PREFIX + queueName, queueName);
context.complete();
} catch (Throwable e) {
context.failed(MessagingLogger.ROOT_LOGGER.failedToCreate(e, "JMS Queue"));
}
}
};
try {
executorInjector.getValue().execute(task);
} catch (RejectedExecutionException e) {
task.run();
} finally {
context.asynchronous();
}
}
@Override
public void stop(final StopContext context) {
}
@Override
public Queue getValue() throws IllegalStateException, IllegalArgumentException {
return queue;
}
public static Service<Queue> installService(final String name, final ServiceTarget serviceTarget, final ServiceName serverServiceName, final String selector, final boolean durable) {
final JMSQueueService service = new JMSQueueService(name, selector, durable);
final ServiceName serviceName = JMSServices.getJmsQueueBaseServiceName(serverServiceName).append(name);
final ServiceBuilder<Queue> serviceBuilder = serviceTarget.addService(serviceName, service);
serviceBuilder.requires(ActiveMQActivationService.getServiceName(serverServiceName));
serviceBuilder.addDependency(JMSServices.getJmsManagerBaseServiceName(serverServiceName), JMSServerManager.class, service.jmsServer);
serviceBuilder.setInitialMode(ServiceController.Mode.PASSIVE);
addServerExecutorDependency(serviceBuilder, service.executorInjector);
serviceBuilder.install();
return service;
}
}
| 5,108
| 41.22314
| 186
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/WildFlyRecoveryRegistry.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq.jms;
import org.jboss.activemq.artemis.wildfly.integration.recovery.WildFlyActiveMQRegistry;
import org.jboss.as.controller.ServiceNameFactory;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.tm.XAResourceRecoveryRegistry;
import org.wildfly.extension.messaging.activemq.MessagingServices;
/**
* @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
* 9/22/11
*/
public class WildFlyRecoveryRegistry extends WildFlyActiveMQRegistry {
static volatile ServiceContainer container;
private XAResourceRecoveryRegistry registry;
public WildFlyRecoveryRegistry() {
registry = getXAResourceRecoveryRegistry();
if (registry == null) {
throw new IllegalStateException("Unable to find Recovery Registry");
}
}
public XAResourceRecoveryRegistry getTMRegistry() {
return registry;
}
private static XAResourceRecoveryRegistry getXAResourceRecoveryRegistry() {
// This parsing isn't 100% ideal as it's somewhat 'internal' knowledge of the relationship between
// capability names and service names. But at this point that relationship really needs to become
// a contract anyway
ServiceName serviceName = ServiceNameFactory.parseServiceName(MessagingServices.TRANSACTION_XA_RESOURCE_RECOVERY_REGISTRY_CAPABILITY);
@SuppressWarnings("unchecked")
ServiceController<XAResourceRecoveryRegistry> service = (ServiceController<XAResourceRecoveryRegistry>) container.getService(serviceName);
return service == null ? null : service.getValue();
}
}
| 2,736
| 42.444444
| 146
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/JMSQueueDefinition.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.wildfly.extension.messaging.activemq.jms;
import static org.jboss.as.controller.SimpleAttributeDefinitionBuilder.create;
import static org.jboss.dmr.ModelType.STRING;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.PAUSED;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.TEMPORARY;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PersistentResourceDefinition;
import org.jboss.as.controller.ReloadRequiredWriteAttributeHandler;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.StringListAttributeDefinition;
import org.jboss.as.controller.access.management.AccessConstraintDefinition;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.wildfly.extension.messaging.activemq.CommonAttributes;
import org.wildfly.extension.messaging.activemq.MessagingExtension;
/**
* Jakarta Messaging Queue resource definition
*
* @author <a href="http://jmesnil.net">Jeff Mesnil</a> (c) 2012 Red Hat Inc.
*/
public class JMSQueueDefinition extends PersistentResourceDefinition {
public static final AttributeDefinition[] ATTRIBUTES = {
CommonAttributes.DESTINATION_ENTRIES,
CommonAttributes.SELECTOR,
CommonAttributes.DURABLE,
CommonAttributes.LEGACY_ENTRIES
};
/**
* Attributes for deployed Jakarta Messaging queue are stored in runtime
*/
static AttributeDefinition[] DEPLOYMENT_ATTRIBUTES = {
new StringListAttributeDefinition.Builder(CommonAttributes.DESTINATION_ENTRIES)
.setStorageRuntime()
.build(),
SimpleAttributeDefinitionBuilder.create(CommonAttributes.SELECTOR)
.setStorageRuntime()
.build(),
SimpleAttributeDefinitionBuilder.create(CommonAttributes.DURABLE)
.setStorageRuntime()
.build(),
new StringListAttributeDefinition.Builder(CommonAttributes.LEGACY_ENTRIES)
.setStorageRuntime()
.build()
};
static final AttributeDefinition QUEUE_ADDRESS = create("queue-address", STRING)
.setStorageRuntime()
.build();
static final AttributeDefinition DEAD_LETTER_ADDRESS = create("dead-letter-address", STRING)
.setRequired(false)
.setStorageRuntime()
.build();
static final AttributeDefinition EXPIRY_ADDRESS = create("expiry-address", STRING)
.setRequired(false)
.setStorageRuntime()
.build();
static final AttributeDefinition[] READONLY_ATTRIBUTES = {
QUEUE_ADDRESS,
EXPIRY_ADDRESS,
DEAD_LETTER_ADDRESS,
PAUSED,
TEMPORARY
};
static final AttributeDefinition[] METRICS = {
CommonAttributes.MESSAGE_COUNT,
CommonAttributes.DELIVERING_COUNT,
CommonAttributes.MESSAGES_ADDED,
CommonAttributes.SCHEDULED_COUNT,
CommonAttributes.CONSUMER_COUNT
};
private final boolean deployed;
private final boolean registerRuntimeOnly;
public JMSQueueDefinition(final boolean deployed, final boolean registerRuntimeOnly) {
super(MessagingExtension.JMS_QUEUE_PATH,
MessagingExtension.getResourceDescriptionResolver(CommonAttributes.JMS_QUEUE),
deployed ? null : JMSQueueAdd.INSTANCE,
deployed ? null : JMSQueueRemove.INSTANCE);
this.deployed = deployed;
this.registerRuntimeOnly = registerRuntimeOnly;
}
@Override
public Collection<AttributeDefinition> getAttributes() {
if (deployed) {
return Arrays.asList(DEPLOYMENT_ATTRIBUTES);
} else{
return Arrays.asList(ATTRIBUTES);
}
}
@Override
public void registerAttributes(ManagementResourceRegistration registry) {
ReloadRequiredWriteAttributeHandler handler = new ReloadRequiredWriteAttributeHandler(getAttributes());
for (AttributeDefinition attr : getAttributes()) {
if (deployed) {
registry.registerReadOnlyAttribute(attr, JMSQueueConfigurationRuntimeHandler.INSTANCE);
} else {
if (attr == CommonAttributes.DESTINATION_ENTRIES ||
attr == CommonAttributes.LEGACY_ENTRIES) {
registry.registerReadWriteAttribute(attr, null, handler);
} else {
registry.registerReadOnlyAttribute(attr, null);
}
}
}
for (AttributeDefinition attr : READONLY_ATTRIBUTES) {
registry.registerReadOnlyAttribute(attr, JMSQueueReadAttributeHandler.INSTANCE);
}
for (AttributeDefinition metric : METRICS) {
registry.registerMetric(metric, JMSQueueReadAttributeHandler.INSTANCE);
}
}
@Override
public void registerOperations(ManagementResourceRegistration registry) {
super.registerOperations(registry);
if (registerRuntimeOnly) {
JMSQueueControlHandler.INSTANCE.registerOperations(registry, getResourceDescriptionResolver());
if (!deployed) {
JMSQueueUpdateJndiHandler.registerOperations(registry, getResourceDescriptionResolver());
}
}
}
@Override
public List<AccessConstraintDefinition> getAccessConstraints() {
return Arrays.asList(MessagingExtension.JMS_QUEUE_ACCESS_CONSTRAINT);
}
}
| 6,721
| 38.541176
| 111
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/JMSQueueAdd.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq.jms;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.DURABLE;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.SELECTOR;
import java.util.List;
import jakarta.jms.Queue;
import org.hornetq.api.jms.HornetQJMSClient;
import org.jboss.as.controller.AbstractAddStepHandler;
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.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.wildfly.extension.messaging.activemq.BinderServiceUtil;
import org.wildfly.extension.messaging.activemq.CommonAttributes;
import org.wildfly.extension.messaging.activemq.MessagingServices;
/**
* Update handler adding a queue to the Jakarta Messaging subsystem. The
* runtime action will create the {@link JMSQueueService}.
*
* @author Emanuel Muckenhuber
* @author <a href="mailto:andy.taylor@jboss.com">Andy Taylor</a>
*/
public class JMSQueueAdd extends AbstractAddStepHandler {
public static final JMSQueueAdd INSTANCE = new JMSQueueAdd();
private JMSQueueAdd() {
super(JMSQueueDefinition.ATTRIBUTES);
}
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
final String name = context.getCurrentAddressValue();
final ServiceTarget serviceTarget = context.getServiceTarget();
final ServiceName serviceName = MessagingServices.getActiveMQServiceName(context.getCurrentAddress());
final ModelNode selectorNode = SELECTOR.resolveModelAttribute(context, model);
final boolean durable = DURABLE.resolveModelAttribute(context, model).asBoolean();
final String selector = selectorNode.isDefined() ? selectorNode.asString() : null;
// Do not pass the JNDI bindings to ActiveMQ but install them directly instead so that the
// dependencies from the BinderServices to the JMSQueueService are not broken
Service<Queue> queueService = JMSQueueService.installService(name, serviceTarget, serviceName, selector, durable);
final ServiceName jmsQueueServiceName = JMSServices.getJmsQueueBaseServiceName(serviceName).append(name);
for (String entry : CommonAttributes.DESTINATION_ENTRIES.unwrap(context, model)) {
BinderServiceUtil.installBinderService(serviceTarget, entry, queueService, jmsQueueServiceName);
}
List<String> legacyEntries = CommonAttributes.LEGACY_ENTRIES.unwrap(context, model);
if (!legacyEntries.isEmpty()) {
Queue legacyQueue = HornetQJMSClient.createQueue(name);
for (String legacyEntry : legacyEntries) {
BinderServiceUtil.installBinderService(serviceTarget, legacyEntry, legacyQueue);
}
}
}
}
| 3,986
| 44.306818
| 131
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/PooledConnectionFactoryConfigProperties.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq.jms;
/**
* @author <a href="mailto:andy.taylor@jboss.com">Andy Taylor</a>
* Date: 5/16/11
* Time: 5:09 PM
*/
public class PooledConnectionFactoryConfigProperties {
private final String name;
private final String value;
private String type;
private final ConnectionFactoryAttribute.ConfigType configType;
/**
* @param configType can be {@code null} to configure a property on the resource adapter.
*/
public PooledConnectionFactoryConfigProperties(String name, String value, String type, ConnectionFactoryAttribute.ConfigType configType) {
this.name = name;
this.value = value;
this.type = type;
this.configType = configType;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
public String getType() {
return type;
}
public ConnectionFactoryAttribute.ConfigType getConfigType() {
return configType;
}
}
| 2,073
| 31.40625
| 142
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/PooledConnectionFactoryStatisticsService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq.jms;
import static org.wildfly.extension.messaging.activemq.logging.MessagingLogger.ROOT_LOGGER;
import org.jboss.as.connector.dynamicresource.StatisticsResourceDefinition;
import org.jboss.as.connector.metadata.deployment.ResourceAdapterDeployment;
import org.jboss.as.connector.subsystems.datasources.DataSourcesSubsystemProviders;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.PlaceholderResource;
import org.jboss.as.controller.registry.Resource;
import org.jboss.jca.core.spi.statistics.StatisticsPlugin;
import org.jboss.jca.deployers.common.CommonDeployment;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
/**
* Service providing statistics for the pooled-connection-factory's pool.
*
* copied from {@link org.jboss.as.connector.services.datasources.statistics.DataSourceStatisticsService}
*/
public class PooledConnectionFactoryStatisticsService implements Service<ManagementResourceRegistration> {
private static final PathElement POOL_STATISTICS = PathElement.pathElement("statistics", "pool");
private final ManagementResourceRegistration registration;
private final boolean statsEnabled;
protected final InjectedValue<ResourceAdapterDeployment> injectedRADeployment = new InjectedValue<>();
/**
* create an instance *
*/
public PooledConnectionFactoryStatisticsService(final ManagementResourceRegistration registration,
final boolean statsEnabled) {
super();
this.registration = registration;
this.statsEnabled = statsEnabled;
}
@Override
public void start(StartContext context) throws StartException {
ROOT_LOGGER.debugf("start PooledConnectionFactoryStatisticsService");
synchronized (POOL_STATISTICS) {
ResourceAdapterDeployment raDeployment = injectedRADeployment.getValue();
CommonDeployment deployment = raDeployment.getDeployment();
StatisticsPlugin poolStats = deployment.getConnectionManagers()[0].getPool().getStatistics();
poolStats.setEnabled(statsEnabled);
int poolStatsSize = poolStats.getNames().size();
if (poolStatsSize > 0
&& registration != null
&& registration.getSubModel(PathAddress.pathAddress(POOL_STATISTICS)) == null) {
ManagementResourceRegistration poolRegistration = registration
.registerSubModel(new StatisticsResourceDefinition(POOL_STATISTICS,
DataSourcesSubsystemProviders.RESOURCE_NAME, poolStats));
}
}
}
@Override
public void stop(StopContext context) {
synchronized (POOL_STATISTICS) {
if (registration != null) {
registration.unregisterSubModel(POOL_STATISTICS);
}
}
}
@Override
public ManagementResourceRegistration getValue() throws IllegalStateException, IllegalArgumentException {
return registration;
}
public Injector<ResourceAdapterDeployment> getRADeploymentInjector() {
return injectedRADeployment;
}
public static void registerStatisticsResources(Resource resource) {
synchronized (POOL_STATISTICS) {
if (!resource.hasChild(POOL_STATISTICS)) {
resource.registerChild(POOL_STATISTICS, new PlaceholderResource.PlaceholderResourceEntry(POOL_STATISTICS));
}
}
}
public static void removeStatisticsResources(Resource resource) {
synchronized (POOL_STATISTICS) {
if (resource.hasChild(POOL_STATISTICS)) {
resource.removeChild(POOL_STATISTICS);
}
}
}
}
| 5,139
| 38.538462
| 123
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/JMSService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq.jms;
import static org.jboss.as.server.Services.addServerExecutorDependency;
import static org.jboss.msc.service.ServiceController.Mode.ACTIVE;
import static org.jboss.msc.service.ServiceController.Mode.REMOVE;
import static org.jboss.msc.service.ServiceController.State.REMOVED;
import static org.jboss.msc.service.ServiceController.State.STOPPING;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import org.apache.activemq.artemis.core.security.ActiveMQPrincipal;
import org.apache.activemq.artemis.core.server.ActivateCallback;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.jms.server.JMSServerManager;
import org.apache.activemq.artemis.jms.server.impl.JMSServerManagerImpl;
import org.jboss.msc.service.LifecycleEvent;
import org.jboss.msc.service.LifecycleListener;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceController.Mode;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.wildfly.extension.messaging.activemq.ActiveMQActivationService;
import org.wildfly.extension.messaging.activemq.DefaultCredentials;
import org.wildfly.extension.messaging.activemq.MessagingServices;
import org.wildfly.extension.messaging.activemq.logging.MessagingLogger;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* The {@code JMSServerManager} service.
*
* @author Emanuel Muckenhuber
*/
public class JMSService implements Service<JMSServerManager> {
private final InjectedValue<ActiveMQServer> activeMQServer = new InjectedValue<>();
private final InjectedValue<ExecutorService> serverExecutor = new InjectedValue<>();
private final ServiceName serverServiceName;
private final boolean overrideInVMSecurity;
private JMSServerManager jmsServer;
public static ServiceController<JMSServerManager> addService(final ServiceTarget target, ServiceName serverServiceName, boolean overrideInVMSecurity) {
final JMSService service = new JMSService(serverServiceName, overrideInVMSecurity);
ServiceBuilder<JMSServerManager> builder = target.addService(JMSServices.getJmsManagerBaseServiceName(serverServiceName), service);
builder.addDependency(serverServiceName, ActiveMQServer.class, service.activeMQServer);
builder.requires(MessagingServices.ACTIVEMQ_CLIENT_THREAD_POOL);
builder.setInitialMode(Mode.ACTIVE);
addServerExecutorDependency(builder, service.serverExecutor);
return builder.install();
}
protected JMSService(ServiceName serverServiceName, boolean overrideInVMSecurity) {
this.serverServiceName = serverServiceName;
this.overrideInVMSecurity = overrideInVMSecurity;
}
public synchronized JMSServerManager getValue() throws IllegalStateException {
if (jmsServer == null) {
throw new IllegalStateException();
}
return jmsServer;
}
@Override
public void start(final StartContext context) throws StartException {
final Runnable task = new Runnable() {
@Override
public void run() {
try {
doStart(context);
context.complete();
} catch (StartException e) {
context.failed(e);
}
}
};
try {
serverExecutor.getValue().submit(task);
} catch (RejectedExecutionException e) {
task.run();
} finally {
context.asynchronous();
}
}
@Override
public void stop(final StopContext context) {
final Runnable task = new Runnable() {
@Override
public void run() {
doStop(context);
context.complete();
}
};
try {
serverExecutor.getValue().submit(task);
} catch (RejectedExecutionException e) {
task.run();
} finally {
context.asynchronous();
}
}
private synchronized void doStart(final StartContext context) throws StartException {
final ServiceContainer serviceContainer = context.getController().getServiceContainer();
ClassLoader oldTccl = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(getClass());
try {
jmsServer = new JMSServerManagerImpl(activeMQServer.getValue(), new WildFlyBindingRegistry(context.getController().getServiceContainer())) {
@Override
public void stop(ActiveMQServer server) {
// Suppress ARTEMIS-2438
}
};
activeMQServer.getValue().registerActivationFailureListener(e -> {
StartException se = new StartException(e);
context.failed(se);
});
activeMQServer.getValue().registerActivateCallback(new ActivateCallback() {
private volatile ServiceController<Void> activeMQActivationController;
public void preActivate() {
}
public void activated() {
if (overrideInVMSecurity) {
activeMQServer.getValue().getRemotingService().allowInvmSecurityOverride(new ActiveMQPrincipal(DefaultCredentials.getUsername(), DefaultCredentials.getPassword()));
}
// ActiveMQ only provides a callback to be notified when ActiveMQ core server is activated.
// but the Jakarta Messaging service start must not be completed until the JMSServerManager wrappee is indeed started (and has deployed the Jakarta Messaging resources, etc.).
// It is possible that the activation service has already been installed but becomes passive when a backup server has failed over (-> ACTIVE) and failed back (-> PASSIVE)
// [WFLY-6178] check if the service container is shutdown to avoid an IllegalStateException if an
// ActiveMQ backup server is activated during failover while the WildFly server is shutting down.
if (serviceContainer.isShutdown()) {
return;
}
if (activeMQActivationController == null) {
activeMQActivationController = serviceContainer.addService(ActiveMQActivationService.getServiceName(serverServiceName), new ActiveMQActivationService())
.setInitialMode(Mode.ACTIVE)
.install();
} else {
activeMQActivationController.setMode(ACTIVE);
}
}
@Override
public void activationComplete() {
}
public void deActivate() {
// passivate the activation service only if the ActiveMQ server is deactivated when it fails back
// and *not* during AS7 service container shutdown or reload (AS7-6840 / AS7-6881)
if (activeMQActivationController != null
&& !activeMQActivationController.getState().in(STOPPING, REMOVED)) {
// [WFLY-4597] When Artemis is deactivated during failover, we block until its
// activation controller is REMOVED before giving back control to Artemis.
// This allow to properly stop any service depending on the activation controller
// and avoid spurious warning messages because the resources used by the services
// are stopped outside the control of the services.
final CountDownLatch latch = new CountDownLatch(1);
activeMQActivationController.compareAndSetMode(ACTIVE, REMOVE);
activeMQActivationController.addListener(new LifecycleListener() {
@Override
public void handleEvent(ServiceController<?> controller, LifecycleEvent event) {
if (event == LifecycleEvent.REMOVED) {
latch.countDown();
}
}
});
try {
latch.await(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
activeMQActivationController = null;
}
}
});
jmsServer.start();
} catch(StartException e){
throw e;
} catch (Throwable t) {
throw new StartException(t);
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);
}
}
private synchronized void doStop(StopContext context) {
try {
jmsServer.stop();
jmsServer = null;
} catch (Exception e) {
MessagingLogger.ROOT_LOGGER.errorStoppingJmsServer(e);
}
}
}
| 10,694
| 45.703057
| 195
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/JMSQueueControlHandler.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.wildfly.extension.messaging.activemq.jms;
import static org.apache.activemq.artemis.utils.SelectorTranslator.convertToActiveMQFilterString;
import static org.wildfly.extension.messaging.activemq.OperationDefinitionHelper.createNonEmptyStringAttribute;
import static org.wildfly.extension.messaging.activemq.jms.JMSQueueService.JMS_QUEUE_PREFIX;
import org.apache.activemq.artemis.api.core.management.QueueControl;
import org.apache.activemq.artemis.api.core.management.ResourceNames;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.dmr.ModelNode;
import org.wildfly.extension.messaging.activemq.AbstractQueueControlHandler;
/**
* Handler for runtime operations that invoke on a ActiveMQ {@link QueueControl}.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class JMSQueueControlHandler extends AbstractQueueControlHandler<QueueControl> {
public static final JMSQueueControlHandler INSTANCE = new JMSQueueControlHandler();
private static final AttributeDefinition MESSAGE_ID = createNonEmptyStringAttribute("message-id");
private JMSQueueControlHandler() {
}
@Override
protected AttributeDefinition getMessageIDAttributeDefinition() {
return MESSAGE_ID;
}
@Override
protected AttributeDefinition[] getReplyMessageParameterDefinitions() {
return JMSManagementHelper.JMS_MESSAGE_PARAMETERS;
}
@Override
protected DelegatingQueueControl<QueueControl> getQueueControl(ActiveMQServer server, String queueName){
String name = queueName;
if (queueName.startsWith(JMS_QUEUE_PREFIX)) {
name = queueName.substring(JMS_QUEUE_PREFIX.length());
}
QueueControl queueControl = QueueControl.class.cast(server.getManagementService().getResource(ResourceNames.QUEUE + JMS_QUEUE_PREFIX + name));
if (queueControl == null) {
//For backward compatibility
queueControl = QueueControl.class.cast(server.getManagementService().getResource(ResourceNames.QUEUE + JMS_QUEUE_PREFIX + queueName));
if (queueControl == null) {
return null;
}
}
final QueueControl control = queueControl;
return new DelegatingQueueControl<QueueControl>() {
@Override
public QueueControl getDelegate() {
return control;
}
@Override
public String listMessagesAsJSON(String filter) throws Exception {
String result = control.listMessagesAsJSON(convertToActiveMQFilterString(filter));
return convertToJMSProperties(result);
}
@Override
public long countMessages(String filter) throws Exception {
return control.countMessages(convertToActiveMQFilterString(filter));
}
@Override
public boolean removeMessage(ModelNode id) throws Exception {
int n = control.removeMessages(createFilterForJMSMessageID(id));
return n == 1;
}
@Override
public int removeMessages(String filter) throws Exception {
return control.removeMessages(convertToActiveMQFilterString(filter));
}
@Override
public int expireMessages(String filter) throws Exception {
return control.expireMessages(convertToActiveMQFilterString(filter));
}
@Override
public boolean expireMessage(ModelNode id) throws Exception {
int n = control.expireMessages(createFilterForJMSMessageID(id));
return n == 1;
}
@Override
public boolean sendMessageToDeadLetterAddress(ModelNode id) throws Exception {
int n = control.sendMessagesToDeadLetterAddress(createFilterForJMSMessageID(id));
return n == 1;
}
@Override
public int sendMessagesToDeadLetterAddress(String filter) throws Exception {
return control.sendMessagesToDeadLetterAddress(convertToActiveMQFilterString(filter));
}
@Override
public boolean changeMessagePriority(ModelNode id, int priority) throws Exception {
int n = control.changeMessagesPriority(createFilterForJMSMessageID(id), priority);
return n == 1;
}
@Override
public int changeMessagesPriority(String filter, int priority) throws Exception {
return control.changeMessagesPriority(convertToActiveMQFilterString(filter), priority);
}
@Override
public boolean moveMessage(ModelNode id, String otherQueue) throws Exception {
int n = control.moveMessages(createFilterForJMSMessageID(id), JMS_QUEUE_PREFIX + otherQueue);
return n == 1;
}
@Override
public boolean moveMessage(ModelNode id, String otherQueue, boolean rejectDuplicates) throws Exception {
int n = control.moveMessages(createFilterForJMSMessageID(id), JMS_QUEUE_PREFIX + otherQueue, rejectDuplicates);
return n == 1;
}
@Override
public int moveMessages(String filter, String otherQueue) throws Exception {
return control.moveMessages(convertToActiveMQFilterString(filter), JMS_QUEUE_PREFIX + otherQueue);
}
@Override
public int moveMessages(String filter, String otherQueue, boolean rejectDuplicates) throws Exception {
return control.moveMessages(convertToActiveMQFilterString(filter), JMS_QUEUE_PREFIX + otherQueue, rejectDuplicates);
}
@Override
public String listMessageCounter() throws Exception {
return control.listMessageCounter();
}
@Override
public void resetMessageCounter() throws Exception {
control.resetMessageCounter();
}
@Override
public String listMessageCounterAsHTML() throws Exception {
return control.listMessageCounterAsHTML();
}
@Override
public String listMessageCounterHistory() throws Exception {
return control.listMessageCounterHistory();
}
@Override
public String listMessageCounterHistoryAsHTML() throws Exception {
return control.listMessageCounterHistoryAsHTML();
}
@Override
public void pause() throws Exception {
control.pause();
}
@Override
public void resume() throws Exception {
control.resume();
}
@Override
public String listConsumersAsJSON() throws Exception {
return control.listConsumersAsJSON();
}
@Override
public String listScheduledMessagesAsJSON() throws Exception {
return control.listScheduledMessagesAsJSON();
}
@Override
public String listDeliveringMessagesAsJSON() throws Exception {
return control.listDeliveringMessagesAsJSON();
}
private String createFilterForJMSMessageID(ModelNode id) {
return "AMQUserID='" + id.asString() + "'";
}
private String convertToJMSProperties(String text) {
return text.replaceAll("priority", "JMSPriority")
.replaceAll("timestamp", "JMSTimestamp")
.replaceAll("expiration", "JMSExpiration")
.replaceAll("durable", "JMSDeliveryMode")
.replaceAll("userID", "JMSMessageID");
}
};
}
@Override
protected Object handleAdditionalOperation(String operationName, ModelNode operation, OperationContext context,
QueueControl queueControl) throws OperationFailedException {
throwUnimplementedOperationException(operationName);
return null;
}
@Override
protected void revertAdditionalOperation(String operationName, ModelNode operation, OperationContext context, QueueControl queueControl, Object handback) {
// no-op
}
}
| 9,648
| 39.71308
| 159
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/ExternalConnectionFactoryAdd.java
|
/*
* Copyright 2018 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.wildfly.extension.messaging.activemq.jms;
import static org.wildfly.extension.messaging.activemq.Capabilities.ELYTRON_SSL_CONTEXT_CAPABILITY;
import static org.wildfly.extension.messaging.activemq.Capabilities.OUTBOUND_SOCKET_BINDING_CAPABILITY;
import static org.wildfly.extension.messaging.activemq.Capabilities.SOCKET_BINDING_CAPABILITY;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.HA;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.JGROUPS_CLUSTER;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.JGROUPS_DISCOVERY_GROUP;
import static org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.Common.DESERIALIZATION_ALLOWLIST;
import static org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.Common.DESERIALIZATION_BLACKLIST;
import static org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.Common.DESERIALIZATION_BLOCKLIST;
import static org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.Common.DESERIALIZATION_WHITELIST;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
import org.apache.activemq.artemis.api.core.DiscoveryGroupConfiguration;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
import org.apache.activemq.artemis.api.jms.JMSFactoryType;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.network.OutboundSocketBinding;
import org.jboss.as.network.SocketBinding;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.wildfly.extension.messaging.activemq.BinderServiceUtil;
import org.wildfly.extension.messaging.activemq.CommonAttributes;
import org.wildfly.extension.messaging.activemq.DiscoveryGroupDefinition;
import org.wildfly.extension.messaging.activemq.GroupBindingService;
import org.wildfly.extension.messaging.activemq.JGroupsDiscoveryGroupDefinition;
import org.wildfly.extension.messaging.activemq.MessagingServices;
import org.wildfly.extension.messaging.activemq.TransportConfigOperationHandlers;
import org.wildfly.extension.messaging.activemq.broadcast.BroadcastCommandDispatcherFactory;
import org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.Common;
import org.wildfly.extension.messaging.activemq.logging.MessagingLogger;
import static org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.External.ENABLE_AMQ1_PREFIX;
import javax.net.ssl.SSLContext;
import org.apache.activemq.artemis.jms.server.config.ConnectionFactoryConfiguration;
import org.jboss.as.controller.AttributeDefinition;
/**
* Update adding a connection factory to the subsystem. The
* runtime action will create the {@link ExternalConnectionFactoryService}.
*
* @author Emmanuel Hugonnet (c) 2018 Red Hat, inc.
*/
public class ExternalConnectionFactoryAdd extends AbstractAddStepHandler {
public static final ExternalConnectionFactoryAdd INSTANCE = new ExternalConnectionFactoryAdd();
private ExternalConnectionFactoryAdd() {
super(ExternalConnectionFactoryDefinition.ATTRIBUTES);
}
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
final String name = context.getCurrentAddressValue();
final ServiceName serviceName = ExternalConnectionFactoryDefinition.CAPABILITY.getCapabilityServiceName(context.getCurrentAddress());
boolean ha = HA.resolveModelAttribute(context, model).asBoolean();
boolean enable1Prefixes = ENABLE_AMQ1_PREFIX.resolveModelAttribute(context, model).asBoolean();
final ModelNode discoveryGroupName = Common.DISCOVERY_GROUP.resolveModelAttribute(context, model);
final ConnectionFactoryConfiguration config = ConnectionFactoryAdd.createConfiguration(context, name, model);
JMSFactoryType jmsFactoryType = ConnectionFactoryType.valueOf(ConnectionFactoryAttributes.Regular.FACTORY_TYPE.resolveModelAttribute(context, model).asString()).getType();
List<String> connectorNames = Common.CONNECTORS.unwrap(context, model);
ServiceBuilder<?> builder = context.getServiceTarget()
.addService(serviceName)
.addAliases(JMSServices.getConnectionFactoryBaseServiceName(MessagingServices.getActiveMQServiceName()).append(name));
ExternalConnectionFactoryService service;
if (discoveryGroupName.isDefined()) {
// mapping between the {discovery}-groups and the cluster names they use
Map<String, String> clusterNames = new HashMap<>();
Map<String, Supplier<SocketBinding>> groupBindings = new HashMap<>();
// mapping between the {discovery}-groups and the command dispatcher factory they use
Map<String, Supplier<BroadcastCommandDispatcherFactory>> commandDispatcherFactories = new HashMap<>();
final String dgname = discoveryGroupName.asString();
final String key = "discovery" + dgname;
ModelNode discoveryGroupModel;
try {
discoveryGroupModel = context.readResourceFromRoot(context.getCurrentAddress().getParent().append(JGROUPS_DISCOVERY_GROUP, dgname)).getModel();
} catch (Resource.NoSuchResourceException ex) {
discoveryGroupModel = new ModelNode();
}
if (discoveryGroupModel.hasDefined(JGROUPS_CLUSTER.getName())) {
ModelNode channel = JGroupsDiscoveryGroupDefinition.JGROUPS_CHANNEL.resolveModelAttribute(context, discoveryGroupModel);
ServiceName commandDispatcherFactoryServiceName = MessagingServices.getBroadcastCommandDispatcherFactoryServiceName(channel.asStringOrNull());
Supplier<BroadcastCommandDispatcherFactory> commandDispatcherFactorySupplier = builder.requires(commandDispatcherFactoryServiceName);
commandDispatcherFactories.put(key, commandDispatcherFactorySupplier);
String clusterName = JGROUPS_CLUSTER.resolveModelAttribute(context, discoveryGroupModel).asString();
clusterNames.put(key, clusterName);
} else {
final ServiceName groupBinding = GroupBindingService.getDiscoveryBaseServiceName(MessagingServices.getActiveMQServiceName()).append(dgname);
Supplier<SocketBinding> groupBindingSupplier = builder.requires(groupBinding);
groupBindings.put(key, groupBindingSupplier);
}
service = new ExternalConnectionFactoryService(getDiscoveryGroup(context, dgname), commandDispatcherFactories, groupBindings, clusterNames, jmsFactoryType, ha, enable1Prefixes, config);
} else {
Map<String, Supplier<SocketBinding>> socketBindings = new HashMap<>();
Map<String, Supplier<OutboundSocketBinding>> outboundSocketBindings = new HashMap<>();
Set<String> connectorsSocketBindings = new HashSet<>();
final Set<String> sslContextNames = new HashSet<>();
TransportConfiguration[] transportConfigurations = TransportConfigOperationHandlers.processConnectors(context, connectorNames, connectorsSocketBindings, sslContextNames);
Map<String, Boolean> outbounds = TransportConfigOperationHandlers.listOutBoundSocketBinding(context, connectorsSocketBindings);
for (final String connectorSocketBinding : connectorsSocketBindings) {
// find whether the connectorSocketBinding references a SocketBinding or an OutboundSocketBinding
if (outbounds.get(connectorSocketBinding)) {
final ServiceName outboundSocketName = OUTBOUND_SOCKET_BINDING_CAPABILITY.getCapabilityServiceName(connectorSocketBinding);
Supplier<OutboundSocketBinding> outboundSupplier = builder.requires(outboundSocketName);
outboundSocketBindings.put(connectorSocketBinding, outboundSupplier);
} else {
final ServiceName socketName = SOCKET_BINDING_CAPABILITY.getCapabilityServiceName(connectorSocketBinding);
Supplier<SocketBinding> socketBindingsSupplier = builder.requires(socketName);
socketBindings.put(connectorSocketBinding, socketBindingsSupplier);
}
}
Map<String, Supplier<SSLContext>> sslContexts = new HashMap<>();
for (final String entry : sslContextNames) {
Supplier<SSLContext> sslContext = builder.requires(ELYTRON_SSL_CONTEXT_CAPABILITY.getCapabilityServiceName(entry));
sslContexts.put(entry, sslContext);
}
service = new ExternalConnectionFactoryService(transportConfigurations, socketBindings, outboundSocketBindings, sslContexts, jmsFactoryType, ha, enable1Prefixes, config);
}
builder.setInstance(service);
builder.install();
for (String entry : Common.ENTRIES.unwrap(context, model)) {
MessagingLogger.ROOT_LOGGER.debugf("Referencing %s with JNDI name %s", serviceName, entry);
BinderServiceUtil.installBinderService(context.getServiceTarget(), entry, service, serviceName);
}
}
static DiscoveryGroupConfiguration getDiscoveryGroup(final OperationContext context, final String name) throws OperationFailedException {
Resource discoveryGroup;
try {
discoveryGroup = context.readResourceFromRoot(context.getCurrentAddress().getParent().append(PathElement.pathElement(CommonAttributes.JGROUPS_DISCOVERY_GROUP, name)), true);
} catch (Resource.NoSuchResourceException ex) {
discoveryGroup = context.readResourceFromRoot(context.getCurrentAddress().getParent().append(PathElement.pathElement(CommonAttributes.SOCKET_DISCOVERY_GROUP, name)), true);
}
if (discoveryGroup != null) {
final long refreshTimeout = DiscoveryGroupDefinition.REFRESH_TIMEOUT.resolveModelAttribute(context, discoveryGroup.getModel()).asLong();
final long initialWaitTimeout = DiscoveryGroupDefinition.INITIAL_WAIT_TIMEOUT.resolveModelAttribute(context, discoveryGroup.getModel()).asLong();
return new DiscoveryGroupConfiguration()
.setName(name)
.setRefreshTimeout(refreshTimeout)
.setDiscoveryInitialWaitTimeout(initialWaitTimeout);
}
return null;
}
@Override
protected void populateModel(final ModelNode operation, final ModelNode model) throws OperationFailedException {
for (AttributeDefinition attr : attributes) {
if (DESERIALIZATION_BLACKLIST.equals(attr)) {
if (operation.hasDefined(DESERIALIZATION_BLACKLIST.getName())) {
DESERIALIZATION_BLOCKLIST.validateAndSet(operation, model);
}
} else if (DESERIALIZATION_WHITELIST.equals(attr)) {
if (operation.hasDefined(DESERIALIZATION_WHITELIST.getName())) {
DESERIALIZATION_ALLOWLIST.validateAndSet(operation, model);
}
} else {
attr.validateAndSet(operation, model);
}
}
}
}
| 12,166
| 62.701571
| 197
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/ConnectionFactoryService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq.jms;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import org.apache.activemq.artemis.jms.server.JMSServerManager;
import org.apache.activemq.artemis.jms.server.config.ConnectionFactoryConfiguration;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.wildfly.extension.messaging.activemq.logging.MessagingLogger;
/**
* {@code Service} responsible for creating and destroying a {@code jakarta.jms.ConnectionFactory}.
*
* @author Emanuel Muckenhuber
*/
class ConnectionFactoryService implements Service<Void> {
private final String name;
private final ConnectionFactoryConfiguration configuration;
private final InjectedValue<JMSServerManager> jmsServer = new InjectedValue<>();
private final InjectedValue<ExecutorService> executorInjector = new InjectedValue<>();
public ConnectionFactoryService(final ConnectionFactoryConfiguration configuration) {
name = configuration.getName();
if(name == null) {
throw MessagingLogger.ROOT_LOGGER.nullVar("cf name");
}
this.configuration = configuration;
}
/** {@inheritDoc} */
public synchronized void start(final StartContext context) throws StartException {
final JMSServerManager jmsManager = jmsServer.getValue();
final Runnable task = new Runnable() {
@Override
public void run() {
try {
jmsManager.createConnectionFactory(false, configuration, configuration.getBindings());
context.complete();
} catch (Throwable e) {
context.failed(MessagingLogger.ROOT_LOGGER.failedToCreate(e, "connection-factory"));
}
}
};
try {
executorInjector.getValue().execute(task);
} catch (RejectedExecutionException e) {
task.run();
} finally {
context.asynchronous();
}
}
/** {@inheritDoc} */
public synchronized void stop(final StopContext context) {
final JMSServerManager jmsManager = jmsServer.getValue();
final Runnable task = new Runnable() {
@Override
public void run() {
try {
jmsManager.destroyConnectionFactory(name);
} catch (Throwable e) {
MessagingLogger.ROOT_LOGGER.failedToDestroy("connection-factory", name);
}
context.complete();
}
};
// Jakarta Messaging Server Manager uses locking which waits on service completion, use async to prevent starvation
try {
executorInjector.getValue().execute(task);
} catch (RejectedExecutionException e) {
task.run();
} finally {
context.asynchronous();
}
}
/** {@inheritDoc} */
public Void getValue() throws IllegalStateException {
return null;
}
InjectedValue<JMSServerManager> getJmsServer() {
return jmsServer;
}
public InjectedValue<ExecutorService> getExecutorInjector() {
return executorInjector;
}
}
| 4,418
| 36.449153
| 123
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/JMSTopicRemove.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq.jms;
import static org.wildfly.extension.messaging.activemq.jms.JMSTopicService.JMS_TOPIC_PREFIX;
import org.apache.activemq.artemis.jms.server.JMSServerManager;
import org.jboss.as.controller.AbstractRemoveStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.wildfly.extension.messaging.activemq.CommonAttributes;
import org.wildfly.extension.messaging.activemq.MessagingServices;
/**
* Update handler removing a topic from the Jakarta Messaging subsystem. The
* runtime action will remove the corresponding {@link JMSTopicService}.
*
* @author Emanuel Muckenhuber
* @author <a href="mailto:andy.taylor@jboss.com">Andy Taylor</a>
*/
public class JMSTopicRemove extends AbstractRemoveStepHandler {
public static final JMSTopicRemove INSTANCE = new JMSTopicRemove();
private JMSTopicRemove() {
}
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
final ServiceName serviceName = MessagingServices.getActiveMQServiceName(PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)));
final ServiceName jmsServiceName = JMSServices.getJmsManagerBaseServiceName(serviceName);
final String name = context.getCurrentAddress().getLastElement().getValue();
ServiceController<?> service = context.getServiceRegistry(true).getService(jmsServiceName);
JMSServerManager server = JMSServerManager.class.cast(service.getValue());
try {
server.destroyTopic(JMS_TOPIC_PREFIX + name, true);
} catch (Exception e) {
throw new OperationFailedException(e);
}
context.removeService(JMSServices.getJmsTopicBaseServiceName(serviceName).append(name));
for (String entry : CommonAttributes.DESTINATION_ENTRIES.unwrap(context, model)) {
final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(entry);
ServiceName binderServiceName = bindInfo.getBinderServiceName();
context.removeService(binderServiceName);
}
for (String legacyEntry : CommonAttributes.LEGACY_ENTRIES.unwrap(context, model)) {
final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(legacyEntry);
ServiceName binderServiceName = bindInfo.getBinderServiceName();
context.removeService(binderServiceName);
}
}
protected void recoverServices(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
JMSTopicAdd.INSTANCE.performRuntime(context, operation, model);
}
}
| 4,045
| 45.505747
| 156
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/JMSTopicAdd.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq.jms;
import java.util.List;
import jakarta.jms.Topic;
import org.hornetq.api.jms.HornetQJMSClient;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.wildfly.extension.messaging.activemq.BinderServiceUtil;
import org.wildfly.extension.messaging.activemq.CommonAttributes;
import org.wildfly.extension.messaging.activemq.MessagingServices;
/**
* Update handler adding a topic to the Jakarta Messaging subsystem. The
* runtime action, will create the {@link JMSTopicService}.
*
* @author Emanuel Muckenhuber
* @author <a href="mailto:andy.taylor@jboss.com">Andy Taylor</a>
*/
public class JMSTopicAdd extends AbstractAddStepHandler {
public static final JMSTopicAdd INSTANCE = new JMSTopicAdd();
private JMSTopicAdd() {
super(JMSTopicDefinition.ATTRIBUTES);
}
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
final String name = context.getCurrentAddressValue();
final ServiceName serviceName = MessagingServices.getActiveMQServiceName(context.getCurrentAddress());
final ServiceTarget serviceTarget = context.getServiceTarget();
// Do not pass the JNDI bindings to ActiveMQ but install them directly instead so that the
// dependencies from the BinderServices to the JMSQueueService are not broken
JMSTopicService jmsTopicService = JMSTopicService.installService(name, serviceName, serviceTarget);
final ServiceName jmsTopicServiceName = JMSServices.getJmsTopicBaseServiceName(serviceName).append(name);
for (String entry : CommonAttributes.DESTINATION_ENTRIES.unwrap(context, model)) {
BinderServiceUtil.installBinderService(serviceTarget, entry, jmsTopicService, jmsTopicServiceName);
}
List<String> legacyEntries = CommonAttributes.LEGACY_ENTRIES.unwrap(context, model);
if (!legacyEntries.isEmpty()) {
Topic legacyTopic = HornetQJMSClient.createTopic(name);
for (String legacyEntry : legacyEntries) {
BinderServiceUtil.installBinderService(serviceTarget, legacyEntry, legacyTopic);
}
}
}
}
| 3,502
| 43.341772
| 131
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/JMSServices.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq.jms;
import java.util.HashSet;
import java.util.Set;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceName;
/**
* @author Emanuel Muckenhuber
* @author <a href="mailto:andy.taylor@jboss.com">Andy Taylor</a>
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2012 Red Hat inc
*/
public class JMSServices {
private static final String[] NO_BINDINGS = new String[0];
private static final String JMS = "jms";
private static final String JMS_MANAGER = "manager";
private static final String JMS_QUEUE_BASE = "queue";
private static final String JMS_TOPIC_BASE = "topic";
private static final String JMS_CF_BASE = "connection-factory";
public static final String JMS_POOLED_CF_BASE = "pooled-connection-factory";
public static ServiceName getJmsManagerBaseServiceName(ServiceName activeMQServiceName) {
return activeMQServiceName.append(JMS).append(JMS_MANAGER);
}
public static ServiceName getJmsQueueBaseServiceName(ServiceName activeMQServiceName) {
return activeMQServiceName.append(JMS).append(JMS_QUEUE_BASE);
}
public static ServiceName getJmsTopicBaseServiceName(ServiceName activeMQServiceName) {
return activeMQServiceName.append(JMS).append(JMS_TOPIC_BASE);
}
public static ServiceName getConnectionFactoryBaseServiceName(ServiceName activeMQServiceName) {
return activeMQServiceName.append(JMS).append(JMS_CF_BASE);
}
public static ServiceName getPooledConnectionFactoryBaseServiceName(ServiceName activeMQServiceName) {
return activeMQServiceName.append(JMS).append(JMS_POOLED_CF_BASE);
}
public static String[] getJndiBindings(final ModelNode node) {
if (node.isDefined()) {
final Set<String> bindings = new HashSet<String>();
for (final ModelNode entry : node.asList()) {
bindings.add(entry.asString());
}
return bindings.toArray(new String[bindings.size()]);
}
return NO_BINDINGS;
}
}
| 3,115
| 38.948718
| 106
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/JsonUtil.java
|
/*
* Copyright 2022 JBoss by Red Hat.
*
* 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.wildfly.extension.messaging.activemq.jms;
import java.util.Map;
import jakarta.json.Json;
import jakarta.json.JsonArrayBuilder;
import jakarta.json.JsonObject;
import jakarta.json.JsonObjectBuilder;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.utils.Base64;
/**
* Temporary class to be removed once we upgrade to Artemis 2.20
* @author Emmanuel Hugonnet (c) 2021 Red Hat, Inc.
*/
public class JsonUtil {
static String toJSON(final Map<String, Object>[] messages) {
JsonArrayBuilder array = Json.createArrayBuilder();
for (Map<String, Object> message : messages) {
array.add(toJsonObject(message));
}
return array.build().toString();
}
private static JsonObject toJsonObject(Map<String, ?> map) {
JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
for (Map.Entry<String, ?> entry : map.entrySet()) {
addToObject(String.valueOf(entry.getKey()), entry.getValue(), jsonObjectBuilder);
}
return jsonObjectBuilder.build();
}
private static void addToObject(final String key, final Object param, final JsonObjectBuilder jsonObjectBuilder) {
if (param instanceof Integer) {
jsonObjectBuilder.add(key, (Integer) param);
} else if (param instanceof Long) {
jsonObjectBuilder.add(key, (Long) param);
} else if (param instanceof Double) {
jsonObjectBuilder.add(key, (Double) param);
} else if (param instanceof String) {
jsonObjectBuilder.add(key, (String) param);
} else if (param instanceof Boolean) {
jsonObjectBuilder.add(key, (Boolean) param);
} else if (param instanceof Map) {
JsonObject mapObject = toJsonObject((Map<String, Object>) param);
jsonObjectBuilder.add(key, mapObject);
} else if (param instanceof Short) {
jsonObjectBuilder.add(key, (Short) param);
} else if (param instanceof Byte) {
jsonObjectBuilder.add(key, ((Byte) param).shortValue());
} else if (param instanceof Number) {
jsonObjectBuilder.add(key, ((Number) param).doubleValue());
} else if (param instanceof SimpleString) {
jsonObjectBuilder.add(key, param.toString());
} else if (param == null) {
jsonObjectBuilder.addNull(key);
} else if (param instanceof byte[]) {
JsonArrayBuilder byteArrayObject = toJsonArrayBuilder((byte[]) param);
jsonObjectBuilder.add(key, byteArrayObject);
} else if (param instanceof Object[]) {
final JsonArrayBuilder objectArrayBuilder = Json.createArrayBuilder();
for (Object parameter : (Object[]) param) {
addToArray(parameter, objectArrayBuilder);
}
jsonObjectBuilder.add(key, objectArrayBuilder);
} else {
jsonObjectBuilder.add(key, param.toString());
}
}
private static void addToArray(final Object param, final JsonArrayBuilder jsonArrayBuilder) {
if (param instanceof Integer) {
jsonArrayBuilder.add((Integer) param);
} else if (param instanceof Long) {
jsonArrayBuilder.add((Long) param);
} else if (param instanceof Double) {
jsonArrayBuilder.add((Double) param);
} else if (param instanceof String) {
jsonArrayBuilder.add((String) param);
} else if (param instanceof Boolean) {
jsonArrayBuilder.add((Boolean) param);
} else if (param instanceof Map) {
JsonObject mapObject = toJsonObject((Map<String, Object>) param);
jsonArrayBuilder.add(mapObject);
} else if (param instanceof Short) {
jsonArrayBuilder.add((Short) param);
} else if (param instanceof Byte) {
jsonArrayBuilder.add(((Byte) param).shortValue());
} else if (param instanceof Number) {
jsonArrayBuilder.add(((Number)param).doubleValue());
} else if (param == null) {
jsonArrayBuilder.addNull();
} else if (param instanceof byte[]) {
JsonArrayBuilder byteArrayObject = toJsonArrayBuilder((byte[]) param);
jsonArrayBuilder.add(byteArrayObject);
} else if (param instanceof CompositeData[]) {
JsonArrayBuilder innerJsonArray = Json.createArrayBuilder();
for (Object data : (CompositeData[])param) {
String s = Base64.encodeObject((CompositeDataSupport) data);
innerJsonArray.add(s);
}
JsonObjectBuilder jsonObject = Json.createObjectBuilder();
jsonObject.add(CompositeData.class.getName(), innerJsonArray);
jsonArrayBuilder.add(jsonObject);
} else if (param instanceof Object[]) {
JsonArrayBuilder objectArrayBuilder = Json.createArrayBuilder();
for (Object parameter : (Object[])param) {
addToArray(parameter, objectArrayBuilder);
}
jsonArrayBuilder.add(objectArrayBuilder);
} else {
jsonArrayBuilder.add(param.toString());
}
}
private static JsonArrayBuilder toJsonArrayBuilder(byte[] byteArray) {
JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
if (byteArray != null) {
for (int i = 0; i < byteArray.length; i++) {
jsonArrayBuilder.add(((Byte) byteArray[i]).shortValue());
}
}
return jsonArrayBuilder;
}
}
| 6,192
| 42.006944
| 118
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/PooledConnectionFactoryDefinition.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.wildfly.extension.messaging.activemq.jms;
import static java.lang.System.arraycopy;
import static org.wildfly.extension.messaging.activemq.AbstractTransportDefinition.CONNECTOR_CAPABILITY_NAME;
import static org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttribute.getDefinitions;
import static org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.Common.DESERIALIZATION_ALLOWLIST;
import static org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.Common.DESERIALIZATION_BLACKLIST;
import static org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.Common.DESERIALIZATION_BLOCKLIST;
import static org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.Common.DESERIALIZATION_WHITELIST;
import static org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.Pooled.CREDENTIAL_REFERENCE;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.jboss.as.controller.AbstractAttributeDefinitionBuilder;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.AttributeMarshaller;
import org.jboss.as.controller.AttributeParser;
import org.jboss.as.controller.PersistentResourceDefinition;
import org.jboss.as.controller.PrimitiveListAttributeDefinition;
import org.jboss.as.controller.ReloadRequiredWriteAttributeHandler;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleListAttributeDefinition;
import org.jboss.as.controller.SimpleMapAttributeDefinition;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.StringListAttributeDefinition;
import org.jboss.as.controller.capability.DynamicNameMappers;
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.security.CredentialReferenceWriteAttributeHandler;
import org.wildfly.extension.messaging.activemq.AbstractTransportDefinition;
import org.wildfly.extension.messaging.activemq.CommonAttributes;
import org.wildfly.extension.messaging.activemq.MessagingExtension;
import org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.Common;
import org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.Pooled;
/**
* Jakarta Messaging pooled Connection Factory resource definition.
*
* @author <a href="http://jmesnil.net">Jeff Mesnil</a> (c) 2012 Red Hat Inc.
*/
public class PooledConnectionFactoryDefinition extends PersistentResourceDefinition {
static final String CAPABILITY_NAME = "org.wildfly.messaging.activemq.server.pooled-connection-factory";
static final RuntimeCapability<Void> CAPABILITY = RuntimeCapability.Builder.of(CAPABILITY_NAME, true, PooledConnectionFactoryService.class)
.setDynamicNameMapper(DynamicNameMappers.PARENT)
.build();
// the generation of the Pooled CF attributes is a bit ugly but it is with purpose:
// * factorize the attributes which are common between the regular CF and the pooled CF
// * keep in a single place the subtle differences (e.g. different default values for reconnect-attempts between
// the regular and pooled CF
private static ConnectionFactoryAttribute[] define(ConnectionFactoryAttribute[] specific, ConnectionFactoryAttribute... common) {
int size = common.length + specific.length;
ConnectionFactoryAttribute[] result = new ConnectionFactoryAttribute[size];
arraycopy(specific, 0, result, 0, specific.length);
for (int i = 0; i < common.length; i++) {
ConnectionFactoryAttribute attr = common[i];
AttributeDefinition definition = attr.getDefinition();
ConnectionFactoryAttribute newAttr;
// replace the reconnect-attempts attribute to use a different default value for pooled CF
if (definition == Common.RECONNECT_ATTEMPTS) {
AttributeDefinition copy = copy(Pooled.RECONNECT_ATTEMPTS, AttributeAccess.Flag.RESTART_ALL_SERVICES);
newAttr = ConnectionFactoryAttribute.create(copy, Pooled.RECONNECT_ATTEMPTS_PROP_NAME, true);
} else if (definition == Common.CONNECTORS) {
StringListAttributeDefinition copy = new StringListAttributeDefinition.Builder(Common.CONNECTORS)
.setAlternatives(CommonAttributes.DISCOVERY_GROUP)
.setRequired(true)
.setAttributeParser(AttributeParser.STRING_LIST)
.setAttributeMarshaller(AttributeMarshaller.STRING_LIST)
.setCapabilityReference(new AbstractTransportDefinition.TransportCapabilityReferenceRecorder(CAPABILITY_NAME, CONNECTOR_CAPABILITY_NAME, false))
.setRestartAllServices()
.build();
newAttr = ConnectionFactoryAttribute.create(copy, attr.getPropertyName(), attr.isResourceAdapterProperty(), attr.getConfigType());
}else {
AttributeDefinition copy = copy(definition, AttributeAccess.Flag.RESTART_ALL_SERVICES);
newAttr = ConnectionFactoryAttribute.create(copy, attr.getPropertyName(), attr.isResourceAdapterProperty(), attr.getConfigType());
}
result[specific.length + i] = newAttr;
}
return result;
}
private static AttributeDefinition copy(AttributeDefinition attribute, AttributeAccess.Flag flag) {
AbstractAttributeDefinitionBuilder builder;
if (attribute instanceof SimpleListAttributeDefinition) {
builder = new SimpleListAttributeDefinition.Builder((SimpleListAttributeDefinition)attribute);
} else if (attribute instanceof SimpleMapAttributeDefinition) {
builder = new SimpleMapAttributeDefinition.Builder((SimpleMapAttributeDefinition)attribute);
} else if (attribute instanceof PrimitiveListAttributeDefinition) {
builder = new PrimitiveListAttributeDefinition.Builder((PrimitiveListAttributeDefinition)attribute);
} else {
builder = new SimpleAttributeDefinitionBuilder((SimpleAttributeDefinition)attribute);
}
builder.setFlags(flag);
return builder.build();
}
public static final ConnectionFactoryAttribute[] ATTRIBUTES = define(Pooled.ATTRIBUTES, Common.ATTRIBUTES);
public static Map<String, ConnectionFactoryAttribute> getAttributesMap() {
Map<String, ConnectionFactoryAttribute> attrs = new HashMap<String, ConnectionFactoryAttribute>(ATTRIBUTES.length);
for (ConnectionFactoryAttribute attribute : ATTRIBUTES) {
attrs.put(attribute.getDefinition().getName(), attribute);
}
return attrs;
}
private final boolean deployed;
private final boolean external;
public PooledConnectionFactoryDefinition(final boolean deployed) {
this(new SimpleResourceDefinition.Parameters(MessagingExtension.POOLED_CONNECTION_FACTORY_PATH, MessagingExtension.getResourceDescriptionResolver(CommonAttributes.POOLED_CONNECTION_FACTORY))
.setAddHandler(PooledConnectionFactoryAdd.INSTANCE)
.setRemoveHandler(PooledConnectionFactoryRemove.INSTANCE)
.setCapabilities(CAPABILITY), deployed);
}
protected PooledConnectionFactoryDefinition(SimpleResourceDefinition.Parameters parameters, final boolean deployed) {
this(parameters, deployed, false);
}
protected PooledConnectionFactoryDefinition(SimpleResourceDefinition.Parameters parameters, final boolean deployed, final boolean external) {
super(parameters);
this.deployed = deployed;
this.external = external;
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return Arrays.asList(getDefinitions(ATTRIBUTES));
}
@Override
public void registerAttributes(ManagementResourceRegistration registry) {
Collection<AttributeDefinition> definitions = getAttributes();
ReloadRequiredWriteAttributeHandler reloadRequiredWriteAttributeHandler = new ReloadRequiredWriteAttributeHandler(definitions);
CredentialReferenceWriteAttributeHandler credentialReferenceWriteAttributeHandler = new CredentialReferenceWriteAttributeHandler(CREDENTIAL_REFERENCE);
for (AttributeDefinition attr : definitions) {
if (!attr.getFlags().contains(AttributeAccess.Flag.STORAGE_RUNTIME)) {
if (deployed) {
registry.registerReadOnlyAttribute(attr, external ? PooledConnectionFactoryConfigurationRuntimeHandler.EXTERNAL_INSTANCE: PooledConnectionFactoryConfigurationRuntimeHandler.INSTANCE);
} else {
if (CREDENTIAL_REFERENCE.equals(attr)) {
registry.registerReadWriteAttribute(attr, null, credentialReferenceWriteAttributeHandler);
} else {
registry.registerReadWriteAttribute(attr, null, reloadRequiredWriteAttributeHandler);
}
}
}
}
ConnectionFactoryAttributes.registerAliasAttribute(registry, deployed, DESERIALIZATION_WHITELIST, DESERIALIZATION_ALLOWLIST.getName());
ConnectionFactoryAttributes.registerAliasAttribute(registry, deployed, DESERIALIZATION_BLACKLIST, DESERIALIZATION_BLOCKLIST.getName());
}
}
| 10,639
| 57.78453
| 203
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/ExternalJMSQueueAdd.java
|
/*
* Copyright 2018 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.wildfly.extension.messaging.activemq.jms;
import static org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.External.ENABLE_AMQ1_PREFIX;
import static org.wildfly.extension.messaging.activemq.logging.MessagingLogger.ROOT_LOGGER;
import jakarta.jms.Queue;
import org.jboss.as.controller.AbstractAddStepHandler;
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.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.wildfly.extension.messaging.activemq.BinderServiceUtil;
import org.wildfly.extension.messaging.activemq.CommonAttributes;
import org.wildfly.extension.messaging.activemq.MessagingServices;
/**
* Update handler adding a queue to the Jakarta Messaging subsystem. The
* runtime action will create the {@link JMSQueueService}.
*
* @author Emmanuel Hugonnet (c) 2018 Red Hat, inc.
*/
public class ExternalJMSQueueAdd extends AbstractAddStepHandler {
public static final ExternalJMSQueueAdd INSTANCE = new ExternalJMSQueueAdd();
private ExternalJMSQueueAdd() {
super(ExternalJMSQueueDefinition.ATTRIBUTES);
}
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
final String name = context.getCurrentAddressValue();
final ServiceTarget serviceTarget = context.getServiceTarget();
// Do not pass the JNDI bindings to ActiveMQ but install them directly instead so that the
// dependencies from the BinderServices to the JMSQueueService are not broken
final ServiceName jmsQueueServiceName = JMSServices.getJmsQueueBaseServiceName(MessagingServices.getActiveMQServiceName((String) null)).append(name);
final boolean enabledAMQ1Prefix = ENABLE_AMQ1_PREFIX.resolveModelAttribute(context, model).asBoolean();
Service<Queue> queueService = ExternalJMSQueueService.installService(name, serviceTarget, jmsQueueServiceName, enabledAMQ1Prefix);
for (String entry : CommonAttributes.DESTINATION_ENTRIES.unwrap(context, model)) {
ROOT_LOGGER.boundJndiName(entry);
BinderServiceUtil.installBinderService(serviceTarget, entry, queueService, jmsQueueServiceName);
}
}
}
| 2,989
| 45
| 157
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/ExternalJMSQueueRemove.java
|
/*
* Copyright 2018 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.wildfly.extension.messaging.activemq.jms;
import org.jboss.as.controller.AbstractRemoveStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceName;
import org.wildfly.extension.messaging.activemq.CommonAttributes;
import org.wildfly.extension.messaging.activemq.MessagingServices;
/**
* Update handler removing a queue from the Jakarta Messaging subsystem. The
* runtime action will remove the corresponding {@link JMSQueueService}.
*
* @author Emmanuel Hugonnet (c) 2018 Red Hat, inc.
*/
public class ExternalJMSQueueRemove extends AbstractRemoveStepHandler {
static final ExternalJMSQueueRemove INSTANCE = new ExternalJMSQueueRemove();
private ExternalJMSQueueRemove() {
}
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
final String name = context.getCurrentAddressValue();
context.removeService(JMSServices.getJmsQueueBaseServiceName(MessagingServices.getActiveMQServiceName((String) null)).append(name));
for (String entry : CommonAttributes.DESTINATION_ENTRIES.unwrap(context, model)) {
final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(entry);
ServiceName binderServiceName = bindInfo.getBinderServiceName();
context.removeService(binderServiceName);
}
}
@Override
protected void recoverServices(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
ExternalJMSQueueAdd.INSTANCE.performRuntime(context, operation, model);
}
}
| 2,399
| 41.105263
| 140
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/PooledConnectionFactoryConfigurationRuntimeHandler.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq.jms;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.PathAddress;
import org.jboss.dmr.ModelNode;
/**
* Read handler for deployed Jakarta Messaging pooled connection factories
*
* @author Stuart Douglas
*/
public class PooledConnectionFactoryConfigurationRuntimeHandler extends AbstractJMSRuntimeHandler<ModelNode> {
public static final PooledConnectionFactoryConfigurationRuntimeHandler INSTANCE = new PooledConnectionFactoryConfigurationRuntimeHandler(false);
public static final PooledConnectionFactoryConfigurationRuntimeHandler EXTERNAL_INSTANCE = new PooledConnectionFactoryConfigurationRuntimeHandler(true);
private final boolean external;
private PooledConnectionFactoryConfigurationRuntimeHandler(final boolean external) {
this.external = external;
}
@Override
protected void executeReadAttribute(final String attributeName, final OperationContext context, final ModelNode connectionFactory, final PathAddress address, final boolean includeDefault) {
if (connectionFactory.hasDefined(attributeName)) {
context.getResult().set(connectionFactory.get(attributeName));
} else {
ConnectionFactoryAttribute attribute = external ? ExternalPooledConnectionFactoryDefinition.getAttributesMap().get(attributeName) : PooledConnectionFactoryDefinition.getAttributesMap().get(attributeName);
if (attribute != null && attribute.getDefinition().getDefaultValue() != null && attribute.getDefinition().getDefaultValue().isDefined()) {
context.getResult().set(attribute.getDefinition().getDefaultValue());
}
}
}
}
| 2,749
| 46.413793
| 216
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/ConnectionFactoryAdd.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq.jms;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.CALL_FAILOVER_TIMEOUT;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.CALL_TIMEOUT;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.CLIENT_ID;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.HA;
import static org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.Common.DESERIALIZATION_ALLOWLIST;
import static org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.Common.DESERIALIZATION_BLACKLIST;
import static org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.Common.DESERIALIZATION_BLOCKLIST;
import static org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.Common.DESERIALIZATION_WHITELIST;
import java.util.List;
import org.apache.activemq.artemis.api.jms.JMSFactoryType;
import org.apache.activemq.artemis.jms.server.JMSServerManager;
import org.apache.activemq.artemis.jms.server.config.ConnectionFactoryConfiguration;
import org.apache.activemq.artemis.jms.server.config.impl.ConnectionFactoryConfigurationImpl;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController.Mode;
import org.jboss.msc.service.ServiceName;
import org.wildfly.extension.messaging.activemq.ActiveMQActivationService;
import org.wildfly.extension.messaging.activemq.MessagingServices;
import org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.Common;
/**
* Update adding a connection factory to the subsystem. The
* runtime action will create the {@link ConnectionFactoryService}.
*
* @author Emanuel Muckenhuber
* @author <a href="mailto:andy.taylor@jboss.com">Andy Taylor</a>
*/
public class ConnectionFactoryAdd extends AbstractAddStepHandler {
public static final ConnectionFactoryAdd INSTANCE = new ConnectionFactoryAdd();
private ConnectionFactoryAdd() {
super(ConnectionFactoryDefinition.ATTRIBUTES);
}
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
final String name = context.getCurrentAddressValue();
final ServiceName activeMQServiceName = MessagingServices.getActiveMQServiceName(context.getCurrentAddress());
final ConnectionFactoryConfiguration configuration = createConfiguration(context, name, model);
final ConnectionFactoryService service = new ConnectionFactoryService(configuration);
final ServiceName aliasServiceName = JMSServices.getConnectionFactoryBaseServiceName(activeMQServiceName).append(name);
final ServiceName serviceName = ConnectionFactoryDefinition.CAPABILITY.getCapabilityServiceName(context.getCurrentAddress());
ServiceBuilder<?> serviceBuilder = context.getServiceTarget()
.addService(serviceName, service)
.addAliases(aliasServiceName);
serviceBuilder.requires(ActiveMQActivationService.getServiceName(activeMQServiceName));
serviceBuilder.addDependency(JMSServices.getJmsManagerBaseServiceName(activeMQServiceName), JMSServerManager.class, service.getJmsServer());
serviceBuilder.setInitialMode(Mode.PASSIVE);
org.jboss.as.server.Services.addServerExecutorDependency(serviceBuilder, service.getExecutorInjector());
serviceBuilder.install();
}
static ConnectionFactoryConfiguration createConfiguration(final OperationContext context, final String name, final ModelNode model) throws OperationFailedException {
final List<String> entries = Common.ENTRIES.unwrap(context, model);
final ConnectionFactoryConfiguration config = new ConnectionFactoryConfigurationImpl()
.setName(name)
.setHA(false)
.setBindings(entries.toArray(new String[entries.size()]));
config.setHA(HA.resolveModelAttribute(context, model).asBoolean());
config.setAutoGroup(Common.AUTO_GROUP.resolveModelAttribute(context, model).asBoolean());
config.setBlockOnAcknowledge(Common.BLOCK_ON_ACKNOWLEDGE.resolveModelAttribute(context, model).asBoolean());
config.setBlockOnDurableSend(Common.BLOCK_ON_DURABLE_SEND.resolveModelAttribute(context, model).asBoolean());
config.setBlockOnNonDurableSend(Common.BLOCK_ON_NON_DURABLE_SEND.resolveModelAttribute(context, model).asBoolean());
config.setCacheLargeMessagesClient(Common.CACHE_LARGE_MESSAGE_CLIENT.resolveModelAttribute(context, model).asBoolean());
config.setCallTimeout(CALL_TIMEOUT.resolveModelAttribute(context, model).asLong());
config.setClientFailureCheckPeriod(Common.CLIENT_FAILURE_CHECK_PERIOD.resolveModelAttribute(context, model).asInt());
config.setCallFailoverTimeout(CALL_FAILOVER_TIMEOUT.resolveModelAttribute(context, model).asLong());
final ModelNode clientId = CLIENT_ID.resolveModelAttribute(context, model);
if (clientId.isDefined()) {
config.setClientID(clientId.asString());
}
config.setCompressLargeMessages(Common.COMPRESS_LARGE_MESSAGES.resolveModelAttribute(context, model).asBoolean());
config.setConfirmationWindowSize(Common.CONFIRMATION_WINDOW_SIZE.resolveModelAttribute(context, model).asInt());
config.setConnectionTTL(Common.CONNECTION_TTL.resolveModelAttribute(context, model).asLong());
List<String> connectorNames = Common.CONNECTORS.unwrap(context, model);
config.setConnectorNames(connectorNames);
config.setConsumerMaxRate(Common.CONSUMER_MAX_RATE.resolveModelAttribute(context, model).asInt());
config.setConsumerWindowSize(Common.CONSUMER_WINDOW_SIZE.resolveModelAttribute(context, model).asInt());
final ModelNode discoveryGroupName = Common.DISCOVERY_GROUP.resolveModelAttribute(context, model);
if (discoveryGroupName.isDefined()) {
config.setDiscoveryGroupName(discoveryGroupName.asString());
}
config.setDupsOKBatchSize(Common.DUPS_OK_BATCH_SIZE.resolveModelAttribute(context, model).asInt());
config.setFailoverOnInitialConnection(Common.FAILOVER_ON_INITIAL_CONNECTION.resolveModelAttribute(context, model).asBoolean());
final ModelNode groupId = Common.GROUP_ID.resolveModelAttribute(context, model);
if (groupId.isDefined()) {
config.setGroupID(groupId.asString());
}
final ModelNode lbcn = Common.CONNECTION_LOAD_BALANCING_CLASS_NAME.resolveModelAttribute(context, model);
if (lbcn.isDefined()) {
config.setLoadBalancingPolicyClassName(lbcn.asString());
}
config.setMaxRetryInterval(Common.MAX_RETRY_INTERVAL.resolveModelAttribute(context, model).asLong());
config.setMinLargeMessageSize(Common.MIN_LARGE_MESSAGE_SIZE.resolveModelAttribute(context, model).asInt());
config.setPreAcknowledge(Common.PRE_ACKNOWLEDGE.resolveModelAttribute(context, model).asBoolean());
config.setProducerMaxRate(Common.PRODUCER_MAX_RATE.resolveModelAttribute(context, model).asInt());
config.setProducerWindowSize(Common.PRODUCER_WINDOW_SIZE.resolveModelAttribute(context, model).asInt());
config.setReconnectAttempts(Common.RECONNECT_ATTEMPTS.resolveModelAttribute(context, model).asInt());
config.setRetryInterval(Common.RETRY_INTERVAL.resolveModelAttribute(context, model).asLong());
config.setRetryIntervalMultiplier(Common.RETRY_INTERVAL_MULTIPLIER.resolveModelAttribute(context, model).asDouble());
config.setScheduledThreadPoolMaxSize(Common.SCHEDULED_THREAD_POOL_MAX_SIZE.resolveModelAttribute(context, model).asInt());
config.setThreadPoolMaxSize(Common.THREAD_POOL_MAX_SIZE.resolveModelAttribute(context, model).asInt());
config.setTransactionBatchSize(Common.TRANSACTION_BATCH_SIZE.resolveModelAttribute(context, model).asInt());
config.setUseGlobalPools(Common.USE_GLOBAL_POOLS.resolveModelAttribute(context, model).asBoolean());
config.setLoadBalancingPolicyClassName(Common.CONNECTION_LOAD_BALANCING_CLASS_NAME.resolveModelAttribute(context, model).asString());
final ModelNode clientProtocolManagerFactory = Common.PROTOCOL_MANAGER_FACTORY.resolveModelAttribute(context, model);
if (clientProtocolManagerFactory.isDefined()) {
config.setProtocolManagerFactoryStr(clientProtocolManagerFactory.asString());
}
if (model.hasDefined(DESERIALIZATION_BLOCKLIST.getName())) {
List<String> deserializationBlockList = DESERIALIZATION_BLOCKLIST.unwrap(context, model);
if (!deserializationBlockList.isEmpty()) {
config.setDeserializationBlackList(String.join(",", deserializationBlockList));
}
}
if (model.hasDefined(DESERIALIZATION_ALLOWLIST.getName())) {
List<String> deserializationAllowList = DESERIALIZATION_ALLOWLIST.unwrap(context, model);
if (!deserializationAllowList.isEmpty()) {
config.setDeserializationWhiteList(String.join(",", deserializationAllowList));
}
}
JMSFactoryType jmsFactoryType = ConnectionFactoryType.valueOf(ConnectionFactoryAttributes.Regular.FACTORY_TYPE.resolveModelAttribute(context, model).asString()).getType();
config.setFactoryType(jmsFactoryType);
config.setInitialMessagePacketSize(Common.INITIAL_MESSAGE_PACKET_SIZE.resolveModelAttribute(context, model).asInt());
config.setEnableSharedClientID(true);
config.setEnable1xPrefixes(true);
config.setUseTopologyForLoadBalancing(Common.USE_TOPOLOGY.resolveModelAttribute(context, model).asBoolean());
return config;
}
@Override
protected void populateModel(final ModelNode operation, final ModelNode model) throws OperationFailedException {
for (AttributeDefinition attr : attributes) {
if (DESERIALIZATION_BLACKLIST.equals(attr)) {
if (operation.hasDefined(DESERIALIZATION_BLACKLIST.getName())) {
DESERIALIZATION_BLOCKLIST.validateAndSet(operation, model);
}
} else if (DESERIALIZATION_WHITELIST.equals(attr)) {
if (operation.hasDefined(DESERIALIZATION_WHITELIST.getName())) {
DESERIALIZATION_ALLOWLIST.validateAndSet(operation, model);
}
} else {
attr.validateAndSet(operation, model);
}
}
}
}
| 11,826
| 61.909574
| 179
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/PooledConnectionFactoryAdd.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq.jms;
import static org.jboss.as.controller.security.CredentialReference.handleCredentialReferenceUpdate;
import static org.jboss.as.controller.security.CredentialReference.rollbackCredentialStoreUpdate;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.JGROUPS_CLUSTER;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.LOCAL;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.LOCAL_TX;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.NONE;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.NO_TX;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.XA_TX;
import static org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttribute.getDefinitions;
import static org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.Common.DESERIALIZATION_ALLOWLIST;
import static org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.Common.DESERIALIZATION_BLACKLIST;
import static org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.Common.DESERIALIZATION_BLOCKLIST;
import static org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.Common.DESERIALIZATION_WHITELIST;
import static org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.Pooled.CREDENTIAL_REFERENCE;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
import org.jboss.as.connector.metadata.deployment.ResourceAdapterDeployment;
import org.jboss.as.controller.AbstractAddStepHandler;
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.registry.Resource;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.deployment.ContextNames.BindInfo;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.wildfly.extension.messaging.activemq.CommonAttributes;
import org.wildfly.extension.messaging.activemq.MessagingServices;
import org.wildfly.extension.messaging.activemq.TransportConfigOperationHandlers;
import org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes.Common;
/**
* @author <a href="mailto:andy.taylor@jboss.com">Andy Taylor</a>
* Date: 5/13/11
* Time: 1:42 PM
*/
public class PooledConnectionFactoryAdd extends AbstractAddStepHandler {
public static final PooledConnectionFactoryAdd INSTANCE = new PooledConnectionFactoryAdd();
private PooledConnectionFactoryAdd() {
super(getDefinitions(PooledConnectionFactoryDefinition.ATTRIBUTES));
}
@Override
protected void populateModel(final OperationContext context, final ModelNode operation, final Resource resource) throws OperationFailedException {
super.populateModel(context, operation, resource);
handleCredentialReferenceUpdate(context, resource.getModel());
}
@Override
protected void populateModel(final ModelNode operation, final ModelNode model) throws OperationFailedException {
for (AttributeDefinition attr : attributes) {
if (DESERIALIZATION_BLACKLIST.equals(attr)) {
if (operation.hasDefined(DESERIALIZATION_BLACKLIST.getName())) {
DESERIALIZATION_BLOCKLIST.validateAndSet(operation, model);
}
} else if (DESERIALIZATION_WHITELIST.equals(attr)) {
if (operation.hasDefined(DESERIALIZATION_WHITELIST.getName())) {
DESERIALIZATION_ALLOWLIST.validateAndSet(operation, model);
}
} else {
attr.validateAndSet(operation, model);
}
}
}
@Override
protected void performRuntime(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException {
ModelNode model = resource.getModel();
PathAddress address = context.getCurrentAddress();
final String name = context.getCurrentAddressValue();
final ModelNode resolvedModel = model.clone();
for(final AttributeDefinition attribute : attributes) {
resolvedModel.get(attribute.getName()).set(attribute.resolveModelAttribute(context, resolvedModel ));
}
// We validated that jndiName part of the model in populateModel
final List<String> jndiNames = new ArrayList<>();
for (ModelNode node : resolvedModel.get(Common.ENTRIES.getName()).asList()) {
jndiNames.add(node.asString());
}
final BindInfo bindInfo = ContextNames.bindInfoFor(jndiNames.get(0));
List<String> jndiAliases;
if(jndiNames.size() > 1) {
jndiAliases = new ArrayList<>(jndiNames.subList(1, jndiNames.size()));
} else {
jndiAliases = Collections.emptyList();
}
String managedConnectionPoolClassName = resolvedModel.get(ConnectionFactoryAttributes.Pooled.MANAGED_CONNECTION_POOL.getName()).asStringOrNull();
final int minPoolSize = resolvedModel.get(ConnectionFactoryAttributes.Pooled.MIN_POOL_SIZE.getName()).asInt();
final int maxPoolSize = resolvedModel.get(ConnectionFactoryAttributes.Pooled.MAX_POOL_SIZE.getName()).asInt();
Boolean enlistmentTrace = resolvedModel.get(ConnectionFactoryAttributes.Pooled.ENLISTMENT_TRACE.getName()).asBooleanOrNull();
String txSupport = getTxSupport(resolvedModel);
List<String> connectors = Common.CONNECTORS.unwrap(context, model);
String discoveryGroupName = getDiscoveryGroup(resolvedModel);
String jgroupClusterName = null;
final PathAddress serverAddress = MessagingServices.getActiveMQServerPathAddress(address);
if (discoveryGroupName != null) {
Resource dgResource;
try {
dgResource = context.readResourceFromRoot(serverAddress.append(CommonAttributes.SOCKET_DISCOVERY_GROUP, discoveryGroupName), false);
} catch (Resource.NoSuchResourceException ex) {
dgResource = context.readResourceFromRoot(serverAddress.append(CommonAttributes.JGROUPS_DISCOVERY_GROUP, discoveryGroupName), false);
}
ModelNode dgModel = dgResource.getModel();
ModelNode jgroupCluster = JGROUPS_CLUSTER.resolveModelAttribute(context, dgModel);
if(jgroupCluster.isDefined()) {
jgroupClusterName = jgroupCluster.asString();
}
}
List<PooledConnectionFactoryConfigProperties> adapterParams = getAdapterParams(resolvedModel, context, PooledConnectionFactoryDefinition.ATTRIBUTES);
final Set<String> connectorsSocketBindings = new HashSet<>();
final Set<String> sslContextNames = new HashSet<>();
TransportConfiguration[] transportConfigurations = TransportConfigOperationHandlers.processConnectors(context, connectors, connectorsSocketBindings, sslContextNames);
String serverName = serverAddress.getLastElement().getValue();
PooledConnectionFactoryService.installService(context,
name, serverName, connectors, discoveryGroupName, jgroupClusterName,
adapterParams, bindInfo, jndiAliases, txSupport, minPoolSize, maxPoolSize, managedConnectionPoolClassName, enlistmentTrace, model);
boolean statsEnabled = ConnectionFactoryAttributes.Pooled.STATISTICS_ENABLED.resolveModelAttribute(context, model).asBoolean();
if (statsEnabled) {
// Add the stats resource. This is kind of a hack as we are modifying the resource
// in runtime, but oh well. We don't use readResourceForUpdate for this reason.
// This only runs in this add op anyway, and because it's an add we know readResource
// is going to be returning the current write snapshot of the model, i.e. the one we want
PooledConnectionFactoryStatisticsService.registerStatisticsResources(resource);
installStatistics(context, name);
}
}
@Override
protected void rollbackRuntime(OperationContext context, final ModelNode operation, final Resource resource) {
rollbackCredentialStoreUpdate(CREDENTIAL_REFERENCE, context, resource);
}
static String getTxSupport(final ModelNode resolvedModel) {
String txType = resolvedModel.get(ConnectionFactoryAttributes.Pooled.TRANSACTION.getName()).asStringOrNull();
switch (txType) {
case LOCAL:
return LOCAL_TX;
case NONE:
return NO_TX;
default:
return XA_TX;
}
}
static String getDiscoveryGroup(final ModelNode model) {
if(model.hasDefined(Common.DISCOVERY_GROUP.getName())) {
return model.get(Common.DISCOVERY_GROUP.getName()).asString();
}
return null;
}
static List<PooledConnectionFactoryConfigProperties> getAdapterParams(ModelNode model, OperationContext context, ConnectionFactoryAttribute[] attributes) throws OperationFailedException {
List<PooledConnectionFactoryConfigProperties> configs = new ArrayList<PooledConnectionFactoryConfigProperties>();
for (ConnectionFactoryAttribute nodeAttribute : attributes)
{
if (!nodeAttribute.isResourceAdapterProperty())
continue;
AttributeDefinition definition = nodeAttribute.getDefinition();
ModelNode node = definition.resolveModelAttribute(context, model);
if (node.isDefined()) {
String attributeName = definition.getName();
final String value;
if (attributeName.equals(Common.DESERIALIZATION_BLOCKLIST.getName())) {
value = String.join(",", Common.DESERIALIZATION_BLOCKLIST.unwrap(context, model));
} else if (attributeName.equals(Common.DESERIALIZATION_ALLOWLIST.getName())) {
value = String.join(",", Common.DESERIALIZATION_ALLOWLIST.unwrap(context, model));
} else {
value = node.asString();
}
configs.add(new PooledConnectionFactoryConfigProperties(nodeAttribute.getPropertyName(), value, nodeAttribute.getClassType(), nodeAttribute.getConfigType()));
}
}
return configs;
}
static void installStatistics(OperationContext context, String name) {
ServiceName raActivatorsServiceName = PooledConnectionFactoryService.getResourceAdapterActivatorsServiceName(name);
PooledConnectionFactoryStatisticsService statsService = new PooledConnectionFactoryStatisticsService(context.getResourceRegistrationForUpdate(), true);
context.getServiceTarget().addService(raActivatorsServiceName.append("statistics"), statsService)
.addDependency(raActivatorsServiceName, ResourceAdapterDeployment.class, statsService.getRADeploymentInjector())
.setInitialMode(ServiceController.Mode.PASSIVE)
.install();
}
}
| 12,391
| 53.350877
| 191
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/ExternalJMSQueueService.java
|
/*
* Copyright 2018 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.wildfly.extension.messaging.activemq.jms;
import java.util.Collection;
import jakarta.jms.ConnectionFactory;
import jakarta.jms.JMSException;
import jakarta.jms.Queue;
import javax.naming.NamingException;
import org.apache.activemq.artemis.api.core.client.ClientSessionFactory;
import org.apache.activemq.artemis.api.core.client.ClusterTopologyListener;
import org.apache.activemq.artemis.api.core.client.ServerLocator;
import org.apache.activemq.artemis.api.core.client.TopologyMember;
import org.apache.activemq.artemis.core.client.impl.TopologyMemberImpl;
import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
import org.apache.activemq.artemis.jms.client.ActiveMQDestination;
import org.apache.activemq.artemis.ra.ActiveMQRAConnectionFactory;
import org.apache.activemq.artemis.spi.core.remoting.ClientProtocolManagerFactory;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.as.naming.NamingContext;
import org.jboss.as.naming.NamingStore;
import org.jboss.as.naming.service.NamingService;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.wildfly.extension.messaging.activemq.logging.MessagingLogger;
/**
* Service responsible for creating and destroying a client {@code jakarta.jms.Queue}.
*
* @author Emmanuel Hugonnet (c) 2018 Red Hat, inc.
*/
public class ExternalJMSQueueService implements Service<Queue> {
static final String JMS_QUEUE_PREFIX = "jms.queue.";
private final String queueName;
private final DestinationConfiguration config;
private final InjectedValue<NamingStore> namingStoreInjector = new InjectedValue<NamingStore>();
private final InjectedValue<ExternalPooledConnectionFactoryService> pcfInjector = new InjectedValue<ExternalPooledConnectionFactoryService>();
private Queue queue;
private ClientSessionFactory sessionFactory;
private ExternalJMSQueueService(final String queueName, final boolean enabledAMQ1Prefix) {
this.queueName = enabledAMQ1Prefix ? JMS_QUEUE_PREFIX + queueName : queueName;
this.config = null;
}
private ExternalJMSQueueService(final DestinationConfiguration config, final boolean enabledAMQ1Prefix) {
this.queueName = enabledAMQ1Prefix ? JMS_QUEUE_PREFIX + config.getName() : config.getName();
this.config = config;
}
@Override
public synchronized void start(final StartContext context) throws StartException {
NamingStore namingStore = namingStoreInjector.getOptionalValue();
if(namingStore!= null) {
final Queue managementQueue = config.getManagementQueue();
final NamingContext storeBaseContext = new NamingContext(namingStore, null);
try {
ConnectionFactory cf = (ConnectionFactory) storeBaseContext.lookup(pcfInjector.getValue().getBindInfo().getAbsoluteJndiName());
if (cf instanceof ActiveMQRAConnectionFactory) {
final ActiveMQRAConnectionFactory raCf = (ActiveMQRAConnectionFactory) cf;
final ServerLocator locator = raCf.getDefaultFactory().getServerLocator();
final ClientProtocolManagerFactory protocolManagerFactory = locator.getProtocolManagerFactory();
sessionFactory = locator.createSessionFactory();
ClusterTopologyListener listener = new ClusterTopologyListener() {
@Override
public void nodeUP(TopologyMember member, boolean last) {
try (ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(false, member.getLive())) {
factory.getServerLocator().setProtocolManagerFactory(protocolManagerFactory);
MessagingLogger.ROOT_LOGGER.infof("Creating queue %s on node UP %s - %s", queueName, member.getNodeId(), member.getLive().toString());
config.createQueue(factory, managementQueue, queueName);
} catch (JMSException | StartException ex) {
MessagingLogger.ROOT_LOGGER.errorf(ex, "Creating queue %s on node UP %s failed", queueName, member.getLive().toString());
throw new RuntimeException(ex);
}
if (member.getBackup() != null) {
try (ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(false, member.getBackup())) {
factory.getServerLocator().setProtocolManagerFactory(protocolManagerFactory);
MessagingLogger.ROOT_LOGGER.infof("Creating queue %s on backup node UP %s - %s", queueName, member.getNodeId(), member.getBackup().toString());
config.createQueue(factory, managementQueue, queueName);
} catch (JMSException | StartException ex) {
throw new RuntimeException(ex);
}
}
}
@Override
public void nodeDown(long eventUID, String nodeID) {}
};
Collection<TopologyMemberImpl> members = locator.getTopology().getMembers();
if (members == null || members.isEmpty() || members.size() == 1) {
config.createQueue(cf, managementQueue, queueName);
}
locator.addClusterTopologyListener(listener);
} else {
config.createQueue(cf, managementQueue, queueName);
}
} catch (Exception ex) {
MessagingLogger.ROOT_LOGGER.errorf(ex, "Error starting the external queue service %s", ex.getMessage());
throw new StartException(ex);
} finally {
try {
storeBaseContext.close();
} catch (NamingException ex) {
MessagingLogger.ROOT_LOGGER.tracef(ex, "Error closing the naming context %s", ex.getMessage());
}
}
}
queue = ActiveMQDestination.createQueue(queueName);
}
@Override
public synchronized void stop(final StopContext context) {
if(sessionFactory != null) {
sessionFactory.close();
}
}
@Override
public Queue getValue() throws IllegalStateException, IllegalArgumentException {
return queue;
}
public static Service<Queue> installService(final String name, final ServiceTarget serviceTarget, final ServiceName serviceName, final boolean enabledAMQ1Prefix) {
final ExternalJMSQueueService service = new ExternalJMSQueueService(name, enabledAMQ1Prefix);
final ServiceBuilder<Queue> serviceBuilder = serviceTarget.addService(serviceName, service);
serviceBuilder.install();
return service;
}
public static Service<Queue> installRuntimeQueueService(final DestinationConfiguration config, final ServiceTarget serviceTarget, final ServiceName pcf, final boolean enabledAMQ1Prefix) {
final ExternalJMSQueueService service = new ExternalJMSQueueService(config, enabledAMQ1Prefix);
final ServiceBuilder<Queue> serviceBuilder = serviceTarget.addService(config.getDestinationServiceName(), service);
serviceBuilder.addDependency(NamingService.SERVICE_NAME, NamingStore.class, service.namingStoreInjector);
serviceBuilder.addDependency(pcf, ExternalPooledConnectionFactoryService.class, service.pcfInjector);
serviceBuilder.requires(ConnectorServices.RESOURCE_ADAPTER_SERVICE_PREFIX.append(config.getResourceAdapter()));
serviceBuilder.install();
return service;
}
}
| 8,746
| 52.335366
| 191
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/ConnectionFactoryRemove.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq.jms;
import static org.wildfly.extension.messaging.activemq.MessagingServices.isSubsystemResource;
import org.jboss.as.controller.AbstractRemoveStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceName;
import org.wildfly.extension.messaging.activemq.MessagingServices;
/**
* Update handler removing a connection factory from the Jakarta Messaging subsystem. The
* runtime action will remove the corresponding {@link ConnectionFactoryService}.
*
* @author Emanuel Muckenhuber
* @author <a href="mailto:andy.taylor@jboss.com">Andy Taylor</a>
*/
public class ConnectionFactoryRemove extends AbstractRemoveStepHandler {
public static final ConnectionFactoryRemove INSTANCE = new ConnectionFactoryRemove();
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
ServiceName serviceName;
if(isSubsystemResource(context)) {
serviceName = MessagingServices.getActiveMQServiceName();
} else {
serviceName = MessagingServices.getActiveMQServiceName(context.getCurrentAddress());
}
context.removeService(JMSServices.getConnectionFactoryBaseServiceName(serviceName).append(context.getCurrentAddressValue()));
}
@Override
protected void recoverServices(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
ConnectionFactoryAdd.INSTANCE.performRuntime(context, operation, model);
}
}
| 2,718
| 43.57377
| 133
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/AbstractJMSRuntimeHandler.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.wildfly.extension.messaging.activemq.jms;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_DEFAULTS;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.SERVER;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
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.dmr.ModelNode;
import org.wildfly.extension.messaging.activemq.logging.MessagingLogger;
/**
* Base type for runtime operations on XML deployed message resources
*
* @author Stuart Douglas
*/
public abstract class AbstractJMSRuntimeHandler<T> extends AbstractRuntimeOnlyHandler {
private final Map<ResourceConfig, T> resources = Collections.synchronizedMap(new HashMap<ResourceConfig, T>());
@Override
protected void executeRuntimeStep(OperationContext context, ModelNode operation) throws OperationFailedException {
String opName = operation.require(ModelDescriptionConstants.OP).asString();
PathAddress address = PathAddress.pathAddress(operation.require(ModelDescriptionConstants.OP_ADDR));
final T dataSource = getResourceConfig(address);
boolean includeDefault = operation.hasDefined(INCLUDE_DEFAULTS) ? operation.get(INCLUDE_DEFAULTS).asBoolean() : false;
if (ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION.equals(opName)) {
final String attributeName = operation.require(ModelDescriptionConstants.NAME).asString();
executeReadAttribute(attributeName, context, dataSource, address, includeDefault);
} else {
throw unknownOperation(opName);
}
}
public void registerResource(final String server, final String name, final T resource) {
resources.put(new ResourceConfig(server, name), resource);
}
public void unregisterResource(final String server, final String name) {
resources.remove(new ResourceConfig(server, name));
}
protected abstract void executeReadAttribute(final String attributeName, final OperationContext context, final T destination, final PathAddress address, final boolean includeDefault);
private static IllegalStateException unknownOperation(String opName) {
throw MessagingLogger.ROOT_LOGGER.operationNotValid(opName);
}
private T getResourceConfig(final PathAddress operationAddress) throws OperationFailedException {
final String name = operationAddress.getLastElement().getValue();
PathElement serverElt = operationAddress.getParent().getLastElement();
final String server;
if(serverElt != null && SERVER.equals(serverElt.getKey())) {
server = serverElt.getValue();
} else {
server = "";
}
T config = resources.get(new ResourceConfig(server, name));
if (config == null) {
throw new OperationFailedException(MessagingLogger.ROOT_LOGGER.noDestinationRegisteredForAddress(operationAddress));
}
return config;
}
private static final class ResourceConfig {
private final String server;
private final String name;
private ResourceConfig(final String server, final String name) {
this.name = name;
if (server == null) {
this.server = "";
} else {
this.server = server;
}
}
@Override
public int hashCode() {
int result = Objects.hashCode(this.server);
result = 31 * result + Objects.hashCode(this.name);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ResourceConfig other = (ResourceConfig) obj;
if (!Objects.equals(this.server, other.server)) {
return false;
}
if (!Objects.equals(this.name, other.name)) {
return false;
}
return true;
}
}
}
| 5,544
| 37.506944
| 187
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/JMSQueueConfigurationRuntimeHandler.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.wildfly.extension.messaging.activemq.jms;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.PathAddress;
import org.jboss.dmr.ModelNode;
/**
* Read handler for XML deployed Jakarta Messaging queues
*
* @author Stuart Douglas
*/
public class JMSQueueConfigurationRuntimeHandler extends AbstractJMSRuntimeHandler<ModelNode> {
public static final JMSQueueConfigurationRuntimeHandler INSTANCE = new JMSQueueConfigurationRuntimeHandler();
private JMSQueueConfigurationRuntimeHandler() {
}
@Override
protected void executeReadAttribute(final String attributeName, final OperationContext context, final ModelNode destination, final PathAddress address, final boolean includeDefault) {
if (destination.hasDefined(attributeName)) {
context.getResult().set(destination.get(attributeName));
} else if(includeDefault) {
for (AttributeDefinition attr : JMSQueueDefinition.DEPLOYMENT_ATTRIBUTES) {
if(attr.getName().equals(attributeName)) {
ModelNode resultNode = context.getResult();
ModelNode defaultValue = attr.getDefaultValue();
if (defaultValue != null) {
resultNode.set(defaultValue);
}
}
}
}
}
}
| 2,440
| 38.370968
| 187
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/ExternalJMSTopicService.java
|
/*
* Copyright 2018 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.wildfly.extension.messaging.activemq.jms;
import java.util.Collection;
import jakarta.jms.ConnectionFactory;
import jakarta.jms.JMSException;
import jakarta.jms.Queue;
import jakarta.jms.Topic;
import javax.naming.NamingException;
import org.apache.activemq.artemis.api.core.client.ClientSessionFactory;
import org.apache.activemq.artemis.api.core.client.ClusterTopologyListener;
import org.apache.activemq.artemis.api.core.client.ServerLocator;
import org.apache.activemq.artemis.api.core.client.TopologyMember;
import org.apache.activemq.artemis.core.client.impl.TopologyMemberImpl;
import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
import org.apache.activemq.artemis.jms.client.ActiveMQDestination;
import org.apache.activemq.artemis.ra.ActiveMQRAConnectionFactory;
import org.apache.activemq.artemis.spi.core.remoting.ClientProtocolManagerFactory;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.as.naming.NamingContext;
import org.jboss.as.naming.NamingStore;
import org.jboss.as.naming.service.NamingService;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.wildfly.extension.messaging.activemq.logging.MessagingLogger;
/**
* Service responsible for creating and destroying a client {@code jakarta.jms.Topic}.
*
* @author Emmanuel Hugonnet (c) 2018 Red Hat, inc.
*/
public class ExternalJMSTopicService implements Service<Topic> {
static final String JMS_TOPIC_PREFIX = "jms.topic.";
private final InjectedValue<NamingStore> namingStoreInjector = new InjectedValue<NamingStore>();
private final InjectedValue<ExternalPooledConnectionFactoryService> pcfInjector = new InjectedValue<ExternalPooledConnectionFactoryService>();
private Topic topic;
private final String topicName;
private final DestinationConfiguration config;
private ClientSessionFactory sessionFactory;
private ExternalJMSTopicService(final String name, final boolean enabledAMQ1Prefix) {
this.topicName = enabledAMQ1Prefix ? JMS_TOPIC_PREFIX + name : name;
this.config = null;
}
private ExternalJMSTopicService(final DestinationConfiguration config, final boolean enabledAMQ1Prefix) {
this.topicName = enabledAMQ1Prefix ? JMS_TOPIC_PREFIX + config.getName() : config.getName();
this.config = config;
}
@Override
public synchronized void start(final StartContext context) throws StartException {
NamingStore namingStore = namingStoreInjector.getOptionalValue();
if (namingStore != null) {
final Queue managementQueue = config.getManagementQueue();
final NamingContext storeBaseContext = new NamingContext(namingStore, null);
try {
ConnectionFactory cf = (ConnectionFactory) storeBaseContext.lookup(pcfInjector.getValue().getBindInfo().getAbsoluteJndiName());
if (cf instanceof ActiveMQRAConnectionFactory) {
final ActiveMQRAConnectionFactory raCf = (ActiveMQRAConnectionFactory) cf;
final ServerLocator locator = raCf.getDefaultFactory().getServerLocator();
final ClientProtocolManagerFactory protocolManagerFactory = locator.getProtocolManagerFactory();
sessionFactory = locator.createSessionFactory();
ClusterTopologyListener listener = new ClusterTopologyListener() {
@Override
public void nodeUP(TopologyMember member, boolean last) {
try (ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(false, member.getLive())) {
factory.getServerLocator().setProtocolManagerFactory(protocolManagerFactory);
MessagingLogger.ROOT_LOGGER.infof("Creating topic %s on node UP %s - %s", topicName, member.getNodeId(), member.getLive().toString());
config.createTopic(factory, managementQueue, topicName);
} catch (JMSException | StartException ex) {
MessagingLogger.ROOT_LOGGER.errorf(ex, "Creating topic %s on node UP %s failed", topicName, member.getLive().toString());
throw new RuntimeException(ex);
}
if (member.getBackup() != null) {
try (ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(false, member.getBackup())) {
factory.getServerLocator().setProtocolManagerFactory(protocolManagerFactory);
MessagingLogger.ROOT_LOGGER.infof("Creating topic %s on backup node UP %s - %s", topicName, member.getNodeId(), member.getBackup().toString());
config.createTopic(factory, managementQueue, topicName);
} catch (JMSException | StartException ex) {
throw new RuntimeException(ex);
}
}
}
@Override
public void nodeDown(long eventUID, String nodeID) {
}
};
locator.addClusterTopologyListener(listener);
Collection<TopologyMemberImpl> members = locator.getTopology().getMembers();
if (members == null || members.isEmpty()) {
config.createTopic(cf, managementQueue, topicName);
}
} else {
config.createTopic(cf, managementQueue, topicName);
}
} catch (Exception ex) {
MessagingLogger.ROOT_LOGGER.errorf(ex, "Error starting the external queue service %s", ex.getMessage());
throw new StartException(ex);
} finally {
try {
storeBaseContext.close();
} catch (NamingException ex) {
MessagingLogger.ROOT_LOGGER.tracef(ex, "Error closing the naming context %s", ex.getMessage());
}
}
}
topic = ActiveMQDestination.createTopic(topicName);
}
@Override
public synchronized void stop(final StopContext context) {
if (sessionFactory != null) {
sessionFactory.close();
}
}
@Override
public Topic getValue() throws IllegalStateException {
return topic;
}
public static ExternalJMSTopicService installService(final String name, final ServiceName serviceName, final ServiceTarget serviceTarget, final boolean enabledAMQ1Prefix) {
final ExternalJMSTopicService service = new ExternalJMSTopicService(name, enabledAMQ1Prefix);
final ServiceBuilder<Topic> serviceBuilder = serviceTarget.addService(serviceName, service);
serviceBuilder.install();
return service;
}
public static ExternalJMSTopicService installRuntimeTopicService(final DestinationConfiguration config, final ServiceTarget serviceTarget, final ServiceName pcf, final boolean enabledAMQ1Prefix) {
final ExternalJMSTopicService service = new ExternalJMSTopicService(config, enabledAMQ1Prefix);
final ServiceBuilder<Topic> serviceBuilder = serviceTarget.addService(config.getDestinationServiceName(), service);
serviceBuilder.addDependency(NamingService.SERVICE_NAME, NamingStore.class, service.namingStoreInjector);
serviceBuilder.addDependency(pcf, ExternalPooledConnectionFactoryService.class, service.pcfInjector);
serviceBuilder.requires(ConnectorServices.RESOURCE_ADAPTER_SERVICE_PREFIX.append(config.getResourceAdapter()));
serviceBuilder.install();
return service;
}
}
| 8,753
| 52.054545
| 200
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/JMSQueueReadAttributeHandler.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.wildfly.extension.messaging.activemq.jms;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.wildfly.extension.messaging.activemq.ActiveMQActivationService.ignoreOperationIfServerNotActive;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.NAME;
import static org.wildfly.extension.messaging.activemq.jms.JMSQueueService.JMS_QUEUE_PREFIX;
import org.apache.activemq.artemis.api.core.management.QueueControl;
import org.apache.activemq.artemis.api.core.management.ResourceNames;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
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.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.logging.ControllerLogger;
import org.jboss.as.controller.operations.validation.ParametersValidator;
import org.jboss.as.controller.operations.validation.StringLengthValidator;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.wildfly.extension.messaging.activemq.CommonAttributes;
import org.wildfly.extension.messaging.activemq.MessagingServices;
import org.wildfly.extension.messaging.activemq.logging.MessagingLogger;
/**
* Implements the {@code read-attribute} operation for runtime attributes exposed by a ActiveMQ
* {@link QueueControl}.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class JMSQueueReadAttributeHandler extends AbstractRuntimeOnlyHandler {
public static final JMSQueueReadAttributeHandler INSTANCE = new JMSQueueReadAttributeHandler();
private ParametersValidator validator = new ParametersValidator();
private JMSQueueReadAttributeHandler() {
validator.registerValidator(NAME, new StringLengthValidator(1));
}
@Override
public void executeRuntimeStep(OperationContext context, ModelNode operation) throws OperationFailedException {
if (ignoreOperationIfServerNotActive(context, operation)) {
return;
}
validator.validate(operation);
final String attributeName = operation.require(ModelDescriptionConstants.NAME).asString();
QueueControl control = getControl(context, operation);
if (control == null) {
PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR));
throw ControllerLogger.ROOT_LOGGER.managementResourceNotFound(address);
}
if (CommonAttributes.MESSAGE_COUNT.getName().equals(attributeName)) {
try {
context.getResult().set(control.getMessageCount());
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
} else if (CommonAttributes.SCHEDULED_COUNT.getName().equals(attributeName)) {
context.getResult().set(control.getScheduledCount());
} else if (CommonAttributes.CONSUMER_COUNT.getName().equals(attributeName)) {
context.getResult().set(control.getConsumerCount());
} else if (CommonAttributes.DELIVERING_COUNT.getName().equals(attributeName)) {
context.getResult().set(control.getDeliveringCount());
} else if (CommonAttributes.MESSAGES_ADDED.getName().equals(attributeName)) {
context.getResult().set(control.getMessagesAdded());
} else if (JMSQueueDefinition.QUEUE_ADDRESS.getName().equals(attributeName)) {
context.getResult().set(control.getAddress());
} else if (JMSQueueDefinition.EXPIRY_ADDRESS.getName().equals(attributeName)) {
// create the result node in all cases
ModelNode result = context.getResult();
String expiryAddress = control.getExpiryAddress();
if (expiryAddress != null) {
result.set(expiryAddress);
}
} else if (JMSQueueDefinition.DEAD_LETTER_ADDRESS.getName().equals(attributeName)) {
// create the result node in all cases
ModelNode result = context.getResult();
String dla = control.getDeadLetterAddress();
if (dla != null) {
result.set(dla);
}
} else if (CommonAttributes.PAUSED.getName().equals(attributeName)) {
try {
context.getResult().set(control.isPaused());
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
} else if (CommonAttributes.TEMPORARY.getName().equals(attributeName)) {
context.getResult().set(control.isTemporary());
} else {
throw MessagingLogger.ROOT_LOGGER.unsupportedAttribute(attributeName);
}
}
private QueueControl getControl(OperationContext context, ModelNode operation) {
String queueName = PathAddress.pathAddress(operation.require(ModelDescriptionConstants.OP_ADDR)).getLastElement().getValue();
final ServiceName serviceName = MessagingServices.getActiveMQServiceName(PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)));
ServiceController<?> service = context.getServiceRegistry(false).getService(serviceName);
ActiveMQServer server = ActiveMQServer.class.cast(service.getValue());
QueueControl control = QueueControl.class.cast(server.getManagementService().getResource(ResourceNames.QUEUE + JMS_QUEUE_PREFIX + queueName));
return control;
}
}
| 6,761
| 48
| 156
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/JMSTopicControlHandler.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.wildfly.extension.messaging.activemq.jms;
import static org.jboss.as.controller.SimpleAttributeDefinitionBuilder.create;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.dmr.ModelType.BOOLEAN;
import static org.jboss.dmr.ModelType.INT;
import static org.jboss.dmr.ModelType.LIST;
import static org.jboss.dmr.ModelType.LONG;
import static org.jboss.dmr.ModelType.STRING;
import static org.wildfly.extension.messaging.activemq.ActiveMQActivationService.rollbackOperationIfServerNotActive;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.FILTER;
import static org.wildfly.extension.messaging.activemq.OperationDefinitionHelper.createNonEmptyStringAttribute;
import static org.wildfly.extension.messaging.activemq.OperationDefinitionHelper.resolveFilter;
import static org.wildfly.extension.messaging.activemq.OperationDefinitionHelper.runtimeOnlyOperation;
import static org.wildfly.extension.messaging.activemq.OperationDefinitionHelper.runtimeReadOnlyOperation;
import static org.wildfly.extension.messaging.activemq.jms.JMSTopicService.JMS_TOPIC_PREFIX;
import static org.wildfly.extension.messaging.activemq.jms.JsonUtil.toJSON;
import java.util.List;
import java.util.Map;
import jakarta.json.Json;
import jakarta.json.JsonObjectBuilder;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.Pair;
import org.apache.activemq.artemis.api.core.RoutingType;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.api.core.management.ActiveMQServerControl;
import org.apache.activemq.artemis.api.core.management.AddressControl;
import org.apache.activemq.artemis.api.core.management.QueueControl;
import org.apache.activemq.artemis.api.core.management.ResourceNames;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.management.ManagementService;
import org.apache.activemq.artemis.jms.client.ActiveMQDestination;
import org.apache.activemq.artemis.jms.client.ActiveMQMessage;
import org.apache.activemq.artemis.utils.SelectorTranslator;
import org.jboss.as.controller.AbstractRuntimeOnlyHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.ObjectListAttributeDefinition;
import org.jboss.as.controller.ObjectTypeAttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.descriptions.ResourceDescriptionResolver;
import org.jboss.as.controller.logging.ControllerLogger;
import org.jboss.as.controller.operations.validation.StringLengthValidator;
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.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.wildfly.extension.messaging.activemq.CommonAttributes;
import org.wildfly.extension.messaging.activemq.MessagingServices;
import org.wildfly.extension.messaging.activemq.jms.JMSTopicReadAttributeHandler.DurabilityType;
import org.wildfly.extension.messaging.activemq.logging.MessagingLogger;
/**
* Handler for runtime operations that invoke on a ActiveMQ Topic.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class JMSTopicControlHandler extends AbstractRuntimeOnlyHandler {
public static final JMSTopicControlHandler INSTANCE = new JMSTopicControlHandler();
private static final String REMOVE_MESSAGES = "remove-messages";
private static final String DROP_ALL_SUBSCRIPTIONS = "drop-all-subscriptions";
private static final String DROP_DURABLE_SUBSCRIPTION = "drop-durable-subscription";
private static final String COUNT_MESSAGES_FOR_SUBSCRIPTION = "count-messages-for-subscription";
private static final String LIST_MESSAGES_FOR_SUBSCRIPTION_AS_JSON = "list-messages-for-subscription-as-json";
private static final String LIST_MESSAGES_FOR_SUBSCRIPTION = "list-messages-for-subscription";
private static final String LIST_NON_DURABLE_SUBSCRIPTIONS_AS_JSON = "list-non-durable-subscriptions-as-json";
private static final String LIST_NON_DURABLE_SUBSCRIPTIONS = "list-non-durable-subscriptions";
private static final String LIST_DURABLE_SUBSCRIPTIONS_AS_JSON = "list-durable-subscriptions-as-json";
private static final String LIST_DURABLE_SUBSCRIPTIONS = "list-durable-subscriptions";
private static final String LIST_ALL_SUBSCRIPTIONS_AS_JSON = "list-all-subscriptions-as-json";
private static final String LIST_ALL_SUBSCRIPTIONS = "list-all-subscriptions";
public static final String PAUSE = "pause";
public static final String RESUME = "resume";
private static final AttributeDefinition CLIENT_ID = create(CommonAttributes.CLIENT_ID)
.setRequired(true)
.setValidator(new StringLengthValidator(1))
.build();
private static final AttributeDefinition SUBSCRIPTION_NAME = createNonEmptyStringAttribute("subscription-name");
private static final AttributeDefinition QUEUE_NAME = createNonEmptyStringAttribute(CommonAttributes.QUEUE_NAME);
private static final AttributeDefinition PERSIST = create("persist", ModelType.BOOLEAN, true)
.setDefaultValue(ModelNode.FALSE)
.build();
private static final AttributeDefinition[] SUBSCRIPTION_REPLY_PARAMETER_DEFINITIONS = new AttributeDefinition[]{
createNonEmptyStringAttribute("queueName"),
createNonEmptyStringAttribute("clientID"),
createNonEmptyStringAttribute("selector"),
createNonEmptyStringAttribute("name"),
create("durable", BOOLEAN).build(),
create("messageCount", LONG).build(),
create("deliveringCount", INT).build(),
ObjectListAttributeDefinition.Builder.of("consumers",
ObjectTypeAttributeDefinition.Builder.of("consumers",
createNonEmptyStringAttribute("consumerID"),
createNonEmptyStringAttribute("connectionID"),
createNonEmptyStringAttribute("sessionID"),
create("browseOnly", BOOLEAN).build(),
create("creationTime", BOOLEAN).build()
).build()
).build()
};
private JMSTopicControlHandler() {
}
@Override
protected void executeRuntimeStep(OperationContext context, ModelNode operation) throws OperationFailedException {
if (rollbackOperationIfServerNotActive(context, operation)) {
return;
}
final ServiceName serviceName = MessagingServices.getActiveMQServiceName(PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)));
final String operationName = context.getCurrentOperationName();
String topicName = context.getCurrentAddressValue();
boolean readOnly = context.getResourceRegistration().getOperationFlags(PathAddress.EMPTY_ADDRESS, operationName).contains(OperationEntry.Flag.READ_ONLY);
ServiceController<?> service = context.getServiceRegistry(!readOnly).getService(serviceName);
ActiveMQServer server = ActiveMQServer.class.cast(service.getValue());
ManagementService managementService = server.getManagementService();
if (topicName.startsWith(JMS_TOPIC_PREFIX)) {
topicName = topicName.substring(JMS_TOPIC_PREFIX.length());
}
AddressControl control = AddressControl.class.cast(managementService.getResource(ResourceNames.ADDRESS + JMS_TOPIC_PREFIX + topicName));
if (control == null) {
PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR));
throw ControllerLogger.ROOT_LOGGER.managementResourceNotFound(address);
}
try {
if (LIST_ALL_SUBSCRIPTIONS.equals(operationName)) {
String json = listAllSubscriptionsAsJSON(control, managementService);
ModelNode jsonAsNode = ModelNode.fromJSONString(json);
context.getResult().set(jsonAsNode);
} else if (LIST_ALL_SUBSCRIPTIONS_AS_JSON.equals(operationName)) {
context.getResult().set(listAllSubscriptionsAsJSON(control, managementService));
} else if (LIST_DURABLE_SUBSCRIPTIONS.equals(operationName)) {
String json = listDurableSubscriptionsAsJSON(control, managementService);
ModelNode jsonAsNode = ModelNode.fromJSONString(json);
context.getResult().set(jsonAsNode);
} else if (LIST_DURABLE_SUBSCRIPTIONS_AS_JSON.equals(operationName)) {
context.getResult().set(listDurableSubscriptionsAsJSON(control, managementService));
} else if (LIST_NON_DURABLE_SUBSCRIPTIONS.equals(operationName)) {
String json = listNonDurableSubscriptionsAsJSON(control, managementService);
ModelNode jsonAsNode = ModelNode.fromJSONString(json);
context.getResult().set(jsonAsNode);
} else if (LIST_NON_DURABLE_SUBSCRIPTIONS_AS_JSON.equals(operationName)) {
context.getResult().set(listNonDurableSubscriptionsAsJSON(control, managementService));
} else if (LIST_MESSAGES_FOR_SUBSCRIPTION.equals(operationName)) {
final String queueName = QUEUE_NAME.resolveModelAttribute(context, operation).asString();
String json = listMessagesForSubscriptionAsJSON(queueName, managementService);
context.getResult().set(ModelNode.fromJSONString(json));
} else if (LIST_MESSAGES_FOR_SUBSCRIPTION_AS_JSON.equals(operationName)) {
final String queueName = QUEUE_NAME.resolveModelAttribute(context, operation).asString();
context.getResult().set(listMessagesForSubscriptionAsJSON(queueName, managementService));
} else if (COUNT_MESSAGES_FOR_SUBSCRIPTION.equals(operationName)) {
String clientId = CLIENT_ID.resolveModelAttribute(context, operation).asString();
String subscriptionName = SUBSCRIPTION_NAME.resolveModelAttribute(context, operation).asString();
String filter = resolveFilter(context, operation);
context.getResult().set(countMessagesForSubscription(clientId, subscriptionName, filter, managementService));
} else if (DROP_DURABLE_SUBSCRIPTION.equals(operationName)) {
String clientId = CLIENT_ID.resolveModelAttribute(context, operation).asString();
String subscriptionName = SUBSCRIPTION_NAME.resolveModelAttribute(context, operation).asString();
dropDurableSubscription(clientId, subscriptionName, managementService);
context.getResult();
} else if (DROP_ALL_SUBSCRIPTIONS.equals(operationName)) {
dropAllSubscriptions(control, managementService);
context.getResult();
} else if (REMOVE_MESSAGES.equals(operationName)) {
String filter = resolveFilter(context, operation);
context.getResult().set(removeMessages(filter, control, managementService));
} else if (PAUSE.equals(operationName)) {
pause(control, PERSIST.resolveModelAttribute(context, operation).asBoolean());
context.getResult();
} else if (RESUME.equals(operationName)) {
resume(control);
context.getResult();
} else {
// Bug
throw MessagingLogger.ROOT_LOGGER.unsupportedOperation(operationName);
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
context.getFailureDescription().set(e.toString());
}
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
public void registerOperations(ManagementResourceRegistration registry, ResourceDescriptionResolver resolver) {
registry.registerOperationHandler(runtimeReadOnlyOperation(LIST_ALL_SUBSCRIPTIONS, resolver)
.setReplyType(LIST)
.setReplyParameters(SUBSCRIPTION_REPLY_PARAMETER_DEFINITIONS)
.build(),
this);
registry.registerOperationHandler(runtimeReadOnlyOperation(LIST_ALL_SUBSCRIPTIONS_AS_JSON, resolver)
.setReplyType(STRING)
.build(),
this);
registry.registerOperationHandler(runtimeReadOnlyOperation(LIST_DURABLE_SUBSCRIPTIONS, resolver)
.setReplyType(LIST)
.setReplyParameters(SUBSCRIPTION_REPLY_PARAMETER_DEFINITIONS)
.build(),
this);
registry.registerOperationHandler(runtimeReadOnlyOperation(LIST_DURABLE_SUBSCRIPTIONS_AS_JSON, resolver)
.setReplyType(STRING)
.build(),
this);
registry.registerOperationHandler(runtimeReadOnlyOperation(LIST_NON_DURABLE_SUBSCRIPTIONS, resolver)
.setReplyType(LIST)
.setReplyParameters(SUBSCRIPTION_REPLY_PARAMETER_DEFINITIONS)
.build(),
this);
registry.registerOperationHandler(runtimeReadOnlyOperation(LIST_NON_DURABLE_SUBSCRIPTIONS_AS_JSON, resolver)
.setReplyType(STRING)
.build(),
this);
registry.registerOperationHandler(runtimeReadOnlyOperation(LIST_MESSAGES_FOR_SUBSCRIPTION, resolver)
.setParameters(QUEUE_NAME)
.setReplyType(LIST)
.setReplyParameters(JMSManagementHelper.JMS_MESSAGE_PARAMETERS)
.build(),
this);
registry.registerOperationHandler(runtimeReadOnlyOperation(LIST_MESSAGES_FOR_SUBSCRIPTION_AS_JSON, resolver)
.setParameters(QUEUE_NAME)
.setReplyType(STRING)
.build(),
this);
registry.registerOperationHandler(runtimeReadOnlyOperation(COUNT_MESSAGES_FOR_SUBSCRIPTION, resolver)
.setParameters(CLIENT_ID, SUBSCRIPTION_NAME, FILTER)
.setReplyType(INT)
.build(),
this);
registry.registerOperationHandler(runtimeOnlyOperation(DROP_DURABLE_SUBSCRIPTION, resolver)
.setParameters(CLIENT_ID, SUBSCRIPTION_NAME)
.build(),
this);
registry.registerOperationHandler(runtimeOnlyOperation(DROP_ALL_SUBSCRIPTIONS, resolver)
.build(),
this);
registry.registerOperationHandler(runtimeOnlyOperation(REMOVE_MESSAGES, resolver)
.setParameters(FILTER)
.setReplyType(INT)
.build(),
this);
registry.registerOperationHandler(runtimeOnlyOperation(PAUSE, resolver)
.setParameters(PERSIST)
.build(),
this);
registry.registerOperationHandler(runtimeOnlyOperation(RESUME, resolver)
.build(),
this);
}
private int removeMessages(final String filterStr, AddressControl addressControl, ManagementService managementService) throws Exception {
String filter = createFilterFromJMSSelector(filterStr);
int count = 0;
String[] queues = addressControl.getQueueNames();
for (String queue : queues) {
QueueControl coreQueueControl = (QueueControl) managementService.getResource(ResourceNames.QUEUE + queue);
if (coreQueueControl != null) {
count += coreQueueControl.removeMessages(filter);
}
}
return count;
}
private long countMessagesForSubscription(String clientID, String subscriptionName, String filterStr, ManagementService managementService) throws Exception {
SimpleString queueName = ActiveMQDestination.createQueueNameForSubscription(true, clientID, subscriptionName);
QueueControl coreQueueControl = (QueueControl) managementService.getResource(ResourceNames.QUEUE + queueName);
if (coreQueueControl == null) {
throw new IllegalArgumentException("No subscriptions with name " + queueName + " for clientID " + clientID);
}
String filter = createFilterFromJMSSelector(filterStr);
return coreQueueControl.countMessages(filter);
}
private void dropAllSubscriptions(AddressControl addressControl, ManagementService managementService) throws Exception {
ActiveMQServerControl serverControl = (ActiveMQServerControl) managementService.getResource(ResourceNames.BROKER);
String[] queues = addressControl.getQueueNames();
for (String queue : queues) {
// Drop all subscription shouldn't delete the dummy queue used to identify if the topic exists on the core queues.
// we will just ignore this queue
if (!queue.equals(addressControl.getAddress())) {
serverControl.destroyQueue(queue);
}
}
}
private void dropDurableSubscription(final String clientID, final String subscriptionName, ManagementService managementService) throws Exception {
SimpleString queueName = ActiveMQDestination.createQueueNameForSubscription(true, clientID, subscriptionName);
QueueControl coreQueueControl = (QueueControl) managementService.getResource(ResourceNames.QUEUE + queueName);
if (coreQueueControl == null) {
throw new IllegalArgumentException("No subscriptions with name " + queueName + " for clientID " + clientID);
}
ActiveMQServerControl serverControl = (ActiveMQServerControl) managementService.getResource(ResourceNames.BROKER);
serverControl.destroyQueue(queueName.toString(), true);
}
private String listAllSubscriptionsAsJSON(AddressControl addressControl, ManagementService managementService) {
return listSubscribersInfosAsJSON(DurabilityType.ALL, addressControl, managementService);
}
private String listDurableSubscriptionsAsJSON(AddressControl addressControl, ManagementService managementService) throws Exception {
return listSubscribersInfosAsJSON(DurabilityType.DURABLE, addressControl, managementService);
}
private String listNonDurableSubscriptionsAsJSON(AddressControl addressControl, ManagementService managementService) throws Exception {
return listSubscribersInfosAsJSON(DurabilityType.NON_DURABLE, addressControl, managementService);
}
public String listMessagesForSubscriptionAsJSON(final String queueName, ManagementService managementService) throws Exception {
return toJSON(listMessagesForSubscription(queueName, managementService));
}
private Map<String, Object>[] listMessagesForSubscription(final String queueName, ManagementService managementService) throws Exception {
QueueControl coreQueueControl = (QueueControl) managementService.getResource(ResourceNames.QUEUE + queueName);
if (coreQueueControl == null) {
throw new IllegalArgumentException("No subscriptions with name " + queueName);
}
Map<String, Object>[] coreMessages = coreQueueControl.listMessages(null);
Map<String, Object>[] jmsMessages = new Map[coreMessages.length];
int i = 0;
for (Map<String, Object> coreMessage : coreMessages) {
jmsMessages[i++] = ActiveMQMessage.coreMaptoJMSMap(coreMessage);
}
return jmsMessages;
}
private String listSubscribersInfosAsJSON(final DurabilityType durability, AddressControl addressControl, ManagementService managementService) {
jakarta.json.JsonArrayBuilder array = Json.createArrayBuilder();
try {
List<QueueControl> queues = JMSTopicReadAttributeHandler.getQueues(durability, addressControl, managementService);
for (QueueControl queue : queues) {
String clientID = null;
String subName = null;
if (queue.isDurable() && RoutingType.MULTICAST.toString().equals(queue.getRoutingType())) {
Pair<String, String> pair = ActiveMQDestination.decomposeQueueNameForDurableSubscription(queue.getName());
clientID = pair.getA();
subName = pair.getB();
} else if (RoutingType.MULTICAST.toString().equals(queue.getRoutingType())) {
// in the case of heirarchical topics the queue name will not follow the <part>.<part> pattern of normal
// durable subscribers so skip decomposing the name for the client ID and subscription name and just
// hard-code it
clientID = "ActiveMQ";
subName = "ActiveMQ";
}
String filter = queue.getFilter() != null ? queue.getFilter() : null;
JsonObjectBuilder info = Json.createObjectBuilder()
.add("queueName", queue.getName())
.add("durable", queue.isDurable())
.add("messageCount", queue.getMessageCount())
.add("deliveringCount", queue.getDeliveringCount())
.add("consumers", queue.listConsumersAsJSON());
if (clientID == null) {
info.addNull("clientID");
} else {
info.add("clientID", clientID);
}
if (filter == null) {
info.addNull("selector");
} else {
info.add("selector", filter);
}
if (subName == null) {
info.addNull("name");
} else {
info.add("name", subName);
}
array.add(info.build());
}
} catch (Exception e) {
rethrow(e);
}
return array.build().toString();
}
private void pause(AddressControl control, boolean persist) {
try {
control.pause(persist);
} catch (Exception e) {
rethrow(e);
}
}
private void resume(AddressControl control) {
try {
control.resume();
} catch (Exception e) {
rethrow(e);
}
}
private static String createFilterFromJMSSelector(final String selectorStr) throws ActiveMQException {
return selectorStr == null || selectorStr.trim().length() == 0 ? null : SelectorTranslator.convertToActiveMQFilterString(selectorStr);
}
@SuppressWarnings("unchecked")
public static <T extends Throwable> void rethrow(Throwable t) throws T {
throw (T) t;
}
}
| 23,934
| 53.397727
| 161
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/JMSTopicReadAttributeHandler.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.wildfly.extension.messaging.activemq.jms;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.NAME;
import static org.wildfly.extension.messaging.activemq.ActiveMQActivationService.ignoreOperationIfServerNotActive;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.PAUSED;
import static org.wildfly.extension.messaging.activemq.jms.JMSTopicDefinition.DURABLE_MESSAGE_COUNT;
import static org.wildfly.extension.messaging.activemq.jms.JMSTopicDefinition.DURABLE_SUBSCRIPTION_COUNT;
import static org.wildfly.extension.messaging.activemq.jms.JMSTopicDefinition.NON_DURABLE_MESSAGE_COUNT;
import static org.wildfly.extension.messaging.activemq.jms.JMSTopicDefinition.NON_DURABLE_SUBSCRIPTION_COUNT;
import static org.wildfly.extension.messaging.activemq.jms.JMSTopicDefinition.SUBSCRIPTION_COUNT;
import static org.wildfly.extension.messaging.activemq.jms.JMSTopicDefinition.TOPIC_ADDRESS;
import static org.wildfly.extension.messaging.activemq.jms.JMSTopicService.JMS_TOPIC_PREFIX;
import org.apache.activemq.artemis.api.core.management.AddressControl;
import org.apache.activemq.artemis.api.core.management.QueueControl;
import org.apache.activemq.artemis.api.core.management.ResourceNames;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.management.ManagementService;
import org.jboss.as.controller.AbstractRuntimeOnlyHandler;
import org.jboss.as.controller.logging.ControllerLogger;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.validation.ParametersValidator;
import org.jboss.as.controller.operations.validation.StringLengthValidator;
import org.wildfly.extension.messaging.activemq.CommonAttributes;
import org.wildfly.extension.messaging.activemq.logging.MessagingLogger;
import org.wildfly.extension.messaging.activemq.MessagingServices;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Implements the {@code read-attribute} operation for runtime attributes exposed by a ActiveMQ
* Topic.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class JMSTopicReadAttributeHandler extends AbstractRuntimeOnlyHandler {
public static final JMSTopicReadAttributeHandler INSTANCE = new JMSTopicReadAttributeHandler();
private ParametersValidator validator = new ParametersValidator();
private JMSTopicReadAttributeHandler() {
validator.registerValidator(NAME, new StringLengthValidator(1));
}
@Override
public void executeRuntimeStep(OperationContext context, ModelNode operation) throws OperationFailedException {
if (ignoreOperationIfServerNotActive(context, operation)) {
return;
}
validator.validate(operation);
final String attributeName = operation.require(ModelDescriptionConstants.NAME).asString();
String topicName = PathAddress.pathAddress(operation.require(ModelDescriptionConstants.OP_ADDR)).getLastElement().getValue();
final ServiceName serviceName = MessagingServices.getActiveMQServiceName(PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)));
ServiceController<?> service = context.getServiceRegistry(false).getService(serviceName);
ActiveMQServer server = ActiveMQServer.class.cast(service.getValue());
ManagementService managementService = server.getManagementService();
AddressControl control = AddressControl.class.cast(managementService.getResource(ResourceNames.ADDRESS + JMS_TOPIC_PREFIX + topicName));
if (control == null) {
PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR));
throw ControllerLogger.ROOT_LOGGER.managementResourceNotFound(address);
}
if (CommonAttributes.MESSAGE_COUNT.getName().equals(attributeName)) {
try {
context.getResult().set(control.getMessageCount());
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
} else if (CommonAttributes.DELIVERING_COUNT.getName().equals(attributeName)) {
context.getResult().set(getDeliveringCount(control, managementService));
} else if (CommonAttributes.MESSAGES_ADDED.getName().equals(attributeName)) {
context.getResult().set(getMessagesAdded(control, managementService));
} else if (DURABLE_MESSAGE_COUNT.getName().equals(attributeName)) {
context.getResult().set(getDurableMessageCount(control, managementService));
} else if (NON_DURABLE_MESSAGE_COUNT.getName().equals(attributeName)) {
context.getResult().set(getNonDurableMessageCount(control, managementService));
} else if (SUBSCRIPTION_COUNT.getName().equals(attributeName)) {
context.getResult().set(getSubscriptionCount(control, managementService));
} else if (DURABLE_SUBSCRIPTION_COUNT.getName().equals(attributeName)) {
context.getResult().set(getDurableSubscriptionCount(control, managementService));
} else if (NON_DURABLE_SUBSCRIPTION_COUNT.getName().equals(attributeName)) {
context.getResult().set(getNonDurableSubscriptionCount(control, managementService));
} else if (TOPIC_ADDRESS.getName().equals(attributeName)) {
context.getResult().set(control.getAddress());
} else if (CommonAttributes.TEMPORARY.getName().equals(attributeName)) {
// This attribute does not make sense. Jakarta Messaging topics created by the management API are always
// managed and not temporary. Only topics created by the Clients can be temporary.
context.getResult().set(false);
} else if (PAUSED.getName().equals(attributeName)) {
context.getResult().set(control.isPaused());
} else {
throw MessagingLogger.ROOT_LOGGER.unsupportedAttribute(attributeName);
}
}
private int getDeliveringCount(AddressControl addressControl, ManagementService managementService) {
List<QueueControl> queues = getQueues(DurabilityType.ALL, addressControl, managementService);
int count = 0;
for (QueueControl queue : queues) {
count += queue.getDeliveringCount();
}
return count;
}
private long getMessagesAdded(AddressControl addressControl, ManagementService managementService) {
List<QueueControl> queues = getQueues(DurabilityType.ALL, addressControl, managementService);
long count = 0;
for (QueueControl queue : queues) {
count += queue.getMessagesAdded();
}
return count;
}
private int getDurableMessageCount(AddressControl addressControl, ManagementService managementService) {
return getMessageCount(DurabilityType.DURABLE, addressControl, managementService);
}
private int getNonDurableMessageCount(AddressControl addressControl, ManagementService managementService) {
return getMessageCount(DurabilityType.NON_DURABLE, addressControl, managementService);
}
private int getMessageCount(final DurabilityType durability, AddressControl addressControl, ManagementService managementService) {
List<QueueControl> queues = getQueues(durability, addressControl, managementService);
int count = 0;
for (QueueControl queue : queues) {
count += queue.getMessageCount();
}
return count;
}
public int getSubscriptionCount(AddressControl addressControl, ManagementService managementService) {
return getQueues(DurabilityType.ALL, addressControl, managementService).size();
}
public int getDurableSubscriptionCount(AddressControl addressControl, ManagementService managementService) {
return getQueues(DurabilityType.DURABLE, addressControl, managementService).size();
}
public int getNonDurableSubscriptionCount(AddressControl addressControl, ManagementService managementService) {
return getQueues(DurabilityType.NON_DURABLE, addressControl, managementService).size();
}
public static List<QueueControl> getQueues(final DurabilityType durability, AddressControl addressControl, ManagementService managementService) {
try {
List<QueueControl> matchingQueues = new ArrayList<>();
String[] queues = addressControl.getQueueNames();
for (String queue : queues) {
QueueControl coreQueueControl = (QueueControl) managementService.getResource(ResourceNames.QUEUE + queue);
// Ignore the "special" subscription
if (coreQueueControl != null
&& !coreQueueControl.getName().equals(addressControl.getAddress())
&& (durability == DurabilityType.ALL
|| durability == DurabilityType.DURABLE && coreQueueControl.isDurable()
|| durability == DurabilityType.NON_DURABLE && !coreQueueControl.isDurable())) {
matchingQueues.add(coreQueueControl);
}
}
return matchingQueues;
} catch (Exception e) {
return Collections.emptyList();
}
}
public enum DurabilityType {
ALL, DURABLE, NON_DURABLE
}
}
| 10,817
| 49.551402
| 156
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/cli/DeleteJMSResourceHandlerProvider.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.wildfly.extension.messaging.activemq.jms.cli;
import org.jboss.as.cli.CommandContext;
import org.jboss.as.cli.CommandHandler;
import org.jboss.as.cli.CommandHandlerProvider;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2015 Red Hat inc.
*/
public class DeleteJMSResourceHandlerProvider implements CommandHandlerProvider {
@Override
public CommandHandler createCommandHandler(CommandContext ctx) {
return new DeleteJMSResourceHandler(ctx);
}
@Override
public boolean isTabComplete() {
return false;
}
@Override
public String[] getNames() {
return new String[] { "delete-jms-resource" };
}
}
| 1,711
| 34.666667
| 81
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/cli/CreateJMSResourceHandler.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.wildfly.extension.messaging.activemq.jms.cli;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.jboss.as.cli.CommandContext;
import org.jboss.as.cli.CommandFormatException;
import org.jboss.as.cli.handlers.BatchModeCommandHandler;
import org.jboss.as.cli.operation.OperationFormatException;
import org.jboss.as.cli.operation.impl.DefaultOperationRequestBuilder;
import org.jboss.dmr.ModelNode;
/**
*
* @author Alexey Loubyansky
*/
class CreateJMSResourceHandler extends BatchModeCommandHandler {
public CreateJMSResourceHandler(CommandContext ctx) {
super(ctx, "create-jms-resource", true);
this.addRequiredPath("/subsystem=messaging-activemq");
}
@Override
public ModelNode buildRequestWithoutHeaders(CommandContext ctx) throws OperationFormatException {
try {
if(!ctx.getParsedCommandLine().hasProperties()) {
throw new OperationFormatException("Arguments are missing");
}
} catch (CommandFormatException e) {
throw new OperationFormatException(e.getLocalizedMessage());
}
//String target = null;
String restype = null;
//String description = null;
String propsStr = null;
//boolean enabled = false;
String jndiName = null;
String[] args = ctx.getArgumentsString().split("\\s+");
int i = 0;
while(i < args.length) {
String arg = args[i++];
if(arg.equals("--restype")) {
if(i < args.length) {
restype = args[i++];
}
} else if(arg.equals("--target")) {
// if(i < args.length) {
// target = args[i++];
// }
} else if(arg.equals("--description")) {
// if(i < args.length) {
// restype = args[i++];
// }
} else if(arg.equals("--property")) {
if (i < args.length) {
propsStr = args[i++];
}
} else if(arg.equals("--enabled")) {
// if (i < args.length) {
// enabled = Boolean.parseBoolean(args[i++]);
// }
} else {
jndiName = arg;
}
}
if(restype == null) {
throw new OperationFormatException("Required parameter --restype is missing.");
}
if(jndiName == null) {
throw new OperationFormatException("JNDI name is missing.");
}
String name = null;
String serverName = "default"; // TODO read server name from props
final Map<String, String> props;
if(propsStr != null) {
props = new HashMap<String, String>();
String[] propsArr = propsStr.split(":");
for(String prop : propsArr) {
int equalsIndex = prop.indexOf('=');
if(equalsIndex < 0 || equalsIndex == prop.length() - 1) {
throw new OperationFormatException("Failed to parse property '" + prop + "'");
}
String propName = prop.substring(0, equalsIndex).trim();
String propValue = prop.substring(equalsIndex + 1).trim();
if(propName.isEmpty()) {
throw new OperationFormatException("Failed to parse property '" + prop + "'");
}
if(propName.equals("imqDestinationName") ||propName.equalsIgnoreCase("name")) {
name = propValue;
} else if("ClientId".equals(propName)) {
props.put("client-id", propValue);
}
}
} else {
props = Collections.emptyMap();
}
if(name == null) {
name = jndiName.replace('/', '_');
}
if(restype.equals("jakarta.jms.Queue")) {
DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder();
builder.addNode("subsystem", "messaging-activemq");
builder.addNode("server", serverName);
builder.addNode("jms-queue", name);
builder.setOperationName("add");
builder.getModelNode().get("entries").add(jndiName);
addProperties(props, builder);
return builder.buildRequest();
} else if(restype.equals("jakarta.jms.Topic")) {
DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder();
builder.addNode("subsystem", "messaging-activemq");
builder.addNode("server", serverName);
builder.addNode("jms-topic", name);
builder.setOperationName("add");
builder.getModelNode().get("entries").add(jndiName);
addProperties(props, builder);
return builder.buildRequest();
} else if(restype.equals("jakarta.jms.ConnectionFactory") ||
restype.equals("jakarta.jms.TopicConnectionFactory") ||
restype.equals("jakarta.jms.QueueConnectionFactory")) {
DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder();
builder.addNode("subsystem", "messaging-activemq");
builder.addNode("server", serverName);
builder.addNode("connection-factory", name);
builder.setOperationName("add");
builder.getModelNode().get("entries").add(jndiName);
addProperties(props, builder);
return builder.buildRequest();
} else {
throw new OperationFormatException("Resource type " + restype + " isn't supported.");
}
}
private void addProperties(Map<String, String> props, DefaultOperationRequestBuilder builder) {
for (Map.Entry<String, String> entry : props.entrySet()) {
builder.addProperty(entry.getKey(), entry.getValue());
}
}
}
| 6,998
| 36.629032
| 101
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/cli/ConnectionFactoryHandlerProvider.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.wildfly.extension.messaging.activemq.jms.cli;
import org.jboss.as.cli.CommandContext;
import org.jboss.as.cli.CommandHandler;
import org.jboss.as.cli.CommandHandlerProvider;
import org.jboss.as.cli.handlers.GenericTypeOperationHandler;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2015 Red Hat inc.
*/
public class ConnectionFactoryHandlerProvider implements CommandHandlerProvider {
@Override
public CommandHandler createCommandHandler(CommandContext ctx) {
return new GenericTypeOperationHandler(ctx, "/subsystem=messaging-activemq/server=default/connection-factory", null);
}
@Override
public boolean isTabComplete() {
return true;
}
@Override
public String[] getNames() {
return new String[] { "connection-factory" };
}
}
| 1,848
| 36.734694
| 126
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/cli/JMSQueueHandlerProvider.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.wildfly.extension.messaging.activemq.jms.cli;
import org.jboss.as.cli.CommandContext;
import org.jboss.as.cli.CommandHandler;
import org.jboss.as.cli.CommandHandlerProvider;
import org.jboss.as.cli.handlers.GenericTypeOperationHandler;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2015 Red Hat inc.
*/
public class JMSQueueHandlerProvider implements CommandHandlerProvider {
@Override
public CommandHandler createCommandHandler(CommandContext ctx) {
return new GenericTypeOperationHandler(ctx, "/subsystem=messaging-activemq/server=default/jms-queue", "queue-address");
}
@Override
public boolean isTabComplete() {
return true;
}
@Override
public String[] getNames() {
return new String[] { "jms-queue" };
}
}
| 1,832
| 36.408163
| 128
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/cli/JMSTopicHandlerProvider.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.wildfly.extension.messaging.activemq.jms.cli;
import org.jboss.as.cli.CommandContext;
import org.jboss.as.cli.CommandHandler;
import org.jboss.as.cli.CommandHandlerProvider;
import org.jboss.as.cli.handlers.GenericTypeOperationHandler;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2015 Red Hat inc.
*/
public class JMSTopicHandlerProvider implements CommandHandlerProvider {
@Override
public CommandHandler createCommandHandler(CommandContext ctx) {
return new GenericTypeOperationHandler(ctx, "/subsystem=messaging-activemq/server=default/jms-topic", "topic-address");
}
@Override
public boolean isTabComplete() {
return true;
}
@Override
public String[] getNames() {
return new String[] { "jms-topic" };
}
}
| 1,832
| 36.408163
| 128
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/cli/CreateJMSResourceHandlerProvider.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.wildfly.extension.messaging.activemq.jms.cli;
import org.jboss.as.cli.CommandContext;
import org.jboss.as.cli.CommandHandler;
import org.jboss.as.cli.CommandHandlerProvider;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2015 Red Hat inc.
*/
public class CreateJMSResourceHandlerProvider implements CommandHandlerProvider {
@Override
public CommandHandler createCommandHandler(CommandContext ctx) {
return new CreateJMSResourceHandler(ctx);
}
@Override
public boolean isTabComplete() {
return false;
}
@Override
public String[] getNames() {
return new String[] { "create-jms-resource" };
}
}
| 1,711
| 34.666667
| 81
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/cli/DeleteJMSResourceHandler.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.wildfly.extension.messaging.activemq.jms.cli;
import org.jboss.as.cli.CommandContext;
import org.jboss.as.cli.CommandFormatException;
import org.jboss.as.cli.Util;
import org.jboss.as.cli.handlers.BatchModeCommandHandler;
import org.jboss.as.cli.operation.OperationFormatException;
import org.jboss.as.cli.operation.impl.DefaultOperationRequestBuilder;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.dmr.ModelNode;
/**
*
* @author Alexey Loubyansky
*/
class DeleteJMSResourceHandler extends BatchModeCommandHandler {
public DeleteJMSResourceHandler(CommandContext ctx) {
super(ctx, "delete-jms-resource", true);
this.addRequiredPath("/subsystem=messaging-activemq");
}
@Override
public ModelNode buildRequestWithoutHeaders(CommandContext ctx)
throws OperationFormatException {
try {
if(!ctx.getParsedCommandLine().hasProperties()) {
throw new OperationFormatException("Arguments are missing");
}
} catch (CommandFormatException e) {
throw new OperationFormatException(e.getLocalizedMessage());
}
//String target = null;
String jndiName = null;
String serverName = "default"; // TODO read server name from props
String[] args = ctx.getArgumentsString().split("\\s+");
int i = 0;
while(i < args.length) {
String arg = args[i++];
if(arg.equals("--target")) {
// if(i < args.length) {
// target = args[i++];
// }
} else {
jndiName = arg;
}
}
if(jndiName == null) {
throw new OperationFormatException("name is missing.");
}
ModelControllerClient client = ctx.getModelControllerClient();
final String resource;
if(Util.isTopic(client, jndiName)) {
resource = "jms-topic";
} else if(Util.isQueue(client, jndiName)) {
resource = "jms-queue";
} else if(Util.isConnectionFactory(client, jndiName)) {
resource = "connection-factory";
} else {
throw new OperationFormatException("'" + jndiName +"' wasn't found among existing JMS resources.");
}
DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder();
builder.addNode("subsystem", "messaging");
builder.addNode("server", serverName);
builder.addNode(resource, jndiName);
builder.setOperationName("remove");
return builder.buildRequest();
}
}
| 3,655
| 36.690722
| 111
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/bridge/JMSBridgeAdd.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.wildfly.extension.messaging.activemq.jms.bridge;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.security.CredentialReference.handleCredentialReferenceUpdate;
import static org.jboss.as.controller.security.CredentialReference.rollbackCredentialStoreUpdate;
import static org.jboss.as.server.Services.requireServerExecutor;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.function.Supplier;
import org.apache.activemq.artemis.jms.bridge.ConnectionFactoryFactory;
import org.apache.activemq.artemis.jms.bridge.DestinationFactory;
import org.apache.activemq.artemis.jms.bridge.JMSBridge;
import org.apache.activemq.artemis.jms.bridge.QualityOfServiceMode;
import org.apache.activemq.artemis.jms.bridge.impl.JMSBridgeImpl;
import org.apache.activemq.artemis.jms.bridge.impl.JNDIConnectionFactoryFactory;
import org.apache.activemq.artemis.jms.bridge.impl.JNDIDestinationFactory;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.ObjectTypeAttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.controller.security.CredentialReference;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoadException;
import org.jboss.modules.ModuleNotFoundException;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController.Mode;
import org.jboss.msc.service.ServiceName;
import org.wildfly.common.function.ExceptionSupplier;
import org.wildfly.extension.messaging.activemq.CommonAttributes;
import org.wildfly.extension.messaging.activemq.MessagingServices;
import org.wildfly.extension.messaging.activemq.logging.MessagingLogger;
import org.wildfly.security.credential.source.CredentialSource;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Jakarta Messaging Bridge add update.
*
* @author Jeff Mesnil (c) 2012 Red Hat Inc.
*/
public class JMSBridgeAdd extends AbstractAddStepHandler {
public static final JMSBridgeAdd INSTANCE = new JMSBridgeAdd();
private JMSBridgeAdd() {
super(JMSBridgeDefinition.ATTRIBUTES);
}
@Override
protected void populateModel(final OperationContext context, final ModelNode operation, final Resource resource) throws OperationFailedException {
super.populateModel(context, operation, resource);
final ModelNode model = resource.getModel();
handleCredentialReferenceUpdate(context, model.get(JMSBridgeDefinition.SOURCE_CREDENTIAL_REFERENCE.getName()), JMSBridgeDefinition.SOURCE_CREDENTIAL_REFERENCE.getName());
handleCredentialReferenceUpdate(context, model.get(JMSBridgeDefinition.TARGET_CREDENTIAL_REFERENCE.getName()), JMSBridgeDefinition.TARGET_CREDENTIAL_REFERENCE.getName());
}
@Override
protected void performRuntime(final OperationContext context, final ModelNode operation, final ModelNode model)
throws OperationFailedException {
context.addStep(new OperationStepHandler() {
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR));
String moduleName = resolveAttribute(JMSBridgeDefinition.MODULE, context, model);
final JMSBridge bridge = createJMSBridge(context, model);
final String bridgeName = address.getLastElement().getValue();
final ServiceName bridgeServiceName = MessagingServices.getJMSBridgeServiceName(bridgeName);
final ServiceBuilder jmsBridgeServiceBuilder = context.getServiceTarget().addService(bridgeServiceName);
jmsBridgeServiceBuilder.requires(context.getCapabilityServiceName(MessagingServices.LOCAL_TRANSACTION_PROVIDER_CAPABILITY, null));
jmsBridgeServiceBuilder.setInitialMode(Mode.ACTIVE);
Supplier<ExecutorService> executorSupplier = requireServerExecutor(jmsBridgeServiceBuilder);
if (dependsOnLocalResources(context, model, JMSBridgeDefinition.SOURCE_CONTEXT)) {
addDependencyForJNDIResource(jmsBridgeServiceBuilder, model, context, JMSBridgeDefinition.SOURCE_CONNECTION_FACTORY);
addDependencyForJNDIResource(jmsBridgeServiceBuilder, model, context, JMSBridgeDefinition.SOURCE_DESTINATION);
}
if (dependsOnLocalResources(context, model, JMSBridgeDefinition.TARGET_CONTEXT)) {
addDependencyForJNDIResource(jmsBridgeServiceBuilder, model, context, JMSBridgeDefinition.TARGET_CONNECTION_FACTORY);
addDependencyForJNDIResource(jmsBridgeServiceBuilder, model, context, JMSBridgeDefinition.TARGET_DESTINATION);
}
// add a dependency to the Artemis thread pool so that if either the source or target Jakarta Messaging broker
// corresponds to a local Artemis server, the pool will be cleaned up after the Jakarta Messaging bridge is stopped.
jmsBridgeServiceBuilder.requires(MessagingServices.ACTIVEMQ_CLIENT_THREAD_POOL);
// adding credential source supplier which will later resolve password from CredentialStore using credential-reference
final JMSBridgeService bridgeService = new JMSBridgeService(moduleName, bridgeName, bridge, executorSupplier,
getCredentialStoreReference(JMSBridgeDefinition.SOURCE_CREDENTIAL_REFERENCE, context, model, jmsBridgeServiceBuilder),
getCredentialStoreReference(JMSBridgeDefinition.TARGET_CREDENTIAL_REFERENCE, context, model, jmsBridgeServiceBuilder));
jmsBridgeServiceBuilder.setInstance(bridgeService);
jmsBridgeServiceBuilder.install();
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
}, OperationContext.Stage.RUNTIME);
}
@Override
protected void rollbackRuntime(OperationContext context, final ModelNode operation, final Resource resource) {
rollbackCredentialStoreUpdate(JMSBridgeDefinition.SOURCE_CREDENTIAL_REFERENCE, context, resource);
rollbackCredentialStoreUpdate(JMSBridgeDefinition.TARGET_CREDENTIAL_REFERENCE, context, resource);
}
private boolean dependsOnLocalResources(OperationContext context, ModelNode model, AttributeDefinition attr) throws OperationFailedException {
// if either the source or target context attribute is resolved to a null or empty Properties, this means that the Jakarta Messaging resources will be
// looked up from the local ActiveMQ server.
return resolveContextProperties(attr, context, model).isEmpty();
}
private void addDependencyForJNDIResource(final ServiceBuilder builder, final ModelNode model, final OperationContext context,
final AttributeDefinition attribute) throws OperationFailedException {
String jndiName = attribute.resolveModelAttribute(context, model).asString();
builder.requires(ContextNames.bindInfoFor(jndiName).getBinderServiceName());
}
private JMSBridge createJMSBridge(OperationContext context, ModelNode model) throws OperationFailedException {
final Properties sourceContextProperties = resolveContextProperties(JMSBridgeDefinition.SOURCE_CONTEXT, context, model);
final String sourceConnectionFactoryName = JMSBridgeDefinition.SOURCE_CONNECTION_FACTORY.resolveModelAttribute(context, model).asString();
final ConnectionFactoryFactory sourceCff = new JNDIConnectionFactoryFactory(sourceContextProperties , sourceConnectionFactoryName);
final String sourceDestinationName = JMSBridgeDefinition.SOURCE_DESTINATION.resolveModelAttribute(context, model).asString();
final DestinationFactory sourceDestinationFactory = new JNDIDestinationFactory(sourceContextProperties, sourceDestinationName);
final Properties targetContextProperties = resolveContextProperties(JMSBridgeDefinition.TARGET_CONTEXT, context, model);
final String targetConnectionFactoryName = JMSBridgeDefinition.TARGET_CONNECTION_FACTORY.resolveModelAttribute(context, model).asString();
final ConnectionFactoryFactory targetCff = new JNDIConnectionFactoryFactory(targetContextProperties, targetConnectionFactoryName);
final String targetDestinationName = JMSBridgeDefinition.TARGET_DESTINATION.resolveModelAttribute(context, model).asString();
final DestinationFactory targetDestinationFactory = new JNDIDestinationFactory(targetContextProperties, targetDestinationName);
final String sourceUsername = resolveAttribute(JMSBridgeDefinition.SOURCE_USER, context, model);
final String sourcePassword = resolveAttribute(JMSBridgeDefinition.SOURCE_PASSWORD, context, model);
final String targetUsername = resolveAttribute(JMSBridgeDefinition.TARGET_USER, context, model);
final String targetPassword = resolveAttribute(JMSBridgeDefinition.TARGET_PASSWORD, context, model);
final String selector = resolveAttribute(CommonAttributes.SELECTOR, context, model);
final long failureRetryInterval = JMSBridgeDefinition.FAILURE_RETRY_INTERVAL.resolveModelAttribute(context, model).asLong();
final int maxRetries = JMSBridgeDefinition.MAX_RETRIES.resolveModelAttribute(context, model).asInt();
final QualityOfServiceMode qosMode = QualityOfServiceMode.valueOf( JMSBridgeDefinition.QUALITY_OF_SERVICE.resolveModelAttribute(context, model).asString());
final int maxBatchSize = JMSBridgeDefinition.MAX_BATCH_SIZE.resolveModelAttribute(context, model).asInt();
final long maxBatchTime = JMSBridgeDefinition.MAX_BATCH_TIME.resolveModelAttribute(context, model).asLong();
final String subName = resolveAttribute(JMSBridgeDefinition.SUBSCRIPTION_NAME, context, model);
final String clientID = resolveAttribute(JMSBridgeDefinition.CLIENT_ID, context, model);
final boolean addMessageIDInHeader = JMSBridgeDefinition.ADD_MESSAGE_ID_IN_HEADER.resolveModelAttribute(context, model).asBoolean();
final String moduleName = resolveAttribute(JMSBridgeDefinition.MODULE, context, model);
final ClassLoader oldTccl= WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
// if a module is specified, use it to instantiate the JMSBridge to ensure its ExecutorService
// will use the correct class loader to execute its threads
if (moduleName != null) {
Module module = Module.getCallerModuleLoader().loadModule(ModuleIdentifier.fromString(moduleName));
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(module.getClassLoader());
}
return new JMSBridgeImpl(sourceCff,
targetCff,
sourceDestinationFactory,
targetDestinationFactory,
sourceUsername,
sourcePassword,
targetUsername,
targetPassword,
selector,
failureRetryInterval,
maxRetries,
qosMode,
maxBatchSize,
maxBatchTime,
subName,
clientID,
addMessageIDInHeader).setBridgeName(context.getCurrentAddressValue());
} catch (ModuleNotFoundException e) {
throw MessagingLogger.ROOT_LOGGER.moduleNotFound(moduleName, e.getMessage(), e);
} catch (ModuleLoadException e) {
throw MessagingLogger.ROOT_LOGGER.unableToLoadModule(moduleName, e);
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);
}
}
private Properties resolveContextProperties(AttributeDefinition attribute, OperationContext context, ModelNode model) throws OperationFailedException {
final ModelNode contextModel = attribute.resolveModelAttribute(context, model);
final Properties contextProperties = new Properties();
if (contextModel.isDefined()) {
for (Property property : contextModel.asPropertyList()) {
contextProperties.put(property.getName(), property.getValue().asString());
}
}
return contextProperties;
}
/**
* Return null if the resolved attribute is not defined
*/
private String resolveAttribute(SimpleAttributeDefinition attr, OperationContext context, ModelNode model) throws OperationFailedException {
final ModelNode node = attr.resolveModelAttribute(context, model);
return node.isDefined() ? node.asString() : null;
}
private static ExceptionSupplier<CredentialSource, Exception> getCredentialStoreReference(ObjectTypeAttributeDefinition credentialReferenceAttributeDefinition, OperationContext context, ModelNode model, ServiceBuilder<?> serviceBuilder, String... modelFilter) throws OperationFailedException {
if (model.hasDefined(credentialReferenceAttributeDefinition.getName())) {
ModelNode filteredModelNode = model;
if (modelFilter != null && modelFilter.length > 0) {
for (String path : modelFilter) {
if (filteredModelNode.get(path).isDefined()) {
filteredModelNode = filteredModelNode.get(path);
} else {
break;
}
}
}
ModelNode value = credentialReferenceAttributeDefinition.resolveModelAttribute(context, filteredModelNode);
if (value.isDefined()) {
return CredentialReference.getCredentialSourceSupplier(context, credentialReferenceAttributeDefinition, filteredModelNode, serviceBuilder);
}
}
return null;
}
}
| 15,551
| 60.714286
| 297
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/bridge/JMSBridgeService.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.wildfly.extension.messaging.activemq.jms.bridge;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.apache.activemq.artemis.jms.bridge.JMSBridge;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.wildfly.common.function.ExceptionSupplier;
import org.wildfly.extension.messaging.activemq.logging.MessagingLogger;
import org.wildfly.security.credential.PasswordCredential;
import org.wildfly.security.credential.source.CredentialSource;
import org.wildfly.security.manager.WildFlySecurityManager;
import org.wildfly.security.password.interfaces.ClearPassword;
import org.wildfly.transaction.client.ContextTransactionManager;
/**
* Service responsible for Jakarta Messaging Bridges.
*
* @author Jeff Mesnil (c) 2012 Red Hat Inc.
*/
class JMSBridgeService implements Service<JMSBridge> {
private final JMSBridge bridge;
private final String bridgeName;
private final String moduleName;
private final Supplier<ExecutorService> executorSupplier;
private final ExceptionSupplier<CredentialSource, Exception> sourceCredentialSourceSupplier;
private final ExceptionSupplier<CredentialSource, Exception> targetCredentialSourceSupplier;
public JMSBridgeService(final String moduleName, final String bridgeName, final JMSBridge bridge,
Supplier<ExecutorService> executorSupplier,
ExceptionSupplier<CredentialSource, Exception> sourceCredentialSourceSupplier,
ExceptionSupplier<CredentialSource, Exception> targetCredentialSourceSupplier) {
if(bridge == null) {
throw MessagingLogger.ROOT_LOGGER.nullVar("bridge");
}
this.moduleName = moduleName;
this.bridgeName = bridgeName;
this.bridge = bridge;
this.executorSupplier = executorSupplier;
this.sourceCredentialSourceSupplier = sourceCredentialSourceSupplier;
this.targetCredentialSourceSupplier = targetCredentialSourceSupplier;
}
@Override
public synchronized void start(final StartContext context) throws StartException {
final Runnable task = new Runnable() {
@Override
public void run() {
try {
bridge.setTransactionManager(ContextTransactionManager.getInstance());
startBridge();
context.complete();
} catch (Throwable e) {
context.failed(MessagingLogger.ROOT_LOGGER.failedToCreate(e, "JMS Bridge"));
}
}
};
try {
executorSupplier.get().execute(task);
} catch (RejectedExecutionException e) {
task.run();
} finally {
context.asynchronous();
}
}
public void startBridge() throws Exception {
final Module module;
if (moduleName != null) {
ModuleIdentifier moduleID = ModuleIdentifier.fromString(moduleName);
module = Module.getContextModuleLoader().loadModule(moduleID);
} else {
module = Module.forClass(JMSBridgeService.class);
}
ClassLoader oldTccl= WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(module.getClassLoader());
setJMSBridgePasswordsFromCredentialSource();
bridge.start();
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);
}
MessagingLogger.ROOT_LOGGER.startedService("JMS Bridge", bridgeName);
}
@Override
public synchronized void stop(final StopContext context) {
final Runnable task = new Runnable() {
@Override
public void run() {
try {
bridge.stop();
MessagingLogger.ROOT_LOGGER.stoppedService("JMS Bridge", bridgeName);
context.complete();
} catch(Exception e) {
MessagingLogger.ROOT_LOGGER.failedToDestroy("JMS Bridge", bridgeName);
}
}
};
try {
executorSupplier.get().execute(task);
} catch (RejectedExecutionException e) {
task.run();
} finally {
context.asynchronous();
}
}
@Override
public JMSBridge getValue() throws IllegalStateException {
return bridge;
}
private void setJMSBridgePasswordsFromCredentialSource() {
setNewJMSBridgePassword(sourceCredentialSourceSupplier, bridge::setSourcePassword);
setNewJMSBridgePassword(targetCredentialSourceSupplier, bridge::setTargetPassword);
}
private void setNewJMSBridgePassword(ExceptionSupplier<CredentialSource, Exception> credentialSourceSupplier, Consumer<String> passwordConsumer) {
if (credentialSourceSupplier != null) {
try {
CredentialSource credentialSource = credentialSourceSupplier.get();
if (credentialSource != null) {
char[] password = credentialSource.getCredential(PasswordCredential.class).getPassword(ClearPassword.class).getPassword();
if (password != null) {
passwordConsumer.accept(new String(password));
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
| 6,803
| 39.260355
| 150
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/bridge/JMSBridgeRemove.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.wildfly.extension.messaging.activemq.jms.bridge;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import org.jboss.as.controller.AbstractRemoveStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.wildfly.extension.messaging.activemq.logging.MessagingLogger;
import org.wildfly.extension.messaging.activemq.MessagingServices;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceRegistry;
/**
* Removes a Jakarta Messaging Bridge.
*
* @author Jeff Mesnil (c) 2011 Red Hat Inc.
*/
class JMSBridgeRemove extends AbstractRemoveStepHandler {
static final JMSBridgeRemove INSTANCE = new JMSBridgeRemove();
private JMSBridgeRemove() {
}
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) {
final PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR));
final String bridgeName = address.getLastElement().getValue();
context.removeService(MessagingServices.getJMSBridgeServiceName(bridgeName));
}
protected void recoverServices(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
final PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR));
final String bridgeName = address.getLastElement().getValue();
final ServiceRegistry registry = context.getServiceRegistry(true);
final ServiceName jmsBridgeServiceName = MessagingServices.getJMSBridgeServiceName(bridgeName);
final ServiceController<?> jmsBridgeServiceController = registry.getService(jmsBridgeServiceName);
if (jmsBridgeServiceController != null && jmsBridgeServiceController.getState() == ServiceController.State.UP) {
JMSBridgeService jmsBridgeService = (JMSBridgeService) jmsBridgeServiceController.getService();
try {
jmsBridgeService.startBridge();
} catch (Exception e) {
throw MessagingLogger.ROOT_LOGGER.failedToRecover(e, bridgeName);
}
}
}
}
| 3,329
| 44.616438
| 132
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/bridge/JMSBridgeDefinition.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.wildfly.extension.messaging.activemq.jms.bridge;
import static org.jboss.as.controller.SimpleAttributeDefinitionBuilder.create;
import static org.jboss.as.controller.client.helpers.MeasurementUnit.MILLISECONDS;
import static org.jboss.as.controller.registry.AttributeAccess.Flag.COUNTER_METRIC;
import static org.jboss.dmr.ModelType.BOOLEAN;
import static org.jboss.dmr.ModelType.INT;
import static org.jboss.dmr.ModelType.LONG;
import static org.jboss.dmr.ModelType.STRING;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.CONNECTION_FACTORY;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.DESTINATION;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.PASSWORD;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.SOURCE;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.TARGET;
import static org.wildfly.extension.messaging.activemq.MessagingExtension.MESSAGING_SECURITY_SENSITIVE_TARGET;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.AttributeMarshallers;
import org.jboss.as.controller.AttributeParsers;
import org.jboss.as.controller.ObjectTypeAttributeDefinition;
import org.jboss.as.controller.PersistentResourceDefinition;
import org.jboss.as.controller.PropertiesAttributeDefinition;
import org.jboss.as.controller.ReloadRequiredWriteAttributeHandler;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleOperationDefinitionBuilder;
import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.validation.EnumValidator;
import org.jboss.as.controller.operations.validation.IntRangeValidator;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.security.CredentialReference;
import org.jboss.as.controller.security.CredentialReferenceWriteAttributeHandler;
import org.jboss.dmr.ModelNode;
import org.wildfly.extension.messaging.activemq.CommonAttributes;
import org.wildfly.extension.messaging.activemq.InfiniteOrPositiveValidators;
import org.wildfly.extension.messaging.activemq.MessagingExtension;
/**
* @author Jeff Mesnil (c) 2012 Red Hat Inc.
*/
public class JMSBridgeDefinition extends PersistentResourceDefinition {
public static final String PAUSE = "pause";
public static final String RESUME = "resume";
private static final String SOURCE_CREDENTIAL_REFERENCE_NAME = "source-" + CredentialReference.CREDENTIAL_REFERENCE;
private static final String TARGET_CREDENTIAL_REFERENCE_NAME = "target-" + CredentialReference.CREDENTIAL_REFERENCE;
public static final SimpleAttributeDefinition MODULE = create("module", STRING, false)
.build();
public static final SimpleAttributeDefinition SOURCE_CONNECTION_FACTORY = create("source-connection-factory", STRING)
.setAttributeGroup(SOURCE)
.setXmlName(CONNECTION_FACTORY)
.build();
public static final SimpleAttributeDefinition SOURCE_DESTINATION = create("source-destination", STRING)
.setAttributeGroup(SOURCE)
.setXmlName(DESTINATION)
.build();
public static final SimpleAttributeDefinition SOURCE_USER = create("source-user", STRING)
.setAttributeGroup(SOURCE)
.setXmlName("user")
.setRequired(false)
.setAllowExpression(true)
.addAccessConstraint(SensitiveTargetAccessConstraintDefinition.CREDENTIAL)
.addAccessConstraint(MESSAGING_SECURITY_SENSITIVE_TARGET)
.build();
public static final SimpleAttributeDefinition SOURCE_PASSWORD = create("source-password", STRING, true)
.setAttributeGroup(SOURCE)
.setXmlName(PASSWORD)
.setAllowExpression(true)
.addAccessConstraint(SensitiveTargetAccessConstraintDefinition.CREDENTIAL)
.addAccessConstraint(MESSAGING_SECURITY_SENSITIVE_TARGET)
.setAlternatives(SOURCE_CREDENTIAL_REFERENCE_NAME)
.build();
public static final ObjectTypeAttributeDefinition SOURCE_CREDENTIAL_REFERENCE =
CredentialReference.getAttributeBuilder(SOURCE_CREDENTIAL_REFERENCE_NAME, SOURCE_CREDENTIAL_REFERENCE_NAME, true)
.setAttributeGroup(SOURCE)
.addAccessConstraint(SensitiveTargetAccessConstraintDefinition.CREDENTIAL)
.addAccessConstraint(MESSAGING_SECURITY_SENSITIVE_TARGET)
.setAlternatives(SOURCE_PASSWORD.getName())
.build();
public static final PropertiesAttributeDefinition SOURCE_CONTEXT = new PropertiesAttributeDefinition.Builder("source-context", true)
.setAttributeGroup(SOURCE)
.setAttributeParser(new AttributeParsers.PropertiesParser())
.setAttributeMarshaller(new AttributeMarshallers.PropertiesAttributeMarshaller())
.setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition TARGET_CONNECTION_FACTORY = create("target-connection-factory", STRING)
.setAttributeGroup(TARGET)
.setXmlName(CONNECTION_FACTORY)
.build();
public static final SimpleAttributeDefinition TARGET_DESTINATION = create("target-destination", STRING)
.setAttributeGroup(TARGET)
.setXmlName(DESTINATION)
.build();
public static final SimpleAttributeDefinition TARGET_USER = create("target-user", STRING)
.setAttributeGroup(TARGET)
.setXmlName("user")
.setRequired(false)
.setAllowExpression(true)
.addAccessConstraint(SensitiveTargetAccessConstraintDefinition.CREDENTIAL)
.addAccessConstraint(MESSAGING_SECURITY_SENSITIVE_TARGET)
.build();
public static final SimpleAttributeDefinition TARGET_PASSWORD = create("target-password", STRING, true)
.setAttributeGroup(TARGET)
.setXmlName(PASSWORD)
.setAllowExpression(true)
.addAccessConstraint(SensitiveTargetAccessConstraintDefinition.CREDENTIAL)
.addAccessConstraint(MESSAGING_SECURITY_SENSITIVE_TARGET)
.setAlternatives(TARGET_CREDENTIAL_REFERENCE_NAME)
.build();
public static final ObjectTypeAttributeDefinition TARGET_CREDENTIAL_REFERENCE =
CredentialReference.getAttributeBuilder(TARGET_CREDENTIAL_REFERENCE_NAME, TARGET_CREDENTIAL_REFERENCE_NAME, true)
.setAttributeGroup(TARGET)
.addAccessConstraint(SensitiveTargetAccessConstraintDefinition.CREDENTIAL)
.addAccessConstraint(MESSAGING_SECURITY_SENSITIVE_TARGET)
.setAlternatives(TARGET_PASSWORD.getName())
.build();
public static final PropertiesAttributeDefinition TARGET_CONTEXT = new PropertiesAttributeDefinition.Builder("target-context", true)
.setAttributeGroup(TARGET)
.setAttributeParser(new AttributeParsers.PropertiesParser())
.setAttributeMarshaller(new AttributeMarshallers.PropertiesAttributeMarshaller())
.setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition QUALITY_OF_SERVICE = create("quality-of-service", STRING, true)
.setValidator(new EnumValidator<>(QualityOfServiceMode.class, EnumSet.allOf(QualityOfServiceMode.class)))
.setAllowExpression(true)
.setDefaultValue(new ModelNode(QualityOfServiceMode.AT_MOST_ONCE.name()))
.build();
public static final SimpleAttributeDefinition FAILURE_RETRY_INTERVAL = create("failure-retry-interval", LONG, true)
.setMeasurementUnit(MILLISECONDS)
.setValidator(InfiniteOrPositiveValidators.LONG_INSTANCE)
.setAllowExpression(true)
.setDefaultValue(new ModelNode(5000L))
.build();
public static final SimpleAttributeDefinition MAX_RETRIES = create("max-retries", INT, true)
.setCorrector(InfiniteOrPositiveValidators.NEGATIVE_VALUE_CORRECTOR)
.setValidator(InfiniteOrPositiveValidators.INT_INSTANCE)
.setDefaultValue(new ModelNode(-1))
.setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition MAX_BATCH_SIZE = create("max-batch-size", INT, true)
.setValidator(new IntRangeValidator(0, Integer.MAX_VALUE, false, false))
.setAllowExpression(true)
.setDefaultValue(new ModelNode(1))
.build();
public static final SimpleAttributeDefinition MAX_BATCH_TIME = create("max-batch-time", LONG, true)
.setMeasurementUnit(MILLISECONDS)
.setCorrector(InfiniteOrPositiveValidators.NEGATIVE_VALUE_CORRECTOR)
.setValidator(InfiniteOrPositiveValidators.LONG_INSTANCE)
.setAllowExpression(true)
.setDefaultValue(new ModelNode(-1L))
.build();
public static final SimpleAttributeDefinition SUBSCRIPTION_NAME = create("subscription-name", STRING)
.setRequired(false)
.setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition CLIENT_ID = create("client-id", STRING)
.setRequired(false)
.setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition ADD_MESSAGE_ID_IN_HEADER = create("add-messageID-in-header", BOOLEAN)
.setRequired(false)
.setDefaultValue(ModelNode.FALSE)
.setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition STARTED = create(CommonAttributes.STARTED, BOOLEAN)
.setStorageRuntime()
.build();
public static final SimpleAttributeDefinition ABORTED_MESSAGE_COUNT = create("aborted-message-count", LONG)
.setStorageRuntime()
.setUndefinedMetricValue(new ModelNode(0))
.addFlag(COUNTER_METRIC)
.build();
public static final AttributeDefinition[] ATTRIBUTES = {
MODULE,
QUALITY_OF_SERVICE,
FAILURE_RETRY_INTERVAL, MAX_RETRIES,
MAX_BATCH_SIZE, MAX_BATCH_TIME,
CommonAttributes.SELECTOR,
SUBSCRIPTION_NAME,
CommonAttributes.CLIENT_ID,
ADD_MESSAGE_ID_IN_HEADER,
SOURCE_CONNECTION_FACTORY,
SOURCE_DESTINATION,
SOURCE_USER,
SOURCE_PASSWORD,
SOURCE_CREDENTIAL_REFERENCE,
SOURCE_CONTEXT,
TARGET_CONNECTION_FACTORY,
TARGET_DESTINATION,
TARGET_USER,
TARGET_PASSWORD,
TARGET_CREDENTIAL_REFERENCE,
TARGET_CONTEXT
};
public static final AttributeDefinition[] READONLY_ATTRIBUTES = {
STARTED, CommonAttributes.PAUSED
};
public static final AttributeDefinition[] METRICS = {
CommonAttributes.MESSAGE_COUNT, ABORTED_MESSAGE_COUNT
};
public static final String[] OPERATIONS = {
ModelDescriptionConstants.START, ModelDescriptionConstants.STOP,
PAUSE, RESUME
};
public JMSBridgeDefinition() {
super(MessagingExtension.JMS_BRIDGE_PATH,
MessagingExtension.getResourceDescriptionResolver(CommonAttributes.JMS_BRIDGE),
JMSBridgeAdd.INSTANCE,
JMSBridgeRemove.INSTANCE);
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return Arrays.asList(ATTRIBUTES);
}
@Override
public void registerAttributes(ManagementResourceRegistration registry) {
ReloadRequiredWriteAttributeHandler reloadRequiredWriteAttributeHandler = new ReloadRequiredWriteAttributeHandler(ATTRIBUTES);
CredentialReferenceWriteAttributeHandler credentialReferenceWriteAttributeHandler = new CredentialReferenceWriteAttributeHandler(SOURCE_CREDENTIAL_REFERENCE, TARGET_CREDENTIAL_REFERENCE);
for (AttributeDefinition attr : ATTRIBUTES) {
if (attr.equals(SOURCE_CREDENTIAL_REFERENCE) || attr.equals(TARGET_CREDENTIAL_REFERENCE)) {
registry.registerReadWriteAttribute(attr, null, credentialReferenceWriteAttributeHandler);
} else {
registry.registerReadWriteAttribute(attr, null, reloadRequiredWriteAttributeHandler);
}
}
for (AttributeDefinition attr : READONLY_ATTRIBUTES) {
registry.registerReadOnlyAttribute(attr, JMSBridgeHandler.INSTANCE);
}
for (AttributeDefinition attr : METRICS) {
registry.registerMetric(attr, JMSBridgeHandler.READ_ONLY_INSTANCE);
}
}
@Override
public void registerOperations(ManagementResourceRegistration registry) {
super.registerOperations(registry);
for (final String operationName : OPERATIONS) {
registry.registerOperationHandler(SimpleOperationDefinitionBuilder.of(operationName, getResourceDescriptionResolver()).build(), JMSBridgeHandler.INSTANCE);
}
}
private enum QualityOfServiceMode {
AT_MOST_ONCE, DUPLICATES_OK, ONCE_AND_ONLY_ONCE;
}
}
| 14,498
| 48.316327
| 195
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/bridge/JMSBridgeHandler.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.wildfly.extension.messaging.activemq.jms.bridge;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.START;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STOP;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.NAME;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.PAUSED;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.STARTED;
import static org.wildfly.extension.messaging.activemq.jms.bridge.JMSBridgeDefinition.ABORTED_MESSAGE_COUNT;
import static org.wildfly.extension.messaging.activemq.jms.bridge.JMSBridgeDefinition.PAUSE;
import static org.wildfly.extension.messaging.activemq.jms.bridge.JMSBridgeDefinition.RESUME;
import org.apache.activemq.artemis.jms.bridge.JMSBridge;
import org.jboss.as.controller.AbstractRuntimeOnlyHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.logging.ControllerLogger;
import org.jboss.as.controller.operations.validation.ParametersValidator;
import org.jboss.as.controller.operations.validation.StringLengthValidator;
import org.wildfly.extension.messaging.activemq.MessagingServices;
import org.wildfly.extension.messaging.activemq.logging.MessagingLogger;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.wildfly.extension.messaging.activemq.CommonAttributes;
/**
* @author Jeff Mesnil (c) 2012 Red Hat Inc.
*/
public class JMSBridgeHandler extends AbstractRuntimeOnlyHandler {
public static final JMSBridgeHandler INSTANCE = new JMSBridgeHandler(false);
public static final JMSBridgeHandler READ_ONLY_INSTANCE = new JMSBridgeHandler(true);
private final ParametersValidator readAttributeValidator = new ParametersValidator();
private final boolean readOnly;
private JMSBridgeHandler(boolean readOnly) {
this.readOnly = readOnly;
readAttributeValidator.registerValidator(NAME, new StringLengthValidator(1));
}
@Override
protected void executeRuntimeStep(OperationContext context, ModelNode operation) throws OperationFailedException {
final String bridgeName = context.getCurrentAddressValue();
final String operationName = operation.require(OP).asString();
if (null == operationName) {
throw MessagingLogger.ROOT_LOGGER.unsupportedOperation(operationName);
}
final boolean modify = !READ_ATTRIBUTE_OPERATION.equals(operationName);
final ServiceName bridgeServiceName = MessagingServices.getJMSBridgeServiceName(bridgeName);
final ServiceController<?> bridgeService = context.getServiceRegistry(modify).getService(bridgeServiceName);
if (bridgeService == null) {
if (!readOnly) {
throw ControllerLogger.ROOT_LOGGER.managementResourceNotFound(context.getCurrentAddress());
}
return;
}
final JMSBridge bridge = JMSBridge.class.cast(bridgeService.getValue());
switch (operationName) {
case READ_ATTRIBUTE_OPERATION:
readAttributeValidator.validate(operation);
final String name = operation.require(NAME).asString();
if (STARTED.equals(name)) {
context.getResult().set(bridge.isStarted());
} else if (PAUSED.getName().equals(name)) {
context.getResult().set(bridge.isPaused());
} else if (CommonAttributes.MESSAGE_COUNT.getName().equals(name)) {
context.getResult().set(bridge.getMessageCount());
} else if (ABORTED_MESSAGE_COUNT.getName().equals(name)) {
context.getResult().set(bridge.getAbortedMessageCount());
} else {
throw MessagingLogger.ROOT_LOGGER.unsupportedAttribute(name);
}
break;
case START:
try {
// we do not start the bridge directly but call startBridge() instead
// to ensure the class loader will be able to load any external resources
JMSBridgeService service = (JMSBridgeService) bridgeService.getService();
service.startBridge();
} catch (Exception e) {
throw new RuntimeException(e);
} break;
case STOP:
try {
bridge.stop();
} catch (Exception e) {
throw new RuntimeException(e);
} break;
case PAUSE:
try {
bridge.pause();
} catch (Exception e) {
throw new RuntimeException(e);
} break;
case RESUME:
try {
bridge.resume();
} catch (Exception e) {
throw new RuntimeException(e);
}
break;
default:
throw MessagingLogger.ROOT_LOGGER.unsupportedOperation(operationName);
}
context.completeStep(new OperationContext.RollbackHandler() {
@Override
public void handleRollback(OperationContext context, ModelNode operation) {
try {
switch (operationName) {
case START:
bridge.stop();
break;
case STOP:
JMSBridgeService service = (JMSBridgeService) bridgeService.getService();
service.startBridge();
break;
case PAUSE:
bridge.resume();
break;
case RESUME:
bridge.pause();
break;
}
} catch (Exception e) {
MessagingLogger.ROOT_LOGGER.revertOperationFailed(e, getClass().getSimpleName(), operationName, context.getCurrentAddress());
}
}
});
}
}
| 7,519
| 46.898089
| 145
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/legacy/LegacyConnectionFactoryRemove.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.wildfly.extension.messaging.activemq.jms.legacy;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.LEGACY;
import org.jboss.as.controller.AbstractRemoveStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceName;
import org.wildfly.extension.messaging.activemq.MessagingServices;
import org.wildfly.extension.messaging.activemq.jms.JMSServices;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2015 Red Hat inc.
*/
public class LegacyConnectionFactoryRemove extends AbstractRemoveStepHandler {
static final LegacyConnectionFactoryRemove INSTANCE = new LegacyConnectionFactoryRemove();
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
String name = context.getCurrentAddressValue();
final ServiceName activeMQServerServiceName = MessagingServices.getActiveMQServiceName(context.getCurrentAddress());
final ServiceName serviceName = JMSServices.getConnectionFactoryBaseServiceName(activeMQServerServiceName).append(LEGACY, name);
context.removeService(serviceName);
for (String legacyEntry : LegacyConnectionFactoryDefinition.ENTRIES.unwrap(context, model)) {
final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(legacyEntry);
ServiceName binderServiceName = bindInfo.getBinderServiceName();
context.removeService(binderServiceName);
}
}
@Override
protected void recoverServices(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
LegacyConnectionFactoryAdd.INSTANCE.performRuntime(context, operation, model);
}
}
| 2,945
| 45.761905
| 136
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/legacy/LegacyConnectionFactoryAdd.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.wildfly.extension.messaging.activemq.jms.legacy;
import static org.hornetq.api.jms.JMSFactoryType.CF;
import static org.hornetq.api.jms.JMSFactoryType.QUEUE_CF;
import static org.hornetq.api.jms.JMSFactoryType.QUEUE_XA_CF;
import static org.hornetq.api.jms.JMSFactoryType.TOPIC_CF;
import static org.hornetq.api.jms.JMSFactoryType.TOPIC_XA_CF;
import static org.hornetq.api.jms.JMSFactoryType.XA_CF;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.CALL_FAILOVER_TIMEOUT;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.CALL_TIMEOUT;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.CLIENT_ID;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.AUTO_GROUP;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.BLOCK_ON_ACKNOWLEDGE;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.BLOCK_ON_DURABLE_SEND;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.BLOCK_ON_NON_DURABLE_SEND;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.CACHE_LARGE_MESSAGE_CLIENT;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.CLIENT_FAILURE_CHECK_PERIOD;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.COMPRESS_LARGE_MESSAGES;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.CONFIRMATION_WINDOW_SIZE;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.CONNECTION_LOAD_BALANCING_CLASS_NAME;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.CONNECTION_TTL;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.CONNECTORS;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.CONSUMER_MAX_RATE;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.CONSUMER_WINDOW_SIZE;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.DISCOVERY_GROUP;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.DUPS_OK_BATCH_SIZE;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.FAILOVER_ON_INITIAL_CONNECTION;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.GROUP_ID;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.INITIAL_CONNECT_ATTEMPTS;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.INITIAL_MESSAGE_PACKET_SIZE;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.MAX_RETRY_INTERVAL;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.MIN_LARGE_MESSAGE_SIZE;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.PRE_ACKNOWLEDGE;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.PRODUCER_MAX_RATE;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.PRODUCER_WINDOW_SIZE;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.RECONNECT_ATTEMPTS;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.RETRY_INTERVAL;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.RETRY_INTERVAL_MULTIPLIER;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.SCHEDULED_THREAD_POOL_MAX_SIZE;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.THREAD_POOL_MAX_SIZE;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.TRANSACTION_BATCH_SIZE;
import static org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.USE_GLOBAL_POOLS;
import org.hornetq.api.jms.HornetQJMSClient;
import org.hornetq.api.jms.JMSFactoryType;
import org.hornetq.jms.client.HornetQConnectionFactory;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceName;
import org.wildfly.extension.messaging.activemq.BinderServiceUtil;
import org.wildfly.extension.messaging.activemq.MessagingServices;
import org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition.HornetQConnectionFactoryType;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2015 Red Hat inc.
*/
public class LegacyConnectionFactoryAdd extends AbstractAddStepHandler {
static final LegacyConnectionFactoryAdd INSTANCE = new LegacyConnectionFactoryAdd();
public LegacyConnectionFactoryAdd() {
super(LegacyConnectionFactoryDefinition.ATTRIBUTES);
}
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
String name = context.getCurrentAddressValue();
final ServiceName activeMQServerServiceName = MessagingServices.getActiveMQServiceName(context.getCurrentAddress());
HornetQConnectionFactory incompleteCF = createLegacyConnectionFactory(context, model);
ModelNode discoveryGroup = DISCOVERY_GROUP.resolveModelAttribute(context, model);
String discoveryGroupName = discoveryGroup.isDefined() ? discoveryGroup.asString() : null;
LegacyConnectionFactoryService service = LegacyConnectionFactoryService.installService(name, activeMQServerServiceName, context.getServiceTarget(), incompleteCF, discoveryGroupName, CONNECTORS.unwrap(context, model));
for (String legacyEntry : LegacyConnectionFactoryDefinition.ENTRIES.unwrap(context, model)) {
BinderServiceUtil.installBinderService(context.getServiceTarget(), legacyEntry, service, null);
}
}
private HornetQConnectionFactory createLegacyConnectionFactory(OperationContext context, ModelNode model) throws OperationFailedException {
boolean ha = LegacyConnectionFactoryDefinition.HA.resolveModelAttribute(context, model).asBoolean();
String factoryTypeStr = LegacyConnectionFactoryDefinition.FACTORY_TYPE.resolveModelAttribute(context, model).asString();
JMSFactoryType factoryType = getType(HornetQConnectionFactoryType.valueOf(factoryTypeStr));
final HornetQConnectionFactory incompleteCF;
if (ha) {
incompleteCF = HornetQJMSClient.createConnectionFactoryWithHA(factoryType);
} else {
incompleteCF = HornetQJMSClient.createConnectionFactoryWithoutHA(factoryType);
}
incompleteCF.setAutoGroup(AUTO_GROUP.resolveModelAttribute(context, model).asBoolean());
incompleteCF.setBlockOnAcknowledge(BLOCK_ON_ACKNOWLEDGE.resolveModelAttribute(context, model).asBoolean());
incompleteCF.setBlockOnDurableSend(BLOCK_ON_DURABLE_SEND.resolveModelAttribute(context, model).asBoolean());
incompleteCF.setBlockOnNonDurableSend(BLOCK_ON_NON_DURABLE_SEND.resolveModelAttribute(context, model).asBoolean());
incompleteCF.setCacheLargeMessagesClient(CACHE_LARGE_MESSAGE_CLIENT.resolveModelAttribute(context, model).asBoolean());
incompleteCF.setCallFailoverTimeout(CALL_FAILOVER_TIMEOUT.resolveModelAttribute(context, model).asLong());
incompleteCF.setCallTimeout(CALL_TIMEOUT.resolveModelAttribute(context, model).asLong());
incompleteCF.setClientFailureCheckPeriod(CLIENT_FAILURE_CHECK_PERIOD.resolveModelAttribute(context, model).asLong());
final ModelNode clientID = CLIENT_ID.resolveModelAttribute(context, model);
if (clientID.isDefined()) {
incompleteCF.setClientID(clientID.asString());
}
incompleteCF.setCompressLargeMessage(COMPRESS_LARGE_MESSAGES.resolveModelAttribute(context, model).asBoolean());
incompleteCF.setConfirmationWindowSize(CONFIRMATION_WINDOW_SIZE.resolveModelAttribute(context, model).asInt());
final ModelNode connectionLoadBalancingClassName = CONNECTION_LOAD_BALANCING_CLASS_NAME.resolveModelAttribute(context, model);
if (connectionLoadBalancingClassName.isDefined()) {
incompleteCF.setConnectionLoadBalancingPolicyClassName(connectionLoadBalancingClassName.asString());
}
incompleteCF.setConnectionTTL(CONNECTION_TTL.resolveModelAttribute(context, model).asLong());
incompleteCF.setConsumerMaxRate(CONSUMER_MAX_RATE.resolveModelAttribute(context, model).asInt());
incompleteCF.setConsumerWindowSize(CONSUMER_WINDOW_SIZE.resolveModelAttribute(context, model).asInt());
incompleteCF.setConfirmationWindowSize(CONFIRMATION_WINDOW_SIZE.resolveModelAttribute(context, model).asInt());
incompleteCF.setDupsOKBatchSize(DUPS_OK_BATCH_SIZE.resolveModelAttribute(context, model).asInt());
incompleteCF.setFailoverOnInitialConnection(FAILOVER_ON_INITIAL_CONNECTION.resolveModelAttribute(context, model).asBoolean());
final ModelNode groupID = GROUP_ID.resolveModelAttribute(context, model);
if (groupID.isDefined()) {
incompleteCF.setGroupID(groupID.asString());
}
incompleteCF.setInitialConnectAttempts(INITIAL_CONNECT_ATTEMPTS.resolveModelAttribute(context, model).asInt());
incompleteCF.setInitialMessagePacketSize(INITIAL_MESSAGE_PACKET_SIZE.resolveModelAttribute(context, model).asInt());
incompleteCF.setMaxRetryInterval(MAX_RETRY_INTERVAL.resolveModelAttribute(context, model).asLong());
incompleteCF.setMinLargeMessageSize(MIN_LARGE_MESSAGE_SIZE.resolveModelAttribute(context, model).asInt());
incompleteCF.setPreAcknowledge(PRE_ACKNOWLEDGE.resolveModelAttribute(context, model).asBoolean());
incompleteCF.setProducerMaxRate(PRODUCER_MAX_RATE.resolveModelAttribute(context, model).asInt());
incompleteCF.setProducerWindowSize(PRODUCER_WINDOW_SIZE.resolveModelAttribute(context, model).asInt());
incompleteCF.setReconnectAttempts(RECONNECT_ATTEMPTS.resolveModelAttribute(context, model).asInt());
incompleteCF.setRetryInterval(RETRY_INTERVAL.resolveModelAttribute(context, model).asLong());
incompleteCF.setRetryIntervalMultiplier(RETRY_INTERVAL_MULTIPLIER.resolveModelAttribute(context, model).asDouble());
incompleteCF.setScheduledThreadPoolMaxSize(SCHEDULED_THREAD_POOL_MAX_SIZE.resolveModelAttribute(context, model).asInt());
incompleteCF.setThreadPoolMaxSize(THREAD_POOL_MAX_SIZE.resolveModelAttribute(context, model).asInt());
incompleteCF.setTransactionBatchSize(TRANSACTION_BATCH_SIZE.resolveModelAttribute(context, model).asInt());
incompleteCF.setUseGlobalPools(USE_GLOBAL_POOLS.resolveModelAttribute(context, model).asBoolean());
return incompleteCF;
}
private JMSFactoryType getType(HornetQConnectionFactoryType type) {
switch (type) {
case GENERIC:
return CF;
case TOPIC:
return TOPIC_CF;
case QUEUE:
return QUEUE_CF;
case XA_GENERIC:
return XA_CF;
case XA_QUEUE:
return QUEUE_XA_CF;
case XA_TOPIC:
return TOPIC_XA_CF;
}
return CF;
}
}
| 12,975
| 70.296703
| 225
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/legacy/LegacyConnectionFactoryDefinition.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.wildfly.extension.messaging.activemq.jms.legacy;
import static org.jboss.as.controller.SimpleAttributeDefinitionBuilder.create;
import static org.jboss.as.controller.client.helpers.MeasurementUnit.BYTES;
import static org.jboss.as.controller.client.helpers.MeasurementUnit.MILLISECONDS;
import static org.jboss.as.controller.client.helpers.MeasurementUnit.PER_SECOND;
import static org.jboss.dmr.ModelType.BOOLEAN;
import static org.jboss.dmr.ModelType.DOUBLE;
import static org.jboss.dmr.ModelType.INT;
import static org.jboss.dmr.ModelType.LONG;
import static org.jboss.dmr.ModelType.STRING;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration;
import org.apache.activemq.artemis.api.core.client.ActiveMQClient;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.AttributeMarshaller;
import org.jboss.as.controller.AttributeParser;
import org.jboss.as.controller.PersistentResourceDefinition;
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.EnumValidator;
import org.jboss.as.controller.operations.validation.ParameterValidator;
import org.jboss.as.controller.operations.validation.StringLengthValidator;
import org.jboss.as.controller.registry.RuntimePackageDependency;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.wildfly.extension.messaging.activemq.CommonAttributes;
import org.wildfly.extension.messaging.activemq.InfiniteOrPositiveValidators;
import org.wildfly.extension.messaging.activemq.MessagingExtension;
import org.wildfly.extension.messaging.activemq.jms.Validators;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2015 Red Hat inc.
*/
public class LegacyConnectionFactoryDefinition extends PersistentResourceDefinition {
/**
* @see HornetQClient.DEFAULT_AUTO_GROUP
*/
public static final AttributeDefinition AUTO_GROUP = SimpleAttributeDefinitionBuilder.create("auto-group", BOOLEAN)
.setDefaultValue(ModelNode.FALSE)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see HornetQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE
*/
public static final AttributeDefinition BLOCK_ON_ACKNOWLEDGE = SimpleAttributeDefinitionBuilder.create("block-on-acknowledge", BOOLEAN)
.setDefaultValue(ModelNode.FALSE)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see HornetQClient.DEFAULT_BLOCK_ON_DURABLE_SEND
*/
public static final AttributeDefinition BLOCK_ON_DURABLE_SEND = SimpleAttributeDefinitionBuilder.create("block-on-durable-send", BOOLEAN)
.setDefaultValue(ModelNode.TRUE)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see HornetQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND
*/
public static final AttributeDefinition BLOCK_ON_NON_DURABLE_SEND = SimpleAttributeDefinitionBuilder.create("block-on-non-durable-send", BOOLEAN)
.setDefaultValue(ModelNode.FALSE)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see HornetQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT
*/
public static final AttributeDefinition CACHE_LARGE_MESSAGE_CLIENT = SimpleAttributeDefinitionBuilder.create("cache-large-message-client", BOOLEAN)
.setDefaultValue(ModelNode.FALSE)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD
*/
public static final AttributeDefinition CLIENT_FAILURE_CHECK_PERIOD = SimpleAttributeDefinitionBuilder.create("client-failure-check-period", LONG)
.setDefaultValue(new ModelNode(30000L))
.setMeasurementUnit(MILLISECONDS)
.setRequired(false)
.setAllowExpression(true)
.setValidator(InfiniteOrPositiveValidators.LONG_INSTANCE)
.setRestartAllServices()
.build();
/**
* @see HornetQClient.DEFAULT_COMPRESS_LARGE_MESSAGES
*/
public static final AttributeDefinition COMPRESS_LARGE_MESSAGES = SimpleAttributeDefinitionBuilder.create("compress-large-messages", BOOLEAN)
.setDefaultValue(ModelNode.FALSE)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see HornetQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE
*/
public static final AttributeDefinition CONFIRMATION_WINDOW_SIZE = SimpleAttributeDefinitionBuilder.create("confirmation-window-size", INT)
.setDefaultValue(new ModelNode(-1))
.setMeasurementUnit(BYTES)
.setRequired(false)
.setAllowExpression(true)
.setCorrector(InfiniteOrPositiveValidators.NEGATIVE_VALUE_CORRECTOR)
.setValidator(InfiniteOrPositiveValidators.INT_INSTANCE)
.setRestartAllServices()
.build();
/**
* @see HornetQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME
*/
public static final AttributeDefinition CONNECTION_LOAD_BALANCING_CLASS_NAME = SimpleAttributeDefinitionBuilder.create("connection-load-balancing-policy-class-name", STRING)
.setDefaultValue(new ModelNode("org.hornetq.api.core.client.loadbalance.RoundRobinConnectionLoadBalancingPolicy"))
.setRequired(false)
.setAllowExpression(false)
.setRestartAllServices()
.build();
/**
* @see HornetQClient.DEFAULT_CONNECTION_TTL
*/
public static final AttributeDefinition CONNECTION_TTL = new SimpleAttributeDefinitionBuilder("connection-ttl", LONG)
.setDefaultValue(new ModelNode(60000L))
.setRequired(false)
.setAllowExpression(true)
.setValidator(InfiniteOrPositiveValidators.LONG_INSTANCE)
.setMeasurementUnit(MILLISECONDS)
.setRestartAllServices()
.build();
/**
* @see HornetQClient.DEFAULT_CONSUMER_MAX_RATE
*/
public static final AttributeDefinition CONSUMER_MAX_RATE = SimpleAttributeDefinitionBuilder.create("consumer-max-rate", INT)
.setDefaultValue(new ModelNode(-1))
.setMeasurementUnit(PER_SECOND)
.setRequired(false)
.setAllowExpression(true)
.setCorrector(InfiniteOrPositiveValidators.NEGATIVE_VALUE_CORRECTOR)
.setValidator(InfiniteOrPositiveValidators.INT_INSTANCE)
.setRestartAllServices()
.build();
/**
* @see HornetQClient.DEFAULT_CONSUMER_WINDOW_SIZE
*/
public static final AttributeDefinition CONSUMER_WINDOW_SIZE = SimpleAttributeDefinitionBuilder.create("consumer-window-size", INT)
.setDefaultValue(new ModelNode(1024 * 1024))
.setMeasurementUnit(BYTES)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see HornetQClient.DEFAULT_ACK_BATCH_SIZE
*/
public static final AttributeDefinition DUPS_OK_BATCH_SIZE = SimpleAttributeDefinitionBuilder.create("dups-ok-batch-size", INT)
.setDefaultValue(new ModelNode(1024 * 1024))
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
public static final StringListAttributeDefinition ENTRIES = new StringListAttributeDefinition.Builder(CommonAttributes.ENTRIES)
.setRequired(true)
.setAllowExpression(true)
.setListValidator(Validators.noDuplicateElements(new StringLengthValidator(1, false, true)))
.setAttributeParser(AttributeParser.STRING_LIST)
.setAttributeMarshaller(AttributeMarshaller.STRING_LIST)
.setRestartAllServices()
.build();
public static final AttributeDefinition FACTORY_TYPE = create("factory-type", STRING)
.setDefaultValue(new ModelNode().set(HornetQConnectionFactoryType.GENERIC.toString()))
.setValidator(HornetQConnectionFactoryType.VALIDATOR)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see HornetQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION
*/
public static final AttributeDefinition FAILOVER_ON_INITIAL_CONNECTION = SimpleAttributeDefinitionBuilder.create("failover-on-initial-connection", BOOLEAN)
.setDefaultValue(ModelNode.FALSE)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
public static final AttributeDefinition GROUP_ID = SimpleAttributeDefinitionBuilder.create("group-id", STRING)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
public static final SimpleAttributeDefinition HA = create("ha", BOOLEAN)
.setDefaultValue(ModelNode.FALSE)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see HornetQClient.INITIAL_CONNECT_ATTEMPTS
*/
public static final AttributeDefinition INITIAL_CONNECT_ATTEMPTS = SimpleAttributeDefinitionBuilder.create("initial-connect-attempts", INT)
.setDefaultValue(new ModelNode(1))
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see HornetQClient.DEFAULT_INITIAL_MESSAGE_PACKET_SIZE
*/
public static final AttributeDefinition INITIAL_MESSAGE_PACKET_SIZE = SimpleAttributeDefinitionBuilder.create("initial-message-packet-size", INT)
.setDefaultValue(new ModelNode(1500))
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see HornetQClient.DEFAULT_MAX_RETRY_INTERVAL
*/
public static final AttributeDefinition MAX_RETRY_INTERVAL = SimpleAttributeDefinitionBuilder.create("max-retry-interval", LONG)
.setDefaultValue(new ModelNode(2000L))
.setMeasurementUnit(MILLISECONDS)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE
*/
public static final AttributeDefinition MIN_LARGE_MESSAGE_SIZE = SimpleAttributeDefinitionBuilder.create("min-large-message-size", INT)
.setDefaultValue(new ModelNode(100 * 1024))
.setMeasurementUnit(BYTES)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see HornetQClient.DEFAULT_PRE_ACKNOWLEDGE
*/
public static final AttributeDefinition PRE_ACKNOWLEDGE = SimpleAttributeDefinitionBuilder.create("pre-acknowledge", BOOLEAN)
.setDefaultValue(ModelNode.FALSE)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see HornetQClient.DEFAULT_PRODUCER_MAX_RATE
*/
public static final AttributeDefinition PRODUCER_MAX_RATE = SimpleAttributeDefinitionBuilder.create("producer-max-rate", INT)
.setDefaultValue(new ModelNode(-1))
.setMeasurementUnit(PER_SECOND)
.setRequired(false)
.setAllowExpression(true)
.setCorrector(InfiniteOrPositiveValidators.NEGATIVE_VALUE_CORRECTOR)
.setValidator(InfiniteOrPositiveValidators.INT_INSTANCE)
.setRestartAllServices()
.build();
/**
* @see HornetQClient.DEFAULT_PRODUCER_WINDOW_SIZE
*/
public static final AttributeDefinition PRODUCER_WINDOW_SIZE = SimpleAttributeDefinitionBuilder.create("producer-window-size", INT)
.setDefaultValue(new ModelNode(64 * 1024))
.setMeasurementUnit(BYTES)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see HornetQClient.DEFAULT_RECONNECT_ATTEMPTS
*/
public static final AttributeDefinition RECONNECT_ATTEMPTS = create("reconnect-attempts", INT)
.setDefaultValue(ModelNode.ZERO)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see HornetQClient.DEFAULT_RETRY_INTERVAL
*/
public static final AttributeDefinition RETRY_INTERVAL = SimpleAttributeDefinitionBuilder.create("retry-interval", LONG)
.setDefaultValue(new ModelNode(2000L))
.setMeasurementUnit(MILLISECONDS)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see HornetQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER
*/
public static final AttributeDefinition RETRY_INTERVAL_MULTIPLIER = create("retry-interval-multiplier", DOUBLE)
.setDefaultValue(new ModelNode(1.0d))
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see ActiveMQDefaultConfiguration#getDefaultScheduledThreadPoolMaxSize
*/
public static final AttributeDefinition SCHEDULED_THREAD_POOL_MAX_SIZE = SimpleAttributeDefinitionBuilder.create("scheduled-thread-pool-max-size", INT)
.setDefaultValue(new ModelNode(5))
.setRequired(false)
.setAllowExpression(true)
.setCorrector(InfiniteOrPositiveValidators.NEGATIVE_VALUE_CORRECTOR)
.setValidator(InfiniteOrPositiveValidators.INT_INSTANCE)
.setRestartAllServices()
.build();
/**
* @see ActiveMQDefaultConfiguration#getDefaultThreadPoolMaxSize
*/
public static final AttributeDefinition THREAD_POOL_MAX_SIZE = SimpleAttributeDefinitionBuilder.create("thread-pool-max-size", INT)
.setDefaultValue(new ModelNode(30))
.setRequired(false)
.setAllowExpression(true)
.setCorrector(InfiniteOrPositiveValidators.NEGATIVE_VALUE_CORRECTOR)
.setValidator(InfiniteOrPositiveValidators.INT_INSTANCE)
.setRestartAllServices()
.build();
/**
* @see HornetQClient#DEFAULT_ACK_BATCH_SIZE
*/
public static final AttributeDefinition TRANSACTION_BATCH_SIZE = SimpleAttributeDefinitionBuilder.create("transaction-batch-size", INT)
.setDefaultValue(new ModelNode().set(1024 * 1024))
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see HornetQClient#DEFAULT_USE_GLOBAL_POOLS
*/
public static final AttributeDefinition USE_GLOBAL_POOLS = SimpleAttributeDefinitionBuilder.create("use-global-pools", BOOLEAN)
.setDefaultValue(ModelNode.TRUE)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
public static final AttributeDefinition DISCOVERY_GROUP = SimpleAttributeDefinitionBuilder.create(CommonAttributes.DISCOVERY_GROUP, STRING)
.setAlternatives(CommonAttributes.CONNECTORS)
.setRequired(false)
.setRestartAllServices()
.build();
public static final StringListAttributeDefinition CONNECTORS = new StringListAttributeDefinition.Builder(CommonAttributes.CONNECTORS)
.setAlternatives(CommonAttributes.DISCOVERY_GROUP)
.setRequired(false)
.setAttributeParser(AttributeParser.STRING_LIST)
.setAttributeMarshaller(AttributeMarshaller.STRING_LIST)
.setRestartAllServices()
.build();
/**
* @see ActiveMQClient.DEFAULT_CALL_TIMEOUT
*/
public static final AttributeDefinition CALL_TIMEOUT = create("call-timeout", LONG)
.setDefaultValue(new ModelNode(30000L))
.setMeasurementUnit(MILLISECONDS)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
public static final SimpleAttributeDefinition CALL_FAILOVER_TIMEOUT = create("call-failover-timeout", LONG)
// ActiveMQClient.DEFAULT_CALL_FAILOVER_TIMEOUT was changed from -1 to 30000 in ARTEMIS-255
.setDefaultValue(new ModelNode(-1L))
.setRequired(false)
.setAllowExpression(true)
.setMeasurementUnit(MILLISECONDS)
.setRestartAllServices()
.build();
public static final SimpleAttributeDefinition CLIENT_ID = create("client-id", ModelType.STRING)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
static final AttributeDefinition[] ATTRIBUTES = {
ENTRIES,
AUTO_GROUP,
BLOCK_ON_ACKNOWLEDGE,
BLOCK_ON_DURABLE_SEND,
BLOCK_ON_NON_DURABLE_SEND,
CACHE_LARGE_MESSAGE_CLIENT,
CALL_FAILOVER_TIMEOUT,
CALL_TIMEOUT,
CLIENT_FAILURE_CHECK_PERIOD,
CLIENT_ID,
COMPRESS_LARGE_MESSAGES,
CONFIRMATION_WINDOW_SIZE,
CONNECTION_LOAD_BALANCING_CLASS_NAME,
CONNECTION_TTL,
CONSUMER_MAX_RATE,
CONSUMER_WINDOW_SIZE,
DUPS_OK_BATCH_SIZE,
FACTORY_TYPE,
FAILOVER_ON_INITIAL_CONNECTION,
GROUP_ID,
HA,
INITIAL_CONNECT_ATTEMPTS,
INITIAL_MESSAGE_PACKET_SIZE,
MAX_RETRY_INTERVAL,
MIN_LARGE_MESSAGE_SIZE,
PRE_ACKNOWLEDGE,
PRODUCER_MAX_RATE,
PRODUCER_WINDOW_SIZE,
RECONNECT_ATTEMPTS,
RETRY_INTERVAL,
RETRY_INTERVAL_MULTIPLIER,
SCHEDULED_THREAD_POOL_MAX_SIZE,
THREAD_POOL_MAX_SIZE,
TRANSACTION_BATCH_SIZE,
USE_GLOBAL_POOLS,
DISCOVERY_GROUP,
CONNECTORS
};
public LegacyConnectionFactoryDefinition() {
super(new SimpleResourceDefinition.Parameters(
MessagingExtension.LEGACY_CONNECTION_FACTORY_PATH,
MessagingExtension.getResourceDescriptionResolver(CommonAttributes.CONNECTION_FACTORY))
.setAddHandler(LegacyConnectionFactoryAdd.INSTANCE)
.setRemoveHandler(LegacyConnectionFactoryRemove.INSTANCE)
.setAdditionalPackages(RuntimePackageDependency.required("org.hornetq.client")));
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return Arrays.asList(ATTRIBUTES);
}
public enum HornetQConnectionFactoryType {
GENERIC,
TOPIC,
QUEUE,
XA_GENERIC,
XA_QUEUE,
XA_TOPIC;
static final ParameterValidator VALIDATOR = new EnumValidator<>(HornetQConnectionFactoryType.class, EnumSet.allOf(HornetQConnectionFactoryType.class));
}
}
| 20,680
| 40.279441
| 177
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/legacy/LegacyConnectionFactoryService.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.wildfly.extension.messaging.activemq.jms.legacy;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.LEGACY;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jakarta.jms.ConnectionFactory;
import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.hornetq.api.config.HornetQDefaultConfiguration;
import org.hornetq.api.core.BroadcastEndpointFactoryConfiguration;
import org.hornetq.api.core.DiscoveryGroupConfiguration;
import org.hornetq.api.core.TransportConfiguration;
import org.hornetq.api.core.UDPBroadcastGroupConfiguration;
import org.hornetq.api.jms.HornetQJMSClient;
import org.hornetq.api.jms.JMSFactoryType;
import org.hornetq.core.remoting.impl.netty.TransportConstants;
import org.hornetq.jms.client.HornetQConnectionFactory;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.wildfly.extension.messaging.activemq.ActiveMQActivationService;
import org.wildfly.extension.messaging.activemq.jms.JMSServices;
import org.wildfly.extension.messaging.activemq.logging.MessagingLogger;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2015 Red Hat inc.
*/
public class LegacyConnectionFactoryService implements Service<ConnectionFactory> {
/**
* Map ActiveMQ parameters key (using CameCalse convention) to HornetQ parameter keys (using lisp-case convention)
*/
private static final Map<String, String> PARAM_KEY_MAPPING = new HashMap<>();
static {
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.SSL_ENABLED_PROP_NAME,
TransportConstants.SSL_ENABLED_PROP_NAME);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.HTTP_ENABLED_PROP_NAME,
TransportConstants.HTTP_ENABLED_PROP_NAME);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.HTTP_CLIENT_IDLE_PROP_NAME,
TransportConstants.HTTP_CLIENT_IDLE_PROP_NAME);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.HTTP_CLIENT_IDLE_SCAN_PERIOD,
TransportConstants.HTTP_CLIENT_IDLE_SCAN_PERIOD);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.HTTP_REQUIRES_SESSION_ID,
TransportConstants.HTTP_REQUIRES_SESSION_ID);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.HTTP_UPGRADE_ENABLED_PROP_NAME,
TransportConstants.HTTP_UPGRADE_ENABLED_PROP_NAME);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME,
TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.USE_SERVLET_PROP_NAME,
TransportConstants.USE_SERVLET_PROP_NAME);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.SERVLET_PATH,
TransportConstants.SERVLET_PATH);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.USE_NIO_PROP_NAME,
TransportConstants.USE_NIO_PROP_NAME);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.USE_NIO_GLOBAL_WORKER_POOL_PROP_NAME,
TransportConstants.USE_NIO_GLOBAL_WORKER_POOL_PROP_NAME);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.LOCAL_ADDRESS_PROP_NAME,
TransportConstants.LOCAL_ADDRESS_PROP_NAME);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.KEYSTORE_PROVIDER_PROP_NAME,
TransportConstants.KEYSTORE_PROVIDER_PROP_NAME);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.KEYSTORE_PATH_PROP_NAME,
TransportConstants.KEYSTORE_PATH_PROP_NAME);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.KEYSTORE_PASSWORD_PROP_NAME,
TransportConstants.KEYSTORE_PASSWORD_PROP_NAME);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.TRUSTSTORE_PROVIDER_PROP_NAME,
TransportConstants.TRUSTSTORE_PROVIDER_PROP_NAME);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.TRUSTSTORE_PATH_PROP_NAME,
TransportConstants.TRUSTSTORE_PATH_PROP_NAME);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.TRUSTSTORE_PASSWORD_PROP_NAME,
TransportConstants.TRUSTSTORE_PASSWORD_PROP_NAME);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.ENABLED_CIPHER_SUITES_PROP_NAME,
TransportConstants.ENABLED_CIPHER_SUITES_PROP_NAME);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.ENABLED_PROTOCOLS_PROP_NAME,
TransportConstants.ENABLED_PROTOCOLS_PROP_NAME);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.TCP_NODELAY_PROPNAME,
TransportConstants.TCP_NODELAY_PROPNAME);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.TCP_SENDBUFFER_SIZE_PROPNAME,
TransportConstants.TCP_SENDBUFFER_SIZE_PROPNAME);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.TCP_RECEIVEBUFFER_SIZE_PROPNAME,
TransportConstants.TCP_RECEIVEBUFFER_SIZE_PROPNAME);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.NIO_REMOTING_THREADS_PROPNAME,
TransportConstants.NIO_REMOTING_THREADS_PROPNAME);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.BATCH_DELAY,
TransportConstants.BATCH_DELAY);
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.NIO_REMOTING_THREADS_PROPNAME,
TransportConstants.NIO_REMOTING_THREADS_PROPNAME);
PARAM_KEY_MAPPING.put(
ActiveMQDefaultConfiguration.getPropMaskPassword(),
HornetQDefaultConfiguration.getPropMaskPassword());
PARAM_KEY_MAPPING.put(
ActiveMQDefaultConfiguration.getPropPasswordCodec(),
HornetQDefaultConfiguration.getPropPasswordCodec());
PARAM_KEY_MAPPING.put(
org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.NETTY_CONNECT_TIMEOUT,
TransportConstants.NETTY_CONNECT_TIMEOUT);
}
private final InjectedValue<ActiveMQServer> injectedActiveMQServer = new InjectedValue<ActiveMQServer>();
private final HornetQConnectionFactory uncompletedConnectionFactory;
private final String discoveryGroupName;
private final List<String> connectors;
private HornetQConnectionFactory connectionFactory;
public LegacyConnectionFactoryService(HornetQConnectionFactory uncompletedConnectionFactory, String discoveryGroupName, List<String> connectors) {
this.uncompletedConnectionFactory = uncompletedConnectionFactory;
this.discoveryGroupName = discoveryGroupName;
this.connectors = connectors;
}
@Override
public void start(StartContext context) throws StartException {
ActiveMQServer activeMQServer = injectedActiveMQServer.getValue();
DiscoveryGroupConfiguration discoveryGroupConfiguration = null;
if (discoveryGroupName != null) {
if (activeMQServer.getConfiguration().getDiscoveryGroupConfigurations().containsKey(discoveryGroupName)) {
discoveryGroupConfiguration = translateDiscoveryGroupConfiguration(activeMQServer.getConfiguration().getDiscoveryGroupConfigurations().get(discoveryGroupName));
} else {
throw MessagingLogger.ROOT_LOGGER.discoveryGroupIsNotDefined(discoveryGroupName);
}
}
TransportConfiguration[] transportConfigurations = translateTransportGroupConfigurations(activeMQServer.getConfiguration().getConnectorConfigurations(), connectors);
JMSFactoryType factoryType = JMSFactoryType.valueOf(uncompletedConnectionFactory.getFactoryType());
if (uncompletedConnectionFactory.isHA()) {
if (discoveryGroupConfiguration != null) {
connectionFactory = HornetQJMSClient.createConnectionFactoryWithHA(discoveryGroupConfiguration, factoryType);
} else {
connectionFactory = HornetQJMSClient.createConnectionFactoryWithHA(factoryType, transportConfigurations);
}
} else {
if (discoveryGroupConfiguration != null) {
connectionFactory = HornetQJMSClient.createConnectionFactoryWithoutHA(discoveryGroupConfiguration, factoryType);
} else {
connectionFactory = HornetQJMSClient.createConnectionFactoryWithoutHA(factoryType, transportConfigurations);
}
}
connectionFactory.setAutoGroup(uncompletedConnectionFactory.isAutoGroup());
connectionFactory.setBlockOnAcknowledge(uncompletedConnectionFactory.isBlockOnAcknowledge());
connectionFactory.setBlockOnDurableSend(uncompletedConnectionFactory.isBlockOnDurableSend());
connectionFactory.setBlockOnNonDurableSend(uncompletedConnectionFactory.isBlockOnNonDurableSend());
connectionFactory.setCacheLargeMessagesClient(uncompletedConnectionFactory.isCacheLargeMessagesClient());
connectionFactory.setCallFailoverTimeout(uncompletedConnectionFactory.getCallFailoverTimeout());
connectionFactory.setCallTimeout(uncompletedConnectionFactory.getCallTimeout());
connectionFactory.setClientFailureCheckPeriod(uncompletedConnectionFactory.getClientFailureCheckPeriod());
connectionFactory.setClientID(uncompletedConnectionFactory.getClientID());
connectionFactory.setCompressLargeMessage(uncompletedConnectionFactory.isCompressLargeMessage());
connectionFactory.setConfirmationWindowSize(uncompletedConnectionFactory.getConfirmationWindowSize());
connectionFactory.setConnectionLoadBalancingPolicyClassName(uncompletedConnectionFactory.getConnectionLoadBalancingPolicyClassName());
connectionFactory.setConnectionTTL(uncompletedConnectionFactory.getConnectionTTL());
connectionFactory.setConsumerMaxRate(uncompletedConnectionFactory.getConsumerMaxRate());
connectionFactory.setConsumerWindowSize(uncompletedConnectionFactory.getConsumerWindowSize());
connectionFactory.setConfirmationWindowSize(uncompletedConnectionFactory.getConfirmationWindowSize());
connectionFactory.setDupsOKBatchSize(uncompletedConnectionFactory.getDupsOKBatchSize());
connectionFactory.setFailoverOnInitialConnection(uncompletedConnectionFactory.isFailoverOnInitialConnection());
connectionFactory.setGroupID(uncompletedConnectionFactory.getGroupID());
connectionFactory.setInitialConnectAttempts(uncompletedConnectionFactory.getInitialConnectAttempts());
connectionFactory.setInitialMessagePacketSize(uncompletedConnectionFactory.getInitialMessagePacketSize());
connectionFactory.setMaxRetryInterval(uncompletedConnectionFactory.getMaxRetryInterval());
connectionFactory.setMinLargeMessageSize(uncompletedConnectionFactory.getMinLargeMessageSize());
connectionFactory.setPreAcknowledge(uncompletedConnectionFactory.isPreAcknowledge());
connectionFactory.setProducerMaxRate(uncompletedConnectionFactory.getProducerMaxRate());
connectionFactory.setProducerWindowSize(uncompletedConnectionFactory.getProducerWindowSize());
connectionFactory.setReconnectAttempts(uncompletedConnectionFactory.getReconnectAttempts());
connectionFactory.setRetryInterval(uncompletedConnectionFactory.getRetryInterval());
connectionFactory.setRetryIntervalMultiplier(uncompletedConnectionFactory.getRetryIntervalMultiplier());
connectionFactory.setScheduledThreadPoolMaxSize(uncompletedConnectionFactory.getScheduledThreadPoolMaxSize());
connectionFactory.setThreadPoolMaxSize(uncompletedConnectionFactory.getThreadPoolMaxSize());
connectionFactory.setTransactionBatchSize(uncompletedConnectionFactory.getTransactionBatchSize());
connectionFactory.setUseGlobalPools(uncompletedConnectionFactory.isUseGlobalPools());
}
@Override
public void stop(StopContext context) {
connectionFactory = null;
}
@Override
public ConnectionFactory getValue() throws IllegalStateException, IllegalArgumentException {
return connectionFactory;
}
public static LegacyConnectionFactoryService installService(final String name,
final ServiceName activeMQServerServiceName,
final ServiceTarget serviceTarget,
final HornetQConnectionFactory uncompletedConnectionFactory,
final String discoveryGroupName,
final List<String> connectors) {
final LegacyConnectionFactoryService service = new LegacyConnectionFactoryService(uncompletedConnectionFactory, discoveryGroupName, connectors);
final ServiceName serviceName = JMSServices.getConnectionFactoryBaseServiceName(activeMQServerServiceName).append(LEGACY, name);
final ServiceBuilder sb = serviceTarget.addService(serviceName, service);
sb.requires(ActiveMQActivationService.getServiceName(activeMQServerServiceName));
sb.addDependency(activeMQServerServiceName, ActiveMQServer.class, service.injectedActiveMQServer);
sb.setInitialMode(ServiceController.Mode.PASSIVE);
sb.install();
return service;
}
private DiscoveryGroupConfiguration translateDiscoveryGroupConfiguration(org.apache.activemq.artemis.api.core.DiscoveryGroupConfiguration newDiscoveryGroupConfiguration) throws StartException {
org.apache.activemq.artemis.api.core.BroadcastEndpointFactory newBroadcastEndpointFactory = newDiscoveryGroupConfiguration.getBroadcastEndpointFactory();
BroadcastEndpointFactoryConfiguration legacyBroadcastEndpointFactory;
if (newBroadcastEndpointFactory instanceof org.apache.activemq.artemis.api.core.UDPBroadcastEndpointFactory) {
org.apache.activemq.artemis.api.core.UDPBroadcastEndpointFactory factory = (org.apache.activemq.artemis.api.core.UDPBroadcastEndpointFactory) newBroadcastEndpointFactory;
legacyBroadcastEndpointFactory = new UDPBroadcastGroupConfiguration(
factory.getGroupAddress(),
factory.getGroupPort(),
factory.getLocalBindAddress(),
factory.getLocalBindPort());
} else if (newBroadcastEndpointFactory instanceof org.apache.activemq.artemis.api.core.ChannelBroadcastEndpointFactory) {
org.apache.activemq.artemis.api.core.ChannelBroadcastEndpointFactory factory = (org.apache.activemq.artemis.api.core.ChannelBroadcastEndpointFactory) newBroadcastEndpointFactory;
legacyBroadcastEndpointFactory = new org.hornetq.api.core.JGroupsBroadcastGroupConfiguration(
factory.getChannel(),
factory.getChannelName());
} else {
throw MessagingLogger.ROOT_LOGGER.unsupportedBroadcastGroupConfigurationForLegacy(newBroadcastEndpointFactory.getClass().getName());
}
return new DiscoveryGroupConfiguration(newDiscoveryGroupConfiguration.getName(),
newDiscoveryGroupConfiguration.getRefreshTimeout(),
newDiscoveryGroupConfiguration.getDiscoveryInitialWaitTimeout(),
legacyBroadcastEndpointFactory);
}
private TransportConfiguration[] translateTransportGroupConfigurations(Map<String, org.apache.activemq.artemis.api.core.TransportConfiguration> connectorConfigurations, List<String> connectors) throws StartException {
List<TransportConfiguration> legacyConnectorConfigurations = new ArrayList<>();
for (String connectorName : connectors) {
org.apache.activemq.artemis.api.core.TransportConfiguration newTransportConfiguration = connectorConfigurations.get(connectorName);
String legacyFactoryClassName = translateFactoryClassName(newTransportConfiguration.getFactoryClassName());
Map legacyParams = translateParams(newTransportConfiguration.getParams());
TransportConfiguration legacyTransportConfiguration = new TransportConfiguration(
legacyFactoryClassName,
legacyParams,
newTransportConfiguration.getName());
legacyConnectorConfigurations.add(legacyTransportConfiguration);
}
return legacyConnectorConfigurations.toArray(new TransportConfiguration[legacyConnectorConfigurations.size()]);
}
private String translateFactoryClassName(String newFactoryClassName) throws StartException {
if (newFactoryClassName.equals(org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactory.class.getName())) {
return org.hornetq.core.remoting.impl.netty.NettyConnectorFactory.class.getName();
} else {
throw MessagingLogger.ROOT_LOGGER.unsupportedConnectorFactoryForLegacy(newFactoryClassName.getClass().getName());
}
}
private Map translateParams(Map<String, Object> newParams) {
Map<String, Object> legacyParams = new HashMap<>();
for (Map.Entry<String, Object> newEntry : newParams.entrySet()) {
String newKey = newEntry.getKey();
Object value = newEntry.getValue();
String legacyKey = PARAM_KEY_MAPPING.getOrDefault(newKey, newKey);
if (org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.ACTIVEMQ_SERVER_NAME.equals(legacyKey)) {
// property specific to ActiveMQ that can not be mapped to HornetQ
continue;
}
legacyParams.put(legacyKey, value);
}
return legacyParams;
}
}
| 20,684
| 61.304217
| 221
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/ha/ReplicationColocatedDefinition.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.wildfly.extension.messaging.activemq.ha;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.HA_POLICY;
import static org.wildfly.extension.messaging.activemq.MessagingExtension.CONFIGURATION_MASTER_PATH;
import static org.wildfly.extension.messaging.activemq.MessagingExtension.CONFIGURATION_PRIMARY_PATH;
import static org.wildfly.extension.messaging.activemq.MessagingExtension.CONFIGURATION_SECONDARY_PATH;
import static org.wildfly.extension.messaging.activemq.MessagingExtension.CONFIGURATION_SLAVE_PATH;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.BACKUP_PORT_OFFSET;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.BACKUP_REQUEST_RETRIES;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.BACKUP_REQUEST_RETRY_INTERVAL;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.EXCLUDED_CONNECTORS;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.MAX_BACKUPS;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.REQUEST_BACKUP;
import static org.wildfly.extension.messaging.activemq.ha.ManagementHelper.createAddOperation;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.jboss.as.controller.AbstractWriteAttributeHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.PersistentResourceDefinition;
import org.jboss.as.controller.ReloadRequiredRemoveStepHandler;
import org.jboss.as.controller.registry.AliasEntry;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.wildfly.extension.messaging.activemq.ActiveMQReloadRequiredHandlers;
import org.wildfly.extension.messaging.activemq.MessagingExtension;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2014 Red Hat inc.
*/
public class ReplicationColocatedDefinition extends PersistentResourceDefinition {
public static final Collection<AttributeDefinition> ATTRIBUTES = Collections.unmodifiableList(Arrays.asList(
REQUEST_BACKUP,
BACKUP_REQUEST_RETRIES,
BACKUP_REQUEST_RETRY_INTERVAL,
MAX_BACKUPS,
BACKUP_PORT_OFFSET,
EXCLUDED_CONNECTORS
));
public ReplicationColocatedDefinition() {
super(MessagingExtension.REPLICATION_COLOCATED_PATH,
MessagingExtension.getResourceDescriptionResolver(HA_POLICY),
createAddOperation(HA_POLICY, false, ATTRIBUTES),
ReloadRequiredRemoveStepHandler.INSTANCE);
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
AbstractWriteAttributeHandler writeAttribute = new ActiveMQReloadRequiredHandlers.WriteAttributeHandler(ATTRIBUTES);
for (AttributeDefinition attribute : ATTRIBUTES) {
resourceRegistration.registerReadWriteAttribute(attribute, null, writeAttribute);
}
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return ATTRIBUTES;
}
@Override
public void registerChildren(ManagementResourceRegistration resourceRegistration) {
super.registerChildren(resourceRegistration);
resourceRegistration.registerAlias(CONFIGURATION_MASTER_PATH, createAlias(resourceRegistration, CONFIGURATION_PRIMARY_PATH));
resourceRegistration.registerAlias(CONFIGURATION_SLAVE_PATH, createAlias(resourceRegistration, CONFIGURATION_SECONDARY_PATH));
}
private static AliasEntry createAlias(ManagementResourceRegistration resourceRegistration, PathElement target) {
return new AliasEntry(resourceRegistration.getSubModel(PathAddress.pathAddress(target))) {
@Override
public PathAddress convertToTargetAddress(PathAddress aliasAddress, AliasContext aliasContext) {
return aliasAddress.getParent().append(target);
}
};
}
@Override
protected List<? extends PersistentResourceDefinition> getChildren() {
return List.of(
new ReplicationPrimaryDefinition(MessagingExtension.CONFIGURATION_PRIMARY_PATH, true, true),
new ReplicationSecondaryDefinition(MessagingExtension.CONFIGURATION_SECONDARY_PATH, true, true));
}
}
| 5,456
| 48.162162
| 134
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/ha/SharedStoreColocatedDefinition.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.wildfly.extension.messaging.activemq.ha;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.HA_POLICY;
import static org.wildfly.extension.messaging.activemq.MessagingExtension.CONFIGURATION_MASTER_PATH;
import static org.wildfly.extension.messaging.activemq.MessagingExtension.CONFIGURATION_PRIMARY_PATH;
import static org.wildfly.extension.messaging.activemq.MessagingExtension.CONFIGURATION_SECONDARY_PATH;
import static org.wildfly.extension.messaging.activemq.MessagingExtension.CONFIGURATION_SLAVE_PATH;
import static org.wildfly.extension.messaging.activemq.MessagingExtension.SHARED_STORE_COLOCATED_PATH;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.BACKUP_PORT_OFFSET;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.BACKUP_REQUEST_RETRIES;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.BACKUP_REQUEST_RETRY_INTERVAL;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.MAX_BACKUPS;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.REQUEST_BACKUP;
import static org.wildfly.extension.messaging.activemq.ha.ManagementHelper.createAddOperation;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.jboss.as.controller.AbstractWriteAttributeHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.PersistentResourceDefinition;
import org.jboss.as.controller.ReloadRequiredRemoveStepHandler;
import org.jboss.as.controller.registry.AliasEntry;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.wildfly.extension.messaging.activemq.ActiveMQReloadRequiredHandlers;
import org.wildfly.extension.messaging.activemq.MessagingExtension;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2014 Red Hat inc.
*/
public class SharedStoreColocatedDefinition extends PersistentResourceDefinition {
public static final Collection<AttributeDefinition> ATTRIBUTES = Collections.unmodifiableList(Arrays.asList(
(AttributeDefinition) REQUEST_BACKUP,
BACKUP_REQUEST_RETRIES,
BACKUP_REQUEST_RETRY_INTERVAL,
MAX_BACKUPS,
BACKUP_PORT_OFFSET
));
public SharedStoreColocatedDefinition() {
super(SHARED_STORE_COLOCATED_PATH,
MessagingExtension.getResourceDescriptionResolver(HA_POLICY),
createAddOperation(HA_POLICY, false, ATTRIBUTES),
ReloadRequiredRemoveStepHandler.INSTANCE);
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
AbstractWriteAttributeHandler writeAttribute = new ActiveMQReloadRequiredHandlers.WriteAttributeHandler(ATTRIBUTES);
for (AttributeDefinition attribute : ATTRIBUTES) {
resourceRegistration.registerReadWriteAttribute(attribute, null, writeAttribute);
}
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return ATTRIBUTES;
}
@Override
public void registerChildren(ManagementResourceRegistration resourceRegistration) {
super.registerChildren(resourceRegistration);
resourceRegistration.registerAlias(CONFIGURATION_MASTER_PATH, createAlias(resourceRegistration, CONFIGURATION_PRIMARY_PATH));
resourceRegistration.registerAlias(CONFIGURATION_SLAVE_PATH, createAlias(resourceRegistration, CONFIGURATION_SECONDARY_PATH));
}
private static AliasEntry createAlias(ManagementResourceRegistration resourceRegistration, PathElement target) {
return new AliasEntry(resourceRegistration.getSubModel(PathAddress.pathAddress(target))) {
@Override
public PathAddress convertToTargetAddress(PathAddress aliasAddress, AliasContext aliasContext) {
return aliasAddress.getParent().append(target);
}
};
}
@Override
protected List<? extends PersistentResourceDefinition> getChildren() {
return List.of(
new SharedStorePrimaryDefinition(MessagingExtension.CONFIGURATION_PRIMARY_PATH, true),
new SharedStoreSecondaryDefinition(MessagingExtension.CONFIGURATION_SECONDARY_PATH, true));
}
}
| 5,428
| 47.90991
| 134
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/ha/LiveOnlyDefinition.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.wildfly.extension.messaging.activemq.ha;
import static org.jboss.as.controller.OperationContext.Stage.MODEL;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.HA_POLICY;
import java.util.Collection;
import org.jboss.as.controller.AbstractAddStepHandler;
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.PersistentResourceDefinition;
import org.jboss.as.controller.ReloadRequiredRemoveStepHandler;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.wildfly.extension.messaging.activemq.ActiveMQReloadRequiredHandlers;
import org.wildfly.extension.messaging.activemq.MessagingExtension;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2014 Red Hat inc.
*/
public class LiveOnlyDefinition extends PersistentResourceDefinition {
private static final Collection<AttributeDefinition> ATTRIBUTES = ScaleDownAttributes.SCALE_DOWN_ATTRIBUTES;
private static final AbstractAddStepHandler ADD = new ActiveMQReloadRequiredHandlers.AddStepHandler(ATTRIBUTES) {
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
super.execute(context, operation);
context.addStep(ManagementHelper.checkNoOtherSibling(HA_POLICY), MODEL);
}
@Override
protected void populateModel(ModelNode operation, ModelNode model) throws OperationFailedException {
super.populateModel(operation, model);
}
};
private static final AbstractWriteAttributeHandler WRITE_ATTRIBUTE = new ActiveMQReloadRequiredHandlers.WriteAttributeHandler(ATTRIBUTES);
public LiveOnlyDefinition() {
super(MessagingExtension.LIVE_ONLY_PATH,
MessagingExtension.getResourceDescriptionResolver(HA_POLICY),
ADD,
ReloadRequiredRemoveStepHandler.INSTANCE);
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
for (AttributeDefinition attribute : ATTRIBUTES) {
resourceRegistration.registerReadWriteAttribute(attribute, null, WRITE_ATTRIBUTE);
}
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return ATTRIBUTES;
}
}
| 3,548
| 41.759036
| 142
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/ha/ReplicationSecondaryDefinition.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.wildfly.extension.messaging.activemq.ha;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.HA_POLICY;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.ALLOW_FAILBACK;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.CLUSTER_NAME;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.GROUP_NAME;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.INITIAL_REPLICATION_SYNC_TIMEOUT;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.MAX_SAVED_REPLICATED_JOURNAL_SIZE;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.RESTART_BACKUP;
import static org.wildfly.extension.messaging.activemq.ha.ManagementHelper.createAddOperation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import org.jboss.as.controller.AbstractWriteAttributeHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.PersistentResourceDefinition;
import org.jboss.as.controller.ReloadRequiredRemoveStepHandler;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.wildfly.extension.messaging.activemq.ActiveMQReloadRequiredHandlers;
import org.wildfly.extension.messaging.activemq.MessagingExtension;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2014 Red Hat inc.
*/
public class ReplicationSecondaryDefinition extends PersistentResourceDefinition {
public static final Collection<AttributeDefinition> ATTRIBUTES;
static {
Collection<AttributeDefinition> attributes = new ArrayList<>();
attributes.add(CLUSTER_NAME);
attributes.add(GROUP_NAME);
attributes.add(ALLOW_FAILBACK);
attributes.add(INITIAL_REPLICATION_SYNC_TIMEOUT);
attributes.add(MAX_SAVED_REPLICATED_JOURNAL_SIZE);
attributes.add(RESTART_BACKUP);
attributes.addAll(ScaleDownAttributes.SCALE_DOWN_ATTRIBUTES);
ATTRIBUTES = Collections.unmodifiableCollection(attributes);
}
private final boolean registerRuntime;
public ReplicationSecondaryDefinition(PathElement path, boolean allowSibling, boolean registerRuntime) {
super(path,
MessagingExtension.getResourceDescriptionResolver(HA_POLICY),
createAddOperation(path.getKey(), allowSibling, ATTRIBUTES),
ReloadRequiredRemoveStepHandler.INSTANCE);
this.registerRuntime = registerRuntime;
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
AbstractWriteAttributeHandler writeAttribute = new ActiveMQReloadRequiredHandlers.WriteAttributeHandler(ATTRIBUTES);
for (AttributeDefinition attribute : ATTRIBUTES) {
resourceRegistration.registerReadWriteAttribute(attribute, null, writeAttribute);
}
if(registerRuntime) {
HAPolicySynchronizationStatusReadHandler.registerSlaveAttributes(resourceRegistration);
}
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return ATTRIBUTES;
}
}
| 4,236
| 44.55914
| 124
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/ha/HAPolicySynchronizationStatusReadHandler.java
|
/*
* Copyright 2019 JBoss by Red Hat.
*
* 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.wildfly.extension.messaging.activemq.ha;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION;
import org.apache.activemq.artemis.api.core.management.ActiveMQServerControl;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.jboss.as.controller.AbstractRuntimeOnlyHandler;
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.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.wildfly.extension.messaging.activemq.MessagingServices;
import org.wildfly.extension.messaging.activemq.logging.MessagingLogger;
/**
*
* @author Emmanuel Hugonnet (c) 2019 Red Hat, Inc.
*/
public class HAPolicySynchronizationStatusReadHandler extends AbstractRuntimeOnlyHandler {
public static final AttributeDefinition SYNCHRONIZED_WITH_LIVE
= new SimpleAttributeDefinitionBuilder("synchronized-with-live", ModelType.BOOLEAN, false)
.setStorageRuntime()
.build();
public static final AttributeDefinition SYNCHRONIZED_WITH_BACKUP
= new SimpleAttributeDefinitionBuilder("synchronized-with-backup", ModelType.BOOLEAN, false)
.setStorageRuntime()
.build();
public static final HAPolicySynchronizationStatusReadHandler INSTANCE = new HAPolicySynchronizationStatusReadHandler();
@Override
protected void executeRuntimeStep(OperationContext context, ModelNode operation) throws OperationFailedException {
final String operationName = operation.require(OP).asString();
try {
if (READ_ATTRIBUTE_OPERATION.equals(operationName)) {
ActiveMQServerControl serverControl = getServerControl(context, operation);
context.getResult().set(serverControl.isReplicaSync());
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
context.getFailureDescription().set(e.getLocalizedMessage());
}
}
public static void registerSlaveAttributes(final ManagementResourceRegistration registry) {
registry.registerReadOnlyAttribute(SYNCHRONIZED_WITH_LIVE, INSTANCE);
}
public static void registerMasterAttributes(final ManagementResourceRegistration registry) {
registry.registerReadOnlyAttribute(SYNCHRONIZED_WITH_BACKUP, INSTANCE);
}
private ActiveMQServerControl getServerControl(final OperationContext context, ModelNode operation) throws OperationFailedException {
final ServiceName serviceName = MessagingServices.getActiveMQServiceName(PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)));
ServiceController<?> service = context.getServiceRegistry(false).getService(serviceName);
if (service == null || service.getState() != ServiceController.State.UP) {
throw MessagingLogger.ROOT_LOGGER.activeMQServerNotInstalled(serviceName.getSimpleName());
}
ActiveMQServer server = ActiveMQServer.class.cast(service.getValue());
return server.getActiveMQServerControl();
}
}
| 4,249
| 47.295455
| 156
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/ha/ReplicationPrimaryDefinition.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.wildfly.extension.messaging.activemq.ha;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.HA_POLICY;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.CHECK_FOR_LIVE_SERVER;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.CLUSTER_NAME;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.GROUP_NAME;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.INITIAL_REPLICATION_SYNC_TIMEOUT;
import static org.wildfly.extension.messaging.activemq.ha.ManagementHelper.createAddOperation;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.jboss.as.controller.AbstractWriteAttributeHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.PersistentResourceDefinition;
import org.jboss.as.controller.ReloadRequiredRemoveStepHandler;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.wildfly.extension.messaging.activemq.ActiveMQReloadRequiredHandlers;
import org.wildfly.extension.messaging.activemq.MessagingExtension;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2014 Red Hat inc.
*/
public class ReplicationPrimaryDefinition extends PersistentResourceDefinition {
public static final Collection<AttributeDefinition> ATTRIBUTES = Collections.unmodifiableList(Arrays.asList(
(AttributeDefinition) CLUSTER_NAME,
GROUP_NAME,
CHECK_FOR_LIVE_SERVER,
INITIAL_REPLICATION_SYNC_TIMEOUT
));
private final boolean registerRuntime;
public ReplicationPrimaryDefinition(PathElement path, boolean allowSibling, boolean registerRuntime) {
super(path,
MessagingExtension.getResourceDescriptionResolver(HA_POLICY),
createAddOperation(path.getKey(), allowSibling, ATTRIBUTES),
ReloadRequiredRemoveStepHandler.INSTANCE);
this.registerRuntime = registerRuntime;
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
AbstractWriteAttributeHandler writeAttribute = new ActiveMQReloadRequiredHandlers.WriteAttributeHandler(ATTRIBUTES);
for (AttributeDefinition attribute : ATTRIBUTES) {
resourceRegistration.registerReadWriteAttribute(attribute, null, writeAttribute);
}
if(registerRuntime) {
HAPolicySynchronizationStatusReadHandler.registerMasterAttributes(resourceRegistration);
}
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return ATTRIBUTES;
}
}
| 3,745
| 44.682927
| 124
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/ha/SharedStorePrimaryDefinition.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.wildfly.extension.messaging.activemq.ha;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.HA_POLICY;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.FAILOVER_ON_SERVER_SHUTDOWN;
import static org.wildfly.extension.messaging.activemq.ha.ManagementHelper.createAddOperation;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.jboss.as.controller.AbstractWriteAttributeHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.PersistentResourceDefinition;
import org.jboss.as.controller.ReloadRequiredRemoveStepHandler;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.wildfly.extension.messaging.activemq.ActiveMQReloadRequiredHandlers;
import org.wildfly.extension.messaging.activemq.MessagingExtension;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2014 Red Hat inc.
*/
public class SharedStorePrimaryDefinition extends PersistentResourceDefinition {
public static final Collection<AttributeDefinition> ATTRIBUTES = Collections.unmodifiableList(Arrays.asList(
FAILOVER_ON_SERVER_SHUTDOWN
));
public SharedStorePrimaryDefinition(PathElement path, boolean allowSibling) {
super(path,
MessagingExtension.getResourceDescriptionResolver(HA_POLICY),
createAddOperation(path.getKey(), allowSibling, ATTRIBUTES),
ReloadRequiredRemoveStepHandler.INSTANCE);
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
AbstractWriteAttributeHandler writeAttribute = new ActiveMQReloadRequiredHandlers.WriteAttributeHandler(ATTRIBUTES);
for (AttributeDefinition attribute : ATTRIBUTES) {
resourceRegistration.registerReadWriteAttribute(attribute, null, writeAttribute);
}
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return ATTRIBUTES;
}
}
| 3,110
| 42.208333
| 124
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/ha/HAPolicyConfigurationBuilder.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.wildfly.extension.messaging.activemq.ha;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.CONFIGURATION;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.HA_POLICY;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.LIVE_ONLY;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.PRIMARY;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.REPLICATION_COLOCATED;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.REPLICATION_MASTER;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.REPLICATION_PRIMARY;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.REPLICATION_SECONDARY;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.REPLICATION_SLAVE;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.SECONDARY;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.SHARED_STORE_COLOCATED;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.SHARED_STORE_MASTER;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.SHARED_STORE_PRIMARY;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.SHARED_STORE_SECONDARY;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.SHARED_STORE_SLAVE;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.ALLOW_FAILBACK;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.BACKUP_PORT_OFFSET;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.BACKUP_REQUEST_RETRIES;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.BACKUP_REQUEST_RETRY_INTERVAL;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.CHECK_FOR_LIVE_SERVER;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.CLUSTER_NAME;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.EXCLUDED_CONNECTORS;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.FAILOVER_ON_SERVER_SHUTDOWN;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.GROUP_NAME;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.INITIAL_REPLICATION_SYNC_TIMEOUT;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.MAX_BACKUPS;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.MAX_SAVED_REPLICATED_JOURNAL_SIZE;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.REQUEST_BACKUP;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.RESTART_BACKUP;
import static org.wildfly.extension.messaging.activemq.ha.ScaleDownAttributes.addScaleDownConfiguration;
import java.util.List;
import org.apache.activemq.artemis.core.config.Configuration;
import org.apache.activemq.artemis.core.config.HAPolicyConfiguration;
import org.apache.activemq.artemis.core.config.ScaleDownConfiguration;
import org.apache.activemq.artemis.core.config.ha.ColocatedPolicyConfiguration;
import org.apache.activemq.artemis.core.config.ha.LiveOnlyPolicyConfiguration;
import org.apache.activemq.artemis.core.config.ha.ReplicaPolicyConfiguration;
import org.apache.activemq.artemis.core.config.ha.ReplicatedPolicyConfiguration;
import org.apache.activemq.artemis.core.config.ha.SharedStoreMasterPolicyConfiguration;
import org.apache.activemq.artemis.core.config.ha.SharedStoreSlavePolicyConfiguration;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2014 Red Hat inc.
*/
public class HAPolicyConfigurationBuilder {
private static final HAPolicyConfigurationBuilder INSTANCE = new HAPolicyConfigurationBuilder();
private HAPolicyConfigurationBuilder() {
}
public static HAPolicyConfigurationBuilder getInstance() {
return INSTANCE;
}
public void addHAPolicyConfiguration(OperationContext context, Configuration configuration, ModelNode model) throws OperationFailedException {
if (!model.hasDefined(HA_POLICY)) {
return;
}
Property prop = model.get(HA_POLICY).asProperty();
ModelNode haPolicy = prop.getValue();
final HAPolicyConfiguration haPolicyConfiguration;
String type = prop.getName();
switch (type) {
case LIVE_ONLY: {
haPolicyConfiguration = buildLiveOnlyConfiguration(context, haPolicy);
break;
}
case REPLICATION_MASTER:
case REPLICATION_PRIMARY: {
haPolicyConfiguration = buildReplicationPrimaryConfiguration(context, haPolicy);
break;
}
case REPLICATION_SLAVE:
case REPLICATION_SECONDARY: {
haPolicyConfiguration = buildReplicationSecondaryConfiguration(context, haPolicy);
break;
}
case REPLICATION_COLOCATED: {
haPolicyConfiguration = buildReplicationColocatedConfiguration(context, haPolicy);
break;
}
case SHARED_STORE_MASTER:
case SHARED_STORE_PRIMARY: {
haPolicyConfiguration = buildSharedStorePrimaryConfiguration(context, haPolicy);
break;
}
case SHARED_STORE_SLAVE:
case SHARED_STORE_SECONDARY: {
haPolicyConfiguration = buildSharedStoreSecondaryConfiguration(context, haPolicy);
break;
}
case SHARED_STORE_COLOCATED: {
haPolicyConfiguration = buildSharedStoreColocatedConfiguration(context, haPolicy);
break;
}
default: {
throw new OperationFailedException("unknown ha policy type");
}
}
configuration.setHAPolicyConfiguration(haPolicyConfiguration);
}
private HAPolicyConfiguration buildLiveOnlyConfiguration(OperationContext context, ModelNode model) throws OperationFailedException {
ScaleDownConfiguration scaleDownConfiguration = ScaleDownAttributes.addScaleDownConfiguration(context, model);
return new LiveOnlyPolicyConfiguration(scaleDownConfiguration);
}
private HAPolicyConfiguration buildReplicationPrimaryConfiguration(OperationContext context, ModelNode model) throws OperationFailedException {
ReplicatedPolicyConfiguration haPolicyConfiguration = new ReplicatedPolicyConfiguration();
haPolicyConfiguration.setCheckForLiveServer(CHECK_FOR_LIVE_SERVER.resolveModelAttribute(context, model).asBoolean())
.setInitialReplicationSyncTimeout(INITIAL_REPLICATION_SYNC_TIMEOUT.resolveModelAttribute(context, model).asLong());
ModelNode clusterName = CLUSTER_NAME.resolveModelAttribute(context, model);
if (clusterName.isDefined()) {
haPolicyConfiguration.setClusterName(clusterName.asString());
}
ModelNode groupName = GROUP_NAME.resolveModelAttribute(context, model);
if (groupName.isDefined()) {
haPolicyConfiguration.setGroupName(groupName.asString());
}
return haPolicyConfiguration;
}
private HAPolicyConfiguration buildReplicationSecondaryConfiguration(OperationContext context, ModelNode model) throws OperationFailedException {
ReplicaPolicyConfiguration haPolicyConfiguration = new ReplicaPolicyConfiguration()
.setAllowFailBack(ALLOW_FAILBACK.resolveModelAttribute(context, model).asBoolean())
.setInitialReplicationSyncTimeout(INITIAL_REPLICATION_SYNC_TIMEOUT.resolveModelAttribute(context, model).asLong())
.setMaxSavedReplicatedJournalsSize(MAX_SAVED_REPLICATED_JOURNAL_SIZE.resolveModelAttribute(context, model).asInt())
.setScaleDownConfiguration(addScaleDownConfiguration(context, model))
.setRestartBackup(RESTART_BACKUP.resolveModelAttribute(context, model).asBoolean());
ModelNode clusterName = CLUSTER_NAME.resolveModelAttribute(context, model);
if (clusterName.isDefined()) {
haPolicyConfiguration.setClusterName(clusterName.asString());
}
ModelNode groupName = GROUP_NAME.resolveModelAttribute(context, model);
if (groupName.isDefined()) {
haPolicyConfiguration.setGroupName(groupName.asString());
}
return haPolicyConfiguration;
}
private HAPolicyConfiguration buildReplicationColocatedConfiguration(OperationContext context, ModelNode model) throws OperationFailedException {
ColocatedPolicyConfiguration haPolicyConfiguration = new ColocatedPolicyConfiguration()
.setRequestBackup(REQUEST_BACKUP.resolveModelAttribute(context, model).asBoolean())
.setBackupRequestRetries(BACKUP_REQUEST_RETRIES.resolveModelAttribute(context, model).asInt())
.setBackupRequestRetryInterval(BACKUP_REQUEST_RETRY_INTERVAL.resolveModelAttribute(context, model).asLong())
.setMaxBackups(MAX_BACKUPS.resolveModelAttribute(context, model).asInt())
.setBackupPortOffset(BACKUP_PORT_OFFSET.resolveModelAttribute(context, model).asInt());
List<String> connectors = EXCLUDED_CONNECTORS.unwrap(context, model);
if (!connectors.isEmpty()) {
haPolicyConfiguration.setExcludedConnectors(connectors);
}
ModelNode masterConfigurationModel = model.get(CONFIGURATION, PRIMARY);
HAPolicyConfiguration masterConfiguration = buildReplicationPrimaryConfiguration(context, masterConfigurationModel);
haPolicyConfiguration.setLiveConfig(masterConfiguration);
ModelNode slaveConfigurationModel = model.get(CONFIGURATION, SECONDARY);
HAPolicyConfiguration slaveConfiguration = buildReplicationSecondaryConfiguration(context, slaveConfigurationModel);
haPolicyConfiguration.setBackupConfig(slaveConfiguration);
return haPolicyConfiguration;
}
private HAPolicyConfiguration buildSharedStorePrimaryConfiguration(OperationContext context, ModelNode model) throws OperationFailedException {
return new SharedStoreMasterPolicyConfiguration()
.setFailoverOnServerShutdown(FAILOVER_ON_SERVER_SHUTDOWN.resolveModelAttribute(context, model).asBoolean());
}
private HAPolicyConfiguration buildSharedStoreSecondaryConfiguration(OperationContext context, ModelNode model) throws OperationFailedException {
return new SharedStoreSlavePolicyConfiguration()
.setAllowFailBack(ALLOW_FAILBACK.resolveModelAttribute(context, model).asBoolean())
.setFailoverOnServerShutdown(FAILOVER_ON_SERVER_SHUTDOWN.resolveModelAttribute(context, model).asBoolean())
.setRestartBackup(RESTART_BACKUP.resolveModelAttribute(context, model).asBoolean())
.setScaleDownConfiguration(ScaleDownAttributes.addScaleDownConfiguration(context, model));
}
private HAPolicyConfiguration buildSharedStoreColocatedConfiguration(OperationContext context, ModelNode model) throws OperationFailedException {
ColocatedPolicyConfiguration haPolicyConfiguration = new ColocatedPolicyConfiguration()
.setRequestBackup(REQUEST_BACKUP.resolveModelAttribute(context, model).asBoolean())
.setBackupRequestRetries(BACKUP_REQUEST_RETRIES.resolveModelAttribute(context, model).asInt())
.setBackupRequestRetryInterval(BACKUP_REQUEST_RETRY_INTERVAL.resolveModelAttribute(context, model).asLong())
.setMaxBackups(MAX_BACKUPS.resolveModelAttribute(context, model).asInt())
.setBackupPortOffset(BACKUP_PORT_OFFSET.resolveModelAttribute(context, model).asInt());
ModelNode masterConfigurationModel = model.get(CONFIGURATION, PRIMARY);
HAPolicyConfiguration masterConfiguration = buildSharedStorePrimaryConfiguration(context, masterConfigurationModel);
haPolicyConfiguration.setLiveConfig(masterConfiguration);
ModelNode slaveConfigurationModel = model.get(CONFIGURATION, SECONDARY);
HAPolicyConfiguration slaveConfiguration = buildSharedStoreSecondaryConfiguration(context, slaveConfigurationModel);
haPolicyConfiguration.setBackupConfig(slaveConfiguration);
return haPolicyConfiguration;
}
}
| 13,565
| 59.026549
| 149
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/ha/ManagementHelper.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.wildfly.extension.messaging.activemq.ha;
import static org.jboss.as.controller.OperationContext.Stage.MODEL;
import java.util.Collection;
import java.util.Set;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
import org.wildfly.extension.messaging.activemq.ActiveMQReloadRequiredHandlers;
import org.wildfly.extension.messaging.activemq.logging.MessagingLogger;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2014 Red Hat inc.
*/
public class ManagementHelper {
/**
* Create an ADD operation that can check that there is no other sibling when the resource is added.
*
* @param childType the type of children to check for the existence of siblings
* @param allowSibling whether it is allowed to have sibling for the resource that is added.
* @param attributes the attributes of the ADD operation
*/
static AbstractAddStepHandler createAddOperation(final String childType, final boolean allowSibling, Collection<? extends AttributeDefinition> attributes) {
return new ActiveMQReloadRequiredHandlers.AddStepHandler(attributes) {
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
super.execute(context, operation);
if (!allowSibling) {
context.addStep(checkNoOtherSibling(childType), MODEL);
}
}
};
}
static OperationStepHandler checkNoOtherSibling(final String childType) {
return new OperationStepHandler() {
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
PathAddress parentAddress = context.getCurrentAddress().getParent();
Resource parent = context.readResourceFromRoot(parentAddress, false);
Set<String> children = parent.getChildrenNames(childType);
if (children.size() > 1) {
throw MessagingLogger.ROOT_LOGGER.onlyOneChildIsAllowed(childType, children);
}
}
};
}
}
| 3,519
| 43.556962
| 160
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/ha/SharedStoreSecondaryDefinition.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.wildfly.extension.messaging.activemq.ha;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.HA_POLICY;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.ALLOW_FAILBACK;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.FAILOVER_ON_SERVER_SHUTDOWN;
import static org.wildfly.extension.messaging.activemq.ha.HAAttributes.RESTART_BACKUP;
import static org.wildfly.extension.messaging.activemq.ha.ManagementHelper.createAddOperation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import org.jboss.as.controller.AbstractWriteAttributeHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.PersistentResourceDefinition;
import org.jboss.as.controller.ReloadRequiredRemoveStepHandler;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.wildfly.extension.messaging.activemq.ActiveMQReloadRequiredHandlers;
import org.wildfly.extension.messaging.activemq.MessagingExtension;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2014 Red Hat inc.
*/
public class SharedStoreSecondaryDefinition extends PersistentResourceDefinition {
public static final Collection<AttributeDefinition> ATTRIBUTES;
static {
Collection<AttributeDefinition> attributes = new ArrayList<>();
attributes.add(ALLOW_FAILBACK);
attributes.add(FAILOVER_ON_SERVER_SHUTDOWN);
attributes.add(RESTART_BACKUP);
attributes.addAll(ScaleDownAttributes.SCALE_DOWN_ATTRIBUTES);
ATTRIBUTES = Collections.unmodifiableCollection(attributes);
}
private static final AbstractWriteAttributeHandler WRITE_ATTRIBUTE = new ActiveMQReloadRequiredHandlers.WriteAttributeHandler(ATTRIBUTES);
public SharedStoreSecondaryDefinition(PathElement path, boolean allowSibling) {
super(path,
MessagingExtension.getResourceDescriptionResolver(HA_POLICY),
createAddOperation(path.getKey(), allowSibling, ATTRIBUTES),
ReloadRequiredRemoveStepHandler.INSTANCE);
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
for (AttributeDefinition attribute : ATTRIBUTES) {
resourceRegistration.registerReadWriteAttribute(attribute, null, WRITE_ATTRIBUTE);
}
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return ATTRIBUTES;
}
}
| 3,583
| 42.180723
| 142
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/ha/ScaleDownAttributes.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.wildfly.extension.messaging.activemq.ha;
import static org.jboss.dmr.ModelType.BOOLEAN;
import static org.jboss.dmr.ModelType.STRING;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.activemq.artemis.core.config.ScaleDownConfiguration;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.AttributeMarshaller;
import org.jboss.as.controller.AttributeParser;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.StringListAttributeDefinition;
import org.jboss.dmr.ModelNode;
import org.wildfly.extension.messaging.activemq.CommonAttributes;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2014 Red Hat inc.
*/
public class ScaleDownAttributes {
private static final String SCALE_DOWN_DISCOVERY_GROUP_STR = "scale-down-discovery-group";
private static final String SCALE_DOWN_CONNECTORS_STR = "scale-down-connectors";
// if the scale-down attribute is not defined, the whole scale down configuration is ignored
public static final SimpleAttributeDefinition SCALE_DOWN = SimpleAttributeDefinitionBuilder.create(CommonAttributes.SCALE_DOWN, BOOLEAN)
.setAttributeGroup(CommonAttributes.SCALE_DOWN)
.setXmlName(CommonAttributes.ENABLED)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
public static final SimpleAttributeDefinition SCALE_DOWN_CLUSTER_NAME = SimpleAttributeDefinitionBuilder.create("scale-down-cluster-name", STRING)
.setAttributeGroup(CommonAttributes.SCALE_DOWN)
.setXmlName(CommonAttributes.CLUSTER_NAME)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
public static final SimpleAttributeDefinition SCALE_DOWN_GROUP_NAME = SimpleAttributeDefinitionBuilder.create("scale-down-group-name", STRING)
.setAttributeGroup(CommonAttributes.SCALE_DOWN)
.setXmlName(CommonAttributes.GROUP_NAME)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
public static final SimpleAttributeDefinition SCALE_DOWN_DISCOVERY_GROUP = SimpleAttributeDefinitionBuilder.create(SCALE_DOWN_DISCOVERY_GROUP_STR, STRING)
.setAttributeGroup(CommonAttributes.SCALE_DOWN)
.setXmlName(CommonAttributes.DISCOVERY_GROUP)
.setRequired(false)
.setAlternatives(SCALE_DOWN_CONNECTORS_STR)
.setRestartAllServices()
.build();
public static final AttributeDefinition SCALE_DOWN_CONNECTORS = new StringListAttributeDefinition.Builder(SCALE_DOWN_CONNECTORS_STR)
.setAttributeGroup(CommonAttributes.SCALE_DOWN)
.setXmlName(CommonAttributes.CONNECTORS)
.setAlternatives(SCALE_DOWN_DISCOVERY_GROUP_STR)
.setRequired(false)
.setAttributeMarshaller(AttributeMarshaller.STRING_LIST)
.setAttributeParser(AttributeParser.STRING_LIST)
.setRestartAllServices()
.build();
public static final Collection<AttributeDefinition> SCALE_DOWN_ATTRIBUTES = Collections.unmodifiableList(Arrays.asList(
SCALE_DOWN,
SCALE_DOWN_CLUSTER_NAME,
SCALE_DOWN_GROUP_NAME,
SCALE_DOWN_DISCOVERY_GROUP,
SCALE_DOWN_CONNECTORS
));
static ScaleDownConfiguration addScaleDownConfiguration(OperationContext context, ModelNode model) throws OperationFailedException {
if (!model.hasDefined(SCALE_DOWN.getName())) {
return null;
}
ScaleDownConfiguration scaleDownConfiguration = new ScaleDownConfiguration();
scaleDownConfiguration.setEnabled(SCALE_DOWN.resolveModelAttribute(context, model).asBoolean());
ModelNode clusterName = SCALE_DOWN_CLUSTER_NAME.resolveModelAttribute(context, model);
if (clusterName.isDefined()) {
scaleDownConfiguration.setClusterName(clusterName.asString());
}
ModelNode groupName = SCALE_DOWN_GROUP_NAME.resolveModelAttribute(context, model);
if (groupName.isDefined()) {
scaleDownConfiguration.setGroupName(groupName.asString());
}
ModelNode discoveryGroupName = SCALE_DOWN_DISCOVERY_GROUP.resolveModelAttribute(context, model);
if (discoveryGroupName.isDefined()) {
scaleDownConfiguration.setDiscoveryGroup(discoveryGroupName.asString());
}
ModelNode connectors = SCALE_DOWN_CONNECTORS.resolveModelAttribute(context, model);
if (connectors.isDefined()) {
List<String> connectorNames = new ArrayList<>(connectors.keys());
scaleDownConfiguration.setConnectors(connectorNames);
}
return scaleDownConfiguration;
}
}
| 6,179
| 44.777778
| 159
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/ha/HAAttributes.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.wildfly.extension.messaging.activemq.ha;
import static org.jboss.as.controller.SimpleAttributeDefinitionBuilder.create;
import static org.jboss.as.controller.client.helpers.MeasurementUnit.MILLISECONDS;
import static org.jboss.dmr.ModelType.BOOLEAN;
import static org.jboss.dmr.ModelType.INT;
import static org.jboss.dmr.ModelType.LONG;
import static org.jboss.dmr.ModelType.STRING;
import org.jboss.as.controller.AttributeMarshaller;
import org.jboss.as.controller.AttributeParser;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.StringListAttributeDefinition;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.wildfly.extension.messaging.activemq.CommonAttributes;
import org.wildfly.extension.messaging.activemq.InfiniteOrPositiveValidators;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2014 Red Hat inc.
*/
public class HAAttributes {
/**
* @see ActiveMQDefaultConfiguration#isDefaultAllowAutoFailback
*/
public static final SimpleAttributeDefinition ALLOW_FAILBACK = create("allow-failback", BOOLEAN)
.setDefaultValue(ModelNode.TRUE)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see ActiveMQDefaultConfiguration#getDefaultHapolicyBackupPortOffset
*/
public static final SimpleAttributeDefinition BACKUP_PORT_OFFSET = create("backup-port-offset", INT)
.setDefaultValue(new ModelNode(100))
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see ActiveMQDefaultConfiguration#getDefaultHapolicyBackupRequestRetries
*/
public static final SimpleAttributeDefinition BACKUP_REQUEST_RETRIES = create("backup-request-retries", INT)
.setDefaultValue(new ModelNode(-1))
.setRequired(false)
.setAllowExpression(true)
.setCorrector(InfiniteOrPositiveValidators.NEGATIVE_VALUE_CORRECTOR)
.setValidator(InfiniteOrPositiveValidators.INT_INSTANCE)
.setRestartAllServices()
.build();
/**
* @see ActiveMQDefaultConfiguration#getDefaultHapolicyBackupRequestRetryInterval
*/
public static final SimpleAttributeDefinition BACKUP_REQUEST_RETRY_INTERVAL = create("backup-request-retry-interval", LONG)
.setDefaultValue(new ModelNode(5000L))
.setMeasurementUnit(MILLISECONDS)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
// WFLY-8256 change default value to true instead of Artemis's false
public static final SimpleAttributeDefinition CHECK_FOR_LIVE_SERVER = create(CommonAttributes.CHECK_FOR_LIVE_SERVER2, BOOLEAN)
.setDefaultValue(ModelNode.TRUE)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
public static final SimpleAttributeDefinition CLUSTER_NAME = SimpleAttributeDefinitionBuilder.create(CommonAttributes.CLUSTER_NAME, STRING)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
public static final StringListAttributeDefinition EXCLUDED_CONNECTORS = new StringListAttributeDefinition.Builder("excluded-connectors")
.setRequired(false)
.setAttributeMarshaller(AttributeMarshaller.STRING_LIST)
.setAttributeParser(AttributeParser.STRING_LIST)
.setRestartAllServices()
.build();
/**
* @see ActiveMQDefaultConfiguration#isDefaultFailoverOnServerShutdown
*/
public static final SimpleAttributeDefinition FAILOVER_ON_SERVER_SHUTDOWN = create("failover-on-server-shutdown", ModelType.BOOLEAN)
.setDefaultValue(ModelNode.FALSE)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
public static final SimpleAttributeDefinition GROUP_NAME = SimpleAttributeDefinitionBuilder.create(CommonAttributes.GROUP_NAME, STRING)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see ActiveMQDefaultConfiguration#getDefaultInitialReplicationSyncTimeout
*/
public static final SimpleAttributeDefinition INITIAL_REPLICATION_SYNC_TIMEOUT = create("initial-replication-sync-timeout", LONG)
.setDefaultValue(new ModelNode(30000L))
.setMeasurementUnit(MILLISECONDS)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see ActiveMQDefaultConfiguration#getDefaultHapolicyMaxBackups
*/
public static final SimpleAttributeDefinition MAX_BACKUPS = create("max-backups", INT)
.setDefaultValue(new ModelNode(1))
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see ActiveMQDefaultConfiguration#getDefaultMaxSavedReplicatedJournalsSize
*/
public static final SimpleAttributeDefinition MAX_SAVED_REPLICATED_JOURNAL_SIZE = create("max-saved-replicated-journal-size", INT)
.setDefaultValue(new ModelNode(2))
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see ActiveMQDefaultConfiguration#isDefaultHapolicyRequestBackup
*/
public static final SimpleAttributeDefinition REQUEST_BACKUP = create("request-backup", BOOLEAN)
.setDefaultValue(ModelNode.FALSE)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
/**
* @see ActiveMQDefaultConfiguration#isDefaultRestartBackup
*/
public static final SimpleAttributeDefinition RESTART_BACKUP = create("restart-backup", BOOLEAN)
.setDefaultValue(ModelNode.TRUE)
.setRequired(false)
.setAllowExpression(true)
.setRestartAllServices()
.build();
}
| 7,395
| 40.785311
| 143
|
java
|
null |
wildfly-main/messaging-activemq/injection/src/test/java/org/wildfly/extension/messaging/activemq/deployment/injection/AbstractJMSContextTestCase.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.wildfly.extension.messaging.activemq.deployment.injection;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;
import jakarta.jms.ConnectionFactory;
import jakarta.jms.JMSContext;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
/**
* Test class for AbstractJMSContextTes.
*
* @author <a href="http://fnbrandao.com.br/">Fabio Nascimento Brandão</a> (c) 2021 Red Hat inc.
*/
public class AbstractJMSContextTestCase {
@Test
public void testGetContext() throws InterruptedException {
AbstractJMSContext abstractJMSContext = new AbstractJMSContext() {
};
LongAdder adder = new LongAdder();
// Mock info to force the context creation by createContext(sessionMode)
JMSInfo info = Mockito.mock(JMSInfo.class);
Mockito.when(info.getUserName()).thenReturn(null);
// Mock the create context
ConnectionFactory connectionFactory = Mockito.mock(ConnectionFactory.class);
Mockito.when(connectionFactory.createContext(0)).thenAnswer(new Answer<JMSContext>() {
@Override
public JMSContext answer(InvocationOnMock invocation) throws Throwable {
// Count how many contexts were created
adder.increment();
// "Slow" processing
Thread.sleep(1000);
return Mockito.mock(JMSContext.class);
}
});
// 100 threads will be trying to create contexts at the same time
ExecutorService executor = Executors.newFixedThreadPool(100);
List<Callable<JMSContext>> tasks = new LinkedList<>();
for (int i = 0; i < 100; i++) {
final int j = i;
tasks.add(new Callable<JMSContext>() {
@Override
public JMSContext call() throws Exception {
// We will only use 10 differents injectionPointId's
final String injectionPointId = Integer.toString(j % 10);
return abstractJMSContext.getContext(injectionPointId, info, connectionFactory);
}
});
}
// Execute all tasks
for (Callable<JMSContext> task : tasks) {
executor.submit(task);
}
// Shutdown the executor
executor.shutdown();
// Ok, lets wait for only 2 seconds.
executor.awaitTermination(2, TimeUnit.SECONDS);
// If the executor is terminated, we were able to create 10 contexts at the same time.
// When using synchronized (old implementation) we need to wait for 10 seconds to create 10 contexts (serializable creation).
Assert.assertTrue(executor.isTerminated());
// Lets check if we only created 10 contexts.
Assert.assertEquals(10, adder.intValue());
}
}
| 4,146
| 37.398148
| 133
|
java
|
null |
wildfly-main/messaging-activemq/injection/src/main/java/org/wildfly/extension/messaging/activemq/logging/MessagingLogger.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.wildfly.extension.messaging.activemq.logging;
import static org.jboss.logging.Logger.Level.DEBUG;
import static org.jboss.logging.Logger.Level.ERROR;
import static org.jboss.logging.Logger.Level.INFO;
import static org.jboss.logging.Logger.Level.WARN;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import jakarta.jms.IllegalStateRuntimeException;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.RunningMode;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
import org.jboss.modules.ModuleLoadException;
import org.jboss.modules.ModuleNotFoundException;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartException;
/**
* Date: 10.06.2011
*
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@MessageLogger(projectCode = "WFLYMSGAMQ", length = 4)
public interface MessagingLogger extends BasicLogger {
/**
* The logger with the category of the package.
*/
MessagingLogger ROOT_LOGGER = Logger.getMessageLogger(MessagingLogger.class, "org.wildfly.extension.messaging-activemq");
/**
* Logs a info message indicating AIO was not found.
*/
@LogMessage(level = INFO)
@Message(id = 1, value = "AIO wasn't located on this platform, it will fall back to using pure Java NIO.")
void aioInfo();
/**
* Logs an informational message indicating a messaging object was bound to the JNDI name represented by the
* {@code jndiName} parameter.
*
* @param jndiName the name the messaging object was bound to.
*/
@LogMessage(level = INFO)
@Message(id = 2, value = "Bound messaging object to jndi name %s")
void boundJndiName(String jndiName);
/**
* Logs an error message indicating an exception occurred while stopping the Jakarta Messaging server.
*
* @param cause the cause of the error.
*/
@LogMessage(level = ERROR)
@Message(id = 3, value = "Exception while stopping Jakarta Messaging server")
void errorStoppingJmsServer(@Cause Throwable cause);
/**
* Logs a warning message indicating the connection factory was not destroyed.
*
* @param cause the cause of the error.
* @param description the description of what failed to get destroyed.
* @param name the name of the factory.
*/
@LogMessage(level = WARN)
@Message(id = 4, value = "Failed to destroy %s: %s")
void failedToDestroy(@Cause Throwable cause, String description, String name);
/**
* Logs a warning message indicating the connection factory was not destroyed.
*
* @param description the description of what failed to get destroyed.
* @param name the name of the factory.
*/
@LogMessage(level = WARN)
void failedToDestroy(String description, String name);
/**
* Logs an error message indicating the class, represented by the {@code className} parameter, caught an exception
* attempting to revert the operation, represented by the {@code operation} parameter, at the address, represented
* by the {@code address} parameter.
*
* @param cause the cause of the error.
* @param className the name of the class that caused the error.
* @param operation the operation.
* @param address the address.
*/
@LogMessage(level = ERROR)
@Message(id = 5, value = "%s caught exception attempting to revert operation %s at address %s")
void revertOperationFailed(@Cause Throwable cause, String className, String operation, PathAddress address);
/**
* Logs an informational message indicating a messaging object was unbound from the JNDI name represented by the
* {@code jndiName} parameter.
*
* @param jndiName the name the messaging object was bound to.
*/
@LogMessage(level = INFO)
@Message(id = 6, value = "Unbound messaging object to jndi name %s")
void unboundJndiName(String jndiName);
/**
*/
@LogMessage(level = ERROR)
@Message(id = 7, value = "Could not close file %s")
void couldNotCloseFile(String file, @Cause Throwable cause);
/**
* Logs a warning message indicating the messaging object bound to the JNDI name represented by
* the {@code jndiName) has not be unbound in a timely fashion.
*
* @param jndiName the name the messaging object was bound to.
* @param timeout the timeout value
* @param timeUnit the timeout time unit
*/
@LogMessage(level = WARN)
@Message(id = 8, value = "Failed to unbind messaging object bound to jndi name %s in %d %s")
void failedToUnbindJndiName(String jndiName, long timeout, String timeUnit);
// /**
// * Logs a warning message indicating the XML element with the given {@code name}
// * is deprecated and will not be used anymore.
// *
// * @param name the name of the deprecated XML element
// */
// @LogMessage(level = WARN)
// @Message(id = 9, value = "Element %s is deprecated and will not be taken into account")
// void deprecatedXMLElement(String name);
//
// /**
// * Logs a warning message indicating the XML attribute with the given {@code name}
// * is deprecated and will not be used anymore.
// *
// * @param name the name of the deprecated XML attribute
// */
// @LogMessage(level = WARN)
// @Message(id = 10, value = "Attribute %s is deprecated and will not be taken into account")
// void deprecatedXMLAttribute(String name);
/**
* Logs an info message when a service for the given {@code type} and {@code name} is <em>started</em>.
*
* @param type the type of the service
* @param name the name of the service
*/
@LogMessage(level = INFO)
@Message(id = 11, value = "Started %s %s")
void startedService(String type, String name);
/**
* Logs an info message when a service for the given {@code type} and {@code name} is <em>stopped</em>.
*
* @param type the type of the service
* @param name the name of the service
*/
@LogMessage(level = INFO)
@Message(id = 12, value = "Stopped %s %s")
void stoppedService(String type, String name);
// /**
// * Logs a warning message indicating the management attribute with the given {@code name}
// * is deprecated and will not be used anymore.
// *
// * @param name the name of the deprecated XML attribute
// */
// @LogMessage(level = WARN)
// @Message(id = 13, value = "Attribute %s of the resource at %s is deprecated and setting its value will not be taken into account")
// void deprecatedAttribute(String name, PathAddress address);
//
// @Message(id = 14, value = "Can not change the clustered attribute to false: The server resource at %s has cluster-connection children resources and will remain clustered.")
// String canNotChangeClusteredAttribute(PathAddress address);
@LogMessage(level = WARN)
@Message(id = 15, value = "Ignoring %s property that is not a known property for pooled connection factory.")
void unknownPooledConnectionFactoryAttribute(String name);
/**
* Logs an info message when a HTTP Upgrade handler is registered for the given {@code protocol}.
*
* @param name the name of the protocol that is handled
*/
@LogMessage(level = INFO)
@Message(id = 16, value = "Registered HTTP upgrade for %s protocol handled by %s acceptor")
void registeredHTTPUpgradeHandler(String name, String acceptor);
// /**
// * Logs a warning message indicating the XML element with the given {@code name}
// * is deprecated and instead a different attribute will be used.
// *
// * @param name the name of the deprecated XML element
// */
// @LogMessage(level = WARN)
// @Message(id = 17, value = "Element %s is deprecated and %s will be used in its place")
// void deprecatedXMLElement(String name, String replacement);
/**
* Logs a warn message when no connectors were specified for a connection factory definition
* and one connector was picked up to be used.
*
* @param name the name of the connection factory definition
* @param connectorName the name of the connector that was picked
*/
@LogMessage(level = WARN)
@Message(id = 18, value = "No connectors were explicitly defined for the pooled connection factory %s. Using %s as the connector.")
void connectorForPooledConnectionFactory(String name, String connectorName);
// /**
// * A message indicating the alternative attribute represented by the {@code name} parameter is already defined.
// *
// * @param name the attribute name.
// *
// * @return the message.
// */
// @Message(id = 19, value = "Alternative attribute of (%s) is already defined.")
// String altAttributeAlreadyDefined(String name);
// /**
// * Creates an exception indicating that all attribute definitions must have the same XML name.
// *
// * @param nameFound the name found.
// * @param nameRequired the name that is required.
// *
// * @return an {@link IllegalArgumentException} for the error.
// */
// @Message(id = 20, value = "All attribute definitions must have the same xml name -- found %s but already had %s")
// IllegalArgumentException attributeDefinitionsMustMatch(String nameFound, String nameRequired);
//
// /**
// * Creates an exception indicating that all attribute definitions must have unique names.
// *
// * @param nameFound the name found.
// *
// * @return an {@link IllegalArgumentException} for the error.
// */
// @Message(id = 21, value = "All attribute definitions must have unique names -- already found %s")
// IllegalArgumentException attributeDefinitionsNotUnique(String nameFound);
/**
* Creates an exception indicating a {@code null} or empty JNDI name cannot be bound.
*
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 22, value = "Cannot bind a null or empty string as jndi name")
IllegalArgumentException cannotBindJndiName();
// /**
// * A message indicating the operation cannot include the parameter represented by {@code paramName1} and the
// * parameter represented by the {@code paramName2} parameter.
// *
// * @param paramName1 the name of the parameter.
// * @param paramName2 the name of the parameter.
// *
// * @return the message.
// */
// @Message(id = 23, value = "Operation cannot include both parameter %s and parameter %s")
// String cannotIncludeOperationParameters(String paramName1, String paramName2);
//
// /**
// * Creates an exception indicating the attribute, represented by the {@code name} parameter, cannot be marshalled
// * and to use the {@code marshalAsElement} method.
// *
// * @param name the name of the attribute.
// *
// * @return an {@link UnsupportedOperationException} for the error.
// */
// @Message(id = 24, value = "%s cannot be marshalled as an attribute; use marshallAsElement")
// UnsupportedOperationException cannotMarshalAttribute(String name);
/**
* Creates an exception indicating a {@code null} or empty JNDI name cannot be unbound.
*
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 25, value = "Cannot unbind a null or empty string as jndi name")
IllegalArgumentException cannotUnbindJndiName();
/**
* A message indicating a child resource of the type, represented by the {@code type} parameter already exists.
*
* @param type the type that already exists.
*
* @return the message.
*/
@Message(id = 26, value = "A child resource of type %1$s already exists; the messaging subsystem only allows a single resource of type %1$s")
String childResourceAlreadyExists(String type);
/**
* Creates an exception indicating the connector is not defined.
*
* @param connectorName the name of the connector.
*
* @return an {@link IllegalStateException} for the error.
*/
@Message(id = 27, value = "Connector %s not defined")
IllegalStateException connectorNotDefined(String connectorName);
/**
* Create an exception indicating that a messaging resource has failed
* to be created
*
* @param cause the cause of the error.
* @param name the name that failed to be created.
*
* @return the message.
*/
@Message(id = 28, value = "Failed to create %s")
StartException failedToCreate(@Cause Throwable cause, String name);
/**
* Creates an exception indicating a failure to find the SocketBinding for the broadcast binding.
*
* @param name the name of the connector.
*
* @return a {@link StartException} for the error.
*/
@Message(id = 29, value = "Failed to find SocketBinding for broadcast binding: %s")
StartException failedToFindBroadcastSocketBinding(String name);
/**
* Creates an exception indicating a failure to find the SocketBinding for the connector.
*
* @param name the name of the connector.
*
* @return a {@link StartException} for the error.
*/
@Message(id = 30, value = "Failed to find SocketBinding for connector: %s")
StartException failedToFindConnectorSocketBinding(String name);
/**
* Creates an exception indicating a failure to find the SocketBinding for the discovery binding.
*
* @param name the name of the connector.
*
* @return a {@link StartException} for the error.
*/
@Message(id = 31, value = "Failed to find SocketBinding for discovery binding: %s")
StartException failedToFindDiscoverySocketBinding(String name);
/**
* Creates an exception indicating a server failed to shutdown.
*
* @param cause the cause of the error.
* @param server the server that failed to shutdown.
*
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 32, value = "Failed to shutdown %s server")
RuntimeException failedToShutdownServer(@Cause Throwable cause, String server);
/**
* Creates an exception indicating the service failed to start.
*
* @param cause the cause of the error.
*
* @return a {@link StartException} for the error.
*/
@Message(id = 33, value = "Failed to start service")
StartException failedToStartService(@Cause Throwable cause);
// /**
// * Creates an exception indicating an unhandled element is being ignored.
// *
// * @param element the element that's being ignored.
// * @param location the location of the element.
// *
// * @return a {@link XMLStreamException} for the error.
// */
// @Message(id = 34, value = "Ignoring unhandled element: %s, at: %s")
// XMLStreamException ignoringUnhandledElement(String element, String location);
//
// /**
// * A message indicating an illegal element, represented by the {@code illegalElement} parameter, cannot be used
// * when the element, represented by the {@code element} parameter, is used.
// *
// * @param illegalElement the illegal element.
// * @param element the element the {@code illegalElement} cannot be used with.
// *
// * @return the message.
// */
// @Message(id = 35, value = "Illegal element %s: cannot be used when %s is used")
// String illegalElement(String illegalElement, String element);
/**
* A message indicating an illegal value, represented by the {@code value} parameter, for the element, represented
* by the {@code element} parameter.
*
* @param value the illegal value.
* @param element the element.
*
* @return the message.
*/
@Message(id = 36, value = "Illegal value %s for element %s")
String illegalValue(Object value, String element);
// /**
// * A message indicating an illegal value, represented by the {@code value} parameter, for the element, represented
// * by the {@code element} parameter, as it could not be converted to the required type, represented by the
// * {@code expectedType} parameter.
// *
// * @param value the illegal value.
// * @param element the element.
// * @param expectedType the required type.
// *
// * @return the message.
// */
// @Message(id = INHERIT, value = "Illegal value %s for element %s as it could not be converted to required type %s")
// String illegalValue(Object value, String element, ModelType expectedType);
/**
* Creates an exception indicating a resource is immutable.
*
* @return an {@link UnsupportedOperationException} for the error.
*/
@Message(id = 37, value = "Resource is immutable")
UnsupportedOperationException immutableResource();
/**
* A message indicating the object, represented by the {@code obj} parameter, is invalid.
*
* @param obj the invalid object.
*
* @return the message.
*/
@Message(id = 38, value = "%s is invalid")
String invalid(Object obj);
/**
* Creates an exception indicating the attribute, represented by the {@code name} parameter, has an unexpected type,
* represented by the {@code type} parameter.
*
* @param name the name of the attribute.
* @param type the type of the attribute.
*
* @return an {@link IllegalStateException} for the error.
*/
@Message(id = 39, value = "Attribute %s has unexpected type %s")
IllegalStateException invalidAttributeType(String name, ModelType type);
// /**
// * A message indicating the operation must include the parameter represented by {@code paramName1} or the parameter
// * represented by the {@code paramName2} parameter.
// *
// * @param paramName1 the name of the parameter.
// * @param paramName2 the name of the parameter.
// *
// * @return the message.
// */
// @Message(id = 40, value = "Operation must include parameter %s or parameter %s")
// String invalidOperationParameters(String paramName1, String paramName2);
// /**
// * A message indicating the value, represented by the {@code value} parameter, is invalid for the parameter,
// * represented by the {@code name} parameter. The value must must be one of the values defined in the
// * {@code allowedValues} parameter.
// *
// * @param value the invalid value.
// * @param name the name of the parameter.
// * @param allowedValues the values that are allowed.
// *
// * @return the message.
// */
// @Message(id = 41, value = "%s is an invalid value for parameter %s. Values must be one of: %s")
// String invalidParameterValue(Object value, String name, Collection<?> allowedValues);
/**
* Creates an exception indicating the service, represented by the {@code service} parameter, is in an invalid
* state.
*
* @param service the service.
* @param validState the valid state.
* @param currentState the current state of the service.
*
* @return an {@link IllegalStateException} for the error.
*/
@Message(id = 42, value = "Service %s is not in state %s, it is in state %s")
IllegalStateException invalidServiceState(ServiceName service, ServiceController.State validState, ServiceController.State currentState);
/**
* A message indicating the JNDI name has already been registered.
*
* @param jndiName the JNDI name.
*
* @return the message.
*/
@Message(id = 43, value = "JNDI name %s is already registered")
String jndiNameAlreadyRegistered(String jndiName);
// /**
// * Creates an exception indicating multiple children, represented by the {@code element} parameter, were found, but
// * not allowed.
// *
// * @param element the element
// *
// * @return an {@link IllegalStateException} for the error.
// */
// @Message(id = 44, value = "Multiple %s children found; only one is allowed")
// IllegalStateException multipleChildrenFound(String element);
/**
* A message the object, represented by the {@code obj} parameter, is required.
*
* @param obj the object that is required.
*
* @return the message.
*/
@Message(id = 45, value = "%s is required")
String required(Object obj);
/**
* A message indicating either {@code obj1} or {@code obj2} is required.
*
* @param obj1 the first option.
* @param obj2 the second option.
*
* @return the message.
*/
@Message(id = 46, value = "Either %s or %s is required")
String required(Object obj1, Object obj2);
/**
* Creates an exception indicating the variable cannot be {@code null}
*
* @param varName the variable name.
*
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 47, value = "%s is null")
IllegalArgumentException nullVar(String varName);
// /**
// * A message indicating the parameter, represented by the {@code parameter} parameter, is not defined.
// *
// * @param parameter the parameter.
// *
// * @return the message.
// */
// @Message(id = 48, value = "Parameter not defined: %s")
// String parameterNotDefined(Object parameter);
//
// /**
// * A message indicating there is no such attribute.
// *
// * @param name the name of the attribute.
// *
// * @return the message.
// */
// @Message(id = 49, value = "No such attribute (%s)")
// String unknownAttribute(String name);
/**
* Creates an exception indicating the read support for the attribute represented by the {@code name} parameter was
* not properly implemented.
*
* @param name the name of the attribute.
*
* @return an {@link IllegalStateException} for the error.
*/
@Message(id = 50, value = "Read support for attribute %s was not properly implemented")
IllegalStateException unsupportedAttribute(String name);
// /**
// * Creates an exception indicating that no support for the element, represented by the {@code name} parameter, has
// * been implemented.
// *
// * @param name the name of the element.
// *
// * @return an {@link UnsupportedOperationException} for the error.
// */
// @Message(id = 51, value = "Implement support for element %s")
// UnsupportedOperationException unsupportedElement(String name);
/**
* Creates an exception indicating the read support for the operation represented by the {@code name} parameter was
* not properly implemented.
*
* @param name the operation name.
*
* @return an {@link IllegalStateException} for the error.
*/
@Message(id = 52, value = "Support for operation %s was not properly implemented")
IllegalStateException unsupportedOperation(String name);
/**
* Creates an exception indicating the runtime handling of the attribute represented by the {@code name} parameter
* is not implemented.
*
* @param name the name of the attribute.
*
* @return an {@link UnsupportedOperationException} for the error.
*/
@Message(id = 53, value = "Runtime handling for %s is not implemented")
UnsupportedOperationException unsupportedRuntimeAttribute(String name);
/**
* Creates an exception indicating the ActiveMQServerService for the server with the given name is either not installed
* or not started.
*
* @param name the name of the Hornet Q server.
*
* @return an {@link OperationFailedException} for the error.
*/
@Message(id = 54, value = "No ActiveMQ Server is available under name %s")
OperationFailedException activeMQServerNotInstalled(String name);
@Message(id = 55, value = "Could not parse file %s")
DeploymentUnitProcessingException couldNotParseDeployment(final String file, @Cause Throwable cause);
@Message(id = 56, value = "Handler cannot handle operation %s")
IllegalStateException operationNotValid(final String operation);
@Message(id = 57, value = "No message destination registered at address %s")
String noDestinationRegisteredForAddress(final PathAddress address);
@Message(id = 58, value = "SecurityDomainContext has not been set")
IllegalStateException securityDomainContextNotSet();
// /**
// * A message indicating only of of {@code obj1} or {@code obj2} is allowed.
// *
// * @param obj1 the first option.
// * @param obj2 the second option.
// *
// * @return the message.
// */
// @Message(id = 59, value = "Only one of %s or %s is required")
// String onlyOneRequired(Object obj1, Object obj2);
/**
* Create an exception indicating that a messaging resource has failed
* to be recovered
*
* @param cause the cause of the error.
* @param name the name that failed to be recovered.
*
* @return the message.
*/
@Message(id = 60, value = "Failed to recover %s")
OperationFailedException failedToRecover(@Cause Throwable cause, String name);
// /**
// * Create a failure description message indicating that an attribute is not supported by a given model version.
// *
// * @param attributes the name(s) of the unsupported attribute(s)
// * @param version the model version that does not support the attribute
// *
// * @return the message.
// */
// @Message(id = 61, value = "Attribute(s) %s are not supported by messaging management model %s")
// String unsupportedAttributeInVersion(String attributes, ModelVersion version);
//
// /**
// * Create a failure description message indicating that the clustered attribute is deprecated.
// *
// * @return an {@link UnsupportedOperationException} for the error.
// */
// @Message(id = 62, value = "The clustered attribute is deprecated. To create a clustered ActiveMQ server, define at least one cluster-connection")
// UnsupportedOperationException canNotWriteClusteredAttribute();
/**
* Create a failure description message indicating that the resource of given type can not be registered.
*
* @return an {@link UnsupportedOperationException} for the error.
*/
@Message(id = 63, value = "Resources of type %s cannot be registered")
UnsupportedOperationException canNotRegisterResourceOfType(String childType);
/**
* Create a failure description message indicating that the resource of given type can not be removed.
*
* @return an {@link UnsupportedOperationException} for the error.
*/
@Message(id = 64, value = "Resources of type %s cannot be removed")
UnsupportedOperationException canNotRemoveResourceOfType(String childType);
@Message(id = 66, value = "Resource at the address %s can not be managed, the server is in backup mode")
String serverInBackupMode(PathAddress address);
/**
* Create a failure description message indicating that the given broadcast-group's connector reference is not present in the listed connectors.
*
* @return an {@link OperationFailedException} for the error.
*/
@Message(id = 67, value = "The broadcast group '%s' defines reference to nonexistent connector '%s'. Available connectors '%s'.")
OperationFailedException wrongConnectorRefInBroadCastGroup(final String bgName, final String connectorRef, final Collection<String> presentConnectors);
/**
* Create an exception when calling a method not allowed on injected JMSContext.
*
* @return an {@link IllegalStateRuntimeException} for the error.
*/
@Message(id = 68, value = "It is not permitted to call this method on injected JMSContext (see Jakarta Messaging 2.0 spec, §12.4.5).")
IllegalStateRuntimeException callNotPermittedOnInjectedJMSContext();
// /**
// * A message indicating the alternative attribute represented by the {@code name} parameter can not be undefined as the resource
// * has not defined any other alternative .
// *
// * @param name the attribute name.
// *
// * @return the message.
// */
// @Message(id = 69, value = "Attribute (%s) can not been undefined as the resource does not define any alternative to this attribute.")
// String undefineAttributeWithoutAlternative(String name);
//
// @Message(id = 70, value = "Attributes %s is an alias for attribute %s; both cannot be set with conflicting values.")
// OperationFailedException inconsistentStatisticsSettings(String attrOne, String attrTwo);
/**
* Logs a warn message when there is no resource matching the address-settings' expiry-address.
*
* @param address the name of the address-settings' missing expiry-address
* @param addressSettings the name of the address-settings
*/
@LogMessage(level = WARN)
@Message(id = 71, value = "There is no resource matching the expiry-address %s for the address-settings %s, expired messages from destinations matching this address-setting will be lost!")
void noMatchingExpiryAddress(String address, String addressSettings);
/**
* Logs a warn message when there is no resource matching the address-settings' dead-letter-address.
*
* @param address the name of the address-settings' missing dead-letter-address
* @param addressSettings the name of the address-settings
*/
@LogMessage(level = WARN)
@Message(id = 72, value = "There is no resource matching the dead-letter-address %s for the address-settings %s, undelivered messages from destinations matching this address-setting will be lost!")
void noMatchingDeadLetterAddress(String address, String addressSettings);
/**
* A message indicating the resource must have at least one JNDI name.
*
* @param jndiName the JNDI name.
*
* @return the message.
*/
@Message(id = 73, value = "Can not remove JNDI name %s. The resource must have at least one JNDI name")
String canNotRemoveLastJNDIName(String jndiName);
// @Message(id = 74, value = "Invalid parameter key: %s, the allowed keys are %s.")
// OperationFailedException invalidParameterName(String parameterName, Set<String> allowedKeys);
/**
* Logs a INFO message indicating AIO was not found, ask to install LibAIO to enable the AIO on Linux systems to achieve optimal performance.
*/
@LogMessage(level = INFO)
@Message(id = 75, value = "AIO wasn't located on this platform, it will fall back to using pure Java NIO. Your platform is Linux, install LibAIO to enable the AIO journal and achieve optimal performance.")
void aioInfoLinux();
@Message(id = 76, value = "Parameter %s contains duplicate elements [%s]")
OperationFailedException duplicateElements(String parameterName, ModelNode elements);
@Message(id = 77, value = "Can not remove unknown entry %s")
OperationFailedException canNotRemoveUnknownEntry(String entry);
@Message(id = 78, value = "Only one %s child resource is allowed, found children: %s")
OperationFailedException onlyOneChildIsAllowed(String childType, Set<String> childrenNames);
@Message(id = 79, value = "Indexed child resources can only be registered if the parent resource supports ordered children. The parent of '%s' is not indexed")
IllegalStateException indexedChildResourceRegistrationNotAvailable(PathElement address);
@Message(id = 80, value = "Discovery group %s is not defined")
StartException discoveryGroupIsNotDefined(String discoveryGroupName);
@Message(id = 81, value = "Unsupported type of broadcast group configuration for legacy resource: %s")
StartException unsupportedBroadcastGroupConfigurationForLegacy(String broadcastGroupConfigurationClassName);
@Message(id = 82, value = "Unsupported type of connector factory for legacy resource: %s")
StartException unsupportedConnectorFactoryForLegacy(String connectorFactoryClassName);
@Message(id = 83, value = "The %s operation can not be performed: the server must be in %s mode")
OperationFailedException managementOperationAllowedOnlyInRunningMode(String operationName, RunningMode mode);
@Message(id = 84, value = "The server does not define any in-vm connector. One is required to be able to import a journal")
OperationFailedException noInVMConnector();
@Message(id = 85, value = "Unable to load class %s from module %s")
OperationFailedException unableToLoadClassFromModule(String className, String moduleName);
@Message(id = 86, value = "Unable to load module %s")
OperationFailedException unableToLoadModule(String moduleName, @Cause ModuleLoadException cause);
@Message(id = 87, value = "Unable to load connector service factory class: %s")
OperationFailedException unableToLoadConnectorServiceFactoryClass(String factroyClass);
@Message(id = 88, value = "%s is an invalid value for parameter %s, it should be multiple of %s")
OperationFailedException invalidModularParameterValue(long size, String parameterName, long modular);
@LogMessage(level = WARN)
@Message(id = 89, value = "Resource at %s is not correctly configured: when its attribute %s is defined, the other attributes %s will not be taken into account")
void invalidConfiguration(PathAddress address, String definedAttribute, List<String> otherAttributes);
@Message(id = 90, value = "The Elytron security domain cannot be null")
IllegalArgumentException invalidNullSecurityDomain();
@LogMessage(level = DEBUG)
@Message(id = 91, value = "Failed to authenticate username %s. Exception message: %s")
void failedAuthenticationWithException(@Cause final Throwable cause, final String username, final String message);
@LogMessage(level = DEBUG)
@Message(id = 92, value = "Failed to authenticate username %s: cannot verify username/password pair")
void failedAuthentication(final String username);
@LogMessage(level = DEBUG)
@Message(id = 93, value = "Failed to authorize username %s: missing permissions")
void failedAuthorization(final String username);
@LogMessage(level = WARN)
@Message(id = 94, value = "Unable to detect database dialect from connection metadata or JDBC driver name. Please configure this manually using the 'journal-database' property in your configuration. Known database dialect strings are %s")
void jdbcDatabaseDialectDetectionFailed(String databaseDialects);
@LogMessage(level = WARN)
@Message(id = 95, value = "Multiple client-mapping found in [%s] socket binding used by ActiveMQ [%s] transport configuration. Using address: [host: %s, port %s]")
void multipleClientMappingsFound(String socketBindingName, String transportConfigName, String host, int port);
@Message(id = 96, value = "The %s operation can not be performed on a JDBC store journal")
OperationFailedException operationNotAllowedOnJdbcStore(String operationName);
@Message(id = 97, value = "There is no socket-binding or outbound-socket-binding configured with the name %s")
OperationFailedException noSocketBinding(String connectorSocketBinding);
@Message(id = 98, value = "Unable to load module %s - the module or one of its dependencies is missing [%s]")
OperationFailedException moduleNotFound(String moduleName, String missingModule, @Cause ModuleNotFoundException e);
@Message(id = 99, value = "Creating the remote destination %s failed with error %s")
StartException remoteDestinationCreationFailed(String destinationName, String error);
@Message(id = 100, value = "Deleting the remote destination %s failed with error %s")
RuntimeException remoteDestinationDeletionFailed(String destinationName, String error);
@LogMessage(level = WARN)
@Message(id = 101, value = "Invalid value %s for %s, legal values are %s, default value is applied.")
void invalidTransactionNameValue(String value, String name, Collection<?> validValues);
@Message(id = 102, value = "HTTP Upgrade request missing Sec-JbossRemoting-Key header")
IOException upgradeRequestMissingKey();
@Message(id = 103, value = "Broker is not started. It cannot be managed yet.")
IllegalStateException brokerNotStarted();
@Message(id = 104, value = "Legacy security is no longer supported.")
IllegalStateException legacySecurityUnsupported();
@Message(id = 105, value = "The %s %s is configured to use socket-binding %s, but this socket binding doesn't have the multicast-address or a multicast-port attributes configured.")
OperationFailedException socketBindingMulticastNotSet(String resourceType, String resourceName, String socketBindingName);
@Message(id = 106, value = "The bridge %s didn't deploy.")
OperationFailedException failedBridgeDeployment(String bridgeName);
@Message(id = 107, value = "You must define a elytron security doman when security is enabled.")
IllegalStateException securityEnabledWithoutDomain();
@Message(id = 108, value = "Either socket-binding or jgroups-cluster attribute is required.")
OperationFailedException socketBindingOrJGroupsClusterRequired();
}
| 38,915
| 42.578947
| 243
|
java
|
null |
wildfly-main/messaging-activemq/injection/src/main/java/org/wildfly/extension/messaging/activemq/deployment/DefaultJMSConnectionFactoryBinding.java
|
/*
* Copyright 2021 JBoss by Red Hat.
*
* 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.wildfly.extension.messaging.activemq.deployment;
/**
*
* @author Emmanuel Hugonnet (c) 2021 Red Hat, Inc.
*/
public class DefaultJMSConnectionFactoryBinding {
public static final String DEFAULT_JMS_CONNECTION_FACTORY = "DefaultJMSConnectionFactory";
public static final String COMP_DEFAULT_JMS_CONNECTION_FACTORY = "java:comp/"+DEFAULT_JMS_CONNECTION_FACTORY;
}
| 988
| 37.038462
| 113
|
java
|
null |
wildfly-main/messaging-activemq/injection/src/main/java/org/wildfly/extension/messaging/activemq/deployment/injection/JMSContextWrapper.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq.deployment.injection;
import java.io.Serializable;
import jakarta.jms.BytesMessage;
import jakarta.jms.ConnectionMetaData;
import jakarta.jms.Destination;
import jakarta.jms.ExceptionListener;
import jakarta.jms.JMSConsumer;
import jakarta.jms.JMSContext;
import jakarta.jms.JMSProducer;
import jakarta.jms.MapMessage;
import jakarta.jms.Message;
import jakarta.jms.ObjectMessage;
import jakarta.jms.Queue;
import jakarta.jms.QueueBrowser;
import jakarta.jms.StreamMessage;
import jakarta.jms.TemporaryQueue;
import jakarta.jms.TemporaryTopic;
import jakarta.jms.TextMessage;
import jakarta.jms.Topic;
import org.wildfly.extension.messaging.activemq.logging.MessagingLogger;
/**
* Wrapper to restrict use of methods for injected JMSContext (Jakarta Messaging 2.0 spec, §12.4.5).
*
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2016 Red Hat inc.
*/
abstract class JMSContextWrapper implements JMSContext {
abstract JMSContext getDelegate();
// JMSContext interface implementation
@Override
public JMSContext createContext(int sessionMode) {
return getDelegate().createContext(sessionMode);
}
@Override
public JMSProducer createProducer() {
return getDelegate().createProducer();
}
@Override
public String getClientID() {
return getDelegate().getClientID();
}
@Override
public void setClientID(String clientID) {
throw MessagingLogger.ROOT_LOGGER.callNotPermittedOnInjectedJMSContext();
}
@Override
public ConnectionMetaData getMetaData() {
return getDelegate().getMetaData();
}
@Override
public ExceptionListener getExceptionListener() {
return getDelegate().getExceptionListener();
}
@Override
public void setExceptionListener(ExceptionListener listener) {
throw MessagingLogger.ROOT_LOGGER.callNotPermittedOnInjectedJMSContext();
}
@Override
public void start() {
throw MessagingLogger.ROOT_LOGGER.callNotPermittedOnInjectedJMSContext();
}
@Override
public void stop() {
throw MessagingLogger.ROOT_LOGGER.callNotPermittedOnInjectedJMSContext();
}
@Override
public void setAutoStart(boolean autoStart) {
throw MessagingLogger.ROOT_LOGGER.callNotPermittedOnInjectedJMSContext();
}
@Override
public boolean getAutoStart() {
return getDelegate().getAutoStart();
}
@Override
public void close() {
throw MessagingLogger.ROOT_LOGGER.callNotPermittedOnInjectedJMSContext();
}
@Override
public BytesMessage createBytesMessage() {
return getDelegate().createBytesMessage();
}
@Override
public MapMessage createMapMessage() {
return getDelegate().createMapMessage();
}
@Override
public Message createMessage() {
return getDelegate().createMessage();
}
@Override
public ObjectMessage createObjectMessage() {
return getDelegate().createObjectMessage();
}
@Override
public ObjectMessage createObjectMessage(Serializable object) {
return getDelegate().createObjectMessage(object);
}
@Override
public StreamMessage createStreamMessage() {
return getDelegate().createStreamMessage();
}
@Override
public TextMessage createTextMessage() {
return getDelegate().createTextMessage();
}
@Override
public TextMessage createTextMessage(String text) {
return getDelegate().createTextMessage(text);
}
@Override
public boolean getTransacted() {
return getDelegate().getTransacted();
}
@Override
public int getSessionMode() {
return getDelegate().getSessionMode();
}
@Override
public void commit() {
throw MessagingLogger.ROOT_LOGGER.callNotPermittedOnInjectedJMSContext();
}
@Override
public void rollback() {
throw MessagingLogger.ROOT_LOGGER.callNotPermittedOnInjectedJMSContext();
}
@Override
public void recover() {
throw MessagingLogger.ROOT_LOGGER.callNotPermittedOnInjectedJMSContext();
}
@Override
public JMSConsumer createConsumer(Destination destination) {
return getDelegate().createConsumer(destination);
}
@Override
public JMSConsumer createConsumer(Destination destination, String messageSelector) {
return getDelegate().createConsumer(destination, messageSelector);
}
@Override
public JMSConsumer createConsumer(Destination destination, String messageSelector, boolean noLocal) {
return getDelegate().createConsumer(destination, messageSelector, noLocal);
}
@Override
public Queue createQueue(String queueName) {
return getDelegate().createQueue(queueName);
}
@Override
public Topic createTopic(String topicName) {
return getDelegate().createTopic(topicName);
}
@Override
public JMSConsumer createDurableConsumer(Topic topic, String name) {
return getDelegate().createDurableConsumer(topic, name);
}
@Override
public JMSConsumer createDurableConsumer(Topic topic, String name, String messageSelector, boolean noLocal) {
return getDelegate().createDurableConsumer(topic, name, messageSelector, noLocal);
}
@Override
public JMSConsumer createSharedDurableConsumer(Topic topic, String name) {
return getDelegate().createSharedDurableConsumer(topic, name);
}
@Override
public JMSConsumer createSharedDurableConsumer(Topic topic, String name, String messageSelector) {
return getDelegate().createSharedDurableConsumer(topic, name, messageSelector);
}
@Override
public JMSConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName) {
return getDelegate().createSharedConsumer(topic, sharedSubscriptionName);
}
@Override
public JMSConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName, String messageSelector) {
return getDelegate().createSharedConsumer(topic, sharedSubscriptionName, messageSelector);
}
@Override
public QueueBrowser createBrowser(Queue queue) {
return getDelegate().createBrowser(queue);
}
@Override
public QueueBrowser createBrowser(Queue queue, String messageSelector) {
return getDelegate().createBrowser(queue, messageSelector);
}
@Override
public TemporaryQueue createTemporaryQueue() {
return getDelegate().createTemporaryQueue();
}
@Override
public TemporaryTopic createTemporaryTopic() {
return getDelegate().createTemporaryTopic();
}
@Override
public void unsubscribe(String name) {
getDelegate().unsubscribe(name);
}
@Override
public void acknowledge() {
throw MessagingLogger.ROOT_LOGGER.callNotPermittedOnInjectedJMSContext();
}
}
| 7,965
| 28.503704
| 113
|
java
|
null |
wildfly-main/messaging-activemq/injection/src/main/java/org/wildfly/extension/messaging/activemq/deployment/injection/JMSInfo.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq.deployment.injection;
import static jakarta.jms.JMSContext.AUTO_ACKNOWLEDGE;
import static org.wildfly.extension.messaging.activemq.deployment.DefaultJMSConnectionFactoryBinding.COMP_DEFAULT_JMS_CONNECTION_FACTORY;
import jakarta.jms.JMSConnectionFactory;
import jakarta.jms.JMSPasswordCredential;
import jakarta.jms.JMSSessionMode;
import org.jboss.metadata.property.PropertyReplacer;
/**
* Data structure containing the Jakarta Messaging information that can be annotated on an injected JMSContext.
*
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2016 Red Hat inc.
*/
class JMSInfo {
private final String connectionFactoryLookup;
private final String userName;
private final String password;
private final int sessionMode;
JMSInfo(JMSConnectionFactory connectionFactory, JMSPasswordCredential credential, JMSSessionMode sessionMode) {
PropertyReplacer propertyReplacer = JMSCDIExtension.propertyReplacer;
if (connectionFactory != null) {
connectionFactoryLookup = propertyReplacer.replaceProperties(connectionFactory.value());
} else {
connectionFactoryLookup = COMP_DEFAULT_JMS_CONNECTION_FACTORY;
}
if (credential != null) {
userName = propertyReplacer.replaceProperties(credential.userName());
password = propertyReplacer.replaceProperties(credential.password());
} else {
userName = null;
password = null;
}
if (sessionMode != null) {
this.sessionMode = sessionMode.value();
} else {
this.sessionMode = AUTO_ACKNOWLEDGE;
}
}
String getConnectionFactoryLookup() {
return connectionFactoryLookup;
}
String getUserName() {
return userName;
}
String getPassword() {
return password;
}
int getSessionMode() {
return sessionMode;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
JMSInfo jmsInfo = (JMSInfo) o;
if (sessionMode != jmsInfo.sessionMode) return false;
if (connectionFactoryLookup != null ? !connectionFactoryLookup.equals(jmsInfo.connectionFactoryLookup) : jmsInfo.connectionFactoryLookup != null)
return false;
if (password != null ? !password.equals(jmsInfo.password) : jmsInfo.password != null) return false;
if (userName != null ? !userName.equals(jmsInfo.userName) : jmsInfo.userName != null) return false;
return true;
}
@Override
public int hashCode() {
int result = connectionFactoryLookup != null ? connectionFactoryLookup.hashCode() : 0;
result = 31 * result + (userName != null ? userName.hashCode() : 0);
result = 31 * result + (password != null ? password.hashCode() : 0);
result = 31 * result + sessionMode;
return result;
}
}
| 4,047
| 36.481481
| 153
|
java
|
null |
wildfly-main/messaging-activemq/injection/src/main/java/org/wildfly/extension/messaging/activemq/deployment/injection/JMSCDIExtension.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq.deployment.injection;
import jakarta.enterprise.event.Observes;
import jakarta.enterprise.inject.spi.AnnotatedType;
import jakarta.enterprise.inject.spi.BeanManager;
import jakarta.enterprise.inject.spi.BeforeBeanDiscovery;
import jakarta.enterprise.inject.spi.Extension;
import org.jboss.metadata.property.PropertyReplacer;
/**
* Jakarta Contexts and Dependency Injection extension to provide injection of JMSContext resources.
*
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2013 Red Hat inc.
*/
class JMSCDIExtension implements Extension {
static PropertyReplacer propertyReplacer;
JMSCDIExtension(PropertyReplacer propertyReplacer) {
// store the propertyReplacer in a static field so that it can be used in JMSInfo by beans instantiated by Jakarta Contexts and Dependency Injection
JMSCDIExtension.propertyReplacer = propertyReplacer;
}
private void beforeBeanDiscovery(@Observes BeforeBeanDiscovery bbd, BeanManager bm) {
AnnotatedType<RequestedJMSContext> requestedContextBean = bm.createAnnotatedType(RequestedJMSContext.class);
bbd.addAnnotatedType(requestedContextBean, JMSCDIExtension.class.getName() + "-" + RequestedJMSContext.class.getName());
AnnotatedType<TransactedJMSContext> transactedContextBean = bm.createAnnotatedType(TransactedJMSContext.class);
bbd.addAnnotatedType(transactedContextBean, JMSCDIExtension.class.getName() + "-" + TransactedJMSContext.class.getName());
AnnotatedType<InjectedJMSContext> contextBean = bm.createAnnotatedType(InjectedJMSContext.class);
bbd.addAnnotatedType(contextBean, JMSCDIExtension.class.getName() + "-" + InjectedJMSContext.class.getName());
}
}
| 2,787
| 48.785714
| 156
|
java
|
null |
wildfly-main/messaging-activemq/injection/src/main/java/org/wildfly/extension/messaging/activemq/deployment/injection/TransactedJMSContext.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq.deployment.injection;
import jakarta.jms.JMSContext;
import jakarta.transaction.Synchronization;
import jakarta.transaction.TransactionScoped;
import jakarta.transaction.TransactionSynchronizationRegistry;
import static org.wildfly.extension.messaging.activemq.logging.MessagingLogger.ROOT_LOGGER;
/**
* Injection of JMSContext in the @TransactionScoped scope.
*
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2016 Red Hat inc.
*/
@TransactionScoped
class TransactedJMSContext extends AbstractJMSContext {
/**
* Closing of transaction scoped JMSContext is executed through Synchronization listener.
* This method registers listener, which takes care of closing JMSContext.
*
* @param transactionSynchronizationRegistry
* @param contextInstance
*/
void registerCleanUpListener(TransactionSynchronizationRegistry transactionSynchronizationRegistry, JMSContext contextInstance) {
//to avoid registration of more listeners for one context, flag in transaction is used.
Object alreadyRegistered = transactionSynchronizationRegistry.getResource(contextInstance);
if (alreadyRegistered == null) {
transactionSynchronizationRegistry.registerInterposedSynchronization(new AfterCompletionSynchronization(contextInstance));
transactionSynchronizationRegistry.putResource(contextInstance, AfterCompletionSynchronization.class.getName());
}
}
/**
* Synchronization task, which executes "cleanup" on JMSContext in AfterCompletion phase. BeforeCompletion does nothing.
*/
private class AfterCompletionSynchronization implements Synchronization {
final JMSContext context;
public AfterCompletionSynchronization(JMSContext context) {
this.context = context;
}
@Override
public void beforeCompletion() {
//intentionally blank
}
@Override
public void afterCompletion(int status) {
ROOT_LOGGER.debugf("Clean up JMSContext created from %s", TransactedJMSContext.this);
context.close();
}
}
}
| 3,209
| 40.153846
| 134
|
java
|
null |
wildfly-main/messaging-activemq/injection/src/main/java/org/wildfly/extension/messaging/activemq/deployment/injection/AbstractJMSContext.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq.deployment.injection;
import static org.wildfly.extension.messaging.activemq.logging.MessagingLogger.ROOT_LOGGER;
import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import jakarta.jms.ConnectionFactory;
import jakarta.jms.JMSContext;
/**
* Abstract class for managing JMS Contexts.
*
* 2 subclasses are provided with different CDI scope (@RequestScoped and @TransactionScoped).
*
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2016 Red Hat inc.
*/
public abstract class AbstractJMSContext implements Serializable {
private final Map<String, JMSContext> contexts = new ConcurrentHashMap<>();
JMSContext getContext(String injectionPointId, JMSInfo info, ConnectionFactory connectionFactory) {
return contexts.computeIfAbsent(injectionPointId, key -> {
return createContext(info, connectionFactory);
});
}
private JMSContext createContext(JMSInfo info, ConnectionFactory connectionFactory) {
ROOT_LOGGER.debugf("Create JMSContext from %s - %s", info, connectionFactory);
int sessionMode = info.getSessionMode();
String userName = info.getUserName();
final JMSContext context;
if (userName == null) {
context = connectionFactory.createContext(sessionMode);
} else {
String password = info.getPassword();
context = connectionFactory.createContext(userName, password, sessionMode);
}
return context;
}
void cleanUp() {
ROOT_LOGGER.debugf("Clean up JMSContext created from %s", this);
for (JMSContext jmsContext : contexts.values()) {
jmsContext.close();
}
contexts.clear();
}
}
| 2,819
| 37.630137
| 103
|
java
|
null |
wildfly-main/messaging-activemq/injection/src/main/java/org/wildfly/extension/messaging/activemq/deployment/injection/CDIDeploymentProcessor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq.deployment.injection;
import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.ee.structure.EJBAnnotationPropertyReplacement;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.weld.WeldCapability;
import org.jboss.metadata.property.PropertyReplacer;
/**
* Processor that deploys a CDI portable extension to provide injection of JMSContext resource.
*
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2013 Red Hat inc.
*/
public class CDIDeploymentProcessor implements DeploymentUnitProcessor {
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final DeploymentUnit parent = deploymentUnit.getParent() == null ? deploymentUnit : deploymentUnit.getParent();
PropertyReplacer propertyReplacer = EJBAnnotationPropertyReplacement.propertyReplacer(deploymentUnit);
final CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
if (support.hasCapability(WELD_CAPABILITY_NAME)) {
support.getOptionalCapabilityRuntimeAPI(WELD_CAPABILITY_NAME, WeldCapability.class).get()
.registerExtensionInstance(new JMSCDIExtension(propertyReplacer), parent);
}
}
}
| 2,763
| 50.185185
| 119
|
java
|
null |
wildfly-main/messaging-activemq/injection/src/main/java/org/wildfly/extension/messaging/activemq/deployment/injection/RequestedJMSContext.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq.deployment.injection;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.RequestScoped;
/**
* Injection of JMSContext in the @RequestScoped scope.
*
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2016 Red Hat inc.
*/
@RequestScoped
class RequestedJMSContext extends AbstractJMSContext {
@PreDestroy
@Override
void cleanUp() {
super.cleanUp();
}
}
| 1,485
| 34.380952
| 78
|
java
|
null |
wildfly-main/messaging-activemq/injection/src/main/java/org/wildfly/extension/messaging/activemq/deployment/injection/InjectedJMSContext.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq.deployment.injection;
import static org.wildfly.extension.messaging.activemq.logging.MessagingLogger.ROOT_LOGGER;
import java.io.Serializable;
import java.util.UUID;
import jakarta.enterprise.inject.Instance;
import jakarta.enterprise.inject.spi.InjectionPoint;
import jakarta.inject.Inject;
import jakarta.jms.ConnectionFactory;
import jakarta.jms.JMSConnectionFactory;
import jakarta.jms.JMSContext;
import jakarta.jms.JMSPasswordCredential;
import jakarta.jms.JMSSessionMode;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import jakarta.transaction.Status;
import jakarta.transaction.TransactionSynchronizationRegistry;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2016 Red Hat inc.
*/
class InjectedJMSContext extends JMSContextWrapper implements Serializable {
private static final String TRANSACTION_SYNCHRONIZATION_REGISTRY_LOOKUP = "java:comp/TransactionSynchronizationRegistry";
// Metadata to create the actual JMSContext.
private final JMSInfo info;
// JMSContext bean with the @RequestedScope
private final RequestedJMSContext requestedJMSContext;
// Identifier of the injected JMSContext
private final String id;
// JMSContext bean with the @TransactionScoped scope.
// An indirect reference is used as the instance is only valide when the transaction scope is active.
private transient Instance<TransactedJMSContext> transactedJMSContext;
// Cached reference to the connectionFactory used to create the actual JMSContext.
// It is cached to avoid repeated JNDI lookups.
private transient ConnectionFactory connectionFactory;
// Cached reference to the transaction sync registry to determine if a transaction is active
private transient TransactionSynchronizationRegistry transactionSynchronizationRegistry;
@Inject
InjectedJMSContext(InjectionPoint ip, RequestedJMSContext requestedJMSContext, Instance<TransactedJMSContext> transactedJMSContext) {
this.id = UUID.randomUUID().toString();
this.requestedJMSContext = requestedJMSContext;
this.transactedJMSContext = transactedJMSContext;
JMSConnectionFactory connectionFactory = ip.getAnnotated().getAnnotation(JMSConnectionFactory.class);
JMSPasswordCredential credential = ip.getAnnotated().getAnnotation(JMSPasswordCredential.class);
JMSSessionMode sessionMode = ip.getAnnotated().getAnnotation(JMSSessionMode.class);
this.info = new JMSInfo(connectionFactory, credential, sessionMode);
}
/**
* Return the actual JMSContext used by this injection.
*
* The use of the correct AbstractJMSContext (one with the @RequestScoped, the other
* with the @TransactionScoped) is determined by the presence on an active transaction.
*/
@Override
JMSContext getDelegate() {
boolean inTx = isInTransaction();
AbstractJMSContext jmsContext = inTx ? transactedJMSContext.get() : requestedJMSContext;
ROOT_LOGGER.debugf("using %s to create the injected JMSContext", jmsContext, id);
ConnectionFactory connectionFactory = getConnectionFactory();
JMSContext contextInstance = jmsContext.getContext(id, info, connectionFactory);
//fix of WFLY-9501
// CCM tries to clean opened connections before execution of @PreDestroy method on JMSContext - which is executed after completion, see .
// Correct phase to call close is afterCompletion {@see TransactionSynchronizationRegistry.registerInterposedSynchronization}
if(inTx) {
TransactedJMSContext transactedJMSContext = (TransactedJMSContext)jmsContext;
transactedJMSContext.registerCleanUpListener(transactionSynchronizationRegistry, contextInstance);
}
return contextInstance;
}
/**
* check whether there is an active transaction.
*/
private boolean isInTransaction() {
TransactionSynchronizationRegistry tsr = getTransactionSynchronizationRegistry();
boolean inTx = tsr.getTransactionStatus() == Status.STATUS_ACTIVE;
return inTx;
}
/**
* lookup the transactionSynchronizationRegistry and cache it.
*/
private TransactionSynchronizationRegistry getTransactionSynchronizationRegistry() {
TransactionSynchronizationRegistry cachedTSR = transactionSynchronizationRegistry;
if (cachedTSR == null) {
cachedTSR = (TransactionSynchronizationRegistry) lookup(TRANSACTION_SYNCHRONIZATION_REGISTRY_LOOKUP);
transactionSynchronizationRegistry = cachedTSR;
}
return cachedTSR;
}
/**
* lookup the connectionFactory and cache it.
*/
private ConnectionFactory getConnectionFactory() {
ConnectionFactory cachedCF = connectionFactory;
if (cachedCF == null) {
cachedCF = (ConnectionFactory)lookup(info.getConnectionFactoryLookup());
connectionFactory = cachedCF;
}
return cachedCF;
}
private Object lookup(String name) {
Context ctx = null;
try {
ctx = new InitialContext();
return ctx.lookup(name);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (ctx != null) {
try {
ctx.close();
} catch (NamingException e) {
}
}
}
}
}
| 6,551
| 41
| 145
|
java
|
null |
wildfly-main/preview/dist/src/test/java/org/wildfly/dist/subsystem/xml/XSDValidationUnitTestCase.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.wildfly.dist.subsystem.xml;
import org.junit.Test;
import org.wildfly.test.distribution.validation.AbstractValidationUnitTest;
/**
* A XSDValidationUnitTestCase.
*
* @author <a href="alex@jboss.com">Alexey Loubyansky</a>
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
public class XSDValidationUnitTestCase extends AbstractValidationUnitTest {
@Test
public void testJBossXsds() throws Exception {
jbossXsdsTest();
}
}
| 1,505
| 36.65
| 75
|
java
|
null |
wildfly-main/preview/dist/src/test/java/org/wildfly/dist/subsystem/xml/StandardConfigsXMLValidationUnitTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, 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.wildfly.dist.subsystem.xml;
import org.junit.Test;
import org.wildfly.test.distribution.validation.AbstractValidationUnitTest;
/**
* Performs validation against their xsd of the server configuration files in the distribution.
*
* @author Brian Stansberry
*/
public class StandardConfigsXMLValidationUnitTestCase extends AbstractValidationUnitTest {
@Test
public void testHost() throws Exception {
parseXml("domain/configuration/host.xml");
}
@Test
public void testHostSecondary() throws Exception {
parseXml("domain/configuration/host-secondary.xml");
}
@Test
public void testHostPrimary() throws Exception {
parseXml("domain/configuration/host-primary.xml");
}
@Test
public void testDomain() throws Exception {
parseXml("domain/configuration/domain.xml");
}
@Test
public void testStandalone() throws Exception {
parseXml("standalone/configuration/standalone.xml");
}
@Test
public void testStandaloneHA() throws Exception {
parseXml("standalone/configuration/standalone-ha.xml");
}
@Test
public void testStandaloneFull() throws Exception {
parseXml("standalone/configuration/standalone-full.xml");
}
//TODO Leave commented out until domain-jts.xml is definitely removed from the configuration
// @Test
// public void testDomainJTS() throws Exception {
// parseXml("docs/examples/configs/domain-jts.xml");
// }
//
// @Test
// public void testStandaloneEC2HA() throws Exception {
// parseXml("docs/examples/configs/standalone-ec2-ha.xml");
// }
//
// @Test
// public void testStandaloneEC2FullHA() throws Exception {
// parseXml("docs/examples/configs/standalone-ec2-full-ha.xml");
//
// }
// @Test
// public void testStandaloneGossipHA() throws Exception {
// parseXml("docs/examples/configs/standalone-gossip-ha.xml");
// }
//
// @Test
// public void testStandaloneGossipFullHA() throws Exception {
// parseXml("docs/examples/configs/standalone-gossip-full-ha.xml");
// }
@Test
public void testStandaloneJTS() throws Exception {
parseXml("docs/examples/configs/standalone-jts.xml");
}
@Test
public void testStandaloneMinimalistic() throws Exception {
parseXml("docs/examples/configs/standalone-minimalistic.xml");
}
@Test
public void testStandaloneXTS() throws Exception {
parseXml("docs/examples/configs/standalone-xts.xml");
}
@Test
public void testStandaloneRTS() throws Exception {
parseXml("docs/examples/configs/standalone-rts.xml");
}
@Test
public void testStandaloneGenericJMS() throws Exception {
parseXml("docs/examples/configs/standalone-genericjms.xml");
}
@Test
public void testStandaloneActiveMQEmbedded() throws Exception {
parseXml("docs/examples/configs/standalone-activemq-embedded.xml");
}
}
| 4,020
| 30.912698
| 96
|
java
|
null |
wildfly-main/health/src/test/java/org/wildfly/extension/health/HealthSubsystemTestCase.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.wildfly.extension.health;
import java.util.EnumSet;
import java.util.Properties;
import org.jboss.as.subsystem.test.AbstractSubsystemSchemaTest;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2019 Red Hat inc.
*/
@RunWith(Parameterized.class)
public class HealthSubsystemTestCase extends AbstractSubsystemSchemaTest<HealthSubsystemSchema> {
@Parameters
public static Iterable<HealthSubsystemSchema> parameters() {
return EnumSet.allOf(HealthSubsystemSchema.class);
}
public HealthSubsystemTestCase(HealthSubsystemSchema schema) {
super(HealthExtension.SUBSYSTEM_NAME, new HealthExtension(), schema, HealthSubsystemSchema.CURRENT);
}
@Override
protected String getSubsystemXmlPathPattern() {
// Exclude subsystem name from pattern
return "subsystem_%2$d_%3$d.xml";
}
@Override
protected Properties getResolvedProperties() {
return System.getProperties();
}
}
| 2,125
| 36.964286
| 108
|
java
|
null |
wildfly-main/health/src/main/java/org/wildfly/extension/health/ServerProbe.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.wildfly.extension.health;
import org.jboss.dmr.ModelNode;
public interface ServerProbe {
Outcome getOutcome();
String getName();
static class Outcome {
final ModelNode data;
final boolean success;
Outcome(boolean success, ModelNode data) {
this.data = data;
this.success = success;
}
private Outcome(boolean success) {
this(success, new ModelNode());
}
public ModelNode getData() {
return data;
}
public boolean isSuccess() {
return success;
}
static Outcome SUCCESS = new Outcome(true);
static Outcome FAILURE = new Outcome(false);
}
}
| 1,754
| 29.789474
| 70
|
java
|
null |
wildfly-main/health/src/main/java/org/wildfly/extension/health/HealthExtension.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.wildfly.extension.health;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import java.util.EnumSet;
import java.util.List;
import org.jboss.as.controller.Extension;
import org.jboss.as.controller.ExtensionContext;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.PersistentResourceXMLDescription;
import org.jboss.as.controller.PersistentResourceXMLDescriptionReader;
import org.jboss.as.controller.PersistentResourceXMLDescriptionWriter;
import org.jboss.as.controller.SubsystemRegistration;
import org.jboss.as.controller.descriptions.ParentResourceDescriptionResolver;
import org.jboss.as.controller.descriptions.SubsystemResourceDescriptionResolver;
import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler;
import org.jboss.as.controller.parsing.ExtensionParsingContext;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import org.kohsuke.MetaInfServices;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2020 Red Hat inc.
*/
@MetaInfServices(Extension.class)
public class HealthExtension implements Extension {
static final String EXTENSION_NAME = "org.wildfly.extension.health";
/**
* The name of our subsystem within the model.
*/
public static final String SUBSYSTEM_NAME = "health";
protected static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME);
protected static final ModelVersion VERSION_1_0_0 = ModelVersion.create(1, 0, 0);
private static final ModelVersion CURRENT_MODEL_VERSION = VERSION_1_0_0;
static final ParentResourceDescriptionResolver SUBSYSTEM_RESOLVER = new SubsystemResourceDescriptionResolver(SUBSYSTEM_NAME, HealthExtension.class);
private final PersistentResourceXMLDescription currentDescription = HealthSubsystemSchema.CURRENT.getXMLDescription();
@Override
public void initialize(ExtensionContext context) {
final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION);
subsystem.registerXMLElementWriter(new PersistentResourceXMLDescriptionWriter(this.currentDescription));
final ManagementResourceRegistration registration = subsystem.registerSubsystemModel(new HealthSubsystemDefinition());
registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE);
}
@Override
public void initializeParsers(ExtensionParsingContext context) {
for (HealthSubsystemSchema schema : EnumSet.allOf(HealthSubsystemSchema.class)) {
XMLElementReader<List<ModelNode>> reader = (schema == HealthSubsystemSchema.CURRENT) ? new PersistentResourceXMLDescriptionReader(this.currentDescription) : schema;
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, schema.getNamespace().getUri(), reader);
}
}
}
| 4,093
| 47.164706
| 176
|
java
|
null |
wildfly-main/health/src/main/java/org/wildfly/extension/health/HealthSubsystemDefinition.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.wildfly.extension.health;
import java.util.Arrays;
import java.util.Collection;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PersistentResourceDefinition;
import org.jboss.as.controller.ServiceRemoveStepHandler;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2020 Red Hat inc.
*/
public class HealthSubsystemDefinition extends PersistentResourceDefinition {
static final String HTTP_EXTENSIBILITY_CAPABILITY = "org.wildfly.management.http.extensible";
public static final String HEALTH_HTTP_SECURITY_CAPABILITY = "org.wildfly.extension.health.http-context.security-enabled";
static final String CLIENT_FACTORY_CAPABILITY ="org.wildfly.management.model-controller-client-factory";
static final String MANAGEMENT_EXECUTOR ="org.wildfly.management.executor";
static final RuntimeCapability<Void> HEALTH_HTTP_CONTEXT_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.extension.health.http-context", HealthContextService.class)
.addRequirements(HTTP_EXTENSIBILITY_CAPABILITY)
.build();
static final RuntimeCapability<Void> SERVER_HEALTH_PROBES_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.extension.health.server-probes", ServerProbesService.class)
.addRequirements(CLIENT_FACTORY_CAPABILITY, MANAGEMENT_EXECUTOR)
.build();
static final AttributeDefinition SECURITY_ENABLED = SimpleAttributeDefinitionBuilder.create("security-enabled", ModelType.BOOLEAN)
.setDefaultValue(ModelNode.TRUE)
.setRequired(false)
.setRestartAllServices()
.setAllowExpression(true)
.build();
static final AttributeDefinition[] ATTRIBUTES = { SECURITY_ENABLED };
protected HealthSubsystemDefinition() {
super(new SimpleResourceDefinition.Parameters(HealthExtension.SUBSYSTEM_PATH,
HealthExtension.SUBSYSTEM_RESOLVER)
.setAddHandler(HealthSubsystemAdd.INSTANCE)
.setRemoveHandler(new ServiceRemoveStepHandler(HealthSubsystemAdd.INSTANCE))
.addCapabilities(HEALTH_HTTP_CONTEXT_CAPABILITY, SERVER_HEALTH_PROBES_CAPABILITY));
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return Arrays.asList(ATTRIBUTES);
}
}
| 3,604
| 46.434211
| 176
|
java
|
null |
wildfly-main/health/src/main/java/org/wildfly/extension/health/HealthContextService.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.wildfly.extension.health;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME;
import static org.wildfly.extension.health.HealthSubsystemDefinition.HEALTH_HTTP_CONTEXT_CAPABILITY;
import static org.wildfly.extension.health.HealthSubsystemDefinition.HEALTH_HTTP_SECURITY_CAPABILITY;
import static org.wildfly.extension.health.HealthSubsystemDefinition.HTTP_EXTENSIBILITY_CAPABILITY;
import java.util.function.Consumer;
import java.util.function.Supplier;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.server.mgmt.domain.ExtensibleHttpManagement;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc.
*/
public class HealthContextService implements Service {
private static final String CONTEXT_NAME = "health";
public static final String MICROPROFILE_HEALTH_REPORTER_CAPABILITY = "org.wildfly.extension.microprofile.health.reporter";
private final Consumer<HealthContextService> consumer;
private final Supplier<ExtensibleHttpManagement> extensibleHttpManagement;
private final Supplier<Boolean> securityEnabled;
private Supplier<ServerProbesService> serverProbesService;
private HttpHandler overrideableHealthHandler;
private static boolean mpHealthSubsystemActive = false;
static void install(OperationContext context, boolean securityEnabled) {
ServiceBuilder<?> serviceBuilder = context.getServiceTarget().addService(HEALTH_HTTP_CONTEXT_CAPABILITY.getCapabilityServiceName());
Supplier<ExtensibleHttpManagement> extensibleHttpManagement = serviceBuilder.requires(context.getCapabilityServiceName(HTTP_EXTENSIBILITY_CAPABILITY, ExtensibleHttpManagement.class));
Consumer<HealthContextService> consumer = serviceBuilder.provides(HEALTH_HTTP_CONTEXT_CAPABILITY.getCapabilityServiceName());
Supplier<ServerProbesService> serverProbesService = serviceBuilder.requires(HealthSubsystemDefinition.SERVER_HEALTH_PROBES_CAPABILITY.getCapabilityServiceName());
final Supplier<Boolean> securityEnabledSupplier;
if (context.getCapabilityServiceSupport().hasCapability(HEALTH_HTTP_SECURITY_CAPABILITY)) {
securityEnabledSupplier = serviceBuilder.requires(ServiceName.parse(HEALTH_HTTP_SECURITY_CAPABILITY));
} else {
securityEnabledSupplier = new Supplier<Boolean>() {
@Override
public Boolean get() {
return securityEnabled;
}
};
}
// check if we will be also booting the MP Health subsystem. In that case, this subsystem should not be responding.
if (context.getCapabilityServiceSupport().hasCapability(MICROPROFILE_HEALTH_REPORTER_CAPABILITY)) {
mpHealthSubsystemActive = true;
}
serviceBuilder.setInstance(new HealthContextService(extensibleHttpManagement, consumer, securityEnabledSupplier, serverProbesService))
.install();
}
HealthContextService(Supplier<ExtensibleHttpManagement> extensibleHttpManagement, Consumer<HealthContextService> consumer, Supplier<Boolean> securityEnabled, Supplier<ServerProbesService> serverProbesService) {
this.extensibleHttpManagement = extensibleHttpManagement;
this.consumer = consumer;
this.securityEnabled = securityEnabled;
this.serverProbesService = serverProbesService;
}
@Override
public void start(StartContext context) {
extensibleHttpManagement.get().addManagementHandler(CONTEXT_NAME, securityEnabled.get(), new HealthCheckHandler(serverProbesService.get()));
consumer.accept(this);
}
@Override
public void stop(StopContext context) {
extensibleHttpManagement.get().removeContext(CONTEXT_NAME);
consumer.accept(null);
}
public void setOverrideableHealthHandler(HttpHandler handler) {
this.overrideableHealthHandler = handler;
}
private class HealthCheckHandler implements HttpHandler{
public static final String HEALTH = "/" + CONTEXT_NAME;
public static final String HEALTH_LIVE = HEALTH + "/live";
public static final String HEALTH_READY = HEALTH + "/ready";
public static final String HEALTH_STARTED = HEALTH + "/started";
private ServerProbesService serverProbes;
public HealthCheckHandler(ServerProbesService serverProbesService) {
this.serverProbes = serverProbesService;
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
if (overrideableHealthHandler != null) {
overrideableHealthHandler.handleRequest(exchange);
return;
}
if (mpHealthSubsystemActive) {
// if MP Health subsystem is present but not started yet we can't respond with management operation
// as the clients expect JSON which is an object not an array. So respond with 404 status code to
// not confuse consumers with wrong responses. This will still be correctly rejected in kubernetes.
exchange.setStatusCode(404);
return;
}
String requestPath = exchange.getRequestPath();
if (!HEALTH.equals(requestPath) && !HEALTH_LIVE.equals(requestPath) &&
!HEALTH_READY.equals(requestPath) && !HEALTH_STARTED.equals(requestPath)) {
exchange.setStatusCode(404);
return;
}
boolean globalOutcome = true;
ModelNode response = new ModelNode();
response.setEmptyList();
if (HEALTH.equals(requestPath) || HEALTH_READY.equals(requestPath)) {
for (ServerProbe serverProbe : serverProbes.getServerProbes()) {
ServerProbe.Outcome outcome = serverProbe.getOutcome();
if (!outcome.isSuccess()) {
globalOutcome = false;
}
ModelNode probeOutcome = new ModelNode();
probeOutcome.get(NAME).set(serverProbe.getName());
probeOutcome.get(OUTCOME).set(outcome.isSuccess());
if (outcome.getData().isDefined()) {
probeOutcome.get("data").set(outcome.getData());
}
response.add(probeOutcome);
}
}
if (HEALTH.equals(requestPath) || HEALTH_LIVE.equals(requestPath)) {
// always respond to the /health/live positively
ModelNode probeOutcome = new ModelNode();
probeOutcome.get(NAME).set("live-server");
probeOutcome.get(OUTCOME).set(true);
response.add(probeOutcome);
}
if (HEALTH.equals(requestPath) || HEALTH_STARTED.equals(requestPath)) {
// always respond to the /health/started positively
ModelNode probeOutcome = new ModelNode();
probeOutcome.get(NAME).set("started-server");
probeOutcome.get(OUTCOME).set(true);
response.add(probeOutcome);
}
response.add(OUTCOME, globalOutcome);
buildHealthResponse(exchange, globalOutcome ? 200: 503, response.toJSONString(true));
}
private void buildHealthResponse(HttpServerExchange exchange, int status, String response) {
exchange.setStatusCode(status)
.getResponseHeaders().add(Headers.CONTENT_TYPE, "application/json");
exchange.getResponseSender().send(response);
}
}
}
| 9,139
| 47.617021
| 214
|
java
|
null |
wildfly-main/health/src/main/java/org/wildfly/extension/health/HealthSubsystemSchema.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.health;
import static org.jboss.as.controller.PersistentResourceXMLDescription.builder;
import org.jboss.as.controller.PersistentResourceXMLDescription;
import org.jboss.as.controller.PersistentSubsystemSchema;
import org.jboss.as.controller.SubsystemSchema;
import org.jboss.as.controller.xml.VersionedNamespace;
import org.jboss.staxmapper.IntVersion;
/**
* Enumerates the supported namespaces for the health subsystem.
* @author Paul Ferraro
*/
public enum HealthSubsystemSchema implements PersistentSubsystemSchema<HealthSubsystemSchema> {
VERSION_1_0(1),
;
static final HealthSubsystemSchema CURRENT = VERSION_1_0;
private final VersionedNamespace<IntVersion, HealthSubsystemSchema> namespace;
HealthSubsystemSchema(int major) {
this.namespace = SubsystemSchema.createSubsystemURN(HealthExtension.SUBSYSTEM_NAME, new IntVersion(major));
}
@Override
public VersionedNamespace<IntVersion, HealthSubsystemSchema> getNamespace() {
return this.namespace;
}
@Override
public PersistentResourceXMLDescription getXMLDescription() {
return builder(HealthExtension.SUBSYSTEM_PATH, this.namespace)
.addAttributes(HealthSubsystemDefinition.ATTRIBUTES)
.build();
}
}
| 2,328
| 37.180328
| 115
|
java
|
null |
wildfly-main/health/src/main/java/org/wildfly/extension/health/ServerProbesService.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.wildfly.extension.health;
import static org.wildfly.extension.health.HealthSubsystemDefinition.CLIENT_FACTORY_CAPABILITY;
import static org.wildfly.extension.health.HealthSubsystemDefinition.MANAGEMENT_EXECUTOR;
import static org.wildfly.extension.health.HealthSubsystemDefinition.SERVER_HEALTH_PROBES_CAPABILITY;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.jboss.as.controller.LocalModelControllerClient;
import org.jboss.as.controller.ModelControllerClientFactory;
import org.jboss.as.controller.OperationContext;
import org.jboss.msc.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
public class ServerProbesService implements Service {
private Consumer<ServerProbesService> consumer;
private final Supplier<ModelControllerClientFactory> modelControllerClientFactory;
private final Supplier<Executor> managementExecutor;
private LocalModelControllerClient modelControllerClient;
private final Set<ServerProbe> serverProbes = new HashSet<>();
static void install(OperationContext context) {
ServiceBuilder<?> sb = context.getServiceTarget().addService(SERVER_HEALTH_PROBES_CAPABILITY.getCapabilityServiceName());
Consumer<ServerProbesService> consumer = sb.provides(SERVER_HEALTH_PROBES_CAPABILITY.getCapabilityServiceName());
Supplier<ModelControllerClientFactory> modelControllerClientFactory = sb.requires(context.getCapabilityServiceName(CLIENT_FACTORY_CAPABILITY, ModelControllerClientFactory.class));
Supplier<Executor> managementExecutor = sb.requires(context.getCapabilityServiceName(MANAGEMENT_EXECUTOR, Executor.class));
sb.setInstance(new ServerProbesService(consumer, modelControllerClientFactory, managementExecutor))
.install();
}
private ServerProbesService(Consumer<ServerProbesService> consumer, Supplier<ModelControllerClientFactory> modelControllerClientFactory, Supplier<Executor> managementExecutor) {
this.consumer = consumer;
this.modelControllerClientFactory = modelControllerClientFactory;
this.managementExecutor = managementExecutor;
}
@Override
public void start(StartContext context) throws StartException {
// we use a SuperUserClient for the local model controller client so that the server checks can be performed when RBAC is enabled.
// a doPriviledged block is not needed as these calls are initiated from the management endpoint.
// The user accessing the management endpoints must be authenticated (if security-enabled is true) but the server checks are not executed on their behalf.
modelControllerClient = modelControllerClientFactory.get().createSuperUserClient(managementExecutor.get(), true);
serverProbes.add(new ServerProbes.ServerStateCheck(modelControllerClient));
serverProbes.add(new ServerProbes.SuspendStateCheck(modelControllerClient));
serverProbes.add(new ServerProbes.DeploymentsStatusCheck(modelControllerClient));
serverProbes.add(new ServerProbes.NoBootErrorsCheck(modelControllerClient));
consumer.accept(this);
}
@Override
public void stop(StopContext context) {
serverProbes.clear();
consumer.accept(null);
modelControllerClient.close();
}
public Set<ServerProbe> getServerProbes() {
return serverProbes;
}
}
| 4,634
| 47.28125
| 187
|
java
|
null |
wildfly-main/health/src/main/java/org/wildfly/extension/health/ServerProbes.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.wildfly.extension.health;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.BOOT_ERRORS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CORE_SERVICE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEPLOYMENT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MANAGEMENT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
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.OUTCOME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STATUS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUSPEND_STATE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE;
import static org.jboss.as.server.suspend.SuspendController.State.RUNNING;
import java.util.List;
import org.jboss.as.controller.LocalModelControllerClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.dmr.ModelNode;
class ServerProbes {
private static final ModelNode READ_SERVER_STATE_ATTRIBUTE;
private static final ModelNode READ_SUSPEND_STATE_ATTRIBUTE;
private static final ModelNode READ_BOOT_ERRORS;
private static final ModelNode READ_DEPLOYMENTS_STATUS;
static {
READ_SERVER_STATE_ATTRIBUTE = new ModelNode();
READ_SERVER_STATE_ATTRIBUTE.get(OP).set(READ_ATTRIBUTE_OPERATION);
READ_SERVER_STATE_ATTRIBUTE.get(OP_ADDR).set(new ModelNode());
READ_SERVER_STATE_ATTRIBUTE.get(NAME).set("server-state");
READ_SUSPEND_STATE_ATTRIBUTE = new ModelNode();
READ_SUSPEND_STATE_ATTRIBUTE.get(OP).set(READ_ATTRIBUTE_OPERATION);
READ_SUSPEND_STATE_ATTRIBUTE.get(OP_ADDR).set(new ModelNode());
READ_SUSPEND_STATE_ATTRIBUTE.get(NAME).set(SUSPEND_STATE);
READ_BOOT_ERRORS = new ModelNode();
READ_BOOT_ERRORS.get(OP).set("read-boot-errors");
READ_BOOT_ERRORS.get(OP_ADDR).add(CORE_SERVICE, MANAGEMENT);
READ_DEPLOYMENTS_STATUS = new ModelNode();
READ_DEPLOYMENTS_STATUS.get(OP).set(READ_ATTRIBUTE_OPERATION);
READ_DEPLOYMENTS_STATUS.get(OP_ADDR).add(DEPLOYMENT, "*");
READ_DEPLOYMENTS_STATUS.get(NAME).set(STATUS);
}
/**
* Check that the server-state attribute value is "running"
*/
static class ServerStateCheck implements ServerProbe {
private LocalModelControllerClient modelControllerClient;
public ServerStateCheck(LocalModelControllerClient modelControllerClient) {
this.modelControllerClient = modelControllerClient;
}
@Override
public Outcome getOutcome() {
ModelNode response = modelControllerClient.execute(READ_SERVER_STATE_ATTRIBUTE);
if (!SUCCESS.equals(response.get(OUTCOME).asStringOrNull())) {
return Outcome.FAILURE;
}
if (response.hasDefined(FAILURE_DESCRIPTION)) {
ModelNode data = new ModelNode();
data.add(FAILURE_DESCRIPTION, response.get(FAILURE_DESCRIPTION).asString());
return new Outcome(false, data);
}
ModelNode result = response.get(RESULT);
if (!result.isDefined()) {
return Outcome.FAILURE;
}
String value = result.asString();
ModelNode data = new ModelNode();
data.add(VALUE, value);
return new Outcome("running".equals(value), data);
}
@Override
public String getName() {
return "server-state";
}
}
/**
* Check that the suspend-state attribute value is "RUNNING"
*/
static class SuspendStateCheck implements ServerProbe {
private final LocalModelControllerClient modelControllerClient;
public SuspendStateCheck(LocalModelControllerClient modelControllerClient) {
this.modelControllerClient = modelControllerClient;
}
@Override
public Outcome getOutcome() {
ModelNode response = modelControllerClient.execute(READ_SUSPEND_STATE_ATTRIBUTE);
if (!SUCCESS.equals(response.get(OUTCOME).asStringOrNull())) {
return Outcome.FAILURE;
}
if (response.hasDefined(FAILURE_DESCRIPTION)) {
ModelNode data = new ModelNode();
data.add(FAILURE_DESCRIPTION, response.get(FAILURE_DESCRIPTION).asString());
return new Outcome(false, data);
}
ModelNode result = response.get(RESULT);
if (!result.isDefined()) {
return Outcome.FAILURE;
}
String value = result.asString();
ModelNode data = new ModelNode();
data.add(VALUE, value);
return new Outcome(RUNNING.toString().equals(value), data);
}
@Override
public String getName() {
return "suspend-state";
}
}
/**
* Check that /core-service=management:read-boot-errors does not report any errors.
*/
static class NoBootErrorsCheck implements ServerProbe {
private LocalModelControllerClient modelControllerClient;
NoBootErrorsCheck(LocalModelControllerClient modelControllerClient) {
this.modelControllerClient = modelControllerClient;
}
@Override
public Outcome getOutcome() {
ModelNode response = modelControllerClient.execute(READ_BOOT_ERRORS);
if (!SUCCESS.equals(response.get(OUTCOME).asStringOrNull())) {
return Outcome.FAILURE;
}
if (response.hasDefined(FAILURE_DESCRIPTION)) {
ModelNode data = new ModelNode();
data.add(FAILURE_DESCRIPTION, response.get(FAILURE_DESCRIPTION).asString());
return new Outcome(false, data);
}
ModelNode result = response.get(RESULT);
if (!result.isDefined()) {
return Outcome.FAILURE;
}
List<ModelNode> errors = result.asList();
if (errors.isEmpty()) {
return Outcome.SUCCESS;
}
ModelNode data = new ModelNode();
data.add(BOOT_ERRORS, result.toJSONString(true));
return new Outcome(false, data);
}
@Override
public String getName() {
return "boot-errors";
}
}
/**
* Check that all deployments status are OK
*/
static class DeploymentsStatusCheck implements ServerProbe {
private LocalModelControllerClient modelControllerClient;
DeploymentsStatusCheck(LocalModelControllerClient modelControllerClient) {
this.modelControllerClient = modelControllerClient;
}
@Override
public Outcome getOutcome() {
ModelNode responses = modelControllerClient.execute(READ_DEPLOYMENTS_STATUS);
if (!SUCCESS.equals(responses.get(OUTCOME).asStringOrNull())) {
return Outcome.FAILURE;
}
if (!responses.get(RESULT).isDefined()) {
return Outcome.FAILURE;
}
ModelNode data = new ModelNode();
boolean globalStatus = true;
for (ModelNode response : responses.get(RESULT).asList()) {
boolean deploymentUp = false;
String info = null;
if (!SUCCESS.equals(response.get(OUTCOME).asStringOrNull())) {
info = "DMR Query failed";
} else if (response.hasDefined(FAILURE_DESCRIPTION)) {
info = response.get(FAILURE_DESCRIPTION).asString();
}
ModelNode result = response.get(RESULT);
if (!result.isDefined()) {
info = "status undefined";
}
String value = result.asString();
if ("OK".equals(value)) {
deploymentUp = true;
}
if (info == null) {
info = value;
}
PathAddress address = PathAddress.pathAddress(response.get(OP_ADDR));
String deploymentName = address.getElement(0).getValue();
data.add(deploymentName, info);
globalStatus = globalStatus && deploymentUp;
}
return new Outcome(globalStatus, data);
}
@Override
public String getName() {
return "deployments-status";
}
}
}
| 10,229
| 38.346154
| 102
|
java
|
null |
wildfly-main/health/src/main/java/org/wildfly/extension/health/HealthSubsystemAdd.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.wildfly.extension.health;
import static org.wildfly.extension.health._private.HealthLogger.LOGGER;
import org.jboss.as.controller.AbstractBoottimeAddStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.dmr.ModelNode;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc.
*/
public class HealthSubsystemAdd extends AbstractBoottimeAddStepHandler {
HealthSubsystemAdd() {
super(HealthSubsystemDefinition.ATTRIBUTES);
}
static final HealthSubsystemAdd INSTANCE = new HealthSubsystemAdd();
@Override
protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
super.performBoottime(context, operation, model);
final boolean securityEnabled = HealthSubsystemDefinition.SECURITY_ENABLED.resolveModelAttribute(context, model).asBoolean();
HealthContextService.install(context, securityEnabled);
ServerProbesService.install(context);
LOGGER.activatingSubsystem();
}
}
| 2,157
| 39.716981
| 133
|
java
|
null |
wildfly-main/health/src/main/java/org/wildfly/extension/health/_private/HealthLogger.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.wildfly.extension.health._private;
import static org.jboss.logging.Logger.Level.INFO;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
/**
* Log messages for WildFly health Extension.
*
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2020 Red Hat inc.
*/
@MessageLogger(projectCode = "WFLYHEALTH", length = 4)
public interface HealthLogger extends BasicLogger {
/**
* A logger with the category {@code org.wildfly.extension.health}.
*/
HealthLogger LOGGER = Logger.getMessageLogger(HealthLogger.class, "org.wildfly.extension.health");
/**
* Logs an informational message indicating the naming subsystem is being activated.
*/
@LogMessage(level = INFO)
@Message(id = 1, value = "Activating Base Health Subsystem")
void activatingSubsystem();
}
| 2,011
| 38.45098
| 102
|
java
|
null |
wildfly-main/clustering/service/src/main/java/org/wildfly/clustering/service/FunctionalService.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.wildfly.clustering.service;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.jboss.logging.Logger;
import org.jboss.msc.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.wildfly.common.function.Functions;
/**
* @author Paul Ferraro
*/
public class FunctionalService<T, V> implements Service {
private static final Logger LOGGER = Logger.getLogger(FunctionalService.class);
private final Consumer<V> consumer;
private final Function<T, V> mapper;
private final Supplier<T> factory;
private final Consumer<T> destroyer;
private volatile T value;
public FunctionalService(Consumer<V> consumer, Function<T, V> mapper, Supplier<T> factory) {
this(consumer, mapper, factory, Functions.discardingConsumer());
}
public FunctionalService(Consumer<V> consumer, Function<T, V> mapper, Supplier<T> factory, Consumer<T> destroyer) {
this.consumer = consumer;
this.mapper = mapper;
this.factory = factory;
this.destroyer = destroyer;
}
@Override
public void start(StartContext context) throws StartException {
try {
this.value = this.factory.get();
this.consumer.accept(this.mapper.apply(this.value));
} catch (RuntimeException | Error e) {
throw new StartException(e);
}
}
@Override
public void stop(StopContext context) {
try {
this.destroyer.accept(this.value);
} catch (RuntimeException | Error e) {
LOGGER.warn(e.getLocalizedMessage(), e);
} finally {
this.value = null;
}
}
}
| 2,817
| 33.790123
| 119
|
java
|
null |
wildfly-main/clustering/service/src/main/java/org/wildfly/clustering/service/Builder.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.wildfly.clustering.service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceTarget;
/**
* Encapsulates the logic for building a service.
* @author Paul Ferraro
* @param <T> the type of value provided by services built by this builder
* @deprecated Replaced by {@link ServiceConfigurator}.
*/
@Deprecated(forRemoval = true)
public interface Builder<T> extends ServiceConfigurator {
/**
* Builds a service into the specified target.
* @param target the service installation target
* @return a service builder
*/
@Override
ServiceBuilder<T> build(ServiceTarget target);
}
| 1,676
| 38
| 74
|
java
|
null |
wildfly-main/clustering/service/src/main/java/org/wildfly/clustering/service/UnaryRequirement.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.clustering.service;
/**
* Identifies a requirement that provides a service.
* Includes a unary function for resolving its name.
* @author Paul Ferraro
*/
public interface UnaryRequirement extends Requirement {
default String resolve(String name) {
return String.join(".", this.getName(), name);
}
}
| 1,365
| 36.944444
| 70
|
java
|
null |
wildfly-main/clustering/service/src/main/java/org/wildfly/clustering/service/CountDownLifecycleListener.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.wildfly.clustering.service;
import java.util.EnumSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import org.jboss.msc.service.LifecycleEvent;
import org.jboss.msc.service.LifecycleListener;
import org.jboss.msc.service.ServiceController;
/**
* {@link LifecycleListener} that counts down a latch when a target {@link LifecycleEvent} is triggered.
* @author Paul Ferraro
*/
public class CountDownLifecycleListener implements LifecycleListener {
private final Set<LifecycleEvent> targetEvents;
private final CountDownLatch latch;
public CountDownLifecycleListener(CountDownLatch latch) {
this(latch, EnumSet.allOf(LifecycleEvent.class));
}
public CountDownLifecycleListener(CountDownLatch latch, Set<LifecycleEvent> targetEvents) {
this.targetEvents = targetEvents;
this.latch = latch;
}
@Override
public void handleEvent(ServiceController<?> controller, LifecycleEvent event) {
if (this.targetEvents.contains(event)) {
this.latch.countDown();
}
}
}
| 2,103
| 35.912281
| 104
|
java
|
null |
wildfly-main/clustering/service/src/main/java/org/wildfly/clustering/service/ServiceNameRegistry.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.clustering.service;
import org.jboss.msc.service.ServiceName;
/**
* Registry of services names for a set of requirements.
* @author Paul Ferraro
* @deprecated To be removed without replacement.
*/
@Deprecated(forRemoval = true)
public interface ServiceNameRegistry<R extends Requirement> {
/**
* Returns the service name for the specified requirement
* @param requirement a requirement
* @return a service name.
*/
ServiceName getServiceName(R requirement);
}
| 1,538
| 36.536585
| 70
|
java
|
null |
wildfly-main/clustering/service/src/main/java/org/wildfly/clustering/service/SimpleSupplierDependency.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.wildfly.clustering.service;
import org.jboss.msc.service.ServiceBuilder;
/**
* A {@link Dependency} that supplies a static value
* @author Paul Ferraro
*/
public class SimpleSupplierDependency<V> implements SupplierDependency<V> {
private final V value;
public SimpleSupplierDependency(V value) {
this.value = value;
}
@Override
public V get() {
return this.value;
}
@Override
public <T> ServiceBuilder<T> register(ServiceBuilder<T> builder) {
// Nothing to register - value is already known.
return builder;
}
}
| 1,626
| 31.54
| 75
|
java
|
null |
wildfly-main/clustering/service/src/main/java/org/wildfly/clustering/service/ServiceConfigurator.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.wildfly.clustering.service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceTarget;
/**
* Configures the dependencies of a {@link org.jboss.msc.Service}.
* @author Paul Ferraro
*/
public interface ServiceConfigurator extends ServiceNameProvider {
/**
* Adds and configures a {@link org.jboss.msc.Service}.
* @param target a service target
* @return the builder of the service.
*/
ServiceBuilder<?> build(ServiceTarget target);
}
| 1,532
| 36.390244
| 70
|
java
|
null |
wildfly-main/clustering/service/src/main/java/org/wildfly/clustering/service/ServiceNameProvider.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.wildfly.clustering.service;
import org.jboss.msc.service.ServiceName;
/**
* Provides a service name.
* @author Paul Ferraro
*/
public interface ServiceNameProvider {
/**
* Returns the associated service name
* @return a service name
*/
ServiceName getServiceName();
}
| 1,332
| 34.078947
| 70
|
java
|
null |
wildfly-main/clustering/service/src/main/java/org/wildfly/clustering/service/Dependency.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.wildfly.clustering.service;
import org.jboss.msc.service.ServiceBuilder;
/**
* Encapsulates logic for registering a service dependency.
* @author Paul Ferraro
*/
public interface Dependency {
<T> ServiceBuilder<T> register(ServiceBuilder<T> builder);
}
| 1,298
| 37.205882
| 70
|
java
|
null |
wildfly-main/clustering/service/src/main/java/org/wildfly/clustering/service/IdentityServiceConfigurator.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.wildfly.clustering.service;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.jboss.msc.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
/**
* Configures a {@link Service} whose value is provided by another {@link Service}.
* @author Paul Ferraro
*/
public class IdentityServiceConfigurator<T> extends SimpleServiceNameProvider implements ServiceConfigurator {
private final ServiceName requirementName;
private final ServiceController.Mode initialMode;
/**
* Constructs a new service configurator.
* @param name the target service name
* @param targetName the target service
*/
public IdentityServiceConfigurator(ServiceName name, ServiceName requirementName) {
this(name, requirementName, ServiceController.Mode.PASSIVE);
}
/**
* Constructs a new service configurator.
* @param name the target service name
* @param targetName the target service
* @param initialMode the initial mode of the configured service.
*/
public IdentityServiceConfigurator(ServiceName name, ServiceName requirementName, ServiceController.Mode initialMode) {
super(name);
assert initialMode != ServiceController.Mode.REMOVE;
this.requirementName = requirementName;
this.initialMode = initialMode;
}
@Override
public ServiceBuilder<?> build(ServiceTarget target) {
ServiceBuilder<?> builder = target.addService(this.getServiceName());
Consumer<T> injector = builder.provides(this.getServiceName());
Supplier<T> requirement = builder.requires(this.requirementName);
Service service = new FunctionalService<>(injector, Function.identity(), requirement);
return builder.setInstance(service).setInitialMode(this.initialMode);
}
}
| 3,025
| 39.346667
| 123
|
java
|
null |
wildfly-main/clustering/service/src/main/java/org/wildfly/clustering/service/SimpleServiceNameProvider.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.wildfly.clustering.service;
import org.jboss.msc.service.ServiceName;
/**
* {@link ServiceNameProvider} using a pre-defined {@link ServiceName}
* @author Paul Ferraro
*/
public class SimpleServiceNameProvider implements ServiceNameProvider {
private final ServiceName name;
public SimpleServiceNameProvider(ServiceName name) {
this.name = name;
}
@Override
public ServiceName getServiceName() {
return this.name;
}
@Override
public int hashCode() {
return this.name.hashCode();
}
@Override
public boolean equals(Object object) {
if (!(object instanceof ServiceNameProvider)) return false;
ServiceNameProvider provider = (ServiceNameProvider) object;
return this.name.equals(provider.getServiceName());
}
@Override
public String toString() {
return this.name.getCanonicalName();
}
}
| 1,945
| 30.901639
| 71
|
java
|
null |
wildfly-main/clustering/service/src/main/java/org/wildfly/clustering/service/ServiceSupplierDependency.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.wildfly.clustering.service;
import java.util.function.Supplier;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
/**
* Encapsulates a {@link Dependency} on a {@link org.jboss.msc.Service} that supplies a value.
* @author Paul Ferraro
*/
public class ServiceSupplierDependency<V> extends SimpleServiceNameProvider implements SupplierDependency<V> {
private volatile Supplier<V> supplier;
public ServiceSupplierDependency(ServiceName name) {
super(name);
}
public ServiceSupplierDependency(ServiceNameProvider provider) {
super(provider.getServiceName());
}
@Override
public V get() {
return this.supplier.get();
}
@Override
public <T> ServiceBuilder<T> register(ServiceBuilder<T> builder) {
this.supplier = builder.requires(this.getServiceName());
return builder;
}
}
| 1,936
| 32.982456
| 110
|
java
|
null |
wildfly-main/clustering/service/src/main/java/org/wildfly/clustering/service/AsyncServiceConfigurator.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.wildfly.clustering.service;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.function.Supplier;
import org.jboss.msc.Service;
import org.jboss.msc.service.DelegatingServiceBuilder;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* @author Paul Ferraro
*/
public class AsyncServiceConfigurator extends SimpleServiceNameProvider implements ServiceConfigurator {
private static final ServiceName EXECUTOR_SERVICE_NAME = ServiceName.JBOSS.append("as", "server-executor");
private volatile boolean asyncStart = true;
private volatile boolean asyncStop = true;
/**
* Constructs a new builder for building asynchronous service
* @param name the target service name
*/
public AsyncServiceConfigurator(ServiceName name) {
super(name);
}
@Override
public ServiceBuilder<?> build(ServiceTarget target) {
ServiceBuilder<?> builder = target.addService(this.getServiceName());
Supplier<Executor> executor = builder.requires(EXECUTOR_SERVICE_NAME);
return new AsyncServiceBuilder<>(builder, executor, this.asyncStart, this.asyncStop);
}
/**
* Indicates that this service should *not* be started asynchronously.
* @return a reference to this builder
*/
public AsyncServiceConfigurator startSynchronously() {
this.asyncStart = false;
return this;
}
/**
* Indicates that this service should *not* be stopped asynchronously.
* @return a reference to this builder
*/
public AsyncServiceConfigurator stopSynchronously() {
this.asyncStop = false;
return this;
}
private static class AsyncServiceBuilder<T> extends DelegatingServiceBuilder<T> {
private final Supplier<Executor> executor;
private final boolean asyncStart;
private final boolean asyncStop;
AsyncServiceBuilder(ServiceBuilder<T> delegate, Supplier<Executor> executor, boolean asyncStart, boolean asyncStop) {
super(delegate);
this.executor = executor;
this.asyncStart = asyncStart;
this.asyncStop = asyncStop;
}
@Override
public ServiceBuilder<T> setInstance(Service service) {
return super.setInstance(new AsyncService(service, this.executor, this.asyncStart, this.asyncStop));
}
}
private static class AsyncService implements Service {
private final Service service;
private final Supplier<Executor> executor;
private final boolean asyncStart;
private final boolean asyncStop;
AsyncService(Service service, Supplier<Executor> executor, boolean asyncStart, boolean asyncStop) {
this.service = service;
this.executor = executor;
this.asyncStart = asyncStart;
this.asyncStop = asyncStop;
}
@Override
public void start(final StartContext context) throws StartException {
if (this.asyncStart) {
Runnable task = () -> {
try {
this.service.start(context);
context.complete();
} catch (StartException e) {
context.failed(e);
} catch (Throwable e) {
context.failed(new StartException(e));
}
};
try {
this.executor.get().execute(task);
} catch (RejectedExecutionException e) {
task.run();
} finally {
context.asynchronous();
}
} else {
this.service.start(context);
}
}
@Override
public void stop(final StopContext context) {
if (this.asyncStop) {
Runnable task = () -> {
try {
this.service.stop(context);
} finally {
context.complete();
}
};
try {
this.executor.get().execute(task);
} catch (RejectedExecutionException e) {
task.run();
} finally {
context.asynchronous();
}
} else {
this.service.stop(context);
}
}
}
}
| 5,738
| 34.86875
| 125
|
java
|
null |
wildfly-main/clustering/service/src/main/java/org/wildfly/clustering/service/FunctionSupplierDependency.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.wildfly.clustering.service;
import java.util.function.Function;
import org.jboss.msc.service.ServiceBuilder;
/**
* A {@link SupplierDependency} that applies a mapping to the source dependency value.
* @author Paul Ferraro
*/
public class FunctionSupplierDependency<T, R> implements SupplierDependency<R> {
private final SupplierDependency<T> dependency;
private final Function<T, R> mapper;
public FunctionSupplierDependency(SupplierDependency<T> dependency, Function<T, R> mapper) {
this.dependency = dependency;
this.mapper = mapper;
}
@Override
public R get() {
return this.mapper.apply(this.dependency.get());
}
@Override
public <V> ServiceBuilder<V> register(ServiceBuilder<V> builder) {
return this.dependency.register(builder);
}
}
| 1,857
| 34.056604
| 96
|
java
|
null |
wildfly-main/clustering/service/src/main/java/org/wildfly/clustering/service/SupplierDependency.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.wildfly.clustering.service;
import java.util.function.Supplier;
/**
* Encapsulates logic for registering a service dependency that supplies a value.
* @author Paul Ferraro
*/
public interface SupplierDependency<T> extends Supplier<T>, Dependency {
}
| 1,292
| 37.029412
| 81
|
java
|
null |
wildfly-main/clustering/service/src/main/java/org/wildfly/clustering/service/DefaultableBinaryRequirement.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.clustering.service;
/**
* Identifies a requirement that provides a service and can reference some default requirement.
* @author Paul Ferraro
*/
public interface DefaultableBinaryRequirement extends BinaryRequirement {
UnaryRequirement getDefaultRequirement();
@Override
default Class<?> getType() {
return this.getDefaultRequirement().getType();
}
@Override
default String resolve(String parent, String child) {
return (child != null) ? BinaryRequirement.super.resolve(parent, child) : this.getDefaultRequirement().resolve(parent);
}
}
| 1,632
| 36.976744
| 127
|
java
|
null |
wildfly-main/clustering/service/src/main/java/org/wildfly/clustering/service/Requirement.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.wildfly.clustering.service;
/**
* Identifies a requirement that provides a service.
* @author Paul Ferraro
*/
public interface Requirement {
/**
* The base name of this requirement.
* @return the requirement name.
*/
String getName();
/**
* The value type of the service provided by this requirement.
* @return a service value type
*/
Class<?> getType();
}
| 1,444
| 33.404762
| 70
|
java
|
null |
wildfly-main/clustering/service/src/main/java/org/wildfly/clustering/service/ChildTargetService.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.wildfly.clustering.service;
import java.util.function.Consumer;
import org.jboss.msc.Service;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
/**
* Service that performs service installation into the child target on start.
* @author Paul Ferraro
*/
public class ChildTargetService implements Service {
private final Consumer<ServiceTarget> installer;
public ChildTargetService(Consumer<ServiceTarget> installer) {
this.installer = installer;
}
@Override
public void start(StartContext context) {
this.installer.accept(context.getChildTarget());
}
@Override
public void stop(StopContext context) {
// Services installed into child target are auto-removed after this service stops.
}
}
| 1,870
| 34.301887
| 90
|
java
|
null |
wildfly-main/clustering/service/src/main/java/org/wildfly/clustering/service/CascadeRemovalLifecycleListener.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.wildfly.clustering.service;
import java.util.Arrays;
import java.util.Collections;
import org.jboss.msc.service.LifecycleEvent;
import org.jboss.msc.service.LifecycleListener;
import org.jboss.msc.service.ServiceController;
/**
* Lifecycle listener that cascades service removal to a series of services.
* @author Paul Ferraro
*/
public class CascadeRemovalLifecycleListener implements LifecycleListener {
private final Iterable<ServiceController<?>> controllers;
public CascadeRemovalLifecycleListener(ServiceController<?> controller) {
this.controllers = Collections.singleton(controller);
}
public CascadeRemovalLifecycleListener(ServiceController<?>... controllers) {
this.controllers = Arrays.asList(controllers);
}
public CascadeRemovalLifecycleListener(Iterable<ServiceController<?>> controllers) {
this.controllers = controllers;
}
@Override
public void handleEvent(ServiceController<?> source, LifecycleEvent event) {
if (event == LifecycleEvent.REMOVED) {
for (ServiceController<?> controller : this.controllers) {
controller.setMode(ServiceController.Mode.REMOVE);
}
source.removeListener(this);
}
}
}
| 2,292
| 35.983871
| 88
|
java
|
null |
wildfly-main/clustering/service/src/main/java/org/wildfly/clustering/service/BinaryRequirement.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.clustering.service;
/**
* Identifies a requirement that provides a service.
* Includes a binary function for resolving its name.
* @author Paul Ferraro
*/
public interface BinaryRequirement extends Requirement {
default String resolve(String parent, String child) {
return String.join(".", this.getName(), parent, child);
}
}
| 1,393
| 36.675676
| 70
|
java
|
null |
wildfly-main/clustering/service/src/main/java/org/wildfly/clustering/service/ServiceDependency.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.wildfly.clustering.service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
/**
* Encapsulates a {@link Dependency} on a {@link org.jboss.msc.Service}.
* @author Paul Ferraro
*/
public class ServiceDependency extends SimpleServiceNameProvider implements Dependency {
public ServiceDependency(ServiceName name) {
super(name);
}
public ServiceDependency(ServiceNameProvider provider) {
super(provider.getServiceName());
}
@Override
public <T> ServiceBuilder<T> register(ServiceBuilder<T> builder) {
builder.requires(this.getServiceName());
return builder;
}
}
| 1,701
| 34.458333
| 88
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.