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/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ProxyOperationExecutor.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.mod_cluster;
import java.util.function.Function;
import org.jboss.as.clustering.controller.FunctionExecutor;
import org.jboss.as.clustering.controller.FunctionExecutorRegistry;
import org.jboss.as.clustering.controller.Operation;
import org.jboss.as.clustering.controller.OperationExecutor;
import org.jboss.as.clustering.controller.OperationFunction;
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.client.helpers.MeasurementUnit;
import org.jboss.as.controller.operations.validation.IntRangeValidator;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.modcluster.ModClusterServiceMBean;
import org.jboss.msc.service.ServiceName;
/**
* @author Radoslav Husar
*/
public class ProxyOperationExecutor implements OperationExecutor<ModClusterServiceMBean> {
public static final SimpleAttributeDefinition HOST = SimpleAttributeDefinitionBuilder.create("host", ModelType.STRING, false)
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.setStorageRuntime()
.build();
public static final SimpleAttributeDefinition PORT = SimpleAttributeDefinitionBuilder.create("port", ModelType.INT, false)
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.setValidator(new IntRangeValidator(1, Short.MAX_VALUE - Short.MIN_VALUE, false, false))
.setStorageRuntime()
.build();
static final SimpleAttributeDefinition VIRTUAL_HOST = SimpleAttributeDefinitionBuilder.create("virtualhost", ModelType.STRING, false)
.addFlag(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.setStorageRuntime()
.build();
static final SimpleAttributeDefinition WAIT_TIME = SimpleAttributeDefinitionBuilder.create("waittime", ModelType.INT, true)
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.setStorageRuntime()
.setDefaultValue(new ModelNode(10))
.setMeasurementUnit(MeasurementUnit.SECONDS)
.build();
static final SimpleAttributeDefinition CONTEXT = SimpleAttributeDefinitionBuilder.create("context", ModelType.STRING, false)
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.setStorageRuntime()
.build();
private final FunctionExecutorRegistry<ModClusterServiceMBean> executors;
public ProxyOperationExecutor(FunctionExecutorRegistry<ModClusterServiceMBean> executors) {
this.executors = executors;
}
@Override
public ModelNode execute(OperationContext context, ModelNode operation, Operation<ModClusterServiceMBean> executable) throws OperationFailedException {
ServiceName serviceName = ProxyConfigurationResourceDefinition.Capability.SERVICE.getDefinition().getCapabilityServiceName(context.getCurrentAddress());
FunctionExecutor<ModClusterServiceMBean> executor = this.executors.get(serviceName);
return (executor != null) ? executor.execute(new OperationFunction<>(context, operation, Function.identity(), executable)) : null;
}
}
| 4,364 | 48.044944 | 160 |
java
|
null |
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/CustomLoadMetricResourceDefinition.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.mod_cluster;
import java.util.function.UnaryOperator;
import org.jboss.as.clustering.controller.ChildResourceDefinition;
import org.jboss.as.clustering.controller.ReloadRequiredResourceRegistrar;
import org.jboss.as.clustering.controller.ResourceDescriptor;
import org.jboss.as.clustering.controller.validation.ModuleIdentifierValidatorBuilder;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.wildfly.extension.mod_cluster.LoadMetricResourceDefinition.SharedAttribute;
/**
* @author Radoslav Husar
*/
public class CustomLoadMetricResourceDefinition extends ChildResourceDefinition<ManagementResourceRegistration> {
static final PathElement WILDCARD_PATH = pathElement(PathElement.WILDCARD_VALUE);
static PathElement pathElement(String loadMetric) {
return PathElement.pathElement("custom-load-metric", loadMetric);
}
enum Attribute implements org.jboss.as.clustering.controller.Attribute, UnaryOperator<SimpleAttributeDefinitionBuilder> {
CLASS("class", ModelType.STRING),
MODULE("module", ModelType.STRING) {
@Override
public SimpleAttributeDefinitionBuilder apply(SimpleAttributeDefinitionBuilder builder) {
return builder
.setDefaultValue(new ModelNode("org.wildfly.extension.mod_cluster"))
.setRequired(false)
.setValidator(new ModuleIdentifierValidatorBuilder().configure(builder).build())
;
}
},
;
private final AttributeDefinition definition;
Attribute(String name, ModelType type) {
this.definition = this.apply(new SimpleAttributeDefinitionBuilder(name, type)
.setAllowExpression(true)
.setRequired(true)
.setRestartAllServices()
).build();
}
@Override
public AttributeDefinition getDefinition() {
return this.definition;
}
@Override
public SimpleAttributeDefinitionBuilder apply(SimpleAttributeDefinitionBuilder builder) {
return builder;
}
}
CustomLoadMetricResourceDefinition() {
super(WILDCARD_PATH, ModClusterExtension.SUBSYSTEM_RESOLVER.createChildResolver(LoadMetricResourceDefinition.WILDCARD_PATH));
}
@Override
public ManagementResourceRegistration register(ManagementResourceRegistration parent) {
ManagementResourceRegistration registration = parent.registerSubModel(this);
ResourceDescriptor descriptor = new ResourceDescriptor(this.getResourceDescriptionResolver())
.addAttributes(SharedAttribute.class)
.addAttributes(Attribute.class)
;
new ReloadRequiredResourceRegistrar(descriptor).register(registration);
return registration;
}
}
| 4,186 | 39.259615 | 133 |
java
|
null |
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ModClusterLogger.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.mod_cluster;
import static org.jboss.logging.Logger.Level.ERROR;
import static org.jboss.logging.Logger.Level.WARN;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
/**
* @author <a href="mailto:[email protected]">James R. Perkins</a>
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
* @author Radoslav Husar
*/
@MessageLogger(projectCode = "WFLYMODCLS", length = 4)
interface ModClusterLogger extends BasicLogger {
/**
* The root logger with a category of the package name.
*/
ModClusterLogger ROOT_LOGGER = Logger.getMessageLogger(ModClusterLogger.class, "org.wildfly.extension.mod_cluster");
/**
* Logs an error message indicating an error when adding metrics.
*
* @param cause the cause of the error
*/
@LogMessage(level = ERROR)
@Message(id = 1, value = "Error adding metrics.")
void errorAddingMetrics(@Cause Throwable cause);
// /**
// * Logs an error message indicating a start failure.
// *
// * @param cause the cause of the error
// * @param name the name for the service that failed to start
// */
// @LogMessage(level = ERROR)
// @Message(id = 2, value = "%s failed to start.")
// void startFailure(@Cause Throwable cause, String name);
// /**
// * Logs an error message indicating a stop failure.
// *
// * @param cause the cause of the error
// * @param name the name for the service that failed to stop
// */
// @LogMessage(level = ERROR)
// @Message(id = 3, value = "%s failed to stop.")
// void stopFailure(@Cause Throwable cause, String name);
/**
* Logs an error message indicating ModCluster requires advertise, but no multi-cast interface is available.
*/
@LogMessage(level = ERROR)
@Message(id = 4, value = "Mod_cluster requires Advertise but Multicast interface is not available.")
void multicastInterfaceNotAvailable();
@LogMessage(level = WARN)
@Message(id = 5, value = "No mod_cluster load balance factor provider specified for proxy '%s'! Using load balance factor provider with constant factor of '1'.")
void usingSimpleLoadProvider(String proxyName);
/**
* Logs an error message indicating that metric properties could not be applied on a custom load metric.
*
* @param cause exception caught when applying properties
* @param metricClass FQCN of the custom metric
*/
@LogMessage(level = ERROR)
@Message(id = 6, value = "Error applying properties to load metric class '%s'. Metric will not be loaded.")
void errorApplyingMetricProperties(@Cause Throwable cause, String metricClass);
// /**
// * Logs a warning message that this metric type is no longer supported.
// *
// * @param metricType name of the unsupported metric
// */
// @LogMessage(level = WARN)
// @Message(id = 7, value = "Metric of type '%s' is no longer supported and will be ignored.")
// void unsupportedMetric(String metricType);
// /**
// * A message indicating a class attribute is needed for the attribute represented by the {@code attributeName}
// * parameter.
// *
// * @param attributeName the name of the required attribute
// * @return the message
// */
// @Message(id = 8, value = "A class attribute is needed for %s")
// String classAttributeRequired(String attributeName);
// /**
// * A message indicating a type attribute is needed for the attribute represented by the {@code attributeName}
// * parameter.
// *
// * @param attributeName the name of the required attribute
// * @return the message
// */
// @Message(id = 10, value = "A type attribute is needed for %s")
// String typeAttributeRequired(String attributeName);
/**
* A message indicating that the virtual host or the context can't be found by modcluster.
*
* @param host name of the virtual host
* @param context name of the context
* @return the message
*/
@Message(id = 11, value = "Virtual host '%s' or context '%s' not found.")
String contextOrHostNotFound(String host, String context);
// @Message(id = 12, value = "'capacity' is either an expression, is not an integer value, or has a bigger value than Integer.MAX_VALUE: %s")
// String capacityIsExpressionOrGreaterThanIntegerMaxValue(ModelNode value);
// @Message(id = 13, value = "'property' can not have more than one entry")
// String propertyCanOnlyHaveOneEntry();
// /**
// * A message indicating a valid port and host are needed.
// *
// * @return the message
// */
// @Message(id = 14, value = "Need valid host and port in the form host:port, %s is not valid")
// String needHostAndPort(String value);
// @Message(id = 15, value = "session-draining-strategy must either be undefined or have the value \"DEFAULT\"")
// String sessionDrainingStrategyMustBeUndefinedOrDefault();
// /**
// * A message indicating the host of the reverse proxy server could not be resolved.
// *
// * @return the message.
// */
// @Message(id = 16, value = "No IP address could be resolved for the specified host of the proxy.")
// String couldNotResolveProxyIpAddress();
// /**
// * A message explaining that 'proxy-list' attribute has been deprecated and that 'proxies' attribute which is a list
// * of references to outbound-socket-binding(s) should be used instead.
// *
// * @return the message
// */
// @Message(id = 17, value = "'proxy-list' usage not allowed in the current model, can only be used to support older secondary hosts")
// String proxyListNotAllowedInCurrentModel();
// /**
// * Message indicating that only one of 'proxy-list' or 'proxies' attributes is allowed and the former one only
// * to support older EAP 6.x slaves.
// *
// * @return the message
// */
// @Message(id = 18, value = "Usage of only one 'proxy-list' (only to support EAP 6.x slaves) or 'proxies' attributes allowed")
// String proxyListAttributeUsage();
/**
* Logs an error message when excluded contexts are in a wrong format.
*
* @param trimmedContexts value which is in the wrong format
*/
@Message(id = 19, value = "'%s' is not a valid value for excluded-contexts.")
IllegalArgumentException excludedContextsWrongFormat(String trimmedContexts);
// /**
// * Exception thrown when user configures both 'ssl-context' attribute reference and the proxy=X/ssl=configuration.
// */
// @Message(id = 20, value = "Only one of 'ssl-context' attribute or 'ssl' resource can be defined!")
// IllegalStateException bothElytronAndLegacySslContextDefined();
@LogMessage(level = WARN)
@Message(id = 21, value = "Value 'ROOT' for excluded-contexts is deprecated, to exclude the root context use '/' instead.")
void excludedContextsUseSlashInsteadROOT();
// @Message(id = 22, value = "Legacy operations cannot be used with multiple proxy configurations. Use non-deprecated operations at the correct proxy address.")
// String legacyOperationsWithMultipleProxies();
@LogMessage(level = ERROR)
@Message(id = 23, value = "Error loading module '%s' to load custom metric from.")
void errorLoadingModuleForCustomMetric(String moduleName, @Cause Throwable cause);
// @Message(id = 24, value = "Dynamic load factor provider is currently configured. A simple load factor provider needs to be configured first to read or write a static factor.")
// OperationFailedException simpleLoadFactorProviderIsNotConfigured();
@LogMessage(level = WARN)
@Message(id = 25, value = "The '%s' element is no longer supported and will be ignored.")
void ignoredElement(String element);
@LogMessage(level = WARN)
@Message(id = 26, value = "Attribute '%s' of element '%s' is no longer supported and will be ignored.")
void ignoredAttribute(String attribute, String element);
}
| 9,249 | 42.023256 | 181 |
java
|
null |
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/LoadMetricEnum.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.mod_cluster;
import org.jboss.modcluster.load.metric.LoadMetric;
import org.jboss.modcluster.load.metric.impl.ActiveSessionsLoadMetric;
import org.jboss.modcluster.load.metric.impl.AverageSystemLoadMetric;
import org.jboss.modcluster.load.metric.impl.BusyConnectorsLoadMetric;
import org.jboss.modcluster.load.metric.impl.HeapMemoryUsageLoadMetric;
import org.jboss.modcluster.load.metric.impl.ReceiveTrafficLoadMetric;
import org.jboss.modcluster.load.metric.impl.RequestCountLoadMetric;
import org.jboss.modcluster.load.metric.impl.SendTrafficLoadMetric;
/**
* Enumeration of mod_cluster load metrics.
*
* @author Paul Ferraro
* @author Radoslav Husar
*/
public enum LoadMetricEnum {
CPU("cpu", AverageSystemLoadMetric.class),
HEAP_MEMORY("heap", HeapMemoryUsageLoadMetric.class),
ACTIVE_SESSIONS("sessions", ActiveSessionsLoadMetric.class),
RECEIVE_TRAFFIC("receive-traffic", ReceiveTrafficLoadMetric.class),
SEND_TRAFFIC("send-traffic", SendTrafficLoadMetric.class),
REQUEST_COUNT("requests", RequestCountLoadMetric.class),
BUSY_CONNECTORS("busyness", BusyConnectorsLoadMetric.class),
;
private final String type;
private final Class<? extends LoadMetric> loadMetricClass;
LoadMetricEnum(String type, Class<? extends LoadMetric> loadMetricClass) {
this.type = type;
this.loadMetricClass = loadMetricClass;
}
public String getType() {
return this.type;
}
public Class<? extends LoadMetric> getLoadMetricClass() {
return this.loadMetricClass;
}
public static LoadMetricEnum forType(String type) {
for (LoadMetricEnum metric : LoadMetricEnum.values()) {
if (metric.type.equals(type)) {
return metric;
}
}
return null;
}
@Override
public String toString() {
return this.type;
}
}
| 2,928 | 35.6125 | 78 |
java
|
null |
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ModClusterSubsystemModel.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.mod_cluster;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.SubsystemModel;
/**
* Enumerates the supported mod_cluster model versions.
*
* @author Radoslav Husar
*/
public enum ModClusterSubsystemModel implements SubsystemModel {
/* Unsupported model versions - for reference only:
VERSION_1_5_0(1, 5, 0), // EAP 6.3-6.4
VERSION_2_0_0(2, 0, 0), // WildFly 8
VERSION_3_0_0(3, 0, 0), // WildFly 9
VERSION_4_0_0(4, 0, 0), // WildFly 10, EAP 7.0
VERSION_5_0_0(5, 0, 0), // WildFly 11-13, EAP 7.1
VERSION_6_0_0(6, 0, 0), // WildFly 14-15, EAP 7.2
*/
VERSION_7_0_0(7, 0, 0), // WildFly 16-26, EAP 7.3-7.4
VERSION_8_0_0(8, 0, 0), // WildFly 27-present
;
public static final ModClusterSubsystemModel CURRENT = VERSION_8_0_0;
private final ModelVersion version;
ModClusterSubsystemModel(int major, int minor, int micro) {
this.version = ModelVersion.create(major, minor, micro);
}
@Override
public ModelVersion getVersion() {
return this.version;
}
}
| 2,115 | 35.482759 | 73 |
java
|
null |
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ProxyOperation.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.mod_cluster;
import static org.wildfly.extension.mod_cluster.ProxyOperationExecutor.CONTEXT;
import static org.wildfly.extension.mod_cluster.ProxyOperationExecutor.HOST;
import static org.wildfly.extension.mod_cluster.ProxyOperationExecutor.PORT;
import static org.wildfly.extension.mod_cluster.ProxyOperationExecutor.VIRTUAL_HOST;
import static org.wildfly.extension.mod_cluster.ProxyOperationExecutor.WAIT_TIME;
import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.UnaryOperator;
import org.jboss.as.clustering.controller.Operation;
import org.jboss.as.controller.ExpressionResolver;
import org.jboss.as.controller.OperationDefinition;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.SimpleOperationDefinitionBuilder;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.modcluster.ModClusterServiceMBean;
/**
* Enumeration of mod_cluster proxy operations.
*
* @author Radoslav Husar
*/
enum ProxyOperation implements Operation<ModClusterServiceMBean>, UnaryOperator<SimpleOperationDefinitionBuilder> {
ADD_PROXY("add-proxy") {
@Override
public SimpleOperationDefinitionBuilder apply(SimpleOperationDefinitionBuilder builder) {
return builder.setParameters(HOST, PORT).addAccessConstraint(ModClusterExtension.MOD_CLUSTER_PROXIES_DEF);
}
@Override
public ModelNode execute(ExpressionResolver expressionResolver, ModelNode operation, ModClusterServiceMBean service) throws OperationFailedException {
String host = HOST.resolveModelAttribute(expressionResolver, operation).asString();
int port = PORT.resolveModelAttribute(expressionResolver, operation).asInt();
service.addProxy(host, port);
return null;
}
},
REMOVE_PROXY("remove-proxy") {
@Override
public SimpleOperationDefinitionBuilder apply(SimpleOperationDefinitionBuilder builder) {
return builder.setParameters(HOST, PORT).addAccessConstraint(ModClusterExtension.MOD_CLUSTER_PROXIES_DEF);
}
@Override
public ModelNode execute(ExpressionResolver expressionResolver, ModelNode operation, ModClusterServiceMBean service) throws OperationFailedException {
String host = HOST.resolveModelAttribute(expressionResolver, operation).asString();
int port = PORT.resolveModelAttribute(expressionResolver, operation).asInt();
service.removeProxy(host, port);
return null;
}
},
READ_PROXIES_INFO("read-proxies-info") {
@Override
public SimpleOperationDefinitionBuilder apply(SimpleOperationDefinitionBuilder builder) {
return builder.setReadOnly().setReplyType(ModelType.LIST).setReplyValueType(ModelType.STRING).addAccessConstraint(ModClusterExtension.MOD_CLUSTER_PROXIES_DEF);
}
@Override
public ModelNode execute(ExpressionResolver expressionResolver, ModelNode operation, ModClusterServiceMBean service) {
Map<InetSocketAddress, String> map = service.getProxyInfo();
if (!map.isEmpty()) {
final ModelNode result = new ModelNode();
for (Map.Entry<InetSocketAddress, String> entry : map.entrySet()) {
result.add(entry.getKey().getHostName() + ":" + entry.getKey().getPort());
if (entry.getValue() == null) {
result.add();
} else {
result.add(entry.getValue());
}
}
return result;
}
return null;
}
},
LIST_PROXIES("list-proxies") {
@Override
public SimpleOperationDefinitionBuilder apply(SimpleOperationDefinitionBuilder builder) {
return builder.setReadOnly().setReplyType(ModelType.LIST).setReplyValueType(ModelType.STRING).addAccessConstraint(ModClusterExtension.MOD_CLUSTER_PROXIES_DEF);
}
@Override
public ModelNode execute(ExpressionResolver expressionResolver, ModelNode operation, ModClusterServiceMBean service) {
Map<InetSocketAddress, String> map = service.getProxyInfo();
if (!map.isEmpty()) {
final ModelNode result = new ModelNode();
InetSocketAddress[] addresses = map.keySet().toArray(new InetSocketAddress[0]);
for (InetSocketAddress address : addresses) {
result.add(address.getHostName() + ":" + address.getPort());
}
return result;
}
return null;
}
},
READ_PROXIES_CONFIGURATION("read-proxies-configuration") {
@Override
public SimpleOperationDefinitionBuilder apply(SimpleOperationDefinitionBuilder builder) {
return builder.setReadOnly().setReplyType(ModelType.LIST).setReplyValueType(ModelType.STRING).addAccessConstraint(ModClusterExtension.MOD_CLUSTER_PROXIES_DEF);
}
@Override
public ModelNode execute(ExpressionResolver expressionResolver, ModelNode operation, ModClusterServiceMBean service) {
Map<InetSocketAddress, String> map = service.getProxyConfiguration();
if (!map.isEmpty()) {
final ModelNode result = new ModelNode();
for (Map.Entry<InetSocketAddress, String> entry : map.entrySet()) {
result.add(entry.getKey().getHostName() + ":" + entry.getKey().getPort());
if (entry.getValue() == null) {
result.add();
} else {
result.add(entry.getValue());
}
}
return result;
}
return null;
}
},
REFRESH("refresh") {
@Override
public ModelNode execute(ExpressionResolver expressionResolver, ModelNode operation, ModClusterServiceMBean service) {
service.refresh();
return null;
}
},
RESET("reset") {
@Override
public ModelNode execute(ExpressionResolver expressionResolver, ModelNode operation, ModClusterServiceMBean service) {
service.reset();
return null;
}
},
ENABLE("enable") {
@Override
public SimpleOperationDefinitionBuilder apply(SimpleOperationDefinitionBuilder builder) {
return builder.setReplyType(ModelType.BOOLEAN);
}
@Override
public ModelNode execute(ExpressionResolver expressionResolver, ModelNode operation, ModClusterServiceMBean service) {
boolean enabled = service.enable();
return new ModelNode(enabled);
}
},
DISABLE("disable") {
@Override
public SimpleOperationDefinitionBuilder apply(SimpleOperationDefinitionBuilder builder) {
return builder.setReplyType(ModelType.BOOLEAN);
}
@Override
public ModelNode execute(ExpressionResolver expressionResolver, ModelNode operation, ModClusterServiceMBean service) {
boolean disabled = service.disable();
return new ModelNode(disabled);
}
},
STOP("stop") {
@Override
public SimpleOperationDefinitionBuilder apply(SimpleOperationDefinitionBuilder builder) {
return builder.setParameters(WAIT_TIME).setReplyType(ModelType.BOOLEAN);
}
@Override
public ModelNode execute(ExpressionResolver expressionResolver, ModelNode operation, ModClusterServiceMBean service) throws OperationFailedException {
int waitTime = WAIT_TIME.resolveModelAttribute(expressionResolver, operation).asInt();
boolean success = service.stop(waitTime, TimeUnit.SECONDS);
return new ModelNode(success);
}
},
// Context operations
ENABLE_CONTEXT("enable-context") {
@Override
public SimpleOperationDefinitionBuilder apply(SimpleOperationDefinitionBuilder builder) {
return builder.setParameters(VIRTUAL_HOST, CONTEXT).setReplyType(ModelType.BOOLEAN);
}
@Override
public ModelNode execute(ExpressionResolver expressionResolver, ModelNode operation, ModClusterServiceMBean service) throws OperationFailedException {
String virtualHost = VIRTUAL_HOST.resolveModelAttribute(expressionResolver, operation).asString();
String webContext = CONTEXT.resolveModelAttribute(expressionResolver, operation).asString();
try {
boolean enabled = service.enableContext(virtualHost, webContext);
return new ModelNode(enabled);
} catch (IllegalArgumentException e) {
throw new OperationFailedException(ModClusterLogger.ROOT_LOGGER.contextOrHostNotFound(virtualHost, webContext));
}
}
},
DISABLE_CONTEXT("disable-context") {
@Override
public SimpleOperationDefinitionBuilder apply(SimpleOperationDefinitionBuilder builder) {
return builder.setParameters(VIRTUAL_HOST, CONTEXT).setReplyType(ModelType.BOOLEAN);
}
@Override
public ModelNode execute(ExpressionResolver expressionResolver, ModelNode operation, ModClusterServiceMBean service) throws OperationFailedException {
String virtualHost = VIRTUAL_HOST.resolveModelAttribute(expressionResolver, operation).asString();
String webContext = CONTEXT.resolveModelAttribute(expressionResolver, operation).asString();
try {
boolean disabled = service.disableContext(virtualHost, webContext);
return new ModelNode(disabled);
} catch (IllegalArgumentException e) {
throw new OperationFailedException(ModClusterLogger.ROOT_LOGGER.contextOrHostNotFound(virtualHost, webContext));
}
}
},
STOP_CONTEXT("stop-context") {
@Override
public SimpleOperationDefinitionBuilder apply(SimpleOperationDefinitionBuilder builder) {
return builder.setParameters(VIRTUAL_HOST, CONTEXT, WAIT_TIME).setReplyType(ModelType.BOOLEAN);
}
@Override
public ModelNode execute(ExpressionResolver expressionResolver, ModelNode operation, ModClusterServiceMBean service) throws OperationFailedException {
String virtualHost = VIRTUAL_HOST.resolveModelAttribute(expressionResolver, operation).asString();
String webContext = CONTEXT.resolveModelAttribute(expressionResolver, operation).asString();
int waitTime = WAIT_TIME.resolveModelAttribute(expressionResolver, operation).asInt();
try {
boolean success = service.stopContext(virtualHost, webContext, waitTime, TimeUnit.SECONDS);
return new ModelNode(success);
} catch (IllegalArgumentException e) {
throw new OperationFailedException(ModClusterLogger.ROOT_LOGGER.contextOrHostNotFound(virtualHost, webContext));
}
}
},
;
private final OperationDefinition definition;
ProxyOperation(String name) {
this.definition = this.apply(new SimpleOperationDefinitionBuilder(name, ModClusterExtension.SUBSYSTEM_RESOLVER)).setRuntimeOnly().build();
}
@Override
public OperationDefinition getDefinition() {
return this.definition;
}
@Override
public SimpleOperationDefinitionBuilder apply(SimpleOperationDefinitionBuilder builder) {
return builder;
}
}
| 12,695 | 43.236934 | 171 |
java
|
null |
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/DynamicLoadProviderResourceTransformer.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2021, 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.extension.mod_cluster;
import java.util.function.Consumer;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.transform.description.DiscardAttributeChecker;
import org.jboss.as.controller.transform.description.RejectAttributeChecker;
import org.jboss.as.controller.transform.description.ResourceTransformationDescriptionBuilder;
import org.jboss.dmr.ModelNode;
/**
* Transformer logic for {@link DynamicLoadProviderResourceDefinition}.
*
* @author Radoslav Husar
*/
public class DynamicLoadProviderResourceTransformer implements Consumer<ModelVersion> {
private final ResourceTransformationDescriptionBuilder builder;
public DynamicLoadProviderResourceTransformer(ResourceTransformationDescriptionBuilder parent) {
this.builder = parent.addChildResource(DynamicLoadProviderResourceDefinition.PATH);
}
@Override
public void accept(ModelVersion version) {
if (ModClusterSubsystemModel.VERSION_7_0_0.requiresTransformation(version)) {
builder.getAttributeBuilder()
.setDiscard(new DiscardAttributeChecker.DiscardAttributeValueChecker(new ModelNode(-1)), DynamicLoadProviderResourceDefinition.Attribute.INITIAL_LOAD.getDefinition())
.addRejectCheck(RejectAttributeChecker.DEFINED, DynamicLoadProviderResourceDefinition.Attribute.INITIAL_LOAD.getDefinition())
.end();
}
//new LoadMetricResourceTransformer(this.builder).accept(version);
//new CustomLoadMetricResourceTransformer(this.builder).accept(version);
}
}
| 2,634 | 43.661017 | 186 |
java
|
null |
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ModClusterExtension.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.mod_cluster;
import org.jboss.as.clustering.controller.SubsystemExtension;
import org.jboss.as.controller.Extension;
import org.jboss.as.controller.access.constraint.SensitivityClassification;
import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition;
import org.jboss.as.controller.descriptions.ParentResourceDescriptionResolver;
import org.jboss.as.controller.descriptions.SubsystemResourceDescriptionResolver;
import org.kohsuke.MetaInfServices;
/**
* Defines the mod_cluster subsystem and its resources.
*
* @author Jean-Frederic Clere
* @author Tomaz Cerar
* @author Radoslav Husar
*/
@MetaInfServices(Extension.class)
public class ModClusterExtension extends SubsystemExtension<ModClusterSubsystemSchema> {
public static final String SUBSYSTEM_NAME = "modcluster";
static final ParentResourceDescriptionResolver SUBSYSTEM_RESOLVER = new SubsystemResourceDescriptionResolver(SUBSYSTEM_NAME, ModClusterExtension.class);
public static final SensitiveTargetAccessConstraintDefinition MOD_CLUSTER_SECURITY_DEF = new SensitiveTargetAccessConstraintDefinition(
new SensitivityClassification(SUBSYSTEM_NAME, "mod_cluster-security", false, true, true));
public static final SensitiveTargetAccessConstraintDefinition MOD_CLUSTER_PROXIES_DEF = new SensitiveTargetAccessConstraintDefinition(
new SensitivityClassification(SUBSYSTEM_NAME, "mod_cluster-proxies", false, false, false));
public ModClusterExtension() {
super(SUBSYSTEM_NAME, ModClusterSubsystemModel.CURRENT, ModClusterSubsystemResourceDefinition::new, ModClusterSubsystemSchema.CURRENT, new ModClusterSubsystemXMLWriter());
}
}
| 2,740 | 47.946429 | 179 |
java
|
null |
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ContainerEventHandlerServiceConfigurator.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.mod_cluster;
import static org.wildfly.extension.mod_cluster.ModClusterLogger.ROOT_LOGGER;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.jboss.as.clustering.controller.CapabilityServiceNameProvider;
import org.jboss.as.controller.PathAddress;
import org.jboss.modcluster.ModClusterService;
import org.jboss.modcluster.config.ModClusterConfiguration;
import org.jboss.modcluster.load.LoadBalanceFactorProvider;
import org.jboss.msc.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceTarget;
import org.wildfly.clustering.service.AsyncServiceConfigurator;
import org.wildfly.clustering.service.FunctionalService;
import org.wildfly.clustering.service.ServiceConfigurator;
import org.wildfly.clustering.service.ServiceSupplierDependency;
import org.wildfly.clustering.service.SupplierDependency;
/**
* Service starting mod_cluster service.
*
* @author Jean-Frederic Clere
* @author Radoslav Husar
*/
public class ContainerEventHandlerServiceConfigurator extends CapabilityServiceNameProvider implements ServiceConfigurator, Supplier<ModClusterService>, Consumer<ModClusterService> {
private final String proxyName;
private final LoadBalanceFactorProvider factorProvider;
private final SupplierDependency<ModClusterConfiguration> configuration;
ContainerEventHandlerServiceConfigurator(PathAddress address, LoadBalanceFactorProvider factorProvider) {
super(ProxyConfigurationResourceDefinition.Capability.SERVICE, address);
this.configuration = new ServiceSupplierDependency<>(new ProxyConfigurationServiceConfigurator(address));
this.proxyName = address.getLastElement().getValue();
this.factorProvider = factorProvider;
}
@Override
public ServiceBuilder<?> build(ServiceTarget target) {
ServiceBuilder<?> builder = new AsyncServiceConfigurator(this.getServiceName()).build(target);
Consumer<ModClusterService> modClusterService = this.configuration.register(builder).provides(this.getServiceName());
Service service = new FunctionalService<>(modClusterService, Function.identity(), this, this);
return builder.setInstance(service);
}
@Override
public ModClusterService get() {
ROOT_LOGGER.debugf("Starting mod_cluster service for proxy '%s'.", proxyName);
return new ModClusterService(this.configuration.get(), this.factorProvider);
}
@Override
public void accept(ModClusterService service) {
ROOT_LOGGER.debugf("Stopping mod_cluster service for proxy '%s'.", proxyName);
service.shutdown();
}
}
| 3,721 | 42.27907 | 182 |
java
|
null |
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/LoadMetricResourceDefinition.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.mod_cluster;
import java.util.function.UnaryOperator;
import org.jboss.as.clustering.controller.ChildResourceDefinition;
import org.jboss.as.clustering.controller.PropertiesAttributeDefinition;
import org.jboss.as.clustering.controller.ReloadRequiredResourceRegistrar;
import org.jboss.as.clustering.controller.ResourceDescriptor;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.AttributeMarshaller;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.validation.EnumValidator;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.modcluster.load.metric.LoadMetric;
/**
* Definition for resource at address /subsystem=modcluster/proxy=X/dynamic-load-provider=configuration/load-metric=Z
*
* @author Radoslav Husar
*/
class LoadMetricResourceDefinition extends ChildResourceDefinition<ManagementResourceRegistration> {
static final PathElement WILDCARD_PATH = pathElement(PathElement.WILDCARD_VALUE);
static PathElement pathElement(String loadMetric) {
return PathElement.pathElement("load-metric", loadMetric);
}
enum SharedAttribute implements org.jboss.as.clustering.controller.Attribute {
WEIGHT("weight", ModelType.INT, new ModelNode(LoadMetric.DEFAULT_WEIGHT)),
CAPACITY("capacity", ModelType.DOUBLE, new ModelNode(LoadMetric.DEFAULT_CAPACITY)),
PROPERTY(ModelDescriptionConstants.PROPERTY),
;
private final AttributeDefinition definition;
SharedAttribute(String name, ModelType type, ModelNode defaultValue) {
this.definition = new SimpleAttributeDefinitionBuilder(name, type)
.setAllowExpression(true)
.setRequired(false)
.setDefaultValue(defaultValue)
.setRestartAllServices()
.build();
}
SharedAttribute(String name) {
this.definition = new PropertiesAttributeDefinition.Builder(name)
.setAllowExpression(true)
.setRequired(false)
.setRestartAllServices()
.setAttributeMarshaller(AttributeMarshaller.PROPERTIES_MARSHALLER_UNWRAPPED)
.build();
}
@Override
public AttributeDefinition getDefinition() {
return this.definition;
}
}
enum Attribute implements org.jboss.as.clustering.controller.Attribute, UnaryOperator<SimpleAttributeDefinitionBuilder> {
TYPE("type", ModelType.STRING, null) {
@Override
public SimpleAttributeDefinitionBuilder apply(SimpleAttributeDefinitionBuilder builder) {
return builder.setAllowExpression(false).setValidator(EnumValidator.create(LoadMetricEnum.class));
}
},
;
private final AttributeDefinition definition;
Attribute(String name, ModelType type, ModelNode defaultValue) {
this.definition = this.apply(new SimpleAttributeDefinitionBuilder(name, type)
.setAllowExpression(true)
.setRequired(defaultValue == null)
.setDefaultValue(defaultValue)
.setRestartAllServices()
).build();
}
@Override
public AttributeDefinition getDefinition() {
return this.definition;
}
@Override
public SimpleAttributeDefinitionBuilder apply(SimpleAttributeDefinitionBuilder builder) {
return builder;
}
}
LoadMetricResourceDefinition() {
super(WILDCARD_PATH, ModClusterExtension.SUBSYSTEM_RESOLVER.createChildResolver(WILDCARD_PATH));
}
@Override
public ManagementResourceRegistration register(ManagementResourceRegistration parent) {
ManagementResourceRegistration registration = parent.registerSubModel(this);
ResourceDescriptor descriptor = new ResourceDescriptor(this.getResourceDescriptionResolver())
.addAttributes(SharedAttribute.class)
.addAttributes(Attribute.class)
;
new ReloadRequiredResourceRegistrar(descriptor).register(registration);
return registration;
}
}
| 5,530 | 39.372263 | 125 |
java
|
null |
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ModClusterSubsystemResourceDefinition.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.mod_cluster;
import org.jboss.as.clustering.controller.ManagementResourceRegistration;
import org.jboss.as.clustering.controller.ResourceDescriptor;
import org.jboss.as.clustering.controller.ResourceServiceHandler;
import org.jboss.as.clustering.controller.ServiceValueExecutorRegistry;
import org.jboss.as.clustering.controller.SimpleResourceRegistrar;
import org.jboss.as.clustering.controller.SubsystemRegistration;
import org.jboss.as.clustering.controller.SubsystemResourceDefinition;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler;
import org.jboss.modcluster.ModClusterServiceMBean;
/**
* Resource definition for mod_cluster subsystem resource, children of which are respective proxy configurations.
*
* @author Radoslav Husar
*/
class ModClusterSubsystemResourceDefinition extends SubsystemResourceDefinition {
public static final PathElement PATH = pathElement(ModClusterExtension.SUBSYSTEM_NAME);
ModClusterSubsystemResourceDefinition() {
super(PATH, ModClusterExtension.SUBSYSTEM_RESOLVER);
}
@Override
public void register(SubsystemRegistration parent) {
ManagementResourceRegistration registration = parent.registerSubsystemModel(this);
registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE);
ResourceDescriptor descriptor = new ResourceDescriptor(this.getResourceDescriptionResolver());
ServiceValueExecutorRegistry<ModClusterServiceMBean> registry = new ServiceValueExecutorRegistry<>();
ResourceServiceHandler handler = new ModClusterSubsystemServiceHandler(registry);
new SimpleResourceRegistrar(descriptor, handler).register(registration);
new ProxyConfigurationResourceDefinition(registry).register(registration);
}
}
| 2,939 | 44.9375 | 132 |
java
|
null |
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ProxyConfigurationServiceConfigurator.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, 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.extension.mod_cluster;
import static org.wildfly.extension.mod_cluster.ModClusterLogger.ROOT_LOGGER;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.ADVERTISE;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.ADVERTISE_SECURITY_KEY;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.ADVERTISE_SOCKET;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.AUTO_ENABLE_CONTEXTS;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.BALANCER;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.EXCLUDED_CONTEXTS;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.FLUSH_PACKETS;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.FLUSH_WAIT;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.LOAD_BALANCING_GROUP;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.MAX_ATTEMPTS;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.NODE_TIMEOUT;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.PING;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.PROXIES;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.PROXY_URL;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.SESSION_DRAINING_STRATEGY;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.SMAX;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.SOCKET_TIMEOUT;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.SSL_CONTEXT;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.STICKY_SESSION;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.STICKY_SESSION_FORCE;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.STICKY_SESSION_REMOVE;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.STOP_CONTEXT_TIMEOUT;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.TTL;
import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.WORKER_TIMEOUT;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.net.ssl.SSLContext;
import org.jboss.as.clustering.controller.CapabilityServiceNameProvider;
import org.jboss.as.clustering.controller.CommonUnaryRequirement;
import org.jboss.as.clustering.controller.ResourceServiceConfigurator;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.network.ManagedBinding;
import org.jboss.as.network.OutboundSocketBinding;
import org.jboss.as.network.SocketBinding;
import org.jboss.dmr.ModelNode;
import org.jboss.modcluster.config.ModClusterConfiguration;
import org.jboss.modcluster.config.ProxyConfiguration;
import org.jboss.modcluster.config.builder.ModClusterConfigurationBuilder;
import org.jboss.modcluster.config.impl.SessionDrainingStrategyEnum;
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;
import org.wildfly.clustering.service.CompositeDependency;
import org.wildfly.clustering.service.Dependency;
import org.wildfly.clustering.service.FunctionalService;
import org.wildfly.clustering.service.ServiceConfigurator;
import org.wildfly.clustering.service.ServiceSupplierDependency;
import org.wildfly.clustering.service.SupplierDependency;
/**
* @author Radoslav Husar
*/
public class ProxyConfigurationServiceConfigurator extends CapabilityServiceNameProvider implements ResourceServiceConfigurator, Supplier<ModClusterConfiguration>, Consumer<ModClusterConfiguration> {
private volatile SupplierDependency<SocketBinding> advertiseSocketDependency = null;
private final List<SupplierDependency<OutboundSocketBinding>> outboundSocketBindings = new LinkedList<>();
private volatile SupplierDependency<SSLContext> sslContextDependency = null;
private final ModClusterConfigurationBuilder builder = new ModClusterConfigurationBuilder();
ProxyConfigurationServiceConfigurator(PathAddress address) {
super(ProxyConfigurationResourceDefinition.Capability.SERVICE, address);
}
@Override
public ServiceName getServiceName() {
return super.getServiceName().append("configuration");
}
@Override
public ServiceConfigurator configure(OperationContext context, ModelNode model) throws OperationFailedException {
// Advertise
String advertiseSocket = ADVERTISE_SOCKET.resolveModelAttribute(context, model).asStringOrNull();
this.advertiseSocketDependency = (advertiseSocket != null) ? new ServiceSupplierDependency<>(CommonUnaryRequirement.SOCKET_BINDING.getServiceName(context, advertiseSocket)) : null;
this.builder.advertise().setAdvertiseSecurityKey(ADVERTISE_SECURITY_KEY.resolveModelAttribute(context, model).asStringOrNull());
// MCMP
builder.mcmp()
.setAdvertise(ADVERTISE.resolveModelAttribute(context, model).asBoolean())
.setProxyURL(PROXY_URL.resolveModelAttribute(context, model).asString())
.setAutoEnableContexts(AUTO_ENABLE_CONTEXTS.resolveModelAttribute(context, model).asBoolean())
.setStopContextTimeout(STOP_CONTEXT_TIMEOUT.resolveModelAttribute(context, model).asInt())
.setStopContextTimeoutUnit(TimeUnit.valueOf(STOP_CONTEXT_TIMEOUT.getDefinition().getMeasurementUnit().getName()))
.setSocketTimeout(SOCKET_TIMEOUT.resolveModelAttribute(context, model).asInt() * 1000)
.setSessionDrainingStrategy(Enum.valueOf(SessionDrainingStrategyEnum.class, SESSION_DRAINING_STRATEGY.resolveModelAttribute(context, model).asString()))
;
if (model.hasDefined(EXCLUDED_CONTEXTS.getName())) {
String contexts = EXCLUDED_CONTEXTS.resolveModelAttribute(context, model).asString();
Map<String, Set<String>> excludedContextsPerHost;
if (contexts == null) {
excludedContextsPerHost = Collections.emptyMap();
} else {
String trimmedContexts = contexts.trim();
if (trimmedContexts.isEmpty()) {
excludedContextsPerHost = Collections.emptyMap();
} else {
excludedContextsPerHost = new HashMap<>();
for (String c : trimmedContexts.split(",")) {
String[] parts = c.trim().split(":");
if (parts.length > 2) {
throw ROOT_LOGGER.excludedContextsWrongFormat(trimmedContexts);
}
String host = null;
String trimmedContext = parts[0].trim();
if (parts.length == 2) {
host = trimmedContext;
trimmedContext = parts[1].trim();
}
String path;
switch (trimmedContext) {
case "ROOT":
ROOT_LOGGER.excludedContextsUseSlashInsteadROOT();
case "/":
path = "";
break;
default:
// normalize the context by pre-pending or removing trailing slash
trimmedContext = trimmedContext.startsWith("/") ? trimmedContext : ("/" + trimmedContext);
path = trimmedContext.endsWith("/") ? trimmedContext.substring(0, trimmedContext.length() - 1) : trimmedContext;
break;
}
Set<String> paths = excludedContextsPerHost.computeIfAbsent(host, k -> new HashSet<>());
paths.add(path);
}
}
}
builder.mcmp().setExcludedContextsPerHost(excludedContextsPerHost);
}
// Balancer
builder.balancer()
.setStickySession(STICKY_SESSION.resolveModelAttribute(context, model).asBoolean())
.setStickySessionRemove(STICKY_SESSION_REMOVE.resolveModelAttribute(context, model).asBoolean())
.setStickySessionForce(STICKY_SESSION_FORCE.resolveModelAttribute(context, model).asBoolean())
.setMaxAttempts(MAX_ATTEMPTS.resolveModelAttribute(context, model).asInt())
;
ModelNode node = WORKER_TIMEOUT.resolveModelAttribute(context, model);
if (node.isDefined()) {
builder.balancer().setWorkerTimeout(node.asInt());
}
// Node
builder.node()
.setFlushPackets(FLUSH_PACKETS.resolveModelAttribute(context, model).asBoolean())
.setPing(PING.resolveModelAttribute(context, model).asInt())
;
node = FLUSH_WAIT.resolveModelAttribute(context, model);
if (node.isDefined()) {
builder.node().setFlushWait(node.asInt());
}
node = SMAX.resolveModelAttribute(context, model);
if (node.isDefined()) {
builder.node().setSmax(node.asInt());
}
node = TTL.resolveModelAttribute(context, model);
if (node.isDefined()) {
builder.node().setTtl(node.asInt());
}
node = NODE_TIMEOUT.resolveModelAttribute(context, model);
if (node.isDefined()) {
builder.node().setNodeTimeout(node.asInt());
}
node = BALANCER.resolveModelAttribute(context, model);
if (node.isDefined()) {
builder.node().setBalancer(node.asString());
}
node = LOAD_BALANCING_GROUP.resolveModelAttribute(context, model);
if (node.isDefined()) {
builder.node().setLoadBalancingGroup(node.asString());
}
node = PROXIES.resolveModelAttribute(context, model);
if (node.isDefined()) {
for (ModelNode ref : node.asList()) {
String asString = ref.asString();
this.outboundSocketBindings.add(new ServiceSupplierDependency<>(CommonUnaryRequirement.OUTBOUND_SOCKET_BINDING.getServiceName(context, asString)));
}
}
// Elytron-based security support
node = SSL_CONTEXT.resolveModelAttribute(context, model);
if (node.isDefined()) {
this.sslContextDependency = new ServiceSupplierDependency<>(CommonUnaryRequirement.SSL_CONTEXT.getServiceName(context, node.asString()));
}
return this;
}
@Override
public ServiceBuilder<?> build(ServiceTarget target) {
ServiceBuilder<?> builder = target.addService(this.getServiceName());
Consumer<ModClusterConfiguration> config = new CompositeDependency(this.advertiseSocketDependency, this.sslContextDependency).register(builder).provides(this.getServiceName());
for (Dependency dependency : this.outboundSocketBindings) {
dependency.register(builder);
}
Service service = new FunctionalService<>(config, Function.identity(), this, this);
return builder.setInstance(service).setInitialMode(ServiceController.Mode.PASSIVE);
}
@Override
public ModClusterConfiguration get() {
// Advertise
if (advertiseSocketDependency != null) {
final SocketBinding binding = advertiseSocketDependency.get();
builder.advertise()
.setAdvertiseSocketAddress(binding.getMulticastSocketAddress())
.setAdvertiseInterface(binding.getNetworkInterfaceBinding().getNetworkInterfaces().stream().findFirst().orElse(null))
;
// Register the binding with named registry as bound (WFLY-11447)
ManagedBinding simpleManagedBinding = ManagedBinding.Factory.createSimpleManagedBinding(binding);
binding.getSocketBindings().getNamedRegistry().registerBinding(simpleManagedBinding);
if (!isMulticastEnabled(binding.getSocketBindings().getDefaultInterfaceBinding().getNetworkInterfaces())) {
ROOT_LOGGER.multicastInterfaceNotAvailable();
}
}
// Proxies
List<ProxyConfiguration> proxies = new LinkedList<>();
for (final Supplier<OutboundSocketBinding> outboundSocketBindingValueDependency : outboundSocketBindings) {
OutboundSocketBinding binding = outboundSocketBindingValueDependency.get();
proxies.add(new ProxyConfiguration() {
@Override
public InetSocketAddress getRemoteAddress() {
// Both host and port may not be null in the model, no need to validate here
// Don't do resolving here, let mod_cluster deal with it
return new InetSocketAddress(binding.getUnresolvedDestinationAddress(), binding.getDestinationPort());
}
@Override
public InetSocketAddress getLocalAddress() {
if (binding.getOptionalSourceAddress() != null) {
return new InetSocketAddress(binding.getOptionalSourceAddress(), binding.getAbsoluteSourcePort() == null ? 0 : binding.getAbsoluteSourcePort());
} else if (binding.getAbsoluteSourcePort() != null) {
// Bind to port only if source address is not configured
return new InetSocketAddress(binding.getAbsoluteSourcePort());
}
// No binding configured so don't bind
return null;
}
});
}
if (!proxies.isEmpty()) {
builder.mcmp().setProxyConfigurations(proxies);
}
// SSL
if (sslContextDependency != null) {
builder.mcmp().setSocketFactory(sslContextDependency.get().getSocketFactory());
}
return builder.build();
}
// FunctionalService#destroyer implementation
@Override
public void accept(ModClusterConfiguration modClusterConfiguration) {
if (advertiseSocketDependency != null) {
SocketBinding binding = advertiseSocketDependency.get();
ManagedBinding simpleManagedBinding = ManagedBinding.Factory.createSimpleManagedBinding(binding);
binding.getSocketBindings().getNamedRegistry().unregisterBinding(simpleManagedBinding);
}
}
private static boolean isMulticastEnabled(Collection<NetworkInterface> interfaces) {
for (NetworkInterface iface : interfaces) {
try {
if (iface.isUp() && (iface.supportsMulticast() || iface.isLoopback())) {
return true;
}
} catch (SocketException e) {
// Ignore
}
}
return false;
}
}
| 17,150 | 49.149123 | 199 |
java
|
null |
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ModClusterSubsystemSchema.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.mod_cluster;
import java.util.List;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.SubsystemSchema;
import org.jboss.as.controller.xml.VersionedNamespace;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.IntVersion;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* @author Jean-Frederic Clere
* @author Paul Ferraro
* @author Radoslav Husar
*/
public enum ModClusterSubsystemSchema implements SubsystemSchema<ModClusterSubsystemSchema> {
MODCLUSTER_1_0(1, 0), // AS 7.0
MODCLUSTER_1_1(1, 1), // EAP 6.0-6.2
MODCLUSTER_1_2(1, 2), // EAP 6.3-6.4
MODCLUSTER_2_0(2, 0), // WildFly 10, EAP 7.0
MODCLUSTER_3_0(3, 0), // WildFly 11-13, EAP 7.1
MODCLUSTER_4_0(4, 0), // WildFly 14-15, EAP 7.2
MODCLUSTER_5_0(5, 0), // WildFly 16-26, EAP 7.3-7.4
MODCLUSTER_6_0(6, 0), // WildFly 27-present
;
public static final ModClusterSubsystemSchema CURRENT = MODCLUSTER_6_0;
private final VersionedNamespace<IntVersion, ModClusterSubsystemSchema> namespace;
ModClusterSubsystemSchema(int major, int minor) {
this.namespace = SubsystemSchema.createLegacySubsystemURN(ModClusterExtension.SUBSYSTEM_NAME, new IntVersion(major, minor));
}
@Override
public VersionedNamespace<IntVersion, ModClusterSubsystemSchema> getNamespace() {
return this.namespace;
}
@Override
public void readElement(XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
new ModClusterSubsystemXMLReader(this).readElement(reader, operations);
}
}
| 2,638 | 37.808824 | 132 |
java
|
null |
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/DynamicLoadProviderResourceDefinition.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.mod_cluster;
import java.util.function.UnaryOperator;
import org.jboss.as.clustering.controller.ChildResourceDefinition;
import org.jboss.as.clustering.controller.ReloadRequiredResourceRegistrar;
import org.jboss.as.clustering.controller.ResourceDescriptor;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.operations.validation.IntRangeValidator;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.modcluster.load.impl.DynamicLoadBalanceFactorProvider;
/**
* Definition for resource at address /subsystem=modcluster/proxy=X/load-provider=dynamic
*
* @author Radoslav Husar
*/
public class DynamicLoadProviderResourceDefinition extends ChildResourceDefinition<ManagementResourceRegistration> {
public static final PathElement PATH = PathElement.pathElement("load-provider", "dynamic");
enum Attribute implements org.jboss.as.clustering.controller.Attribute, UnaryOperator<SimpleAttributeDefinitionBuilder> {
DECAY("decay", ModelType.DOUBLE, new ModelNode((double) DynamicLoadBalanceFactorProvider.DEFAULT_DECAY_FACTOR)),
HISTORY("history", ModelType.INT, new ModelNode(DynamicLoadBalanceFactorProvider.DEFAULT_HISTORY)),
INITIAL_LOAD("initial-load", ModelType.INT, ModelNode.ZERO) {
@Override
public SimpleAttributeDefinitionBuilder apply(SimpleAttributeDefinitionBuilder simpleAttributeDefinitionBuilder) {
return simpleAttributeDefinitionBuilder.setValidator(new IntRangeValidator(-1, 100, true, true));
}
},
;
private final AttributeDefinition definition;
Attribute(String name, ModelType type, ModelNode defaultValue) {
this.definition = this.apply(new SimpleAttributeDefinitionBuilder(name, type)
.setAllowExpression(true)
.setRequired(false)
.setDefaultValue(defaultValue)
.setRestartAllServices()
).build();
}
@Override
public AttributeDefinition getDefinition() {
return this.definition;
}
@Override
public SimpleAttributeDefinitionBuilder apply(SimpleAttributeDefinitionBuilder builder) {
return builder;
}
}
DynamicLoadProviderResourceDefinition() {
super(PATH, ModClusterExtension.SUBSYSTEM_RESOLVER.createChildResolver(PATH));
}
@Override
public ManagementResourceRegistration register(ManagementResourceRegistration parent) {
ManagementResourceRegistration registration = parent.registerSubModel(this);
ResourceDescriptor descriptor = new ResourceDescriptor(this.getResourceDescriptionResolver())
.addAttributes(Attribute.class)
;
new LoadMetricResourceDefinition().register(registration);
new CustomLoadMetricResourceDefinition().register(registration);
new ReloadRequiredResourceRegistrar(descriptor).register(registration);
return registration;
}
}
| 4,296 | 41.127451 | 126 |
java
|
null |
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ProxyConfigurationResourceTransformer.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.mod_cluster;
import java.util.function.Consumer;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.transform.description.ResourceTransformationDescriptionBuilder;
/**
* @author Radoslav Husar
*/
public class ProxyConfigurationResourceTransformer implements Consumer<ModelVersion> {
private final ResourceTransformationDescriptionBuilder builder;
public ProxyConfigurationResourceTransformer(ResourceTransformationDescriptionBuilder parent) {
this.builder = parent.addChildResource(ProxyConfigurationResourceDefinition.WILDCARD_PATH);
}
@Override
public void accept(ModelVersion version) {
new DynamicLoadProviderResourceTransformer(this.builder).accept(version);
}
}
| 1,795 | 38.043478 | 99 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/test/java/org/wildfly/mod_cluster/undertow/UndertowEngineTestCase.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.mod_cluster.undertow;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import java.util.Collections;
import java.util.Iterator;
import io.undertow.util.StatusCodes;
import org.jboss.as.controller.PathAddress;
import org.jboss.modcluster.container.Connector;
import org.jboss.modcluster.container.Engine;
import org.junit.Test;
import org.wildfly.extension.undertow.Constants;
import org.wildfly.extension.undertow.Host;
import org.wildfly.extension.undertow.HttpsListenerService;
import org.wildfly.extension.undertow.Server;
import org.wildfly.extension.undertow.UndertowService;
import org.xnio.OptionMap;
/**
* @author Paul Ferraro
* @author Radoslav Husar
*/
public class UndertowEngineTestCase {
private final String serverName = "default-server";
private final String hostName = "default-host";
private final String route = "route";
private final Host host = new Host(null, null, null, null, null, this.hostName, Collections.emptyList(), "ROOT.war", StatusCodes.NOT_FOUND, false);
private final HttpsListenerService listener = new HttpsListenerService(null, PathAddress.pathAddress(Constants.HTTPS_LISTENER, "default"), "https", OptionMap.EMPTY, null, OptionMap.EMPTY, false);
private final UndertowService service = new TestUndertowService(null, "default-container", this.serverName, this.hostName, this.route, false, this.server);
private final Server server = new TestServer(this.serverName, this.hostName, this.service, this.host, this.listener);
private final Connector connector = mock(Connector.class);
private final Engine engine = new UndertowEngine(this.serverName, this.server, this.service, this.connector);
@Test
public void getName() {
assertSame(this.serverName, this.engine.getName());
}
@Test
public void getHosts() {
Iterator<org.jboss.modcluster.container.Host> results = this.engine.getHosts().iterator();
assertTrue(results.hasNext());
org.jboss.modcluster.container.Host host = results.next();
assertSame(this.hostName, host.getName());
assertSame(this.engine, host.getEngine());
assertFalse(results.hasNext());
}
@Test
public void getConnectors() {
Iterator<org.jboss.modcluster.container.Connector> results = this.engine.getConnectors().iterator();
assertTrue(results.hasNext());
org.jboss.modcluster.container.Connector connector = results.next();
String listenerName = "default";
assertSame(listenerName, connector.toString());
assertFalse(results.hasNext());
}
@Test
public void getDefaultHost() {
assertSame(this.hostName, this.engine.getDefaultHost());
}
@Test
public void findHost() {
org.jboss.modcluster.container.Host result = this.engine.findHost(this.hostName);
assertSame(this.hostName, result.getName());
assertSame(this.engine, result.getEngine());
assertNull(this.engine.findHost("no-such-host"));
}
@Test
public void getJvmRoute() {
assertSame(this.route, this.engine.getJvmRoute());
}
@Test
public void getObfuscatedJvmRoute() {
// scenario 1, just create a service with obfuscated route but same config as this.service
final TestUndertowService service1 = new TestUndertowService(null, "default-container", this.serverName, this.hostName, this.route, true, null);
final Server server1 = new TestServer(this.serverName, this.hostName, service1, this.host, this.listener);
final Engine engine1 = new UndertowEngine(this.serverName, server1, service1, this.connector);
assertNotEquals(this.route, engine1.getJvmRoute());
// after restart, recreate all objects, is the route still the same if config is kept unchanged?
final Host host2 = new Host(null, null, null, null, null, this.hostName, Collections.emptyList(), "ROOT.war", StatusCodes.NOT_FOUND, false);
final HttpsListenerService listener2 = new HttpsListenerService(null, PathAddress.pathAddress(Constants.HTTPS_LISTENER, "default"), "https", OptionMap.EMPTY, null, OptionMap.EMPTY, false);
final UndertowService service2 = new TestUndertowService(null, "default-container", this.serverName, this.hostName, this.route, true, null);
final Server server2 = new TestServer(this.serverName, this.hostName, service2, host2, listener2);
final Connector connector2 = mock(Connector.class);
final Engine engine2 = new UndertowEngine(this.serverName, server2, service2, connector2);
assertEquals(engine1.getJvmRoute(), engine2.getJvmRoute());
// with a different route, is the obfuscated route different from previous one?
final TestUndertowService service3 = new TestUndertowService(null, "default-container", this.serverName, this.hostName, "adifferentroute", true, null);
final Server server3 = new TestServer(this.serverName, this.hostName, service3, this.host, this.listener);
final Engine engine3 = new UndertowEngine(this.serverName, server3, service3, this.connector);
assertNotEquals(engine1.getJvmRoute(), engine3.getJvmRoute());
// just double check it is obfuscated for engine3 as well
assertNotEquals("adifferentroute", engine3.getJvmRoute());
// with a different server name, is the obfuscated route different from previous one?
final TestUndertowService service4 = new TestUndertowService(null,"default-container", "another.server", this.hostName, "this.route", true, null);
final Server server4 = new TestServer("another.server", this.hostName, service4, this.host, this.listener);
final Engine engine4 = new UndertowEngine(this.serverName, server4, service4, this.connector);
assertNotEquals(engine1.getJvmRoute(), engine4.getJvmRoute());
// just double check it is obfuscated for engine4 as well
assertNotEquals(this.route, engine4.getJvmRoute());
}
@Test
public void getProxyConnector() {
assertSame(this.connector, this.engine.getProxyConnector());
}
}
| 7,398 | 48.326667 | 199 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/test/java/org/wildfly/mod_cluster/undertow/UndertowContextTestCase.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.mod_cluster.undertow;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Collections;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.http.HttpSession;
import io.undertow.servlet.api.Deployment;
import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.core.ApplicationListeners;
import org.jboss.modcluster.container.Context;
import org.jboss.modcluster.container.listeners.HttpSessionListener;
import org.jboss.modcluster.container.listeners.ServletRequestListener;
import org.junit.Test;
public class UndertowContextTestCase {
private final Deployment deployment = mock(Deployment.class);
private final UndertowHost host = mock(UndertowHost.class);
private final Context context = new UndertowContext(this.deployment, this.host);
@Test
public void getHost() {
assertSame(this.host, this.context.getHost());
}
@Test
public void getPath() {
DeploymentInfo info = new DeploymentInfo();
String expected = "";
info.setContextPath(expected);
when(this.deployment.getDeploymentInfo()).thenReturn(info);
String result = this.context.getPath();
assertSame(expected, result);
}
@Test
public void isStarted() throws ServletException {
ServletContext context = mock(ServletContext.class);
ApplicationListeners listeners = new ApplicationListeners(Collections.emptyList(), context);
when(this.deployment.getApplicationListeners()).thenReturn(listeners);
assertFalse(this.context.isStarted());
listeners.start();
assertTrue(this.context.isStarted());
listeners.stop();
assertFalse(this.context.isStarted());
}
@Test
public void addRequestListener() throws ServletException {
ServletRequestListener listener = mock(ServletRequestListener.class);
ServletContext context = mock(ServletContext.class);
ServletRequest request = mock(ServletRequest.class);
ApplicationListeners listeners = new ApplicationListeners(Collections.emptyList(), context);
when(this.deployment.getApplicationListeners()).thenReturn(listeners);
this.context.addRequestListener(listener);
listeners.start();
listeners.requestInitialized(request);
verify(listener).requestInitialized();
listeners.requestDestroyed(request);
verify(listener).requestDestroyed();
}
@Test
public void addSessionListener() throws ServletException {
HttpSessionListener listener = mock(HttpSessionListener.class);
ServletContext context = mock(ServletContext.class);
HttpSession session = mock(HttpSession.class);
ApplicationListeners listeners = new ApplicationListeners(Collections.emptyList(), context);
when(this.deployment.getApplicationListeners()).thenReturn(listeners);
this.context.addSessionListener(listener);
listeners.start();
listeners.sessionCreated(session);
verify(listener).sessionCreated();
listeners.sessionDestroyed(session);
verify(listener).sessionDestroyed();
}
}
| 4,493 | 33.837209 | 100 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/test/java/org/wildfly/mod_cluster/undertow/TestUndertowService.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.mod_cluster.undertow;
import java.util.function.Consumer;
import org.wildfly.extension.undertow.Server;
import org.wildfly.extension.undertow.UndertowService;
public class TestUndertowService extends UndertowService {
public TestUndertowService(final Consumer<UndertowService> serviceConsumer, String defaultContainer, String defaultServer, String defaultVirtualHost, String instanceId, boolean obfuscateRoute, Server server) {
super(serviceConsumer, defaultContainer, defaultServer, defaultVirtualHost, instanceId, obfuscateRoute, true);
this.registerServer(server);
}
}
| 1,643 | 44.666667 | 213 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/test/java/org/wildfly/mod_cluster/undertow/UndertowServerTestCase.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.mod_cluster.undertow;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Iterator;
import org.jboss.modcluster.container.Connector;
import org.jboss.modcluster.container.Engine;
import org.jboss.modcluster.container.Server;
import org.junit.Test;
import org.wildfly.extension.undertow.UndertowService;
/**
* @author Paul Ferraro
* @author Radoslav Husar
*/
public class UndertowServerTestCase {
private final Connector connector = mock(Connector.class);
private final String route = "route";
private final org.wildfly.extension.undertow.Server undertowServer = new TestServer("default-server", "default-host");
private final UndertowService service = new TestUndertowService(null, "default-container", "default-server", "default-virtual-host", this.route, false, this.undertowServer);
private final UndertowEventHandlerAdapterConfiguration configuration = mock(UndertowEventHandlerAdapterConfiguration.class);
private final Server server = new UndertowServer(undertowServer.getName(), this.service, this.connector);
@Test
public void getEngines() {
when(configuration.getServer()).thenReturn(mock(org.wildfly.extension.undertow.Server.class));
when(configuration.getServer().getName()).thenReturn(undertowServer.getName());
Iterator<Engine> engines = this.server.getEngines().iterator();
assertTrue(engines.hasNext());
Engine engine = engines.next();
assertSame(this.connector, engine.getProxyConnector());
assertFalse(engines.hasNext());
}
}
| 2,764 | 42.888889 | 177 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/test/java/org/wildfly/mod_cluster/undertow/UndertowConnectorTestCase.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.mod_cluster.undertow;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.network.NetworkInterfaceBinding;
import org.jboss.as.network.SocketBinding;
import org.jboss.as.network.SocketBindingManager;
import org.jboss.modcluster.container.Connector;
import org.junit.Test;
import org.wildfly.extension.undertow.AjpListenerService;
import org.wildfly.extension.undertow.Constants;
import org.wildfly.extension.undertow.HttpListenerService;
import org.wildfly.extension.undertow.HttpsListenerService;
import org.wildfly.extension.undertow.ListenerService;
import org.xnio.OptionMap;
public class UndertowConnectorTestCase {
private final ListenerService listener = mock(ListenerService.class);
private final Connector connector = new UndertowConnector(this.listener);
@Test
public void getType() {
OptionMap options = OptionMap.builder().getMap();
assertSame(Connector.Type.AJP, new UndertowConnector(new AjpListenerService(null, PathAddress.pathAddress(Constants.AJP_LISTENER, "dummy"), "", options, OptionMap.EMPTY)).getType());
assertSame(Connector.Type.HTTP, new UndertowConnector(new HttpListenerService(null, PathAddress.pathAddress(Constants.HTTP_LISTENER, "dummy"), "", options, OptionMap.EMPTY, false, false, false)).getType());
assertSame(Connector.Type.HTTPS, new UndertowConnector(new HttpsListenerService(null, PathAddress.pathAddress(Constants.HTTPS_LISTENER, "dummy"), "", options, null, OptionMap.EMPTY, false)).getType());
}
@Test
public void getAddress() throws UnknownHostException {
InetAddress expected = InetAddress.getLocalHost();
NetworkInterfaceBinding interfaceBinding = new NetworkInterfaceBinding(Collections.emptySet(), expected);
SocketBindingManager bindingManager = mock(SocketBindingManager.class);
SocketBinding binding = new SocketBinding("socket", 1, true, null, 0, interfaceBinding, bindingManager, Collections.emptyList());
when(this.listener.getSocketBinding()).thenReturn(binding);
InetAddress result = this.connector.getAddress();
assertSame(expected, result);
}
@Test
public void getPort() throws UnknownHostException {
int expected = 10;
NetworkInterfaceBinding interfaceBinding = new NetworkInterfaceBinding(Collections.emptySet(), InetAddress.getLocalHost());
SocketBindingManager bindingManager = mock(SocketBindingManager.class);
SocketBinding binding = new SocketBinding("socket", expected, true, null, 0, interfaceBinding, bindingManager, Collections.emptyList());
when(this.listener.getSocketBinding()).thenReturn(binding);
int result = this.connector.getPort();
assertSame(expected, result);
}
@Test
public void setAddress() throws UnknownHostException {
connector.setAddress(InetAddress.getLocalHost());
verifyNoMoreInteractions(this.listener);
}
}
| 4,264 | 44.860215 | 214 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/test/java/org/wildfly/mod_cluster/undertow/UndertowHostTestCase.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.mod_cluster.undertow;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import io.undertow.server.HttpHandler;
import io.undertow.servlet.api.Deployment;
import io.undertow.servlet.api.DeploymentInfo;
import org.jboss.modcluster.container.Context;
import org.jboss.modcluster.container.Engine;
import org.jboss.modcluster.container.Host;
import org.junit.Test;
import org.wildfly.extension.undertow.UndertowService;
public class UndertowHostTestCase {
private final String hostName = "host";
private final String alias = "alias";
private final org.wildfly.extension.undertow.Server server = new TestServer("serverName", "defaultHost");
private final UndertowService service = new TestUndertowService(null, "default-container", "default-server", "default-virtual-host", "instance-id", false, this.server);
private final org.wildfly.extension.undertow.Host undertowHost = new TestHost(this.hostName, Collections.singletonList(this.alias), this.service, this.server);
private final Engine engine = mock(Engine.class);
private final Host host = new UndertowHost(this.undertowHost, this.engine);
@Test
public void getName() {
assertSame(this.hostName, this.host.getName());
}
@Test
public void getAliases() {
Set<String> result = this.host.getAliases();
assertTrue(result.toString(), result.contains(this.hostName));
assertTrue(result.toString(), result.contains(this.alias));
}
@Test
public void getEngine() {
assertSame(this.engine, this.host.getEngine());
}
@Test
public void getContexts() {
Deployment deployment = mock(Deployment.class);
DeploymentInfo info = new DeploymentInfo();
String expectedPath = "";
info.setContextPath(expectedPath);
HttpHandler handler = mock(HttpHandler.class);
when(deployment.getDeploymentInfo()).thenReturn(info);
this.undertowHost.registerDeployment(deployment, handler);
Iterator<Context> result = this.host.getContexts().iterator();
assertTrue(result.hasNext());
Context context = result.next();
assertSame(this.host, context.getHost());
assertSame(expectedPath, context.getPath());
assertFalse(result.hasNext());
}
@Test
public void findContext() {
Deployment deployment = mock(Deployment.class);
DeploymentInfo info = new DeploymentInfo();
String expectedPath = "";
info.setContextPath(expectedPath);
HttpHandler handler = mock(HttpHandler.class);
when(deployment.getDeploymentInfo()).thenReturn(info);
this.undertowHost.registerDeployment(deployment, handler);
Context result = this.host.findContext(expectedPath);
assertSame(this.host, result.getHost());
assertSame(expectedPath, result.getPath());
result = this.host.findContext("unknown");
assertNull(result);
}
}
| 4,277 | 36.526316 | 172 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/test/java/org/wildfly/mod_cluster/undertow/TestServer.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.mod_cluster.undertow;
import org.wildfly.extension.undertow.Host;
import org.wildfly.extension.undertow.ListenerService;
import org.wildfly.extension.undertow.Server;
import org.wildfly.extension.undertow.UndertowService;
final class TestServer extends Server {
TestServer(final String name, final String defaultHost) {
super(null, null, null, name, defaultHost);
}
TestServer(final String name, final String defaultHost, final UndertowService service, final Host host, final ListenerService listener) {
super(null, null, () -> service, name, defaultHost);
this.registerHost(host);
this.registerListener(listener);
}
}
| 1,713 | 41.85 | 141 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/test/java/org/wildfly/mod_cluster/undertow/TestHost.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.mod_cluster.undertow;
import java.util.List;
import org.wildfly.extension.undertow.Host;
import org.wildfly.extension.undertow.Server;
import org.wildfly.extension.undertow.UndertowService;
class TestHost extends Host {
TestHost(String name, List<String> aliases, UndertowService service, Server server) {
super(null, () -> server, () -> service, null, null, name, aliases, "ROOT.war", 404, true);
}
}
| 1,464 | 40.857143 | 99 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/main/java/org/wildfly/mod_cluster/undertow/UndertowEventHandlerAdapterBuilderProvider.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.mod_cluster.undertow;
import java.time.Duration;
import org.jboss.as.clustering.controller.CapabilityServiceConfigurator;
import org.kohsuke.MetaInfServices;
import org.wildfly.extension.mod_cluster.ContainerEventHandlerAdapterServiceConfiguratorProvider;
/**
* {@link ContainerEventHandlerAdapterServiceConfiguratorProvider} service provider for Undertow.
*
* @author Paul Ferraro
*/
@MetaInfServices(ContainerEventHandlerAdapterServiceConfiguratorProvider.class)
public class UndertowEventHandlerAdapterBuilderProvider implements ContainerEventHandlerAdapterServiceConfiguratorProvider {
@Override
public CapabilityServiceConfigurator getServiceConfigurator(String name, String listenerName, Duration statusInterval) {
return new UndertowEventHandlerAdapterServiceConfigurator(name, listenerName, statusInterval);
}
}
| 1,892 | 42.022727 | 124 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/main/java/org/wildfly/mod_cluster/undertow/UndertowHost.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.mod_cluster.undertow;
import io.undertow.servlet.api.Deployment;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.jboss.as.server.suspend.SuspendController;
import org.jboss.modcluster.container.Context;
import org.jboss.modcluster.container.Engine;
import org.jboss.modcluster.container.Host;
/**
* Adapts {@link org.wildfly.extension.undertow.Host} to an {@link Host}.
*
* @author Radoslav Husar
* @since 8.0
*/
public class UndertowHost implements Host {
private org.wildfly.extension.undertow.Host host;
private Engine engine;
public UndertowHost(org.wildfly.extension.undertow.Host host, Engine engine) {
this.engine = engine;
this.host = host;
}
@Override
public String getName() {
return this.host.getName();
}
@Override
public Engine getEngine() {
return this.engine;
}
@Override
public Iterable<Context> getContexts() {
List<Context> contexts = new ArrayList<>();
for (Deployment deployment : this.host.getDeployments()) {
contexts.add(new UndertowContext(deployment, this));
}
for (String path : this.host.getLocations()) {
contexts.add(new LocationContext(path, this));
}
return contexts;
}
@Override
public Set<String> getAliases() {
return this.host.getAllAliases();
}
@Override
public Context findContext(String path) {
String findPath = "".equals(path) ? "/" : path;
for (Deployment deployment : this.host.getDeployments()) {
if (deployment.getDeploymentInfo().getContextPath().equals(findPath)) {
return new UndertowContext(deployment, this);
}
}
return null;
}
@Override
public boolean equals(Object object) {
if (!(object instanceof UndertowHost)) return false;
UndertowHost host = (UndertowHost) object;
return this.getName().equals(host.getName());
}
@Override
public int hashCode() {
return this.host.getName().hashCode();
}
@Override
public String toString() {
return this.host.getName();
}
boolean isSuspended() {
return this.host.getSuspendState() == SuspendController.State.SUSPENDED;
}
}
| 3,367 | 28.80531 | 83 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/main/java/org/wildfly/mod_cluster/undertow/UndertowConnector.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.mod_cluster.undertow;
import java.net.InetAddress;
import org.jboss.modcluster.container.Connector;
import org.wildfly.extension.undertow.AjpListenerService;
import org.wildfly.extension.undertow.HttpListenerService;
import org.wildfly.extension.undertow.UndertowListener;
import org.wildfly.mod_cluster.undertow.metric.BytesReceivedStreamSourceConduit;
import org.wildfly.mod_cluster.undertow.metric.BytesSentStreamSinkConduit;
import org.wildfly.mod_cluster.undertow.metric.RequestCountHttpHandler;
import org.wildfly.mod_cluster.undertow.metric.RunningRequestsHttpHandler;
/**
* Adapts {@link UndertowListener} to a {@link Connector}.
*
* @author Radoslav Husar
* @since 8.0
*/
public class UndertowConnector implements Connector {
private final UndertowListener listener;
private InetAddress address;
public UndertowConnector(UndertowListener listener) {
this.listener = listener;
}
@Override
public boolean isReverse() {
return false;
}
@Override
public Type getType() {
if (this.listener instanceof AjpListenerService) {
return Type.AJP;
} else if (this.listener instanceof HttpListenerService) {
if (this.listener.isSecure()) {
return Type.HTTPS;
} else {
return Type.HTTP;
}
}
return null;
}
@Override
public InetAddress getAddress() {
return address == null ? this.listener.getSocketBinding().getAddress() : address;
}
@Override
public void setAddress(InetAddress address) {
this.address = address;
}
@Override
public int getPort() {
return this.listener.getSocketBinding().getAbsolutePort();
}
@Override
public boolean isAvailable() {
return !this.listener.isShutdown();
}
/**
* @return int value "-1" to indicate this connector does not maintain corresponding maximum number of threads; capacity
* needs to be defined instead
*/
@Override
public int getMaxThreads() {
return -1;
}
/**
* @return int number of <em>running requests</em> on all connectors as opposed to busy threads
*/
@Override
public int getBusyThreads() {
return RunningRequestsHttpHandler.getRunningRequestCount();
}
/**
* @return long number of bytes sent on all connectors
*/
@Override
public long getBytesSent() {
return BytesSentStreamSinkConduit.getBytesSent();
}
/**
* @return long number of bytes received on all listeners without HTTP request size itself
*/
@Override
public long getBytesReceived() {
return BytesReceivedStreamSourceConduit.getBytesReceived();
}
/**
* @return long number of requests on all listeners as opposed to only this 'connector'
*/
@Override
public long getRequestCount() {
return RequestCountHttpHandler.getRequestCount();
}
@Override
public String toString() {
return this.listener.getName();
}
@Override
public boolean equals(Object object) {
if (!(object instanceof UndertowConnector)) return false;
UndertowConnector connector = (UndertowConnector) object;
return this.listener.getName().equals(connector.listener.getName());
}
@Override
public int hashCode() {
return this.listener.getName().hashCode();
}
}
| 4,502 | 29.221477 | 124 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/main/java/org/wildfly/mod_cluster/undertow/UndertowServer.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.mod_cluster.undertow;
import java.util.Collections;
import org.jboss.modcluster.container.Connector;
import org.jboss.modcluster.container.Engine;
import org.jboss.modcluster.container.Server;
import org.wildfly.extension.undertow.Capabilities;
import org.wildfly.extension.undertow.UndertowService;
/**
* Adapts {@link UndertowService} to a {@link Server}.
*
* @author Radoslav Husar
* @author Paul Ferraro
* @since 8.0
*/
public class UndertowServer implements Server {
private final String serverName;
private final UndertowService service;
private final Connector connector;
public UndertowServer(String serverName, UndertowService service, Connector connector) {
this.serverName = serverName;
this.service = service;
this.connector = connector;
}
@Override
public Iterable<Engine> getEngines() {
for (org.wildfly.extension.undertow.Server server : this.service.getServers()) {
if (server.getName().equals(this.serverName)) {
return Collections.singleton(new UndertowEngine(serverName, server, this.service, this.connector));
}
}
throw new IllegalStateException();
}
@Override
public String toString() {
return Capabilities.CAPABILITY_UNDERTOW;
}
@Override
public boolean equals(Object object) {
if (!(object instanceof UndertowServer)) return false;
UndertowServer server = (UndertowServer) object;
return this.service.equals(server.service);
}
@Override
public int hashCode() {
return this.service.hashCode();
}
}
| 2,676 | 32.4625 | 115 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/main/java/org/wildfly/mod_cluster/undertow/UndertowEventHandlerAdapterConfiguration.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.mod_cluster.undertow;
import java.time.Duration;
import org.jboss.as.server.suspend.SuspendController;
import org.jboss.modcluster.container.ContainerEventHandler;
import org.wildfly.extension.undertow.Server;
import org.wildfly.extension.undertow.UndertowListener;
import org.wildfly.extension.undertow.UndertowService;
/**
* Encapsulates the configuration of an {@link UndertowEventHandlerAdapterService}.
*
* @author Paul Ferraro
* @author Radoslav Husar
*/
public interface UndertowEventHandlerAdapterConfiguration {
Duration getStatusInterval();
UndertowService getUndertowService();
ContainerEventHandler getContainerEventHandler();
SuspendController getSuspendController();
UndertowListener getListener();
Server getServer();
}
| 1,811 | 37.553191 | 83 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/main/java/org/wildfly/mod_cluster/undertow/UndertowEventHandlerAdapterServiceConfigurator.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.mod_cluster.undertow;
import java.time.Duration;
import java.util.function.Supplier;
import org.jboss.as.clustering.controller.CapabilityServiceConfigurator;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.server.suspend.SuspendController;
import org.jboss.modcluster.container.ContainerEventHandler;
import org.jboss.msc.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceTarget;
import org.wildfly.clustering.service.AsyncServiceConfigurator;
import org.wildfly.clustering.service.CompositeDependency;
import org.wildfly.clustering.service.ServiceConfigurator;
import org.wildfly.clustering.service.ServiceSupplierDependency;
import org.wildfly.clustering.service.SupplierDependency;
import org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition;
import org.wildfly.extension.undertow.Capabilities;
import org.wildfly.extension.undertow.Server;
import org.wildfly.extension.undertow.UndertowListener;
import org.wildfly.extension.undertow.UndertowService;
/**
* @author Paul Ferraro
* @author Radoslav Husar
*/
public class UndertowEventHandlerAdapterServiceConfigurator extends UndertowEventHandlerAdapterServiceNameProvider implements CapabilityServiceConfigurator, UndertowEventHandlerAdapterConfiguration {
private final String proxyName;
private final String listenerName;
private final Duration statusInterval;
private volatile Supplier<ContainerEventHandler> eventHandler;
private volatile SupplierDependency<SuspendController> suspendController;
private volatile SupplierDependency<UndertowService> service;
private volatile SupplierDependency<UndertowListener> listener;
public UndertowEventHandlerAdapterServiceConfigurator(String proxyName, String listenerName, Duration statusInterval) {
super(proxyName);
this.proxyName = proxyName;
this.listenerName = listenerName;
this.statusInterval = statusInterval;
}
@Override
public ServiceConfigurator configure(CapabilityServiceSupport support) {
this.service = new ServiceSupplierDependency<>(support.getCapabilityServiceName(Capabilities.CAPABILITY_UNDERTOW));
this.listener = new ServiceSupplierDependency<>(support.getCapabilityServiceName(Capabilities.CAPABILITY_LISTENER, this.listenerName));
this.suspendController = new ServiceSupplierDependency<>(support.getCapabilityServiceName(Capabilities.REF_SUSPEND_CONTROLLER));
return this;
}
@Override
public ServiceBuilder<?> build(ServiceTarget target) {
ServiceBuilder<?> builder = new AsyncServiceConfigurator(this.getServiceName()).build(target);
new CompositeDependency(this.service, this.listener, this.suspendController).register(builder);
this.eventHandler = builder.requires(ProxyConfigurationResourceDefinition.Capability.SERVICE.getDefinition().getCapabilityServiceName(proxyName));
Service service = new UndertowEventHandlerAdapterService(this);
return builder.setInstance(service);
}
@Override
public Duration getStatusInterval() {
return this.statusInterval;
}
@Override
public UndertowService getUndertowService() {
return this.service.get();
}
@Override
public ContainerEventHandler getContainerEventHandler() {
return this.eventHandler.get();
}
@Override
public SuspendController getSuspendController() {
return this.suspendController.get();
}
@Override
public UndertowListener getListener() {
return this.listener.get();
}
@Override
public Server getServer() {
return this.listener.get().getServer();
}
}
| 4,774 | 40.163793 | 199 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/main/java/org/wildfly/mod_cluster/undertow/UndertowEventHandlerAdapterService.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.mod_cluster.undertow;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.jboss.as.server.suspend.ServerActivity;
import org.jboss.as.server.suspend.ServerActivityCallback;
import org.jboss.as.server.suspend.SuspendController.State;
import org.jboss.logging.Logger;
import org.jboss.modcluster.container.Connector;
import org.jboss.modcluster.container.ContainerEventHandler;
import org.jboss.modcluster.container.Context;
import org.jboss.modcluster.container.Engine;
import org.jboss.modcluster.container.Server;
import org.jboss.msc.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
import org.wildfly.clustering.context.DefaultThreadFactory;
import org.wildfly.extension.undertow.Host;
import org.wildfly.extension.undertow.UndertowEventListener;
import org.wildfly.extension.undertow.UndertowService;
import io.undertow.servlet.api.Deployment;
/**
* Builds a service exposing an Undertow subsystem adapter to mod_cluster's {@link ContainerEventHandler}.
*
* @author Paul Ferraro
* @author Radoslav Husar
*/
public class UndertowEventHandlerAdapterService implements UndertowEventListener, Service, Runnable, ServerActivity {
// No logger interface for this module and no reason to create one for this class only
private static final Logger log = Logger.getLogger("org.jboss.mod_cluster.undertow");
private final UndertowEventHandlerAdapterConfiguration configuration;
private final Set<Context> contexts = new HashSet<>();
private volatile ScheduledExecutorService executor;
private volatile Server server;
private volatile Connector connector;
private volatile String serverName;
public UndertowEventHandlerAdapterService(UndertowEventHandlerAdapterConfiguration configuration) {
this.configuration = configuration;
}
@Override
public void start(StartContext context) {
UndertowService service = this.configuration.getUndertowService();
ContainerEventHandler eventHandler = this.configuration.getContainerEventHandler();
this.connector = new UndertowConnector(this.configuration.getListener());
this.serverName = this.configuration.getServer().getName();
this.server = new UndertowServer(this.serverName, service, this.connector);
// Register ourselves as a listener to the container events
service.registerListener(this);
// Initialize mod_cluster and start it now
eventHandler.init(this.server);
eventHandler.start(this.server);
for (Engine engine : this.server.getEngines()) {
for (org.jboss.modcluster.container.Host host : engine.getHosts()) {
host.getContexts().forEach(c->contexts.add(c));
}
}
// Start the periodic STATUS thread
this.executor = Executors.newScheduledThreadPool(1, new DefaultThreadFactory(UndertowEventHandlerAdapterService.class));
this.executor.scheduleWithFixedDelay(this, 0, this.configuration.getStatusInterval().toMillis(), TimeUnit.MILLISECONDS);
this.configuration.getSuspendController().registerActivity(this);
}
@Override
public void stop(StopContext context) {
this.configuration.getSuspendController().unRegisterActivity(this);
this.configuration.getUndertowService().unregisterListener(this);
this.executor.shutdownNow();
try {
this.executor.awaitTermination(this.configuration.getStatusInterval().toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException ignore) {
// Move on.
}
this.configuration.getContainerEventHandler().stop(this.server);
}
private Context createContext(Deployment deployment, Host host) {
return new UndertowContext(deployment, new UndertowHost(host, new UndertowEngine(serverName, host.getServer().getValue(), this.configuration.getUndertowService(), this.connector)));
}
private Context createContext(String contextPath, Host host) {
return new LocationContext(contextPath, new UndertowHost(host, new UndertowEngine(serverName, host.getServer().getValue(), this.configuration.getUndertowService(), this.connector)));
}
private synchronized void onStart(Context context) {
ContainerEventHandler handler = this.configuration.getContainerEventHandler();
handler.add(context);
State state = this.configuration.getSuspendController().getState();
// TODO break into onDeploymentAdd once implemented in Undertow
if(state == State.RUNNING) {
handler.start(context);
}
this.contexts.add(context);
}
private synchronized void onStop(Context context) {
ContainerEventHandler handler = this.configuration.getContainerEventHandler();
handler.stop(context);
// TODO break into onDeploymentRemove once implemented in Undertow
handler.remove(context);
this.contexts.remove(context);
}
@Override
public void onDeploymentStart(Deployment deployment, Host host) {
if (this.filter(host)) {
this.onStart(this.createContext(deployment, host));
}
}
@Override
public void onDeploymentStop(Deployment deployment, Host host) {
if (this.filter(host)) {
this.onStop(this.createContext(deployment, host));
}
}
@Override
public void onDeploymentStart(String contextPath, Host host) {
if (this.filter(host)) {
this.onStart(this.createContext(contextPath, host));
}
}
@Override
public void onDeploymentStop(String contextPath, Host host) {
if (this.filter(host)) {
this.onStop(this.createContext(contextPath, host));
}
}
public boolean filter(Host host) {
return host.getServer().getName().equals(serverName);
}
@Override
public void run() {
try {
for (Engine engine : this.server.getEngines()) {
this.configuration.getContainerEventHandler().status(engine);
}
} catch (Throwable e) {
log.error(e.getMessage(), e);
}
}
@Override
public synchronized void preSuspend(ServerActivityCallback listener) {
try {
for (Context context : this.contexts) {
this.configuration.getContainerEventHandler().stop(context);
}
} finally {
listener.done();
}
}
@Override
public void suspended(ServerActivityCallback listener) {
listener.done();
}
@Override
public void resume() {
for (Context context : this.contexts) {
this.configuration.getContainerEventHandler().start(context);
}
}
}
| 7,965 | 36.933333 | 190 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/main/java/org/wildfly/mod_cluster/undertow/LocationContext.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 2110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.mod_cluster.undertow;
import org.jboss.modcluster.container.Context;
import org.jboss.modcluster.container.Host;
import org.jboss.modcluster.container.listeners.HttpSessionListener;
import org.jboss.modcluster.container.listeners.ServletRequestListener;
/**
* A simulated context, for use by Jakarta Enterprise Beans/HTTP and static locations.
*
* @author Stuart Douglas
* @author Radoslav Husar
*/
public class LocationContext implements Context {
private String contextPath;
private UndertowHost host;
public LocationContext(String contextPath, UndertowHost host) {
this.contextPath = contextPath;
this.host = host;
}
@Override
public Host getHost() {
return this.host;
}
@Override
public String getPath() {
String path = contextPath;
return "/".equals(path) ? "" : path;
}
@Override
public boolean isStarted() {
return !this.host.isSuspended();
}
@Override
public void addRequestListener(ServletRequestListener requestListener) {
}
@Override
public void removeRequestListener(ServletRequestListener requestListener) {
}
@Override
public void addSessionListener(HttpSessionListener sessionListener) {
}
@Override
public void removeSessionListener(HttpSessionListener sessionListener) {
}
@Override
public int getActiveSessionCount() {
return 0;
}
@Override
public boolean isDistributable() {
return false;
}
@Override
public String toString() {
return this.getPath();
}
@Override
public boolean equals(Object object) {
if (!(object instanceof LocationContext)) return false;
LocationContext context = (LocationContext) object;
return this.host.equals(context.host) && this.getPath().equals(context.getPath());
}
@Override
public int hashCode() {
return this.host.hashCode() ^ this.getPath().hashCode();
}
}
| 3,043 | 26.423423 | 90 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/main/java/org/wildfly/mod_cluster/undertow/UndertowEventHandlerAdapterServiceNameProvider.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.mod_cluster.undertow;
import org.jboss.msc.service.ServiceName;
import org.wildfly.clustering.service.ServiceNameProvider;
import org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition;
/**
* @author Radoslav Husar
*/
class UndertowEventHandlerAdapterServiceNameProvider implements ServiceNameProvider {
private final String proxyName;
UndertowEventHandlerAdapterServiceNameProvider(String proxyName) {
this.proxyName = proxyName;
}
@Override
public ServiceName getServiceName() {
return ProxyConfigurationResourceDefinition.Capability.SERVICE.getDefinition().getCapabilityServiceName(proxyName).append("undertow");
}
}
| 1,727 | 37.4 | 142 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/main/java/org/wildfly/mod_cluster/undertow/ModClusterUndertowDeploymentProcessor.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.mod_cluster.undertow;
import java.util.Set;
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.DeploymentUnitProcessor;
import org.jboss.modcluster.load.metric.LoadMetric;
import org.jboss.modcluster.load.metric.impl.BusyConnectorsLoadMetric;
import org.jboss.modcluster.load.metric.impl.ReceiveTrafficLoadMetric;
import org.jboss.modcluster.load.metric.impl.RequestCountLoadMetric;
import org.jboss.modcluster.load.metric.impl.SendTrafficLoadMetric;
import org.wildfly.extension.undertow.deployment.UndertowAttachments;
import org.wildfly.mod_cluster.undertow.metric.BytesReceivedHttpHandler;
import org.wildfly.mod_cluster.undertow.metric.BytesSentHttpHandler;
import org.wildfly.mod_cluster.undertow.metric.RequestCountHttpHandler;
import org.wildfly.mod_cluster.undertow.metric.RunningRequestsHttpHandler;
/**
* {@link DeploymentUnitProcessor} which adds a dependency on {@link UndertowEventHandlerAdapterServiceConfigurator}s to web
* dependencies to support session draining (see <a href="https://issues.jboss.org/browse/WFLY-3942">WFLY-3942</a>) and
* registers metrics on deployment if mod_cluster module is loaded.
* <ul>
* <li>{@link org.wildfly.mod_cluster.undertow.metric.RequestCountHttpHandler}</li>
* <li>{@link org.wildfly.mod_cluster.undertow.metric.RunningRequestsHttpHandler}</li>
* <li>{@link org.wildfly.mod_cluster.undertow.metric.BytesReceivedHttpHandler}</li>
* <li>{@link org.wildfly.mod_cluster.undertow.metric.BytesSentHttpHandler}</li>
* </ul>
*
* @author Radoslav Husar
* @since 8.0
*/
public class ModClusterUndertowDeploymentProcessor implements DeploymentUnitProcessor {
private final Set<String> adapterNames;
private final Set<LoadMetric> enabledMetrics;
public ModClusterUndertowDeploymentProcessor(Set<String> adapterNames, Set<LoadMetric> enabledMetrics) {
this.adapterNames = adapterNames;
this.enabledMetrics = enabledMetrics;
}
@Override
public void deploy(DeploymentPhaseContext phaseContext) {
DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
// Add mod_cluster-undertow integration service as a web deployment dependency
for (String adapter : adapterNames) {
deploymentUnit.addToAttachmentList(Attachments.WEB_DEPENDENCIES, new UndertowEventHandlerAdapterServiceNameProvider(adapter).getServiceName());
}
// Request count wrapping
if (isMetricEnabled(RequestCountLoadMetric.class)) {
deploymentUnit.addToAttachmentList(UndertowAttachments.UNDERTOW_INITIAL_HANDLER_CHAIN_WRAPPERS, RequestCountHttpHandler::new);
}
// Bytes Sent wrapping
if (isMetricEnabled(SendTrafficLoadMetric.class)) {
deploymentUnit.addToAttachmentList(UndertowAttachments.UNDERTOW_INITIAL_HANDLER_CHAIN_WRAPPERS, BytesSentHttpHandler::new);
}
// Bytes Received wrapping
if (isMetricEnabled(ReceiveTrafficLoadMetric.class)) {
deploymentUnit.addToAttachmentList(UndertowAttachments.UNDERTOW_INITIAL_HANDLER_CHAIN_WRAPPERS, BytesReceivedHttpHandler::new);
}
// Busyness thread setup actions
if (isMetricEnabled(BusyConnectorsLoadMetric.class)) {
deploymentUnit.addToAttachmentList(UndertowAttachments.UNDERTOW_OUTER_HANDLER_CHAIN_WRAPPERS, RunningRequestsHttpHandler::new);
}
}
/**
* Checks whether this {@link Class} is configured to be used.
*
* @param metricClass Class to check whether it's configured to be used
* @return true if any of the enabled metrics is enabled, false otherwise
*/
private boolean isMetricEnabled(Class metricClass) {
for (LoadMetric enabledMetric : enabledMetrics) {
if (metricClass.isInstance(enabledMetric)) {
return true;
}
}
return false;
}
}
| 5,063 | 43.421053 | 155 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/main/java/org/wildfly/mod_cluster/undertow/UndertowContext.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.mod_cluster.undertow;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequestEvent;
import jakarta.servlet.ServletRequestListener;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;
import io.undertow.servlet.api.Deployment;
import io.undertow.servlet.api.ListenerInfo;
import io.undertow.servlet.core.InMemorySessionManagerFactory;
import io.undertow.servlet.core.ManagedListener;
import io.undertow.servlet.util.ImmediateInstanceFactory;
import org.jboss.modcluster.container.Context;
import org.jboss.modcluster.container.Host;
/**
* Adapts {@link Deployment} to an {@link Context}.
*
* @author Radoslav Husar
* @author Paul Ferraro
* @since 8.0
*/
public class UndertowContext implements Context {
private final Deployment deployment;
private final UndertowHost host;
public UndertowContext(Deployment deployment, UndertowHost host) {
this.deployment = deployment;
this.host = host;
}
@Override
public Host getHost() {
return this.host;
}
@Override
public String getPath() {
String path = this.deployment.getDeploymentInfo().getContextPath();
return "/".equals(path) ? "" : path;
}
@Override
public boolean isStarted() {
return this.deployment.getApplicationListeners().isStarted()
&& !this.host.isSuspended();
}
@Override
public void addRequestListener(org.jboss.modcluster.container.listeners.ServletRequestListener requestListener) {
ServletRequestListener listener = new ServletRequestListener() {
@Override
public void requestInitialized(ServletRequestEvent sre) {
requestListener.requestInitialized();
}
@Override
public void requestDestroyed(ServletRequestEvent sre) {
requestListener.requestDestroyed();
}
};
ManagedListener ml = new ManagedListener(new ListenerInfo(ServletRequestListener.class, new ImmediateInstanceFactory<>(listener)), true);
try {
ml.start();
} catch (ServletException e) {
throw new RuntimeException(e);
}
this.deployment.getApplicationListeners().addListener(ml);
}
@Override
public void removeRequestListener(org.jboss.modcluster.container.listeners.ServletRequestListener requestListener) {
// Do nothing
}
@Override
public void addSessionListener(org.jboss.modcluster.container.listeners.HttpSessionListener sessionListener) {
HttpSessionListener listener = new HttpSessionListener() {
@Override
public void sessionCreated(HttpSessionEvent se) {
sessionListener.sessionCreated();
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
sessionListener.sessionDestroyed();
}
};
ManagedListener ml = new ManagedListener(new ListenerInfo(HttpSessionListener.class, new ImmediateInstanceFactory<>(listener)), true);
try {
ml.start();
} catch (ServletException e) {
throw new RuntimeException(e);
}
this.deployment.getApplicationListeners().addListener(ml);
}
@Override
public void removeSessionListener(org.jboss.modcluster.container.listeners.HttpSessionListener sessionListener) {
// Do nothing
}
@Override
public int getActiveSessionCount() {
return this.deployment.getSessionManager().getActiveSessions().size();
}
@Override
public boolean isDistributable() {
return !(this.deployment.getDeploymentInfo().getSessionManagerFactory() instanceof InMemorySessionManagerFactory);
}
@Override
public String toString() {
return this.getPath();
}
@Override
public boolean equals(Object object) {
if (!(object instanceof UndertowContext)) return false;
UndertowContext context = (UndertowContext) object;
return this.host.equals(context.host) && this.getPath().equals(context.getPath());
}
@Override
public int hashCode() {
return this.host.hashCode() ^ this.getPath().hashCode();
}
}
| 5,324 | 33.354839 | 145 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/main/java/org/wildfly/mod_cluster/undertow/UndertowEngine.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.mod_cluster.undertow;
import java.util.Iterator;
import io.undertow.server.session.SessionCookieConfig;
import org.jboss.modcluster.container.Connector;
import org.jboss.modcluster.container.Engine;
import org.jboss.modcluster.container.Host;
import org.jboss.modcluster.container.Server;
import org.wildfly.extension.undertow.CookieConfig;
import org.wildfly.extension.undertow.UndertowListener;
import org.wildfly.extension.undertow.UndertowService;
/**
* Adapts {@link org.wildfly.extension.undertow.Server} to an {@link Engine}.
*
* @author Radoslav Husar
* @since 8.0
*/
public class UndertowEngine implements Engine {
private final String serverName;
private final UndertowService service;
private final org.wildfly.extension.undertow.Server server;
private final Connector connector;
public UndertowEngine(String serverName, org.wildfly.extension.undertow.Server server, UndertowService service, Connector connector) {
this.serverName = serverName;
this.server = server;
this.service = service;
this.connector = connector;
}
@Override
public String getName() {
return this.server.getName();
}
@Override
public Server getServer() {
return new UndertowServer(this.serverName, this.service, this.connector);
}
@Override
public Iterable<Host> getHosts() {
final Iterator<org.wildfly.extension.undertow.Host> hosts = this.server.getHosts().iterator();
final Iterator<Host> iterator = new Iterator<Host>() {
@Override
public boolean hasNext() {
return hosts.hasNext();
}
@Override
public Host next() {
org.wildfly.extension.undertow.Host host = hosts.next();
return new UndertowHost(host, UndertowEngine.this);
}
@Override
public void remove() {
hosts.remove();
}
};
return new Iterable<Host>() {
@Override
public Iterator<Host> iterator() {
return iterator;
}
};
}
@Override
public Connector getProxyConnector() {
return this.connector;
}
@Override
public Iterable<Connector> getConnectors() {
final Iterator<UndertowListener> listeners = this.server.getListeners().iterator();
final Iterator<Connector> iterator = new Iterator<Connector>() {
@Override
public boolean hasNext() {
return listeners.hasNext();
}
@Override
public Connector next() {
return new UndertowConnector(listeners.next());
}
@Override
public void remove() {
listeners.remove();
}
};
return new Iterable<Connector>() {
@Override
public Iterator<Connector> iterator() {
return iterator;
}
};
}
@Override
public String getJvmRoute() {
return this.server.getRoute();
}
@Override
public void setJvmRoute(String jvmRoute) {
// Ignore
}
@Override
public Host findHost(String name) {
for (org.wildfly.extension.undertow.Host host : this.server.getHosts()) {
if (host.getName().equals(name)) {
return new UndertowHost(host, UndertowEngine.this);
}
}
return null;
}
/**
* {@inheritDoc}
*
* @return overridden session cookie name if defined, otherwise {@link SessionCookieConfig#DEFAULT_SESSION_ID}
*/
@Override
public String getSessionCookieName() {
CookieConfig override = this.server.getServletContainer().getSessionCookieConfig();
if (override == null || override.getName() == null) {
return SessionCookieConfig.DEFAULT_SESSION_ID;
}
return override.getName();
}
/**
* {@inheritDoc}
*
* @return lowercase value of {@link #getSessionCookieName()}
*/
@Override
public String getSessionParameterName() {
return getSessionCookieName().toLowerCase();
}
@Override
public String getDefaultHost() {
return this.server.getDefaultHost();
}
@Override
public String toString() {
return this.getName();
}
@Override
public boolean equals(Object object) {
if (!(object instanceof UndertowEngine)) return false;
UndertowEngine engine = (UndertowEngine) object;
return this.getName().equals(engine.getName());
}
@Override
public int hashCode() {
return this.server.getName().hashCode();
}
}
| 5,807 | 28.18593 | 138 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/main/java/org/wildfly/mod_cluster/undertow/metric/UndertowBoottimeHandler.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.mod_cluster.undertow.metric;
import java.util.Set;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.server.AbstractDeploymentChainStep;
import org.jboss.as.server.DeploymentProcessorTarget;
import org.jboss.as.server.deployment.Phase;
import org.jboss.modcluster.load.metric.LoadMetric;
import org.kohsuke.MetaInfServices;
import org.wildfly.extension.mod_cluster.BoottimeHandlerProvider;
import org.wildfly.extension.mod_cluster.ModClusterExtension;
import org.wildfly.mod_cluster.undertow.ModClusterUndertowDeploymentProcessor;
/**
* @author Radoslav Husar
* @since 8.0
*/
@MetaInfServices(BoottimeHandlerProvider.class)
public class UndertowBoottimeHandler implements BoottimeHandlerProvider {
@Override
public void performBoottime(OperationContext context, Set<String> adapterNames, Set<LoadMetric> enabledMetrics) {
context.addStep(new AbstractDeploymentChainStep() {
@Override
protected void execute(DeploymentProcessorTarget processorTarget) {
processorTarget.addDeploymentProcessor(ModClusterExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_UNDERTOW_MODCLUSTER, new ModClusterUndertowDeploymentProcessor(adapterNames, enabledMetrics));
}
}, OperationContext.Stage.RUNTIME);
}
}
| 2,352 | 41.781818 | 222 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/main/java/org/wildfly/mod_cluster/undertow/metric/BytesReceivedHttpHandler.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.mod_cluster.undertow.metric;
import io.undertow.server.ConduitWrapper;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.ConduitFactory;
import org.xnio.conduits.StreamSourceConduit;
/**
* {@link HttpHandler} implementation that counts number of bytes received via {@link BytesReceivedStreamSourceConduit}
* wrapping.
*
* @author Radoslav Husar
* @since 8.0
*/
public class BytesReceivedHttpHandler implements HttpHandler {
private final HttpHandler wrappedHandler;
public BytesReceivedHttpHandler(final HttpHandler handler) {
this.wrappedHandler = handler;
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
if (exchange == null) return;
exchange.addRequestWrapper(new ConduitWrapper<StreamSourceConduit>() {
@Override
public StreamSourceConduit wrap(ConduitFactory<StreamSourceConduit> factory, HttpServerExchange exchange) {
return new BytesReceivedStreamSourceConduit(factory.create());
}
});
wrappedHandler.handleRequest(exchange);
}
}
| 2,210 | 34.66129 | 119 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/main/java/org/wildfly/mod_cluster/undertow/metric/BytesSentStreamSinkConduit.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.mod_cluster.undertow.metric;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.atomic.LongAdder;
import org.xnio.channels.StreamSourceChannel;
import org.xnio.conduits.AbstractSinkConduit;
import org.xnio.conduits.StreamSinkConduit;
/**
* Implementation of {@link StreamSinkConduit} wrapping that wraps around byte-transferring methods to calculate total
* number of bytes transferred leveraging {@link LongAdder}.
*
* @author Radoslav Husar
* @since 8.0
*/
public class BytesSentStreamSinkConduit extends AbstractSinkConduit implements StreamSinkConduit {
private final StreamSinkConduit next;
private static final LongAdder bytesSent = new LongAdder();
public BytesSentStreamSinkConduit(StreamSinkConduit next) {
super(next);
this.next = next;
}
@Override
public long transferFrom(FileChannel src, long position, long count) throws IOException {
long bytes = next.transferFrom(src, position, count);
bytesSent.add(bytes);
return bytes;
}
@Override
public long transferFrom(StreamSourceChannel source, long count, ByteBuffer throughBuffer) throws IOException {
long bytes = next.transferFrom(source, count, throughBuffer);
bytesSent.add(bytes);
return bytes;
}
@Override
public int write(ByteBuffer src) throws IOException {
int bytes = next.write(src);
bytesSent.add(bytes);
return bytes;
}
@Override
public long write(ByteBuffer[] srcs, int offs, int len) throws IOException {
long bytes = next.write(srcs, offs, len);
bytesSent.add(bytes);
return bytes;
}
@Override
public int writeFinal(ByteBuffer src) throws IOException {
int bytes = next.writeFinal(src);
bytesSent.add(bytes);
return bytes;
}
@Override
public long writeFinal(ByteBuffer[] srcs, int offset, int length) throws IOException {
long bytes = next.writeFinal(srcs, offset, length);
bytesSent.add(bytes);
return bytes;
}
public static long getBytesSent() {
return bytesSent.longValue();
}
}
| 3,259 | 31.6 | 118 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/main/java/org/wildfly/mod_cluster/undertow/metric/RequestCountHttpHandler.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.mod_cluster.undertow.metric;
import java.util.concurrent.atomic.LongAdder;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
/**
* {@link HttpHandler} that counts number of incoming requests.
*
* @author Radoslav Husar
* @since 8.0
*/
public class RequestCountHttpHandler implements HttpHandler {
private final HttpHandler wrappedHandler;
private static final LongAdder requestCount = new LongAdder();
public RequestCountHttpHandler(final HttpHandler handler) {
this.wrappedHandler = handler;
}
@Override
public void handleRequest(HttpServerExchange httpServerExchange) throws Exception {
// Count incoming request
requestCount.increment();
// Proceed
wrappedHandler.handleRequest(httpServerExchange);
}
/**
* @return long value of all incoming requests on all connectors
*/
public static long getRequestCount() {
return requestCount.longValue();
}
}
| 2,042 | 31.951613 | 87 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/main/java/org/wildfly/mod_cluster/undertow/metric/RunningRequestsHttpHandler.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.mod_cluster.undertow.metric;
import java.util.concurrent.atomic.LongAdder;
import io.undertow.server.ExchangeCompletionListener;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
/**
* {@link HttpHandler} implementation that counts number of active / running requests to replace the busyness
* metric.
*
* @author Radoslav Husar
* @since 8.0
*/
public class RunningRequestsHttpHandler implements HttpHandler {
private static final LongAdder runningCount = new LongAdder();
private final HttpHandler wrappedHandler;
public RunningRequestsHttpHandler(final HttpHandler handler) {
this.wrappedHandler = handler;
}
/**
* Increments the counter and registers a listener to decrement the counter upon exchange complete event.
*/
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
runningCount.increment();
exchange.addExchangeCompleteListener(new ExchangeCompletionListener() {
@Override
public void exchangeEvent(HttpServerExchange exchange, NextListener nextListener) {
runningCount.decrement();
// Proceed to next listener must be called!
nextListener.proceed();
}
});
wrappedHandler.handleRequest(exchange);
}
public static int getRunningRequestCount() {
return runningCount.intValue();
}
}
| 2,501 | 33.273973 | 109 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/main/java/org/wildfly/mod_cluster/undertow/metric/BytesReceivedStreamSourceConduit.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.mod_cluster.undertow.metric;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.atomic.LongAdder;
import org.xnio.channels.StreamSinkChannel;
import org.xnio.conduits.AbstractSourceConduit;
import org.xnio.conduits.StreamSourceConduit;
/**
* Implementation of {@link StreamSourceConduit} wrapping that wraps around byte-transferring methods to calculate total
* number of bytes transferred leveraging {@link LongAdder}.
*
* @author Radoslav Husar
* @since 8.0
*/
public class BytesReceivedStreamSourceConduit extends AbstractSourceConduit implements StreamSourceConduit {
private final StreamSourceConduit next;
private static final LongAdder bytesReceived = new LongAdder();
public BytesReceivedStreamSourceConduit(StreamSourceConduit next) {
super(next);
this.next = next;
}
@Override
public long transferTo(long position, long count, FileChannel target) throws IOException {
long bytes = next.transferTo(position, count, target);
bytesReceived.add(bytes);
return bytes;
}
@Override
public long transferTo(long count, ByteBuffer throughBuffer, StreamSinkChannel target) throws IOException {
long bytes = next.transferTo(count, throughBuffer, target);
bytesReceived.add(bytes);
return bytes;
}
@Override
public int read(ByteBuffer dst) throws IOException {
int bytes = next.read(dst);
bytesReceived.add(bytes);
return bytes;
}
@Override
public long read(ByteBuffer[] dsts, int offs, int len) throws IOException {
long bytes = next.read(dsts, offs, len);
bytesReceived.add(bytes);
return bytes;
}
public static long getBytesReceived() {
return bytesReceived.longValue();
}
}
| 2,900 | 33.129412 | 120 |
java
|
null |
wildfly-main/mod_cluster/undertow/src/main/java/org/wildfly/mod_cluster/undertow/metric/BytesSentHttpHandler.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.mod_cluster.undertow.metric;
import io.undertow.server.ConduitWrapper;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.ConduitFactory;
import org.xnio.conduits.StreamSinkConduit;
/**
* {@link HttpHandler} implementation that counts number of bytes sent via {@link BytesSentStreamSinkConduit}
* wrapping.
*
* @author Radoslav Husar
* @since 8.0
*/
public class BytesSentHttpHandler implements HttpHandler {
private final HttpHandler wrappedHandler;
public BytesSentHttpHandler(final HttpHandler handler) {
this.wrappedHandler = handler;
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
if (exchange == null) return;
exchange.addResponseWrapper(new ConduitWrapper<StreamSinkConduit>() {
@Override
public StreamSinkConduit wrap(ConduitFactory<StreamSinkConduit> factory, HttpServerExchange exchange) {
return new BytesSentStreamSinkConduit(factory.create());
}
});
wrappedHandler.handleRequest(exchange);
}
}
| 2,179 | 34.16129 | 115 |
java
|
null |
wildfly-main/bean-validation/src/test/java/org/jboss/as/ee/beanvalidation/LazyValidatorFactoryTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ee.beanvalidation;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.InputStream;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.hibernate.validator.HibernateValidatorFactory;
import org.jboss.as.ee.beanvalidation.testprovider.MyValidatorImpl;
import org.jboss.as.ee.beanvalidation.testutil.WithContextClassLoader;
import org.jboss.as.ee.beanvalidation.testutil.ContextClassLoaderRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Unit test for {@link LazyValidatorFactory}.
*
* @author Gunnar Morling
*/
public class LazyValidatorFactoryTestCase {
@Rule
public final ContextClassLoaderRule contextClassLoaderRule = new ContextClassLoaderRule();
private ValidatorFactory validatorFactory;
@Before
public void setupValidatorFactory() {
validatorFactory = new LazyValidatorFactory(WildFlySecurityManager.getCurrentContextClassLoaderPrivileged());
}
@Test
public void testHibernateValidatorIsUsedAsProviderByDefault() {
HibernateValidatorFactory hibernateValidatorFactory = validatorFactory.unwrap(HibernateValidatorFactory.class);
assertNotNull("LazyValidatorFactory should delegate to the HV factory by default", hibernateValidatorFactory);
Validator validator = validatorFactory.getValidator();
assertNotNull("LazyValidatorFactory should provide a validator", validator);
}
@Test
@WithContextClassLoader(TestClassLoader.class)
public void testSpecificProviderCanBeConfiguredInValidationXml() {
Validator validator = validatorFactory.getValidator();
assertNotNull("LazyValidatorFactory should provide a validator", validator);
assertTrue("Validator should be of type created by XML-configured provider", validator instanceof MyValidatorImpl);
}
/**
* A class loader which makes the file {@code custom-default-validation-provider-validation.xml} available as
* {@code META-INF/validation.xml}.
*
* @author Gunnar Morling
*/
public static final class TestClassLoader extends ClassLoader {
public TestClassLoader(ClassLoader parent) {
super(parent);
}
@Override
public InputStream getResourceAsStream(String name) {
if (name.equals("META-INF/validation.xml")) {
return LazyValidatorFactoryTestCase.class.getResourceAsStream("custom-default-validation-provider-validation.xml");
}
return super.getResourceAsStream(name);
}
}
}
| 3,733 | 37.494845 | 131 |
java
|
null |
wildfly-main/bean-validation/src/test/java/org/jboss/as/ee/beanvalidation/WildFlyProviderResolverTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ee.beanvalidation;
import static org.junit.Assert.assertEquals;
import java.util.List;
import jakarta.validation.ValidationProviderResolver;
import jakarta.validation.spi.ValidationProvider;
import org.hibernate.validator.HibernateValidator;
import org.jboss.as.ee.beanvalidation.testprovider.MyValidationProvider;
import org.jboss.as.ee.beanvalidation.testutil.ContextClassLoaderRule;
import org.jboss.as.ee.beanvalidation.testutil.WithContextClassLoader;
import org.jboss.as.ee.beanvalidation.testutil.WithContextClassLoader.NullClassLoader;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
/**
* Test for {@link WildFlyProviderResolver}.
*
* @author Gunnar Morling
*/
public class WildFlyProviderResolverTestCase {
@Rule
public final ContextClassLoaderRule contextClassLoaderRule = new ContextClassLoaderRule();
private ValidationProviderResolver providerResolver;
@Before
public void setupProviderResolver() {
providerResolver = new WildFlyProviderResolver();
}
@Test
public void testHibernateValidatorIsFirstProviderInList() {
List<ValidationProvider<?>> validationProviders = providerResolver.getValidationProviders();
assertEquals(2, validationProviders.size());
assertEquals(HibernateValidator.class.getName(), validationProviders.get(0).getClass().getName());
assertEquals(MyValidationProvider.class.getName(), validationProviders.get(1).getClass().getName());
}
@Test
@WithContextClassLoader(NullClassLoader.class)
public void testValidationProvidersCanBeLoadedIfContextLoaderIsNull() {
List<ValidationProvider<?>> validationProviders = providerResolver.getValidationProviders();
assertEquals(2, validationProviders.size());
}
}
| 2,829 | 37.243243 | 108 |
java
|
null |
wildfly-main/bean-validation/src/test/java/org/jboss/as/ee/beanvalidation/testprovider/MyValidationProvider.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ee.beanvalidation.testprovider;
import jakarta.validation.Configuration;
import jakarta.validation.ValidatorFactory;
import jakarta.validation.spi.BootstrapState;
import jakarta.validation.spi.ConfigurationState;
import jakarta.validation.spi.ValidationProvider;
/**
* A {@link ValidationProvider} implementation for testing purposes.
*
* @author Gunnar Morling
*/
public class MyValidationProvider implements ValidationProvider<MyConfiguration> {
@Override
public MyConfiguration createSpecializedConfiguration(BootstrapState state) {
return new MyConfiguration();
}
@Override
public Configuration<?> createGenericConfiguration(BootstrapState state) {
return new MyConfiguration();
}
@Override
public ValidatorFactory buildValidatorFactory(ConfigurationState configurationState) {
return new MyValidatorFactoryImpl();
}
}
| 1,936 | 36.25 | 90 |
java
|
null |
wildfly-main/bean-validation/src/test/java/org/jboss/as/ee/beanvalidation/testprovider/MyConfiguration.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ee.beanvalidation.testprovider;
import java.io.InputStream;
import jakarta.validation.BootstrapConfiguration;
import jakarta.validation.ClockProvider;
import jakarta.validation.Configuration;
import jakarta.validation.ConstraintValidatorFactory;
import jakarta.validation.MessageInterpolator;
import jakarta.validation.ParameterNameProvider;
import jakarta.validation.TraversableResolver;
import jakarta.validation.ValidatorFactory;
import jakarta.validation.valueextraction.ValueExtractor;
/**
* A {@link Configuration} implementation for testing purposes.
*
* @author Gunnar Morling
*/
public class MyConfiguration implements Configuration<MyConfiguration> {
@Override
public MyConfiguration ignoreXmlConfiguration() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public MyConfiguration messageInterpolator(MessageInterpolator interpolator) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public MyConfiguration traversableResolver(TraversableResolver resolver) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public MyConfiguration constraintValidatorFactory(ConstraintValidatorFactory constraintValidatorFactory) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public MyConfiguration parameterNameProvider(ParameterNameProvider parameterNameProvider) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public MyConfiguration addMapping(InputStream stream) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public MyConfiguration addProperty(String name, String value) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public MessageInterpolator getDefaultMessageInterpolator() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public TraversableResolver getDefaultTraversableResolver() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public ConstraintValidatorFactory getDefaultConstraintValidatorFactory() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public ParameterNameProvider getDefaultParameterNameProvider() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public BootstrapConfiguration getBootstrapConfiguration() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public MyConfiguration clockProvider(ClockProvider clockProvider) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public MyConfiguration addValueExtractor(ValueExtractor<?> extractor) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public ClockProvider getDefaultClockProvider() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public ValidatorFactory buildValidatorFactory() {
return new MyValidatorFactoryImpl();
}
}
| 4,263 | 33.666667 | 110 |
java
|
null |
wildfly-main/bean-validation/src/test/java/org/jboss/as/ee/beanvalidation/testprovider/MyValidatorFactoryImpl.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ee.beanvalidation.testprovider;
import jakarta.validation.ClockProvider;
import jakarta.validation.ConstraintValidatorFactory;
import jakarta.validation.MessageInterpolator;
import jakarta.validation.ParameterNameProvider;
import jakarta.validation.TraversableResolver;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorContext;
import jakarta.validation.ValidatorFactory;
/**
* A {@link ValidatorFactory} implementation for testing purposes.
*
* @author Gunnar Morling
*/
public class MyValidatorFactoryImpl implements ValidatorFactory {
@Override
public Validator getValidator() {
return new MyValidatorImpl();
}
@Override
public ValidatorContext usingContext() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public MessageInterpolator getMessageInterpolator() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public TraversableResolver getTraversableResolver() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public ConstraintValidatorFactory getConstraintValidatorFactory() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public ParameterNameProvider getParameterNameProvider() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public ClockProvider getClockProvider() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public <T> T unwrap(Class<T> type) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public void close() {
throw new UnsupportedOperationException("Not implemented");
}
}
| 2,830 | 32.305882 | 71 |
java
|
null |
wildfly-main/bean-validation/src/test/java/org/jboss/as/ee/beanvalidation/testprovider/AnotherValidationProvider.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ee.beanvalidation.testprovider;
import jakarta.validation.Configuration;
import jakarta.validation.ValidatorFactory;
import jakarta.validation.spi.BootstrapState;
import jakarta.validation.spi.ConfigurationState;
import jakarta.validation.spi.ValidationProvider;
/**
* A {@link ValidationProvider} implementation for testing purposes.
*
* @author Gunnar Morling
*/
public class AnotherValidationProvider implements ValidationProvider<MyConfiguration> {
@Override
public MyConfiguration createSpecializedConfiguration(BootstrapState state) {
return new MyConfiguration();
}
@Override
public Configuration<?> createGenericConfiguration(BootstrapState state) {
return new MyConfiguration();
}
@Override
public ValidatorFactory buildValidatorFactory(ConfigurationState configurationState) {
return new MyValidatorFactoryImpl();
}
}
| 1,941 | 36.346154 | 90 |
java
|
null |
wildfly-main/bean-validation/src/test/java/org/jboss/as/ee/beanvalidation/testprovider/MyValidatorImpl.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ee.beanvalidation.testprovider;
import java.util.Set;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import jakarta.validation.executable.ExecutableValidator;
import jakarta.validation.metadata.BeanDescriptor;
/**
* A {@link Validator} implementation for testing purposes.
*
* @author Gunnar Morling
*/
public class MyValidatorImpl implements Validator {
@Override
public <T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public <T> Set<ConstraintViolation<T>> validateProperty(T object, String propertyName, Class<?>... groups) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public <T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType, String propertyName, Object value,
Class<?>... groups) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public BeanDescriptor getConstraintsForClass(Class<?> clazz) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public <T> T unwrap(Class<T> type) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public ExecutableValidator forExecutables() {
throw new UnsupportedOperationException("Not implemented");
}
}
| 2,479 | 34.942029 | 112 |
java
|
null |
wildfly-main/bean-validation/src/test/java/org/jboss/as/ee/beanvalidation/testutil/ContextClassLoaderRule.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ee.beanvalidation.testutil;
import static java.security.AccessController.doPrivileged;
import java.security.PrivilegedAction;
import org.jboss.as.ee.beanvalidation.testutil.WithContextClassLoader.NullClassLoader;
import org.wildfly.security.manager.action.GetContextClassLoaderAction;
import org.wildfly.security.manager.action.SetContextClassLoaderAction;
import org.wildfly.security.manager.WildFlySecurityManager;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
/**
* A JUnit rule which allows to use a specific class loader as context class loader by annotating the concerned test method with
* {@link WithContextClassLoader}. The previous context class loader will be set after test execution.
*
* @author Gunnar Morling
*/
public class ContextClassLoaderRule extends TestWatcher {
private ClassLoader previousContextClassLoader;
@Override
protected void starting(Description description) {
final WithContextClassLoader validationXml = description.getAnnotation(WithContextClassLoader.class);
if (validationXml == null) {
return;
}
previousContextClassLoader = getContextClassLoader();
setContextClassLoader(validationXml.value() == NullClassLoader.class ? null : newClassLoaderInstance(
validationXml.value(), previousContextClassLoader));
}
@Override
protected void finished(Description description) {
if (previousContextClassLoader != null) {
setContextClassLoader(previousContextClassLoader);
}
}
private ClassLoader getContextClassLoader() {
return run(GetContextClassLoaderAction.getInstance());
}
private void setContextClassLoader(ClassLoader classLoader) {
run(new SetContextClassLoaderAction(classLoader));
}
private <T extends ClassLoader> T newClassLoaderInstance(Class<T> clazz, ClassLoader parent) {
return run(new NewClassLoaderInstanceAction<T>(clazz, parent));
}
private <T> T run(PrivilegedAction<T> action) {
return ! WildFlySecurityManager.isChecking() ? action.run() : doPrivileged(action);
}
private static final class NewClassLoaderInstanceAction<T extends ClassLoader> implements PrivilegedAction<T> {
private final Class<T> clazz;
private final ClassLoader parent;
private NewClassLoaderInstanceAction(Class<T> clazz, ClassLoader parent) {
this.clazz = clazz;
this.parent = parent;
}
@Override
public T run() {
try {
return clazz.getConstructor(ClassLoader.class).newInstance(parent);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
| 3,812 | 37.13 | 128 |
java
|
null |
wildfly-main/bean-validation/src/test/java/org/jboss/as/ee/beanvalidation/testutil/WithContextClassLoader.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ee.beanvalidation.testutil;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Specifies the context class loader to use for a given test.
*
* @author Gunnar Morling
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface WithContextClassLoader {
/**
* The context class loader to use for a given test.
*
* @return the context class loader to use for a given test
*/
Class<? extends ClassLoader> value();
/**
* A marker type for setting the context class loader to {@code null}.
*
* @author Gunnar Morling
*/
public static class NullClassLoader extends ClassLoader {
}
}
| 1,850 | 33.924528 | 74 |
java
|
null |
wildfly-main/bean-validation/src/test/java/org/wildfly/extension/beanvalidation/BeanValidationSubsystemTestCase.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.beanvalidation;
import java.util.EnumSet;
import org.jboss.as.subsystem.test.AbstractSubsystemSchemaTest;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
* Jakarta Bean Validation subsystem tests.
*
* @author Eduardo Martins
*/
@RunWith(Parameterized.class)
public class BeanValidationSubsystemTestCase extends AbstractSubsystemSchemaTest<BeanValidationSubsystemSchema> {
@Parameters
public static Iterable<BeanValidationSubsystemSchema> parameters() {
return EnumSet.allOf(BeanValidationSubsystemSchema.class);
}
public BeanValidationSubsystemTestCase(BeanValidationSubsystemSchema schema) {
super(BeanValidationExtension.SUBSYSTEM_NAME, new BeanValidationExtension(), schema, BeanValidationSubsystemSchema.CURRENT);
}
}
| 1,900 | 38.604167 | 132 |
java
|
null |
wildfly-main/bean-validation/src/main/java/org/jboss/as/ee/beanvalidation/BeanValidationFactoryDeployer.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ee.beanvalidation;
import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME;
import jakarta.validation.ValidatorFactory;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.ComponentNamingMode;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.ee.structure.DeploymentType;
import org.jboss.as.ee.structure.DeploymentTypeMarker;
import org.jboss.as.naming.ServiceBasedNamingStore;
import org.jboss.as.naming.ValueManagedReferenceFactory;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.service.BinderService;
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.modules.Module;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
/**
* Creates a Jakarta Bean Validation factory and adds it to the deployment and binds it to JNDI.
* <p/>
* We use a lazy wrapper around the ValidatorFactory to stop it being initialized until it is used.
* TODO: it would be neat if hibernate validator could make use of our annotation scanning etc
*
* @author Stuart Douglas
*/
public class BeanValidationFactoryDeployer implements DeploymentUnitProcessor {
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
final EEModuleDescription moduleDescription = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION);
if(module == null || moduleDescription == null) {
return;
}
final LazyValidatorFactory factory = new LazyValidatorFactory(module.getClassLoader());
deploymentUnit.putAttachment(BeanValidationAttachments.VALIDATOR_FACTORY, factory);
bindFactoryToJndi(factory,deploymentUnit,phaseContext,moduleDescription);
}
private void bindFactoryToJndi(LazyValidatorFactory factory, DeploymentUnit deploymentUnit, DeploymentPhaseContext phaseContext,EEModuleDescription moduleDescription) {
if(moduleDescription == null) {
return;
}
final ServiceTarget serviceTarget = phaseContext.getServiceTarget();
//if this is a war we need to bind to the modules comp namespace
if(DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit) || DeploymentTypeMarker.isType(DeploymentType.APPLICATION_CLIENT, deploymentUnit)) {
final ServiceName moduleContextServiceName = ContextNames.contextServiceNameOfModule(moduleDescription.getApplicationName(), moduleDescription.getModuleName());
bindServices(factory, serviceTarget, moduleDescription, moduleDescription.getModuleName(), moduleContextServiceName);
}
for(ComponentDescription component : moduleDescription.getComponentDescriptions()) {
if(component.getNamingMode() == ComponentNamingMode.CREATE) {
final ServiceName compContextServiceName = ContextNames.contextServiceNameOfComponent(moduleDescription.getApplicationName(),moduleDescription.getModuleName(),component.getComponentName());
bindServices(factory, serviceTarget, moduleDescription, component.getComponentName(), compContextServiceName);
}
}
}
/**
*
* @param factory The ValidatorFactory to bind
* @param serviceTarget The service target
* @param contextServiceName The service name of the context to bind to
*/
private void bindServices(LazyValidatorFactory factory, ServiceTarget serviceTarget, EEModuleDescription description, String componentName, ServiceName contextServiceName) {
BinderService validatorFactoryBindingService = new BinderService("ValidatorFactory");
validatorFactoryBindingService.getManagedObjectInjector().inject(new ValueManagedReferenceFactory(factory));
serviceTarget.addService(contextServiceName.append("ValidatorFactory"), validatorFactoryBindingService)
.addDependency(contextServiceName, ServiceBasedNamingStore.class, validatorFactoryBindingService.getNamingStoreInjector())
.install();
BinderService validatorBindingService = new BinderService("Validator");
validatorBindingService.getManagedObjectInjector().inject(new ValidatorJndiInjectable(factory));
serviceTarget.addService(contextServiceName.append("Validator"), validatorBindingService)
.addDependency(contextServiceName, ServiceBasedNamingStore.class, validatorBindingService.getNamingStoreInjector())
.install();
}
@Override
public void undeploy(DeploymentUnit context) {
ValidatorFactory validatorFactory = context.getAttachment(BeanValidationAttachments.VALIDATOR_FACTORY);
final CapabilityServiceSupport support = context.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
boolean partOfWeldDeployment = false;
if (support.hasCapability(WELD_CAPABILITY_NAME)) {
partOfWeldDeployment = support.getOptionalCapabilityRuntimeAPI(WELD_CAPABILITY_NAME, WeldCapability.class)
.get().isPartOfWeldDeployment(context);
}
if (validatorFactory != null && !partOfWeldDeployment) {
// If the ValidatorFactory is not Jakarta Contexts and Dependency Injection enabled, close it here. Otherwise, it's
// closed via CdiValidatorFactoryService before the Weld service is stopped.
validatorFactory.close();
}
context.removeAttachment(BeanValidationAttachments.VALIDATOR_FACTORY);
}
}
| 7,092 | 51.540741 | 205 |
java
|
null |
wildfly-main/bean-validation/src/main/java/org/jboss/as/ee/beanvalidation/BeanValidationDeploymentDependenciesProcessor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ee.beanvalidation;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.module.ModuleDependency;
import org.jboss.as.server.deployment.module.ModuleSpecification;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleLoader;
/**
* Processor which adds each Jakarta Bean Validation API module as dependency to all deployments.
*
* @author Eduardo Martins
*/
public class BeanValidationDeploymentDependenciesProcessor implements DeploymentUnitProcessor {
private static final String[] DEPENDENCIES = {
"org.hibernate.validator",
"jakarta.validation.api",
};
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);
final ModuleLoader moduleLoader = Module.getBootModuleLoader();
//
for (final String moduleIdentifier : DEPENDENCIES) {
moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, moduleIdentifier, true, false, true, false));
}
}
}
| 2,551 | 43 | 132 |
java
|
null |
wildfly-main/bean-validation/src/main/java/org/jboss/as/ee/beanvalidation/BeanValidationResourceReferenceProcessor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ee.beanvalidation;
import jakarta.validation.Validator;
import org.jboss.as.ee.component.InjectionSource;
import org.jboss.as.ee.component.deployers.EEResourceReferenceProcessor;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.ServiceBuilder;
/**
* Handled resource injections for the Validator
*
* @author Stuart Douglas
*/
public class BeanValidationResourceReferenceProcessor implements EEResourceReferenceProcessor {
public static final BeanValidationResourceReferenceProcessor INSTANCE = new BeanValidationResourceReferenceProcessor();
@Override
public String getResourceReferenceType() {
return Validator.class.getName();
}
@Override
public InjectionSource getResourceReferenceBindingSource() throws DeploymentUnitProcessingException {
return ValidatorInjectionSource.INSTANCE;
}
private static final class ValidatorInjectionSource extends InjectionSource {
public static final ValidatorInjectionSource INSTANCE = new ValidatorInjectionSource();
@Override
public void getResourceValue(final ResolutionContext resolutionContext, final ServiceBuilder<?> serviceBuilder, final DeploymentPhaseContext phaseContext, final Injector<ManagedReferenceFactory> injector) throws DeploymentUnitProcessingException {
final ClassLoader classLoader = phaseContext.getDeploymentUnit().getAttachment(Attachments.MODULE).getClassLoader();
injector.inject(new ValidatorJndiInjectable(new LazyValidatorFactory(classLoader)));
}
}
}
| 2,841 | 42.060606 | 255 |
java
|
null |
wildfly-main/bean-validation/src/main/java/org/jboss/as/ee/beanvalidation/BeanValidationResourceReferenceProcessorRegistryProcessor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ee.beanvalidation;
import org.jboss.as.ee.component.Attachments;
import org.jboss.as.ee.component.deployers.EEResourceReferenceProcessorRegistry;
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;
/**
* DU Processor responsible for registering EEResourceReferenceProcessors wrt Jakarta Bean Validation.
*
* @author Eduardo Martins
*/
public class BeanValidationResourceReferenceProcessorRegistryProcessor implements DeploymentUnitProcessor {
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if(deploymentUnit.getParent() == null) {
final EEResourceReferenceProcessorRegistry eeResourceReferenceProcessorRegistry = deploymentUnit.getAttachment(Attachments.RESOURCE_REFERENCE_PROCESSOR_REGISTRY);
if(eeResourceReferenceProcessorRegistry != null) {
eeResourceReferenceProcessorRegistry.registerResourceReferenceProcessor(BeanValidationResourceReferenceProcessor.INSTANCE);
eeResourceReferenceProcessorRegistry.registerResourceReferenceProcessor(BeanValidationFactoryResourceReferenceProcessor.INSTANCE);
}
}
}
}
| 2,497 | 48.96 | 174 |
java
|
null |
wildfly-main/bean-validation/src/main/java/org/jboss/as/ee/beanvalidation/BeanValidationAttachments.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ee.beanvalidation;
import org.jboss.as.server.deployment.AttachmentKey;
import jakarta.validation.ValidatorFactory;
/**
* @author Stuart Douglas
*/
public class BeanValidationAttachments {
public static final AttachmentKey<ValidatorFactory> VALIDATOR_FACTORY = AttachmentKey.create(ValidatorFactory.class);
private BeanValidationAttachments() {
}
}
| 1,406 | 35.076923 | 121 |
java
|
null |
wildfly-main/bean-validation/src/main/java/org/jboss/as/ee/beanvalidation/LazyValidatorFactory.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ee.beanvalidation;
import jakarta.validation.ClockProvider;
import jakarta.validation.ConstraintValidatorFactory;
import jakarta.validation.MessageInterpolator;
import jakarta.validation.ParameterNameProvider;
import jakarta.validation.TraversableResolver;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorContext;
import jakarta.validation.ValidatorFactory;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* This class lazily initialize the ValidatorFactory on the first usage One benefit is that no domain class is loaded until the
* ValidatorFactory is really needed. Useful to avoid loading classes before Jakarta Persistence is initialized and has enhanced its classes.
*
* @author Emmanuel Bernard
* @author Stuart Douglas
*/
public class LazyValidatorFactory implements ValidatorFactory {
private final ClassLoader classLoader;
private volatile ValidatorFactory delegate; // use as a barrier
public LazyValidatorFactory(ClassLoader classLoader) {
this.classLoader = classLoader;
}
private ValidatorFactory getDelegate() {
ValidatorFactory result = delegate;
if (result == null) {
synchronized (this) {
result = delegate;
if (result == null) {
delegate = result = initFactory();
}
}
}
return result;
}
public void replaceDelegate(ValidatorFactory validatorFactory) {
synchronized (this) {
delegate = validatorFactory;
}
}
@Override
public Validator getValidator() {
return getDelegate().getValidator();
}
private ValidatorFactory initFactory() {
final ClassLoader oldTCCL = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader);
return Validation.byDefaultProvider().providerResolver(new WildFlyProviderResolver()).configure()
.buildValidatorFactory();
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTCCL);
}
}
@Override
public ValidatorContext usingContext() {
final ClassLoader oldTCCL = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
// Make sure the deployment's CL is set
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader);
return getDelegate().usingContext();
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTCCL);
}
}
@Override
public MessageInterpolator getMessageInterpolator() {
return getDelegate().getMessageInterpolator();
}
@Override
public TraversableResolver getTraversableResolver() {
return getDelegate().getTraversableResolver();
}
@Override
public ConstraintValidatorFactory getConstraintValidatorFactory() {
return getDelegate().getConstraintValidatorFactory();
}
@Override
public ParameterNameProvider getParameterNameProvider() {
return getDelegate().getParameterNameProvider();
}
@Override
public ClockProvider getClockProvider() {
return getDelegate().getClockProvider();
}
@Override
public <T> T unwrap(Class<T> clazz) {
return getDelegate().unwrap(clazz);
}
@Override
public void close() {
// Avoid initializing delegate if closing it
if (delegate != null) {
getDelegate().close();
}
}
}
| 4,726 | 33.253623 | 141 |
java
|
null |
wildfly-main/bean-validation/src/main/java/org/jboss/as/ee/beanvalidation/ValidatorJndiInjectable.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ee.beanvalidation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.jboss.as.naming.ContextListAndJndiViewManagedReferenceFactory;
import org.jboss.as.naming.ImmediateManagedReference;
import org.jboss.as.naming.JndiViewManagedReferenceFactory;
import org.jboss.as.naming.ManagedReference;
/**
* @author Stuart Douglas
* @author Eduardo Martins
*/
final class ValidatorJndiInjectable implements ContextListAndJndiViewManagedReferenceFactory {
private final ValidatorFactory factory;
public ValidatorJndiInjectable(ValidatorFactory factory) {
this.factory = factory;
}
@Override
public ManagedReference getReference() {
return new ImmediateManagedReference(factory.getValidator());
}
@Override
public String getInstanceClassName() {
// the default and safe value. A more appropriate value, for instance using the getReference() result, may be provided extending the method
return Validator.class.getName();
}
@Override
public String getJndiViewInstanceValue() {
// the default and safe value. A more appropriate value, for instance using the getReference() result, may be provided extending the method
return JndiViewManagedReferenceFactory.DEFAULT_JNDI_VIEW_INSTANCE_VALUE;
}
}
| 2,368 | 38.483333 | 147 |
java
|
null |
wildfly-main/bean-validation/src/main/java/org/jboss/as/ee/beanvalidation/WildFlyProviderResolver.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ee.beanvalidation;
import java.security.PrivilegedAction;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import jakarta.validation.ValidationProviderResolver;
import jakarta.validation.spi.ValidationProvider;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* A {@link ValidationProviderResolver} to be used within WildFly. If several BV providers are available,
* {@code HibernateValidator} will be the first element of the returned provider list.
* <p/>
* The providers are loaded via the current thread's context class loader; If no providers are found, the loader of this class
* will be tried as fallback.
*
* @author Hardy Ferentschik
* @author Gunnar Morling
*/
public class WildFlyProviderResolver implements ValidationProviderResolver {
/**
* Returns a list with all {@link ValidationProvider} validation providers.
*
* @return a list with all {@link ValidationProvider} validation providers
*/
@Override
public List<ValidationProvider<?>> getValidationProviders() {
// first try the TCCL
List<ValidationProvider<?>> providers = getValidationProviders(WildFlySecurityManager.getCurrentContextClassLoaderPrivileged());
if (providers != null && !providers.isEmpty()) {
return providers;
}
// otherwise use the loader of this class
else {
return getValidationProviders(WildFlySecurityManager.getClassLoaderPrivileged(WildFlyProviderResolver.class));
}
}
private List<ValidationProvider<?>> getValidationProviders(final ClassLoader classLoader) {
if(WildFlySecurityManager.isChecking()) {
return WildFlySecurityManager.doUnchecked(new PrivilegedAction<List<ValidationProvider<?>>>() {
@Override
public List<ValidationProvider<?>> run() {
return loadProviders(classLoader);
}
});
} else {
return loadProviders(classLoader);
}
}
/**
* Retrieves the providers from the given loader, using the service loader mechanism.
*
* @param classLoader the class loader to use
* @return a list with providers retrieved via the given loader. May be empty but never {@code null}
*/
private List<ValidationProvider<?>> loadProviders(ClassLoader classLoader) {
@SuppressWarnings("rawtypes")
Iterator<ValidationProvider> providerIterator = ServiceLoader.load(ValidationProvider.class, classLoader).iterator();
LinkedList<ValidationProvider<?>> providers = new LinkedList<ValidationProvider<?>>();
while (providerIterator.hasNext()) {
try {
ValidationProvider<?> provider = providerIterator.next();
// put Hibernate Validator to the beginning of the list
if (provider.getClass().getName().equals("org.hibernate.validator.HibernateValidator")) {
providers.addFirst(provider);
} else {
providers.add(provider);
}
} catch (ServiceConfigurationError e) {
// ignore, because it can happen when multiple
// providers are present and some of them are not class loader
// compatible with our API.
}
}
return providers;
}
}
| 4,521 | 39.738739 | 136 |
java
|
null |
wildfly-main/bean-validation/src/main/java/org/jboss/as/ee/beanvalidation/BeanValidationFactoryResourceReferenceProcessor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ee.beanvalidation;
import jakarta.validation.ValidatorFactory;
import org.jboss.as.ee.component.InjectionSource;
import org.jboss.as.ee.component.deployers.EEResourceReferenceProcessor;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.naming.ValueManagedReferenceFactory;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.ServiceBuilder;
/**
* Handled resource injections for the Validator Factory
*
* @author Stuart Douglas
*/
public class BeanValidationFactoryResourceReferenceProcessor implements EEResourceReferenceProcessor {
public static final BeanValidationFactoryResourceReferenceProcessor INSTANCE = new BeanValidationFactoryResourceReferenceProcessor();
@Override
public String getResourceReferenceType() {
return ValidatorFactory.class.getName();
}
@Override
public InjectionSource getResourceReferenceBindingSource() throws DeploymentUnitProcessingException {
return ValidatorFactoryInjectionSource.INSTANCE;
}
private static final class ValidatorFactoryInjectionSource extends InjectionSource {
public static final ValidatorFactoryInjectionSource INSTANCE = new ValidatorFactoryInjectionSource();
@Override
public void getResourceValue(final ResolutionContext resolutionContext, final ServiceBuilder<?> serviceBuilder, final DeploymentPhaseContext phaseContext, final Injector<ManagedReferenceFactory> injector) throws DeploymentUnitProcessingException {
final ClassLoader classLoader = phaseContext.getDeploymentUnit().getAttachment(Attachments.MODULE).getClassLoader();
injector.inject(new ValueManagedReferenceFactory(new LazyValidatorFactory(classLoader)));
}
}
}
| 2,974 | 43.402985 | 255 |
java
|
null |
wildfly-main/bean-validation/src/main/java/org/wildfly/extension/beanvalidation/BeanValidationSubsystemAdd.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.beanvalidation;
import org.jboss.as.controller.AbstractBoottimeAddStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.ee.beanvalidation.BeanValidationDeploymentDependenciesProcessor;
import org.jboss.as.ee.beanvalidation.BeanValidationFactoryDeployer;
import org.jboss.as.ee.beanvalidation.BeanValidationResourceReferenceProcessorRegistryProcessor;
import org.jboss.as.server.AbstractDeploymentChainStep;
import org.jboss.as.server.DeploymentProcessorTarget;
import org.jboss.as.server.deployment.Phase;
import org.jboss.dmr.ModelNode;
import static org.wildfly.extension.beanvalidation.logging.BeanValidationLogger.ROOT_LOGGER;
/**
* Handler that adds the Jakarta Bean Validation subsystem.
*
* @author Eduardo Martins
*/
class BeanValidationSubsystemAdd extends AbstractBoottimeAddStepHandler {
static final BeanValidationSubsystemAdd INSTANCE = new BeanValidationSubsystemAdd();
private BeanValidationSubsystemAdd() {
}
@Override
protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
context.addStep(new AbstractDeploymentChainStep() {
protected void execute(DeploymentProcessorTarget processorTarget) {
ROOT_LOGGER.debug("Activating Jakarta Bean Validation subsystem");
processorTarget.addDeploymentProcessor(BeanValidationExtension.SUBSYSTEM_NAME, Phase.STRUCTURE, Phase.STRUCTURE_BEAN_VALIDATION_RESOURCE_INJECTION_REGISTRY, new BeanValidationResourceReferenceProcessorRegistryProcessor());
processorTarget.addDeploymentProcessor(BeanValidationExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_BEAN_VALIDATION, new BeanValidationDeploymentDependenciesProcessor());
processorTarget.addDeploymentProcessor(BeanValidationExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_VALIDATOR_FACTORY, new BeanValidationFactoryDeployer());
}
}, OperationContext.Stage.RUNTIME);
}
}
| 3,176 | 47.876923 | 238 |
java
|
null |
wildfly-main/bean-validation/src/main/java/org/wildfly/extension/beanvalidation/BeanValidationRootDefinition.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.beanvalidation;
import java.util.Collection;
import java.util.Collections;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PersistentResourceDefinition;
import org.jboss.as.controller.ReloadRequiredRemoveStepHandler;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.RuntimePackageDependency;
/**
* Defines the Jakarta Bean Validation subsystem root resource.
*
* @author Eduardo Martins
*/
class BeanValidationRootDefinition extends PersistentResourceDefinition {
private static final RuntimeCapability<Void> BEAN_VALIDATION_CAPABILITY =
RuntimeCapability.Builder.of("org.wildfly.bean-validation").build();
BeanValidationRootDefinition() {
super (new Parameters(BeanValidationExtension.SUBSYSTEM_PATH, BeanValidationExtension.SUBSYSTEM_RESOLVER)
.setAddHandler(BeanValidationSubsystemAdd.INSTANCE)
.setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE)
.setCapabilities(BEAN_VALIDATION_CAPABILITY)
);
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return Collections.emptySet();
}
@Override
public void registerAdditionalRuntimePackages(ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerAdditionalRuntimePackages(RuntimePackageDependency.passive("org.hibernate.validator"));
}
}
| 2,611 | 39.8125 | 124 |
java
|
null |
wildfly-main/bean-validation/src/main/java/org/wildfly/extension/beanvalidation/BeanValidationSubsystemSchema.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.beanvalidation;
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;
/**
* Enum representing the namespaces defined for the Jakarta Bean Validation subsystem.
*
* @author Eduardo Martins
*/
enum BeanValidationSubsystemSchema implements PersistentSubsystemSchema<BeanValidationSubsystemSchema> {
VERSION_1_0(1),
;
static final BeanValidationSubsystemSchema CURRENT = VERSION_1_0;
private final VersionedNamespace<IntVersion, BeanValidationSubsystemSchema> namespace;
BeanValidationSubsystemSchema(int major) {
this.namespace = SubsystemSchema.createLegacySubsystemURN(BeanValidationExtension.SUBSYSTEM_NAME, new IntVersion(major));
}
@Override
public VersionedNamespace<IntVersion, BeanValidationSubsystemSchema> getNamespace() {
return this.namespace;
}
@Override
public PersistentResourceXMLDescription getXMLDescription() {
return builder(BeanValidationExtension.SUBSYSTEM_PATH, this.namespace).build();
}
}
| 2,360 | 37.704918 | 129 |
java
|
null |
wildfly-main/bean-validation/src/main/java/org/wildfly/extension/beanvalidation/BeanValidationExtension.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.beanvalidation;
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;
/*
* This class implements the Jakarta Bean Validation extension.
*
* @author Eduardo Martins
*/
public class BeanValidationExtension implements Extension {
public static final String SUBSYSTEM_NAME = "bean-validation";
static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME);
static final ParentResourceDescriptionResolver SUBSYSTEM_RESOLVER = new SubsystemResourceDescriptionResolver(SUBSYSTEM_NAME, BeanValidationExtension.class);
private static final ModelVersion CURRENT_MODEL_VERSION = ModelVersion.create(1, 0, 0);
private final PersistentResourceXMLDescription currentDescription = BeanValidationSubsystemSchema.CURRENT.getXMLDescription();
@Override
public void initialize(final ExtensionContext context) {
final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION);
final ManagementResourceRegistration registration = subsystem.registerSubsystemModel(new BeanValidationRootDefinition());
registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE, false);
subsystem.registerXMLElementWriter(new PersistentResourceXMLDescriptionWriter(this.currentDescription));
}
@Override
public void initializeParsers(final ExtensionParsingContext context) {
for (BeanValidationSubsystemSchema schema : EnumSet.allOf(BeanValidationSubsystemSchema.class)) {
XMLElementReader<List<ModelNode>> reader = (schema == BeanValidationSubsystemSchema.CURRENT) ? new PersistentResourceXMLDescriptionReader(this.currentDescription) : schema;
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, schema.getNamespace().getUri(), reader);
}
}
}
| 3,920 | 48.632911 | 184 |
java
|
null |
wildfly-main/bean-validation/src/main/java/org/wildfly/extension/beanvalidation/logging/BeanValidationLogger.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.beanvalidation.logging;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.MessageLogger;
/**
* @author Eduardo Martins
*/
@MessageLogger(projectCode = "WFLYBV", length = 4)
public interface BeanValidationLogger extends BasicLogger {
BeanValidationLogger ROOT_LOGGER = Logger.getMessageLogger(BeanValidationLogger.class, "org.wildfly.extension.beanvalidation");
}
| 1,485 | 38.105263 | 131 |
java
|
null |
wildfly-main/mail/src/test/java/org/jboss/as/mail/extension/MailSubsystemTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
import static org.jboss.as.controller.capability.RuntimeCapability.buildDynamicCapabilityName;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ALLOW_RESOURCE_SERVICE_RESTART;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILED;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_HEADERS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
import javax.net.ssl.SSLContext;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.RunningMode;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.capability.registry.RuntimeCapabilityRegistry;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.extension.ExtensionRegistry;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.service.NamingStoreService;
import org.jboss.as.network.OutboundSocketBinding;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.jboss.as.subsystem.test.ControllerInitializer;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.dmr.ModelNode;
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;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.wildfly.security.credential.store.CredentialStore;
/**
* @author Tomaz Cerar (c) 2017 Red Hat Inc.
*/
@RunWith(Parameterized.class)
public class MailSubsystemTestCase extends AbstractSubsystemBaseTest {
// TODO Create formal enumeration of schema versions
@Parameters
public static Collection<Object[]> parameters() {
return List.of(
new Object[] { 1, 0 },
new Object[] { 1, 1 },
new Object[] { 1, 2 },
new Object[] { 2, 0 },
new Object[] { 3, 0 },
new Object[] { 4, 0 });
}
private final Map<ServiceName, Supplier<Object>> values = new ConcurrentHashMap<>();
private final int major;
private final int minor;
public MailSubsystemTestCase(int major, int minor) {
super(MailExtension.SUBSYSTEM_NAME, new MailExtension());
this.major = major;
this.minor = minor;
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource(String.format("subsystem_%d_%d.xml", this.major, this.minor));
}
@Override
protected String getSubsystemXsdPath() throws Exception {
return String.format("schema/%s-mail_%d_%d.xsd", (this.major == 1) ? "jboss-as" : "wildfly", this.major, this.minor);
}
@Override
protected KernelServices standardSubsystemTest(String configId, boolean compareXml) throws Exception {
return super.standardSubsystemTest(configId, false);
}
/**
* Tests that runtime information is the expected one based on the subsystem_4_0.xml subsystem configuration.
*
* @throws Exception
*/
@Test
public void testRuntime() throws Exception {
if (this.major >= 2) {
KernelServices services = createKernelServicesBuilder(new DefaultInitializer(this.values)).setSubsystemXml(getSubsystemXml()).build();
if (!services.isSuccessfulBoot()) {
Assert.fail(services.getBootError().toString());
}
SessionProvider provider = (SessionProvider) this.values.get(MailSessionDefinition.SESSION_CAPABILITY.getCapabilityServiceName("defaultMail").append("provider")).get();
Assert.assertNotNull("session should not be null", provider);
Session session = provider.getSession();
Properties properties = session.getProperties();
Assert.assertNotNull("smtp host should be set", properties.getProperty("mail.smtp.host"));
Assert.assertNotNull("pop3 host should be set", properties.getProperty("mail.pop3.host"));
Assert.assertNotNull("imap host should be set", properties.getProperty("mail.imap.host"));
if (this.major >= 3) {
PasswordAuthentication auth = session.requestPasswordAuthentication(InetAddress.getLocalHost(), 25, "smtp", "", "");
Assert.assertEquals("nobody", auth.getUserName());
Assert.assertEquals("pass", auth.getPassword());
}
provider = (SessionProvider) this.values.get(MailSessionDefinition.SESSION_CAPABILITY.getCapabilityServiceName("default2").append("provider")).get();
session = provider.getSession();
Assert.assertEquals("Debug should be true", true, session.getDebug());
provider = (SessionProvider) this.values.get(MailSessionDefinition.SESSION_CAPABILITY.getCapabilityServiceName("custom").append("provider")).get();
session = provider.getSession();
properties = session.getProperties();
String host = properties.getProperty("mail.smtp.host");
Assert.assertNotNull("smtp host should be set", host);
Assert.assertEquals("mail.example.com", host);
Assert.assertEquals("localhost", properties.get("mail.pop3.host")); //this one should be read out of socket binding
Assert.assertEquals("some-custom-prop-value", properties.get("mail.pop3.custom_prop")); //this one should be extra property
Assert.assertEquals("fully-qualified-prop-name", properties.get("some.fully.qualified.property")); //this one should be extra property
}
}
/**
* Tests that runtime information coming from attribute expressions is the expected one based on the subsystem_4_0.xml subsystem configuration.
*
* @throws Exception
*/
@Test
public void testExpressionsRuntime() throws Exception {
if (this.major >= 4) {
KernelServices services = createKernelServicesBuilder(new DefaultInitializer(this.values)).setSubsystemXml(getSubsystemXml()).build();
if (!services.isSuccessfulBoot()) {
Assert.fail(services.getBootError().toString());
}
ConfigurableSessionProvider provider = (ConfigurableSessionProvider) this.values.get(MailSessionDefinition.SESSION_CAPABILITY.getCapabilityServiceName("default3").append("provider")).get();
MailSessionConfig config = provider.getConfig();
Assert.assertEquals("Unexpected value for mail-session=default3 from attribute", "[email protected]", config.getFrom());
Assert.assertEquals("Unexpected value for mail-session=default3 jndi-name attribute", "java:jboss/mail/Default3", config.getJndiName());
Assert.assertEquals("Unexpected value for mail-session=default3 debug attribute", Boolean.TRUE, config.isDebug());
ServerConfig smtpServerConfig = config.getSmtpServer();
Assert.assertEquals("Unexpected value for mail-session=default3 smtp-server/tls attribute", Boolean.TRUE, smtpServerConfig.isTlsEnabled());
Assert.assertEquals("Unexpected value for mail-session=default3 smtp-server/ssl attribute", Boolean.FALSE, smtpServerConfig.isSslEnabled());
Credentials credentials = smtpServerConfig.getCredentials();
Assert.assertEquals("Unexpected value for mail-session=default3 smtp-server/username attribute", "nobody", credentials.getUsername());
Assert.assertEquals("Unexpected value for mail-session=default3 smtp-server/password attribute", "empty", credentials.getPassword());
provider = (ConfigurableSessionProvider) this.values.get(MailSessionDefinition.SESSION_CAPABILITY.getCapabilityServiceName("custom3").append("provider")).get();
config = provider.getConfig();
CustomServerConfig customServerConfig = config.getCustomServers()[0];
Map<String, String> properties = customServerConfig.getProperties();
Assert.assertEquals("Unexpected value for mail-session=custom3 custom-server/property value attribute", "mail.example.com", properties.get("host"));
}
}
@Test
public void testOperations() throws Exception {
if (this.major >= 2) {
KernelServices services = createKernelServicesBuilder(new DefaultInitializer(this.values)).setSubsystemXml(getSubsystemXml()).build();
if (!services.isSuccessfulBoot()) {
Assert.fail(services.getBootError().toString());
}
PathAddress sessionAddress = PathAddress.pathAddress(MailExtension.SUBSYSTEM_PATH, PathElement.pathElement(MailExtension.MAIL_SESSION_PATH.getKey(), "defaultMail"));
ModelNode result;
ModelNode removeServerOp = Util.createRemoveOperation(sessionAddress.append("server", "imap"));
removeServerOp.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true);
result = services.executeOperation(removeServerOp);
checkResult(result);
ModelNode addServerOp = Util.createAddOperation(sessionAddress.append("server", "imap"));
addServerOp.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true);
addServerOp.get("outbound-socket-binding-ref").set("mail-imap");
addServerOp.get("username").set("user");
addServerOp.get("password").set("pswd");
result = services.executeOperation(addServerOp);
checkResult(result);
checkResult(services.executeOperation(removeServerOp)); //to make sure noting is left behind
checkResult(services.executeOperation(addServerOp));
ModelNode writeOp = Util.createEmptyOperation(WRITE_ATTRIBUTE_OPERATION, sessionAddress);
writeOp.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true);
writeOp.get("name").set("debug");
writeOp.get("value").set(false);
result = services.executeOperation(writeOp);
checkResult(result);
SessionProvider provider = (SessionProvider) this.values.get(MailSessionDefinition.SESSION_CAPABILITY.getCapabilityServiceName("defaultMail").append("provider")).get();
Session session = provider.getSession();
Assert.assertNotNull("session should not be null", session);
Properties properties = session.getProperties();
Assert.assertNotNull("smtp host should be set", properties.getProperty("mail.smtp.host"));
Assert.assertNotNull("imap host should be set", properties.getProperty("mail.imap.host"));
PathAddress nonExisting = PathAddress.pathAddress(MailExtension.SUBSYSTEM_PATH, PathElement.pathElement(MailExtension.MAIL_SESSION_PATH.getKey(), "non-existing-session"));
ModelNode addSession = Util.createAddOperation(nonExisting);
addSession.get("jndi-name").set("java:/bah");
checkResult(services.executeOperation(addSession));
removeServerOp = Util.createRemoveOperation(nonExisting.append("server", "imap"));
removeServerOp.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true);
result = services.executeOperation(removeServerOp);
checkForFailure(result);
}
}
private static ModelNode checkForFailure(ModelNode rsp) {
if (!FAILED.equals(rsp.get(OUTCOME).asString())) {
Assert.fail("Should have failed!");
}
return rsp;
}
private static void checkResult(ModelNode result) {
Assert.assertEquals(result.get(ModelDescriptionConstants.FAILURE_DESCRIPTION).asString(), ModelDescriptionConstants.SUCCESS, result.get(ModelDescriptionConstants.OUTCOME).asString());
if (result.hasDefined(ModelDescriptionConstants.RESPONSE_HEADERS)) {
boolean reload = result.get(ModelDescriptionConstants.RESPONSE_HEADERS, ModelDescriptionConstants.OPERATION_REQUIRES_RELOAD).asBoolean(false);
Assert.assertFalse("Operation should not return requires reload", reload);
}
}
public static class DefaultInitializer extends AdditionalInitialization {
private final Map<String, Integer> sockets = new HashMap<>();
private final Map<ServiceName, Supplier<Object>> values;
public DefaultInitializer(Map<ServiceName, Supplier<Object>> values) {
this.values = values;
sockets.put("mail-imap", 432);
sockets.put("mail-pop3", 1234);
sockets.put("mail-smtp", 25);
}
private void record(ServiceTarget target, ServiceName name) {
ServiceBuilder<?> builder = target.addService(name.append("test-recorder"));
this.values.put(name, builder.requires(name));
builder.setInstance(Service.NULL).setInitialMode(ServiceController.Mode.ACTIVE).install();
}
@Override
protected void setupController(ControllerInitializer controllerInitializer) {
super.setupController(controllerInitializer);
for (Map.Entry<String, Integer> entry : sockets.entrySet()) {
controllerInitializer.addRemoteOutboundSocketBinding(entry.getKey(), "localhost", entry.getValue());
}
//bug in framework, it doesn't work if only outbound socket bindings are present
controllerInitializer.addSocketBinding("useless", 9999);
}
@Override
protected void addExtraServices(ServiceTarget target) {
target.addService(ContextNames.JAVA_CONTEXT_SERVICE_NAME, new NamingStoreService())
.setInitialMode(ServiceController.Mode.ACTIVE)
.install();
target.addService(ContextNames.JBOSS_CONTEXT_SERVICE_NAME, new NamingStoreService())
.setInitialMode(ServiceController.Mode.ACTIVE)
.install();
this.record(target, MailSessionDefinition.SESSION_CAPABILITY.getCapabilityServiceName("defaultMail").append("provider"));
this.record(target, MailSessionDefinition.SESSION_CAPABILITY.getCapabilityServiceName("default2").append("provider"));
this.record(target, MailSessionDefinition.SESSION_CAPABILITY.getCapabilityServiceName("custom").append("provider"));
this.record(target, MailSessionDefinition.SESSION_CAPABILITY.getCapabilityServiceName("default3").append("provider"));
this.record(target, MailSessionDefinition.SESSION_CAPABILITY.getCapabilityServiceName("custom3").append("provider"));
}
@Override
protected void initializeExtraSubystemsAndModel(ExtensionRegistry extensionRegistry, Resource rootResource,
ManagementResourceRegistration rootRegistration, RuntimeCapabilityRegistry capabilityRegistry) {
super.initializeExtraSubystemsAndModel(extensionRegistry, rootResource, rootRegistration, capabilityRegistry);
Map<String, Class> capabilities = new HashMap<>();
capabilities.put(buildDynamicCapabilityName("org.wildfly.security.credential-store", "my-credential-store"), CredentialStore.class);
capabilities.put(buildDynamicCapabilityName("org.wildfly.security.ssl-context", "foo"), SSLContext.class);
//capabilities.put(buildDynamicCapabilityName("org.wildfly.network.outbound-socket-binding","ajp-remote"), OutboundSocketBinding.class);
registerServiceCapabilities(capabilityRegistry, capabilities);
registerCapabilities(capabilityRegistry,
RuntimeCapability.Builder.of("org.wildfly.network.outbound-socket-binding", true, OutboundSocketBinding.class).build(),
RuntimeCapability.Builder.of("org.wildfly.security.ssl-context", true, SSLContext.class).build()
);
}
@Override
protected RunningMode getRunningMode() {
return RunningMode.NORMAL;
}
}
}
| 18,004 | 52.112094 | 201 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailSubsystemDefinition.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PersistentResourceDefinition;
import org.jboss.as.controller.ReloadRequiredRemoveStepHandler;
/**
* @author Tomaz Cerar
* @created 19.12.11 20:04
*/
class MailSubsystemDefinition extends PersistentResourceDefinition {
MailSubsystemDefinition() {
super(MailExtension.SUBSYSTEM_PATH,
MailExtension.getResourceDescriptionResolver(),
new MailSubsystemAdd(),
ReloadRequiredRemoveStepHandler.INSTANCE);
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return Collections.emptySet();
}
@Override
protected List<? extends PersistentResourceDefinition> getChildren() {
return List.of(new MailSessionDefinition());
}
}
| 1,968 | 34.160714 | 74 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailSessionAdd.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
import static org.jboss.as.controller.security.CredentialReference.KEY_DELIMITER;
import static org.jboss.as.controller.security.CredentialReference.rollbackCredentialStoreUpdate;
import static org.jboss.as.mail.extension.MailServerDefinition.OUTBOUND_SOCKET_BINDING_CAPABILITY_NAME;
import static org.jboss.as.mail.extension.MailSessionDefinition.ATTRIBUTES;
import static org.jboss.as.mail.extension.MailSessionDefinition.SESSION_CAPABILITY;
import static org.jboss.as.mail.extension.MailSubsystemModel.CUSTOM;
import static org.jboss.as.mail.extension.MailSubsystemModel.IMAP;
import static org.jboss.as.mail.extension.MailSubsystemModel.POP3;
import static org.jboss.as.mail.extension.MailSubsystemModel.SERVER_TYPE;
import static org.jboss.as.mail.extension.MailSubsystemModel.SMTP;
import static org.jboss.as.mail.extension.MailSubsystemModel.USER_NAME;
import java.util.Map;
import java.util.function.Supplier;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.CapabilityServiceBuilder;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.controller.registry.Resource.ResourceEntry;
import org.jboss.as.controller.security.CredentialReference;
import org.jboss.as.naming.ServiceBasedNamingStore;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.service.BinderService;
import org.jboss.as.network.OutboundSocketBinding;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.jboss.msc.Service;
import org.jboss.msc.service.LifecycleEvent;
import org.jboss.msc.service.LifecycleListener;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
/**
* Add operation handler for the session resource.
* @author Tomaz Cerar
* @author <a href="mailto:[email protected]">Richard Opalka</a>
* @created 27.7.11 0:55
*/
class MailSessionAdd extends AbstractAddStepHandler {
MailSessionAdd() {
super(ATTRIBUTES);
}
/**
* Make any runtime changes necessary to effect the changes indicated by the given {@code operation}. E
* <p>
* It constructs a MailSessionService that provides mail session and registers it to Naming service.
* </p>
*
* @param context the operation context
* @param operation the operation being executed
* @param model persistent configuration model node that corresponds to the address of {@code operation}
* @throws org.jboss.as.controller.OperationFailedException
* if {@code operation} is invalid or updating the runtime otherwise fails
*/
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
ModelNode fullModel = Resource.Tools.readModel(context.readResource(PathAddress.EMPTY_ADDRESS));
installRuntimeServices(context, fullModel);
}
@Override
protected void rollbackRuntime(OperationContext context, ModelNode operation, Resource resource) {
try {
MailSessionRemove.removeRuntimeServices(context, resource.getModel());
for (ResourceEntry entry : resource.getChildren(MailSubsystemModel.SERVER_TYPE)) {
ModelNode resolvedValue = MailServerDefinition.CREDENTIAL_REFERENCE.resolveModelAttribute(context, entry.getModel());
if (resolvedValue.isDefined()) {
rollbackCredentialStoreUpdate(MailServerDefinition.CREDENTIAL_REFERENCE, context, resolvedValue);
}
}
} catch (OperationFailedException e) {
throw new IllegalStateException(e);
}
}
private static void addCredentialStoreReference(ServerConfig serverConfig, OperationContext context, ModelNode model, ServiceBuilder<?> serviceBuilder, final PathElement credRefParentAddress) throws OperationFailedException {
if (serverConfig != null) {
final String servertype = credRefParentAddress.getKey();
final String serverprotocol = credRefParentAddress.getValue();
ModelNode filteredModelNode = model;
if (filteredModelNode.hasDefined(servertype, serverprotocol)) {
filteredModelNode = filteredModelNode.get(servertype, serverprotocol);
} else {
return;
}
String keySuffix = servertype + KEY_DELIMITER + serverprotocol;
ModelNode value = MailServerDefinition.CREDENTIAL_REFERENCE.resolveModelAttribute(context, filteredModelNode);
if (value.isDefined()) {
serverConfig.getCredentialSourceSupplierInjector()
.inject(CredentialReference.getCredentialSourceSupplier(context, MailServerDefinition.CREDENTIAL_REFERENCE, filteredModelNode, serviceBuilder, keySuffix));
}
}
}
static void installSessionProviderService(OperationContext context, ModelNode fullModel) throws OperationFailedException {
installSessionProviderService(context, context.getCurrentAddress(), fullModel);
}
static void installSessionProviderService(OperationContext context, PathAddress address, ModelNode fullModel) throws OperationFailedException {
ServiceName serviceName = SESSION_CAPABILITY.getCapabilityServiceName(address).append("provider");
ServiceBuilder<?> builder = context.getServiceTarget().addService(serviceName);
MailSessionConfig config = from(context, fullModel, builder);
addCredentialStoreReference(config.getImapServer(), context, fullModel, builder, MailSubsystemModel.IMAP_SERVER_PATH);
addCredentialStoreReference(config.getPop3Server(), context, fullModel, builder, MailSubsystemModel.POP3_SERVER_PATH);
addCredentialStoreReference(config.getSmtpServer(), context, fullModel, builder, MailSubsystemModel.SMTP_SERVER_PATH);
for (CustomServerConfig server : config.getCustomServers()) {
addCredentialStoreReference(server, context, fullModel, builder, PathElement.pathElement(MailSubsystemModel.CUSTOM_SERVER_PATH.getKey(), server.getProtocol()));
}
Service providerService = new ConfigurableSessionProviderService(builder.provides(serviceName), config);
builder.setInstance(providerService).setInitialMode(ServiceController.Mode.ON_DEMAND).install();
}
static void installBinderService(OperationContext context, ModelNode fullModel) throws OperationFailedException {
String jndiName = getJndiName(fullModel, context);
ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(jndiName);
String bindName = bindInfo.getBindName();
BinderService service = new BinderService(bindName);
ServiceBuilder<?> builder = context.getServiceTarget().addService(bindInfo.getBinderServiceName(), service).addAliases(ContextNames.JAVA_CONTEXT_SERVICE_NAME.append(bindName));
Supplier<SessionProvider> provider = builder.requires(SESSION_CAPABILITY.getCapabilityServiceName(context.getCurrentAddress()).append("provider"));
service.getManagedObjectInjector().inject(new MailSessionManagedReferenceFactory(provider));
builder.addDependency(bindInfo.getParentContextServiceName(), ServiceBasedNamingStore.class, service.getNamingStoreInjector());
builder.addListener(new LifecycleListener() {
private volatile boolean bound;
@Override
public void handleEvent(final ServiceController<?> controller, final LifecycleEvent event) {
switch (event) {
case UP: {
MailLogger.ROOT_LOGGER.boundMailSession(jndiName);
bound = true;
break;
}
case DOWN: {
if (bound) {
MailLogger.ROOT_LOGGER.unboundMailSession(jndiName);
}
break;
}
case REMOVED: {
MailLogger.ROOT_LOGGER.removedMailSession(jndiName);
break;
}
}
}
});
builder.setInitialMode(ServiceController.Mode.ACTIVE).install();
}
static void installRuntimeServices(OperationContext context, ModelNode fullModel) throws OperationFailedException {
installSessionProviderService(context, fullModel);
ServiceName sessionServiceName = SESSION_CAPABILITY.getCapabilityServiceName(context.getCurrentAddress());
ServiceName providerServiceName = sessionServiceName.append("provider");
// TODO Consider removing this service (and either changing or removing its corresponding capability) - it is never referenced.
CapabilityServiceBuilder<?> mailSessionBuilder = context.getCapabilityServiceTarget().addCapability(SESSION_CAPABILITY);
Service mailService = new MailSessionService(mailSessionBuilder.provides(sessionServiceName), mailSessionBuilder.requires(providerServiceName));
mailSessionBuilder.setInstance(mailService).setInitialMode(ServiceController.Mode.ON_DEMAND).install();
installBinderService(context, fullModel);
}
/**
* Extracts the raw JNDI_NAME value from the given model node, and depending on the value and
* the value of any USE_JAVA_CONTEXT child node, converts the raw name into a compliant jndi name.
*
* @param modelNode the model node; either an operation or the model behind a mail session resource
* @return the compliant jndi name
*/
static String getJndiName(final ModelNode modelNode, OperationContext context) throws OperationFailedException {
final String rawJndiName = MailSessionDefinition.JNDI_NAME.resolveModelAttribute(context, modelNode).asString();
return getJndiName(rawJndiName);
}
public static String getJndiName(final String rawJndiName) {
final String jndiName;
if (!rawJndiName.startsWith("java:")) {
jndiName = "java:jboss/mail/" + rawJndiName;
} else {
jndiName = rawJndiName;
}
return jndiName;
}
private static Supplier<OutboundSocketBinding> requireOutboundSocketBinding(OperationContext context, ServiceBuilder<?> builder, String ref) {
return (ref != null) ? builder.requires(context.getCapabilityServiceName(OUTBOUND_SOCKET_BINDING_CAPABILITY_NAME, OutboundSocketBinding.class, ref)) : null;
}
static MailSessionConfig from(final OperationContext operationContext, final ModelNode model, ServiceBuilder<?> builder) throws OperationFailedException {
MailSessionConfig cfg = new MailSessionConfig();
cfg.setJndiName(MailSessionDefinition.JNDI_NAME.resolveModelAttribute(operationContext, model).asString());
cfg.setDebug(MailSessionDefinition.DEBUG.resolveModelAttribute(operationContext, model).asBoolean());
if (MailSessionDefinition.FROM.resolveModelAttribute(operationContext, model).isDefined()) {
cfg.setFrom(MailSessionDefinition.FROM.resolveModelAttribute(operationContext, model).asString());
}
if (model.hasDefined(SERVER_TYPE)) {
ModelNode server = model.get(SERVER_TYPE);
if (server.hasDefined(SMTP)) {
cfg.setSmtpServer(readServerConfig(operationContext, server.get(SMTP), builder));
}
if (server.hasDefined(POP3)) {
cfg.setPop3Server(readServerConfig(operationContext, server.get(POP3), builder));
}
if (server.hasDefined(IMAP)) {
cfg.setImapServer(readServerConfig(operationContext, server.get(IMAP), builder));
}
}
if (model.hasDefined(CUSTOM)) {
for (Property server : model.get(CUSTOM).asPropertyList()) {
cfg.addCustomServer(readCustomServerConfig(server.getName(), operationContext, server.getValue(), builder));
}
}
return cfg;
}
private static ServerConfig readServerConfig(final OperationContext operationContext, final ModelNode model, ServiceBuilder<?> builder) throws OperationFailedException {
final String socket = MailServerDefinition.OUTBOUND_SOCKET_BINDING_REF.resolveModelAttribute(operationContext, model).asString();
final Credentials credentials = readCredentials(operationContext, model);
boolean ssl = MailServerDefinition.SSL.resolveModelAttribute(operationContext, model).asBoolean();
boolean tls = MailServerDefinition.TLS.resolveModelAttribute(operationContext, model).asBoolean();
return new ServerConfig(requireOutboundSocketBinding(operationContext, builder, socket), credentials, ssl, tls, null);
}
private static CustomServerConfig readCustomServerConfig(final String protocol, final OperationContext operationContext, final ModelNode model, ServiceBuilder<?> builder) throws OperationFailedException {
final String socket = MailServerDefinition.OUTBOUND_SOCKET_BINDING_REF_OPTIONAL.resolveModelAttribute(operationContext, model).asStringOrNull();
final Credentials credentials = readCredentials(operationContext, model);
boolean ssl = MailServerDefinition.SSL.resolveModelAttribute(operationContext, model).asBoolean();
boolean tls = MailServerDefinition.TLS.resolveModelAttribute(operationContext, model).asBoolean();
Map<String, String> properties = MailServerDefinition.PROPERTIES.unwrap(operationContext, model);
return new CustomServerConfig(protocol, requireOutboundSocketBinding(operationContext, builder, socket), credentials, ssl, tls, properties);
}
private static Credentials readCredentials(final OperationContext operationContext, final ModelNode model) throws OperationFailedException {
if (model.get(USER_NAME).isDefined()) {
String un = MailServerDefinition.USERNAME.resolveModelAttribute(operationContext, model).asString();
String pw = MailServerDefinition.PASSWORD.resolveModelAttribute(operationContext, model).asStringOrNull();
ModelNode value = MailServerDefinition.CREDENTIAL_REFERENCE.resolveValue(operationContext, model);
String secret = null;
if (value.isDefined()) {
secret = CredentialReference.credentialReferencePartAsStringIfDefined(value, CredentialReference.CLEAR_TEXT);
}
if (secret != null) {
return new Credentials(un, secret);
} else {
return new Credentials(un, pw);
}
}
return null;
}
}
| 15,986 | 54.127586 | 229 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailDependenciesProcessor.java
|
package org.jboss.as.mail.extension;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.module.ModuleDependency;
import org.jboss.as.server.deployment.module.ModuleSpecification;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleLoader;
import org.jboss.modules.filter.PathFilters;
/**
* @author Stuart Douglas
*/
public class MailDependenciesProcessor implements DeploymentUnitProcessor {
private static final String MAIL_API = "jakarta.mail.api";
private static final String ACTIVATION_API = "jakarta.activation.api";
private static final String ANGUS_MAIL_IMPL = "org.eclipse.angus.mail";
private static final String ANGUS_ACTIVATION_IMPL = "org.eclipse.angus.activation";
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit unit = phaseContext.getDeploymentUnit();
final ModuleLoader moduleLoader = Module.getBootModuleLoader();
final ModuleSpecification moduleSpec = unit.getAttachment(Attachments.MODULE_SPECIFICATION);
moduleSpec.addSystemDependency(new ModuleDependency(moduleLoader, MAIL_API, false, false, true, false));
moduleSpec.addSystemDependency(new ModuleDependency(moduleLoader, ACTIVATION_API, false, false, true, false));
ModuleDependency angusMailModDep = new ModuleDependency(moduleLoader, ANGUS_MAIL_IMPL, false, false, true, false);
angusMailModDep.addImportFilter(PathFilters.getMetaInfFilter(), true);
moduleSpec.addSystemDependency(angusMailModDep);
moduleSpec.addSystemDependency(new ModuleDependency(moduleLoader, ANGUS_ACTIVATION_IMPL, false, false, true, false));
}
}
| 1,988 | 51.342105 | 125 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailSubsystemAdd.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
import org.jboss.as.controller.AbstractBoottimeAddStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.server.AbstractDeploymentChainStep;
import org.jboss.as.server.DeploymentProcessorTarget;
import org.jboss.as.server.deployment.Phase;
import org.jboss.dmr.ModelNode;
/**
* Handler responsible for adding the mail subsystem resource to the model
*
* @author <a href="[email protected]">Tomaz Cerar</a>
*/
class MailSubsystemAdd extends AbstractBoottimeAddStepHandler {
@Override
protected void populateModel(ModelNode operation, ModelNode model) throws OperationFailedException {
model.setEmptyObject();
}
@Override
protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
context.addStep(new AbstractDeploymentChainStep() {
@Override
protected void execute(DeploymentProcessorTarget processorTarget) {
processorTarget.addDeploymentProcessor(MailExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_RESOURCE_DEF_ANNOTATION_MAIL_SESSION, new MailSessionDefinitionAnnotationProcessor());
processorTarget.addDeploymentProcessor(MailExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_MAIL, new MailDependenciesProcessor());
processorTarget.addDeploymentProcessor(MailExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_RESOURCE_DEF_XML_MAIL_SESSION, new MailSessionDefinitionDescriptorProcessor());
}
}, OperationContext.Stage.RUNTIME);
}
}
| 2,725 | 46.824561 | 201 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailSessionManagedReferenceFactory.java
|
/*
*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
* /
*/
package org.jboss.as.mail.extension;
import java.util.function.Supplier;
import org.jboss.as.naming.ContextListAndJndiViewManagedReferenceFactory;
import org.jboss.as.naming.ContextListManagedReferenceFactory;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ValueManagedReference;
/**
* @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc.
*/
class MailSessionManagedReferenceFactory implements ContextListAndJndiViewManagedReferenceFactory {
private final Supplier<SessionProvider> provider;
public MailSessionManagedReferenceFactory(Supplier<SessionProvider> provider) {
this.provider = provider;
}
@Override
public String getJndiViewInstanceValue() {
return String.valueOf(getReference().getInstance());
}
@Override
public String getInstanceClassName() {
final Object value = getReference().getInstance();
return value != null ? value.getClass().getName() : ContextListManagedReferenceFactory.DEFAULT_INSTANCE_CLASS_NAME;
}
@Override
public ManagedReference getReference() {
return new ValueManagedReference(this.provider.get().getSession());
}
}
| 2,251 | 35.918033 | 123 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/ConfigurableSessionProviderService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
import java.util.function.Consumer;
import org.jboss.msc.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* Service that provides a {@link SessionProvider} and its {@link MailSessionConfig} (for use by tests).
* @author Paul Ferraro
*/
class ConfigurableSessionProviderService implements Service {
private final Consumer<ConfigurableSessionProvider> provider;
private final MailSessionConfig config;
ConfigurableSessionProviderService(Consumer<ConfigurableSessionProvider> provider, MailSessionConfig config) {
this.provider = provider;
this.config = config;
}
@Override
public void start(final StartContext startContext) throws StartException {
this.provider.accept(SessionProviderFactory.create(this.config));
}
@Override
public void stop(final StopContext stopContext) {
// Nothing to stop
}
}
| 2,033 | 35.981818 | 114 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailLogger.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
import static org.jboss.logging.Logger.Level.DEBUG;
import static org.jboss.logging.Logger.Level.INFO;
import static org.jboss.logging.Logger.Level.WARN;
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;
import org.jboss.msc.service.StartException;
/**
* Date: 05.11.2011
*
* @author <a href="mailto:[email protected]">James R. Perkins</a>
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
@MessageLogger(projectCode = "WFLYMAIL", length = 4)
interface MailLogger extends BasicLogger {
/**
* A logger with a category of the package name.
*/
MailLogger ROOT_LOGGER = Logger.getMessageLogger(MailLogger.class, "org.jboss.as.mail.extension");
/**
* Logs an info message indicating a jakarta.mail.Session was bound into JNDI.
*
* @param jndiName the JNDI name under which the session was bound.
*/
@LogMessage(level = INFO)
@Message(id = 1, value = "Bound mail session [%s]")
void boundMailSession(String jndiName);
/**
* Logs an info message indicating a jakarta.mail.Session was unbound from JNDI.
*
* @param jndiName the JNDI name under which the session was bound.
*/
@LogMessage(level = INFO)
@Message(id = 2, value = "Unbound mail session [%s]")
void unboundMailSession(String jndiName);
/**
* Logs a debug message indicating a jakarta.mail.Session was removed.
*
* @param jndiName the JNDI name under which the session had been bound.
*/
@LogMessage(level = DEBUG)
@Message(id = 3, value = "Removed mail session [%s]")
void removedMailSession(String jndiName);
/**
* Creates an exception indicating the outgoing socket binding, represented by the {@code outgoingSocketBindingRef}
* parameter, could not be found.
*
* @param outgoingSocketBindingRef the name of the socket binding configuration.
* @return a {@link StartException} for the error.
*/
@Message(id = 4, value = "No outbound socket binding configuration '%s' is available.")
StartException outboundSocketBindingNotAvailable(String outgoingSocketBindingRef);
/**
* Logs an error message indicating that the configured host name could not be resolved.
*
* @param hostName the name of the host which coud not be resolved.
*/
@LogMessage(level = WARN)
@Message(id = 9, value = "Host name [%s] could not be resolved!")
void hostUnknown(String hostName);
}
| 3,686 | 37.40625 | 119 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailServerDefinition.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.AttributeMarshaller;
import org.jboss.as.controller.AttributeParser;
import org.jboss.as.controller.ObjectTypeAttributeDefinition;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.PersistentResourceDefinition;
import org.jboss.as.controller.PropertiesAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.access.constraint.SensitivityClassification;
import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition;
import org.jboss.as.controller.capability.DynamicNameMappers;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.OperationEntry.Flag;
import org.jboss.as.controller.security.CredentialReference;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
/**
* @author Tomaz Cerar
* @since 7.1.0
*/
class MailServerDefinition extends PersistentResourceDefinition {
static final String OUTBOUND_SOCKET_BINDING_CAPABILITY_NAME = "org.wildfly.network.outbound-socket-binding";
static final String CREDENTIAL_STORE_CAPABILITY = "org.wildfly.security.credential-store";
static final RuntimeCapability<Void> SERVER_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.mail.session.server", true)
.setDynamicNameMapper(DynamicNameMappers.PARENT)
.build();
static final SensitivityClassification MAIL_SERVER_SECURITY =
new SensitivityClassification(MailExtension.SUBSYSTEM_NAME, "mail-server-security", false, false, true);
static final SensitiveTargetAccessConstraintDefinition MAIL_SERVER_SECURITY_DEF = new SensitiveTargetAccessConstraintDefinition(MAIL_SERVER_SECURITY);
static final SimpleAttributeDefinition OUTBOUND_SOCKET_BINDING_REF =
new SimpleAttributeDefinitionBuilder(MailSubsystemModel.OUTBOUND_SOCKET_BINDING_REF, ModelType.STRING, false)
.setAllowExpression(true)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.addAccessConstraint(SensitiveTargetAccessConstraintDefinition.SOCKET_BINDING_REF)
.build();
static final SimpleAttributeDefinition OUTBOUND_SOCKET_BINDING_REF_OPTIONAL = SimpleAttributeDefinitionBuilder.create(OUTBOUND_SOCKET_BINDING_REF)
.setCapabilityReference(OUTBOUND_SOCKET_BINDING_CAPABILITY_NAME)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.setRequired(false)
.build();
protected static final SimpleAttributeDefinition SSL =
new SimpleAttributeDefinitionBuilder(MailSubsystemModel.SSL, ModelType.BOOLEAN, true)
.setAllowExpression(true)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.setDefaultValue(ModelNode.FALSE)
.addAccessConstraint(MAIL_SERVER_SECURITY_DEF)
.build();
protected static final SimpleAttributeDefinition TLS =
new SimpleAttributeDefinitionBuilder(MailSubsystemModel.TLS, ModelType.BOOLEAN, true)
.setAllowExpression(true)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.setDefaultValue(ModelNode.FALSE)
.addAccessConstraint(MAIL_SERVER_SECURITY_DEF)
.build();
protected static final SimpleAttributeDefinition USERNAME =
new SimpleAttributeDefinitionBuilder(MailSubsystemModel.USER_NAME, ModelType.STRING, true)
.setAllowExpression(true)
.setXmlName("username")
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.addAccessConstraint(SensitiveTargetAccessConstraintDefinition.CREDENTIAL)
.addAccessConstraint(MAIL_SERVER_SECURITY_DEF)
.build();
static final ObjectTypeAttributeDefinition CREDENTIAL_REFERENCE =
CredentialReference.getAttributeBuilder(true, false)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.addAccessConstraint(SensitiveTargetAccessConstraintDefinition.CREDENTIAL)
.addAccessConstraint(MAIL_SERVER_SECURITY_DEF)
.addAlternatives(MailSubsystemModel.PASSWORD)
.setCapabilityReference(CREDENTIAL_STORE_CAPABILITY)
.build();
protected static final SimpleAttributeDefinition PASSWORD =
new SimpleAttributeDefinitionBuilder(MailSubsystemModel.PASSWORD, ModelType.STRING, true)
.setAllowExpression(true)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.addAccessConstraint(SensitiveTargetAccessConstraintDefinition.CREDENTIAL)
.addAccessConstraint(MAIL_SERVER_SECURITY_DEF)
.setAlternatives(CredentialReference.CREDENTIAL_REFERENCE)
.build();
static final PropertiesAttributeDefinition PROPERTIES = new PropertiesAttributeDefinition.Builder(ModelDescriptionConstants.PROPERTIES, true)
.setAttributeMarshaller(AttributeMarshaller.PROPERTIES_MARSHALLER_UNWRAPPED)
.setAttributeParser(AttributeParser.PROPERTIES_PARSER_UNWRAPPED)
.setAllowExpression(true)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.build();
static final AttributeDefinition[] ATTRIBUTES = {OUTBOUND_SOCKET_BINDING_REF, SSL, TLS, USERNAME, PASSWORD, CREDENTIAL_REFERENCE};
static final AttributeDefinition[] ATTRIBUTES_CUSTOM = {OUTBOUND_SOCKET_BINDING_REF_OPTIONAL, SSL, TLS, USERNAME, PASSWORD, CREDENTIAL_REFERENCE, PROPERTIES};
private final List<AttributeDefinition> attributes;
MailServerDefinition(final PathElement path, AttributeDefinition[] attributes) {
super(new SimpleResourceDefinition.Parameters(path,
MailExtension.getResourceDescriptionResolver(MailSubsystemModel.MAIL_SESSION, MailSubsystemModel.SERVER_TYPE))
.setAddHandler(new MailServerAdd(attributes))
.setAddRestartLevel(Flag.RESTART_RESOURCE_SERVICES)
.setRemoveHandler(new MailServerRemove())
.setRemoveRestartLevel(Flag.RESTART_RESOURCE_SERVICES)
.setCapabilities(SERVER_CAPABILITY)
);
this.attributes = Arrays.asList(attributes);
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return attributes;
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
MailServerWriteAttributeHandler handler = new MailServerWriteAttributeHandler(this.attributes);
for (AttributeDefinition attr : getAttributes()) {
resourceRegistration.registerReadWriteAttribute(attr, null, handler);
}
}
}
| 8,504 | 50.545455 | 162 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/Credentials.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
/**
* @author Tomaz Cerar
* @created 22.8.11 11:50
*/
class Credentials {
private final String username;
private final String password;
public Credentials(String username, String password) {
this.password = password;
this.username = username;
}
public String getPassword() {
return password;
}
public String getUsername() {
return username;
}
}
| 1,477 | 31.130435 | 70 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/ConfigurableSessionProvider.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
/**
* A {@link SessionProvider that additionally exposes its configuration.
* This is used only for test verification.
* @author Paul Ferraro
*/
interface ConfigurableSessionProvider extends SessionProvider {
MailSessionConfig getConfig();
}
| 1,312 | 38.787879 | 72 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailSessionDefinitionInjectionSource.java
|
/*
*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
* /
*/
package org.jboss.as.mail.extension;
import java.util.function.Supplier;
import org.jboss.as.ee.component.Attachments;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.ee.resource.definition.ResourceDefinitionInjectionSource;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.naming.ServiceBasedNamingStore;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.service.BinderService;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.LifecycleEvent;
import org.jboss.msc.service.LifecycleListener;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceTarget;
/**
* A binding description for {@link MailSessionDefinition} annotations.
* <p/>
* The referenced mail session must be directly visible to the
* component declaring the annotation.
*
* @author Tomaz Cerar
* @author Eduardo Martins
*/
class MailSessionDefinitionInjectionSource extends ResourceDefinitionInjectionSource implements Supplier<SessionProvider> {
private final SessionProvider provider;
public MailSessionDefinitionInjectionSource(final String jndiName, final SessionProvider provider) {
super(jndiName);
this.provider = provider;
}
@Override
public SessionProvider get() {
return this.provider;
}
@Override
public void getResourceValue(final ResolutionContext context, final ServiceBuilder<?> serviceBuilder, final DeploymentPhaseContext phaseContext, final Injector<ManagedReferenceFactory> injector) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION);
try {
startMailSession(jndiName, eeModuleDescription, context, phaseContext.getServiceTarget(), serviceBuilder, injector);
} catch (Exception e) {
throw new DeploymentUnitProcessingException(e);
}
}
private void startMailSession(final String jndiName,
final EEModuleDescription moduleDescription,
final ResolutionContext context,
final ServiceTarget serviceTarget,
final ServiceBuilder<?> valueSourceServiceBuilder, final Injector<ManagedReferenceFactory> injector) {
final ContextNames.BindInfo bindInfo = ContextNames.bindInfoForEnvEntry(context.getApplicationName(), context.getModuleName(), context.getComponentName(), !context.isCompUsesModule(), jndiName);
final BinderService binderService = new BinderService(bindInfo.getBindName(), this);
ServiceBuilder<ManagedReferenceFactory> binderBuilder = serviceTarget.addService(bindInfo.getBinderServiceName(), binderService);
binderService.getManagedObjectInjector().inject(new MailSessionManagedReferenceFactory(this));
binderBuilder.addDependency(bindInfo.getParentContextServiceName(), ServiceBasedNamingStore.class, binderService.getNamingStoreInjector()).addListener(new LifecycleListener() {
private volatile boolean bound;
@Override
public void handleEvent(final ServiceController<?> controller, final LifecycleEvent event) {
switch (event) {
case UP: {
MailLogger.ROOT_LOGGER.boundMailSession(jndiName);
bound = true;
break;
}
case DOWN: {
if (bound) {
MailLogger.ROOT_LOGGER.unboundMailSession(jndiName);
}
break;
}
case REMOVED: {
MailLogger.ROOT_LOGGER.debugf("Removed Mail Session [%s]", jndiName);
break;
}
}
}
});
binderBuilder.setInitialMode(ServiceController.Mode.ACTIVE).install();
valueSourceServiceBuilder.addDependency(bindInfo.getBinderServiceName(), ManagedReferenceFactory.class, injector);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
MailSessionDefinitionInjectionSource that = (MailSessionDefinitionInjectionSource) o;
if (provider != null ? !provider.equals(that.provider) : that.provider != null) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (provider != null ? provider.hashCode() : 0);
return result;
}
}
| 6,339 | 43.647887 | 241 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailServerAdd.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
import static org.jboss.as.controller.security.CredentialReference.handleCredentialReferenceUpdate;
import static org.jboss.as.controller.security.CredentialReference.rollbackCredentialStoreUpdate;
import java.util.List;
import java.util.Set;
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.RestartParentResourceAddHandler;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.controller.security.CredentialReference;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
/**
* @author Tomaz Cerar
* @created 8.12.11 0:19
*/
class MailServerAdd extends RestartParentResourceAddHandler {
MailServerAdd(AttributeDefinition[] attributes) {
super(MailSubsystemModel.MAIL_SESSION, Set.of(), List.of(attributes));
}
@Override
protected void updateModel(OperationContext context, ModelNode operation) throws OperationFailedException {
final Resource resource = context.createResource(PathAddress.EMPTY_ADDRESS);
populateModel(operation, resource.getModel());
handleCredentialReferenceUpdate(context, resource.getModel());
recordCapabilitiesAndRequirements(context, operation, resource);
}
@Override
protected boolean isResourceServiceRestartAllowed(OperationContext context, ServiceController<?> service) {
// Perform runtime operations here, as distinct from rollbackRuntime(...)
ModelNode model = context.readResource(PathAddress.EMPTY_ADDRESS).getModel();
try {
ModelNode resolvedValue = MailServerDefinition.CREDENTIAL_REFERENCE.resolveModelAttribute(context, model);
if (resolvedValue.isDefined()) {
// This call will force the creation of the new alias in the credential-store if it is needed
CredentialReference.getCredentialSourceSupplier(context, MailServerDefinition.CREDENTIAL_REFERENCE, model, null);
}
} catch (OperationFailedException e) {
throw new IllegalStateException(e);
}
return super.isResourceServiceRestartAllowed(context, service);
}
@Override
protected void rollbackRuntime(OperationContext context, final ModelNode operation, final Resource resource) {
rollbackCredentialStoreUpdate(MailServerDefinition.CREDENTIAL_REFERENCE, context, resource);
}
@Override
protected void recreateParentService(OperationContext context, PathAddress parentAddress, ModelNode parentModel) throws OperationFailedException {
MailSessionAdd.installSessionProviderService(context, parentAddress, parentModel);
}
@Override
protected ServiceName getParentServiceName(PathAddress parentAddress) {
return MailSessionDefinition.SESSION_CAPABILITY.getCapabilityServiceName(parentAddress).append("provider");
}
}
| 4,107 | 44.142857 | 150 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/SessionProvider.java
|
/*
*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
* /
*/
package org.jboss.as.mail.extension;
import jakarta.mail.Session;
/**
* @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc.
*/
public interface SessionProvider {
Session getSession();
}
| 1,276 | 35.485714 | 88 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailSessionConfig.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
import java.util.Arrays;
/**
* @author <a href="[email protected]">Tomaz Cerar</a>
* @created 25.7.11 15:48
*/
public class MailSessionConfig {
private String jndiName;
private boolean debug = false;
private String from = null;
private ServerConfig smtpServer;
private ServerConfig pop3Server;
private ServerConfig imapServer;
private CustomServerConfig[] customServers = new CustomServerConfig[0];
MailSessionConfig() {
}
MailSessionConfig(String jndiName) {
this.jndiName = jndiName;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getJndiName() {
return jndiName;
}
public void setJndiName(String jndiName) {
this.jndiName = jndiName;
}
public boolean isDebug() {
return debug;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public ServerConfig getImapServer() {
return imapServer;
}
public void setImapServer(ServerConfig imapServer) {
this.imapServer = imapServer;
}
public ServerConfig getPop3Server() {
return pop3Server;
}
public void setPop3Server(ServerConfig pop3Server) {
this.pop3Server = pop3Server;
}
public ServerConfig getSmtpServer() {
return smtpServer;
}
public void setSmtpServer(ServerConfig smtpServer) {
this.smtpServer = smtpServer;
}
public CustomServerConfig[] getCustomServers() {
return customServers;
}
public void setCustomServers(CustomServerConfig... customServer) {
this.customServers = customServer;
}
public void addCustomServer(CustomServerConfig customServer) {
final int i = customServers.length;
customServers = Arrays.copyOf(customServers, i + 1);
customServers[i] = customServer;
}
@Override
public String toString() {
return "MailSessionConfig{" +
"imapServer=" + imapServer +
", jndiName='" + jndiName + '\'' +
", smtpServer=" + smtpServer +
", pop3Server=" + pop3Server +
'}';
}
}
| 3,303 | 26.305785 | 75 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailSessionDefinitionAnnotationProcessor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
import org.jboss.as.ee.resource.definition.ResourceDefinitionAnnotationProcessor;
import org.jboss.as.ee.resource.definition.ResourceDefinitionInjectionSource;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.DotName;
import org.jboss.metadata.javaee.spec.MailSessionMetaData;
import org.jboss.metadata.javaee.spec.PropertiesMetaData;
import org.jboss.metadata.javaee.spec.PropertyMetaData;
import org.jboss.metadata.property.PropertyReplacer;
import jakarta.mail.MailSessionDefinition;
import jakarta.mail.MailSessionDefinitions;
/**
* Deployment processor responsible for processing {@link MailSessionDefinition} and {@link MailSessionDefinitions}.
*
* @author Tomaz Cerar
* @author Eduardo Martins
*/
public class MailSessionDefinitionAnnotationProcessor extends ResourceDefinitionAnnotationProcessor {
private static final DotName MAIL_SESSION_DEFINITION = DotName.createSimple(MailSessionDefinition.class.getName());
private static final DotName MAIL_SESSION_DEFINITIONS = DotName.createSimple(MailSessionDefinitions.class.getName());
@Override
protected DotName getAnnotationDotName() {
return MAIL_SESSION_DEFINITION;
}
@Override
protected DotName getAnnotationCollectionDotName() {
return MAIL_SESSION_DEFINITIONS;
}
@Override
protected ResourceDefinitionInjectionSource processAnnotation(AnnotationInstance annotationInstance, PropertyReplacer propertyReplacer) throws DeploymentUnitProcessingException {
final MailSessionMetaData metaData = new MailSessionMetaData();
metaData.setName(AnnotationElement.asRequiredString(annotationInstance, AnnotationElement.NAME));
metaData.setTransportProtocol(AnnotationElement.asOptionalString(annotationInstance, "transportProtocol"));
metaData.setStoreProtocol(AnnotationElement.asOptionalString(annotationInstance, "storeProtocol"));
metaData.setHost(AnnotationElement.asOptionalString(annotationInstance, "host"));
metaData.setUser(AnnotationElement.asOptionalString(annotationInstance, "user"));
metaData.setPassword(AnnotationElement.asOptionalString(annotationInstance, "password"));
metaData.setFrom(AnnotationElement.asOptionalString(annotationInstance, "from"));
final PropertiesMetaData properties = new PropertiesMetaData();
for (String fullProp : AnnotationElement.asOptionalStringArray(annotationInstance, AnnotationElement.PROPERTIES)) {
PropertyMetaData p = new PropertyMetaData();
String[] prop = fullProp.split("=", 2);
p.setName(prop[0]);
p.setValue(prop[1]);
properties.add(p);
}
metaData.setProperties(properties);
final SessionProvider provider = SessionProviderFactory.create(metaData);
return new MailSessionDefinitionInjectionSource(metaData.getName(), provider);
}
}
| 4,038 | 47.662651 | 182 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailSubsystemParser.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.parsing.ParseUtils.requireAttributes;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
import static org.jboss.as.mail.extension.MailServerDefinition.OUTBOUND_SOCKET_BINDING_REF;
import static org.jboss.as.mail.extension.MailServerDefinition.OUTBOUND_SOCKET_BINDING_REF_OPTIONAL;
import static org.jboss.as.mail.extension.MailServerDefinition.PASSWORD;
import static org.jboss.as.mail.extension.MailServerDefinition.SSL;
import static org.jboss.as.mail.extension.MailServerDefinition.TLS;
import static org.jboss.as.mail.extension.MailSessionDefinition.DEBUG;
import static org.jboss.as.mail.extension.MailSessionDefinition.FROM;
import static org.jboss.as.mail.extension.MailSessionDefinition.JNDI_NAME;
import static org.jboss.as.mail.extension.MailSubsystemModel.IMAP;
import static org.jboss.as.mail.extension.MailSubsystemModel.LOGIN;
import static org.jboss.as.mail.extension.MailSubsystemModel.MAIL_SESSION;
import static org.jboss.as.mail.extension.MailSubsystemModel.NAME;
import static org.jboss.as.mail.extension.MailSubsystemModel.POP3;
import static org.jboss.as.mail.extension.MailSubsystemModel.PROPERTY;
import static org.jboss.as.mail.extension.MailSubsystemModel.SMTP;
import java.util.Collections;
import java.util.List;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.parsing.ParseUtils;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* The 1.x subsystem parser / writer
*
* @author <a href="[email protected]">Tomaz Cerar</a>
*/
class MailSubsystemParser implements XMLStreamConstants, XMLElementReader<List<ModelNode>> {
MailSubsystemParser() {
}
/**
* {@inheritDoc}
*/
public void readElement(XMLExtendedStreamReader reader, List<ModelNode> list) throws XMLStreamException {
final PathAddress address = PathAddress.pathAddress(MailExtension.SUBSYSTEM_PATH);
list.add(Util.createAddOperation(address));
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
switch (Namespace.forUri(reader.getNamespaceURI())) {
case MAIL_1_0:
case MAIL_1_1:
case MAIL_1_2: {
final String element = reader.getLocalName();
switch (element) {
case MAIL_SESSION: {
parseMailSession(reader, list, address);
break;
}
default: {
reader.handleAny(list);
break;
}
}
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private void parseMailSession(final XMLExtendedStreamReader reader, List<ModelNode> list, final PathAddress parent) throws XMLStreamException {
String jndiName = null;
final ModelNode operation = new ModelNode();
for (int i = 0; i < reader.getAttributeCount(); i++) {
String attr = reader.getAttributeLocalName(i);
String value = reader.getAttributeValue(i);
switch (attr) {
case MailSubsystemModel.JNDI_NAME:
jndiName = value;
JNDI_NAME.parseAndSetParameter(value, operation, reader);
break;
case MailSubsystemModel.DEBUG:
DEBUG.parseAndSetParameter(value, operation, reader);
break;
case MailSubsystemModel.FROM:
FROM.parseAndSetParameter(value, operation, reader);
break;
}
}
if (jndiName == null) {
throw ParseUtils.missingRequired(reader, Collections.singleton(JNDI_NAME));
}
final PathAddress address = parent.append(MAIL_SESSION, jndiName);
operation.get(OP_ADDR).set(address.toModelNode());
operation.get(OP).set(ADD);
list.add(operation);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
switch (Namespace.forUri(reader.getNamespaceURI())) {
case MAIL_1_0:
case MAIL_1_1:
case MAIL_1_2: {
final String element = reader.getLocalName();
switch (element) {
case MailSubsystemModel.SMTP_SERVER: {
parseServerConfig(reader, SMTP, address, list);
break;
}
case MailSubsystemModel.POP3_SERVER: {
parseServerConfig(reader, POP3, address, list);
break;
}
case MailSubsystemModel.IMAP_SERVER: {
parseServerConfig(reader, IMAP, address, list);
break;
}
case MailSubsystemModel.CUSTOM_SERVER: {
parseCustomServerConfig(reader, address, list);
break;
}
default: {
reader.handleAny(list);
break;
}
}
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private void parseServerConfig(final XMLExtendedStreamReader reader, final String name, final PathAddress parent, List<ModelNode> list) throws XMLStreamException {
PathAddress address = parent.append(MailSubsystemModel.SERVER_TYPE, name);
final ModelNode operation = Util.createAddOperation(address);
list.add(operation);
String socketBindingRef = null;
for (int i = 0; i < reader.getAttributeCount(); i++) {
String attr = reader.getAttributeLocalName(i);
String value = reader.getAttributeValue(i);
switch (attr) {
case MailSubsystemModel.OUTBOUND_SOCKET_BINDING_REF:
socketBindingRef = value;
OUTBOUND_SOCKET_BINDING_REF.parseAndSetParameter(value, operation, reader);
break;
case MailSubsystemModel.SSL:
SSL.parseAndSetParameter(value, operation, reader);
break;
case MailSubsystemModel.TLS:
TLS.parseAndSetParameter(value, operation, reader);
break;
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
if (socketBindingRef == null) {
throw ParseUtils.missingRequired(reader, Collections.singleton(OUTBOUND_SOCKET_BINDING_REF));
}
parseLogin(reader, operation);
}
private void parseCustomServerConfig(final XMLExtendedStreamReader reader, final PathAddress parent, List<ModelNode> list) throws XMLStreamException {
final ModelNode operation = Util.createAddOperation(parent);
list.add(operation);
String name = null;
for (int i = 0; i < reader.getAttributeCount(); i++) {
String attr = reader.getAttributeLocalName(i);
String value = reader.getAttributeValue(i);
switch (attr) {
case MailSubsystemModel.OUTBOUND_SOCKET_BINDING_REF:
OUTBOUND_SOCKET_BINDING_REF_OPTIONAL.parseAndSetParameter(value, operation, reader);
break;
case MailSubsystemModel.SSL:
SSL.parseAndSetParameter(value, operation, reader);
break;
case MailSubsystemModel.TLS:
TLS.parseAndSetParameter(value, operation, reader);
break;
case MailSubsystemModel.NAME:
name = value;
break;
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final String element = reader.getLocalName();
switch (element) {
case LOGIN: {
for (int i = 0; i < reader.getAttributeCount(); i++) {
String att = reader.getAttributeLocalName(i);
String value = reader.getAttributeValue(i);
if (att.equals(MailSubsystemModel.USER_NAME)) {
MailServerDefinition.USERNAME.parseAndSetParameter(value, operation, reader);
} else if (att.equals(MailSubsystemModel.PASSWORD)) {
PASSWORD.parseAndSetParameter(value, operation, reader);
}
}
ParseUtils.requireNoContent(reader);
break;
}
case PROPERTY: {
final String[] array = requireAttributes(reader, org.jboss.as.controller.parsing.Attribute.NAME.getLocalName(), org.jboss.as.controller.parsing.Attribute.VALUE.getLocalName());
MailServerDefinition.PROPERTIES.parseAndAddParameterElement(array[0], array[1], operation, reader);
ParseUtils.requireNoContent(reader);
break;
}
default: {
throw ParseUtils.unexpectedElement(reader);
}
}
}
if (name == null) {
throw ParseUtils.missingRequired(reader, Collections.singleton(NAME));
}
PathAddress address = parent.append(MailSubsystemModel.CUSTOM, name);
operation.get(OP_ADDR).set(address.toModelNode());
}
private void parseLogin(XMLExtendedStreamReader reader, ModelNode operation) throws XMLStreamException {
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final String element = reader.getLocalName();
switch (element) {
case LOGIN: {
for (int i = 0; i < reader.getAttributeCount(); i++) {
String att = reader.getAttributeLocalName(i);
String value = reader.getAttributeValue(i);
if (att.equals(MailSubsystemModel.USER_NAME)) {
MailServerDefinition.USERNAME.parseAndSetParameter(value, operation, reader);
} else if (att.equals(MailSubsystemModel.PASSWORD)) {
PASSWORD.parseAndSetParameter(value, operation, reader);
}
}
ParseUtils.requireNoContent(reader);
break;
}
}
}
}
}
| 12,557 | 44.5 | 196 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailSubsystemParser3_0.java
|
/*
*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
* /
*/
package org.jboss.as.mail.extension;
import static org.jboss.as.controller.PersistentResourceXMLDescription.builder;
import org.jboss.as.controller.PersistentResourceXMLDescription;
import org.jboss.as.controller.PersistentResourceXMLParser;
/**
* @author Tomaz Cerar (c) 2017 Red Hat Inc.
*/
class MailSubsystemParser3_0 extends PersistentResourceXMLParser {
@Override
public PersistentResourceXMLDescription getParserDescription() {
return builder(MailExtension.SUBSYSTEM_PATH, Namespace.MAIL_3_0.getUriString())
.addChild(
builder(MailExtension.MAIL_SESSION_PATH)
.addAttributes(MailSessionDefinition.DEBUG, MailSessionDefinition.JNDI_NAME, MailSessionDefinition.FROM)
.addChild(
builder(MailSubsystemModel.SMTP_SERVER_PATH)
.addAttributes(MailServerDefinition.OUTBOUND_SOCKET_BINDING_REF, MailServerDefinition.SSL, MailServerDefinition.TLS, MailServerDefinition.USERNAME, MailServerDefinition.PASSWORD, MailServerDefinition.CREDENTIAL_REFERENCE)
.setXmlElementName(MailSubsystemModel.SMTP_SERVER)
)
.addChild(
builder(MailSubsystemModel.POP3_SERVER_PATH)
.addAttributes(MailServerDefinition.OUTBOUND_SOCKET_BINDING_REF, MailServerDefinition.SSL, MailServerDefinition.TLS, MailServerDefinition.USERNAME, MailServerDefinition.PASSWORD, MailServerDefinition.CREDENTIAL_REFERENCE)
.setXmlElementName(MailSubsystemModel.POP3_SERVER)
)
.addChild(
builder(MailSubsystemModel.IMAP_SERVER_PATH)
.addAttributes(MailServerDefinition.OUTBOUND_SOCKET_BINDING_REF, MailServerDefinition.SSL, MailServerDefinition.TLS, MailServerDefinition.USERNAME, MailServerDefinition.PASSWORD, MailServerDefinition.CREDENTIAL_REFERENCE)
.setXmlElementName(MailSubsystemModel.IMAP_SERVER)
)
.addChild(
builder(MailSubsystemModel.CUSTOM_SERVER_PATH)
.addAttributes(MailServerDefinition.OUTBOUND_SOCKET_BINDING_REF_OPTIONAL, MailServerDefinition.SSL, MailServerDefinition.TLS, MailServerDefinition.USERNAME, MailServerDefinition.PASSWORD, MailServerDefinition.CREDENTIAL_REFERENCE, MailServerDefinition.PROPERTIES)
.setXmlElementName(MailSubsystemModel.CUSTOM_SERVER)
)
)
.build();
}
}
| 4,037 | 58.382353 | 311 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailServerWriteAttributeHandler.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
import static org.jboss.as.controller.security.CredentialReference.applyCredentialReferenceUpdateToRuntime;
import static org.jboss.as.controller.security.CredentialReference.handleCredentialReferenceUpdate;
import static org.jboss.as.controller.security.CredentialReference.rollbackCredentialStoreUpdate;
import static org.jboss.as.mail.extension.MailServerDefinition.CREDENTIAL_REFERENCE;
import java.util.Collection;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.RestartParentWriteAttributeHandler;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceName;
/**
* @author Tomaz Cerar
* @created 22.12.11 18:31
*/
class MailServerWriteAttributeHandler extends RestartParentWriteAttributeHandler {
MailServerWriteAttributeHandler(AttributeDefinition... attributeDefinitions) {
super(MailSubsystemModel.MAIL_SESSION, attributeDefinitions);
}
MailServerWriteAttributeHandler(Collection<AttributeDefinition> attributeDefinitions) {
super(MailSubsystemModel.MAIL_SESSION, attributeDefinitions);
}
@Override
protected void finishModelStage(OperationContext context, ModelNode operation, String attributeName, ModelNode newValue,
ModelNode oldValue, Resource resource) throws OperationFailedException {
super.finishModelStage(context, operation, attributeName, newValue, oldValue, resource);
if (attributeName.equals(CREDENTIAL_REFERENCE.getName())) {
handleCredentialReferenceUpdate(context, resource.getModel().get(attributeName), attributeName);
}
}
@Override
protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<ModelNode> handbackHolder) throws OperationFailedException {
if (attributeName.equals(CREDENTIAL_REFERENCE.getName())) {
applyCredentialReferenceUpdateToRuntime(context, operation, resolvedValue, currentValue, attributeName);
}
return super.applyUpdateToRuntime(context, operation, attributeName, resolvedValue, currentValue, handbackHolder);
}
@Override
protected void revertUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode valueToRestore, ModelNode resolvedValue, ModelNode invalidatedParentModel) throws OperationFailedException {
if (attributeName.equals(CREDENTIAL_REFERENCE.getName())) {
rollbackCredentialStoreUpdate(MailServerDefinition.CREDENTIAL_REFERENCE, context, resolvedValue);
}
super.revertUpdateToRuntime(context, operation, attributeName, valueToRestore, resolvedValue, invalidatedParentModel);
}
@Override
protected void recreateParentService(OperationContext context, PathAddress parentAddress, ModelNode parentModel) throws OperationFailedException {
MailSessionAdd.installSessionProviderService(context, parentAddress, parentModel);
}
@Override
protected ServiceName getParentServiceName(PathAddress parentAddress) {
return MailSessionDefinition.SESSION_CAPABILITY.getCapabilityServiceName(parentAddress).append("provider");
}
}
| 4,506 | 49.077778 | 236 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/SessionProviderFactory.java
|
/*
*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
* /
*/
package org.jboss.as.mail.extension;
import java.net.InetSocketAddress;
import java.util.Map;
import java.util.Properties;
import org.jboss.as.network.NetworkUtils;
import org.jboss.as.network.OutboundSocketBinding;
import org.jboss.metadata.javaee.spec.MailSessionMetaData;
import org.jboss.metadata.javaee.spec.PropertyMetaData;
import org.jboss.msc.service.StartException;
import jakarta.mail.Authenticator;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc.
*/
class SessionProviderFactory {
static ConfigurableSessionProvider create(MailSessionConfig config) throws StartException {
return new ManagedSession(config);
}
static SessionProvider create(MailSessionMetaData mailSessionMetaData) {
return new DirectSessionProvider(mailSessionMetaData);
}
private static String getHostKey(final String protocol) {
return new StringBuilder("mail.").append(protocol).append(".host").toString();
}
private static String getPortKey(final String protocol) {
return new StringBuilder("mail.").append(protocol).append(".port").toString();
}
private static String getPropKey(final String protocol, final String name) {
return new StringBuilder("mail.").append(protocol).append(".").append(name).toString();
}
private static class ManagedSession implements ConfigurableSessionProvider {
private final MailSessionConfig sessionConfig;
private final Properties properties = new Properties();
private ManagedSession(MailSessionConfig sessionConfig) throws StartException {
this.sessionConfig = sessionConfig;
configure();
}
@Override
public MailSessionConfig getConfig() {
return this.sessionConfig;
}
/**
* Configures mail session properties
*
* @throws org.jboss.msc.service.StartException if socket binding could not be found
*
* @see <a href="https://eclipse-ee4j.github.io/mail/docs/api/jakarta.mail/com/sun/mail/smtp/package-summary.html>Package SMTP documentation</a>
* @see <a href="https://eclipse-ee4j.github.io/mail/docs/api/jakarta.mail/com/sun/mail/pop3/package-summary.html>Package POP3 documentation</a>
* @see <a href="https://eclipse-ee4j.github.io/mail/docs/api/jakarta.mail/com/sun/mail/imap/package-summary.html>Package IMAP documentation</a>
*/
private void configure() throws StartException {
if (sessionConfig.getSmtpServer() != null) {
properties.setProperty("mail.transport.protocol", "smtp");
setServerProps(properties, sessionConfig.getSmtpServer(), "smtp");
}
if (sessionConfig.getImapServer() != null) {
properties.setProperty("mail.store.protocol", "imap");
setServerProps(properties, sessionConfig.getImapServer(), "imap");
}
if (sessionConfig.getPop3Server() != null) {
properties.setProperty("mail.store.protocol", "pop3");
setServerProps(properties, sessionConfig.getPop3Server(), "pop3");
}
if (sessionConfig.getCustomServers() != null) {
configureCustomServers(properties, sessionConfig.getCustomServers());
}
if (sessionConfig.getFrom() != null) {
properties.setProperty("mail.from", sessionConfig.getFrom());
}
properties.setProperty("mail.debug", String.valueOf(sessionConfig.isDebug()));
MailLogger.ROOT_LOGGER.tracef("props: %s", properties);
}
private void configureCustomServers(final Properties props, final CustomServerConfig... serverConfigs) throws StartException {
for (CustomServerConfig serverConfig : serverConfigs) {
setServerProps(props, serverConfig, serverConfig.getProtocol());
}
}
private void setServerProps(final Properties props, final ServerConfig server, final String protocol) throws StartException {
if (server.isSslEnabled()) {
props.setProperty(getPropKey(protocol, "ssl.enable"), "true");
} else if (server.isTlsEnabled()) {
props.setProperty(getPropKey(protocol, "starttls.enable"), "true");
}
if (server.getCredentials() != null) {
props.setProperty(getPropKey(protocol, "auth"), "true");
props.setProperty(getPropKey(protocol, "user"), server.getCredentials().getUsername());
}
props.setProperty(getPropKey(protocol, "debug"), String.valueOf(sessionConfig.isDebug()));
Map<String, String> customProps = server.getProperties();
if (server.getOutgoingSocketBinding() != null) {
InetSocketAddress socketAddress = getServerSocketAddress(server);
if (socketAddress.getAddress() == null) {
MailLogger.ROOT_LOGGER.hostUnknown(socketAddress.getHostName());
props.setProperty(getHostKey(protocol), NetworkUtils.canonize(socketAddress.getHostName()));
} else {
props.setProperty(getHostKey(protocol), NetworkUtils.canonize(socketAddress.getAddress().getHostName()));
}
props.setProperty(getPortKey(protocol), String.valueOf(socketAddress.getPort()));
} else {
String host = customProps.get("host");
if (host != null && !"".equals(host.trim())) {
props.setProperty(getHostKey(protocol), host);
}
String port = customProps.get("port");
if (port != null && !"".equals(port.trim())) {
props.setProperty(getPortKey(protocol), port);
}
}
if (customProps != null && !customProps.isEmpty()) {
for (Map.Entry<String, String> prop : customProps.entrySet()) {
if (!props.contains(prop.getKey())) {
if (prop.getKey().contains(".")){
props.put(prop.getKey(), prop.getValue());
}else{
props.put(getPropKey(protocol, prop.getKey()), prop.getValue());
}
}
}
}
}
private InetSocketAddress getServerSocketAddress(ServerConfig server) throws StartException {
OutboundSocketBinding binding = server.getOutgoingSocketBinding();
return new InetSocketAddress(binding.getUnresolvedDestinationAddress(), binding.getDestinationPort());
}
@Override
public Session getSession() {
final Session session;
final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
if (current == null) {
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(Session.class.getClassLoader());
session = Session.getInstance(properties, new ManagedPasswordAuthenticator(sessionConfig));
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current);
}
} else {
session = Session.getInstance(properties, new ManagedPasswordAuthenticator(sessionConfig));
}
return session;
}
}
protected static class ManagedPasswordAuthenticator extends Authenticator {
private MailSessionConfig config;
public ManagedPasswordAuthenticator(MailSessionConfig sessionConfig) {
this.config = sessionConfig;
}
@Override
protected jakarta.mail.PasswordAuthentication getPasswordAuthentication() {
String protocol = getRequestingProtocol();
Credentials c = null;
if (MailSubsystemModel.SMTP.equals(protocol) && config.getSmtpServer() != null) {
c = config.getSmtpServer().getCredentials();
} else if (MailSubsystemModel.POP3.equals(protocol) && config.getPop3Server() != null) {
c = config.getPop3Server().getCredentials();
} else if (MailSubsystemModel.IMAP.equals(protocol) && config.getImapServer() != null) {
c = config.getImapServer().getCredentials();
}
if (c == null) {
for (CustomServerConfig ssc : config.getCustomServers()) {
if (ssc.getProtocol().equals(protocol)) {
c = ssc.getCredentials();
break;
}
}
}
if (c != null && c.getPassword() != null) {
return new jakarta.mail.PasswordAuthentication(c.getUsername(), c.getPassword());
}
return null;
}
}
private static class DirectSessionProvider implements SessionProvider {
private final MailSessionMetaData metaData;
private final Properties properties = new Properties();
private PasswordAuthentication authenticator = null;
private DirectSessionProvider(MailSessionMetaData metaData) {
this.metaData = metaData;
configure();
}
private void configure() {
String protocol = metaData.getTransportProtocol();
if (protocol == null) {
protocol = metaData.getStoreProtocol();
}
if (protocol == null) {
protocol = "smtp";
}
properties.put(getHostKey(protocol), metaData.getHost());
if (metaData.getFrom() != null) {
properties.put(getPropKey(protocol, "from"), metaData.getFrom());
}
if (metaData.getProperties() != null) {
for (PropertyMetaData prop : metaData.getProperties()) {
properties.put(prop.getKey(), prop.getValue());
}
}
if (metaData.getUser() != null) {
authenticator = new PasswordAuthentication(metaData.getUser(), metaData.getPassword());
}
}
@Override
public Session getSession() {
return Session.getInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return authenticator;
}
});
}
}
}
| 11,826 | 43.462406 | 152 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailSessionService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
import java.util.function.Consumer;
import java.util.function.Supplier;
import jakarta.mail.Session;
import org.jboss.msc.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* Service that provides a jakarta.mail.Session.
*
* @author Tomaz Cerar
* @created 27.7.11 0:14
*/
public class MailSessionService implements Service {
private final Consumer<Session> session;
private final Supplier<SessionProvider> provider;
public MailSessionService(Consumer<Session> session, Supplier<SessionProvider> provider) {
this.session = session;
this.provider = provider;
}
@Override
public void start(final StartContext startContext) throws StartException {
this.session.accept(this.provider.get().getSession());
}
@Override
public void stop(final StopContext stopContext) {
// Nothing to stop
}
}
| 2,021 | 32.7 | 94 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailSessionRemove.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
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.registry.Resource;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.dmr.ModelNode;
/**
* Remove operation handler for the session resource.
* @author Paul Ferraro
*/
class MailSessionRemove extends AbstractRemoveStepHandler {
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
if (context.isResourceServiceRestartAllowed()) {
removeRuntimeServices(context, model);
} else {
context.reloadRequired();
}
}
static void removeSessionProviderService(OperationContext context, ModelNode model) {
removeSessionProviderService(context, context.getCurrentAddress(), model);
}
static void removeSessionProviderService(OperationContext context, PathAddress address, ModelNode model) {
context.removeService(MailSessionDefinition.SESSION_CAPABILITY.getCapabilityServiceName(address).append("provider"));
}
static void removeBinderService(OperationContext context, ModelNode model) throws OperationFailedException {
final String jndiName = MailSessionAdd.getJndiName(model, context);
context.removeService(ContextNames.bindInfoFor(jndiName).getBinderServiceName());
}
static void removeRuntimeServices(OperationContext context, ModelNode model) throws OperationFailedException {
removeSessionProviderService(context, model);
context.removeService(MailSessionDefinition.SESSION_CAPABILITY.getCapabilityServiceName(context.getCurrentAddress()));
removeBinderService(context, model);
}
@Override
protected void recoverServices(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
if (context.isResourceServiceRestartAllowed()) {
MailSessionAdd.installRuntimeServices(context, Resource.Tools.readModel(context.readResource(PathAddress.EMPTY_ADDRESS)));
} else {
context.revertReloadRequired();
}
}
}
| 3,356 | 42.038462 | 134 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailSessionDefinition.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
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.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.access.constraint.ApplicationTypeConfig;
import org.jboss.as.controller.access.management.AccessConstraintDefinition;
import org.jboss.as.controller.access.management.ApplicationTypeAccessConstraintDefinition;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.OperationEntry;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.wildfly.common.function.ExceptionBiConsumer;
import jakarta.mail.Session;
/**
* @author Tomaz Cerar
* @created 19.12.11
*/
class MailSessionDefinition extends PersistentResourceDefinition {
static final RuntimeCapability<Void> SESSION_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.mail.session", true, Session.class)
.build();
private final List<AccessConstraintDefinition> accessConstraints;
protected static final SimpleAttributeDefinition JNDI_NAME =
new SimpleAttributeDefinitionBuilder(MailSubsystemModel.JNDI_NAME, ModelType.STRING, false)
.setAllowExpression(true)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.build();
protected static final SimpleAttributeDefinition FROM =
new SimpleAttributeDefinitionBuilder(MailSubsystemModel.FROM, ModelType.STRING, true)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.setAllowExpression(true)
.setRequired(false)
.build();
protected static final SimpleAttributeDefinition DEBUG =
new SimpleAttributeDefinitionBuilder(MailSubsystemModel.DEBUG, ModelType.BOOLEAN, true)
.setAllowExpression(true)
.setDefaultValue(ModelNode.FALSE)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.build();
static final AttributeDefinition[] ATTRIBUTES = {DEBUG, JNDI_NAME, FROM};
MailSessionDefinition() {
super(new SimpleResourceDefinition.Parameters(MailExtension.MAIL_SESSION_PATH,
MailExtension.getResourceDescriptionResolver(MailSubsystemModel.MAIL_SESSION))
.setAddHandler(new MailSessionAdd())
.setRemoveHandler(new MailSessionRemove())
.setRemoveRestartLevel(OperationEntry.Flag.RESTART_RESOURCE_SERVICES)
.setCapabilities(SESSION_CAPABILITY)
);
ApplicationTypeConfig atc = new ApplicationTypeConfig(MailExtension.SUBSYSTEM_NAME, MailSubsystemModel.MAIL_SESSION);
accessConstraints = new ApplicationTypeAccessConstraintDefinition(atc).wrapAsList();
}
@Override
public void registerAttributes(final ManagementResourceRegistration registration) {
ExceptionBiConsumer<OperationContext, ModelNode, OperationFailedException> remover = MailSessionRemove::removeSessionProviderService;
ExceptionBiConsumer<OperationContext, ModelNode, OperationFailedException> installer = MailSessionAdd::installSessionProviderService;
for (AttributeDefinition attribute : ATTRIBUTES) {
if (!attribute.getName().equals(JNDI_NAME.getName())) {
registration.registerReadWriteAttribute(attribute, null, new MailSessionWriteAttributeHandler(attribute, remover, installer));
}
}
registration.registerReadWriteAttribute(JNDI_NAME, null, new MailSessionWriteAttributeHandler(JNDI_NAME, MailSessionRemove::removeBinderService, MailSessionAdd::installBinderService));
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return Arrays.asList(ATTRIBUTES);
}
@Override
protected List<? extends PersistentResourceDefinition> getChildren() {
return List.of(
// /subsystem=mail/mail-session=java:/Mail/server=imap
new MailServerDefinition(MailSubsystemModel.IMAP_SERVER_PATH, MailServerDefinition.ATTRIBUTES),
// /subsystem=mail/mail-session=java:/Mail/server=pop3
new MailServerDefinition(MailSubsystemModel.POP3_SERVER_PATH, MailServerDefinition.ATTRIBUTES),
// /subsystem=mail/mail-session=java:/Mail/server=smtp
new MailServerDefinition(MailSubsystemModel.SMTP_SERVER_PATH, MailServerDefinition.ATTRIBUTES),
// /subsystem=mail/mail-session=java:/Mail/custom=*
new MailServerDefinition(MailSubsystemModel.CUSTOM_SERVER_PATH, MailServerDefinition.ATTRIBUTES_CUSTOM)
);
}
@Override
public List<AccessConstraintDefinition> getAccessConstraints() {
return accessConstraints;
}
}
| 6,357 | 48.286822 | 192 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailExtension.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
import org.jboss.as.controller.Extension;
import org.jboss.as.controller.ExtensionContext;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SubsystemRegistration;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver;
import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler;
import org.jboss.as.controller.parsing.ExtensionParsingContext;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
/**
* @author <a href="[email protected]">Tomaz Cerar</a>
* @since Jboss AS 7.1.0
*/
public class MailExtension implements Extension {
public static final String SUBSYSTEM_NAME = "mail";
private static final String RESOURCE_NAME = MailExtension.class.getPackage().getName() + ".LocalDescriptions";
static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, SUBSYSTEM_NAME);
static final PathElement MAIL_SESSION_PATH = PathElement.pathElement(MailSubsystemModel.MAIL_SESSION);
static StandardResourceDescriptionResolver getResourceDescriptionResolver(final String... keyPrefix) {
StringBuilder prefix = new StringBuilder(SUBSYSTEM_NAME);
for (String kp : keyPrefix) {
prefix.append('.').append(kp);
}
return new StandardResourceDescriptionResolver(prefix.toString(), RESOURCE_NAME, MailExtension.class.getClassLoader(), true, false);
}
@Override
public void initializeParsers(ExtensionParsingContext context) {
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.MAIL_1_0.getUriString(), MailSubsystemParser::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.MAIL_1_1.getUriString(), MailSubsystemParser::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.MAIL_1_2.getUriString(), MailSubsystemParser::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.MAIL_2_0.getUriString(), MailSubsystemParser2_0::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.MAIL_3_0.getUriString(), MailSubsystemParser3_0::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.MAIL_4_0.getUriString(), MailSubsystemParser4_0::new);
}
static final ModelVersion CURRENT_MODEL_VERSION = ModelVersion.create(4, 0, 0);
@Override
public void initialize(ExtensionContext context) {
final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION);
final ManagementResourceRegistration subsystemRegistration = subsystem.registerSubsystemModel(new MailSubsystemDefinition());
subsystemRegistration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE);
subsystem.registerXMLElementWriter(new MailSubsystemParser4_0());
}
}
| 4,057 | 49.725 | 141 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailSessionWriteAttributeHandler.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
import java.util.List;
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.ReloadRequiredWriteAttributeHandler;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
import org.wildfly.common.function.ExceptionBiConsumer;
/**
* Write attribute operation handler for attributes of the session resource.
* @author Paul Ferraro
*/
class MailSessionWriteAttributeHandler extends ReloadRequiredWriteAttributeHandler {
private final ExceptionBiConsumer<OperationContext, ModelNode, OperationFailedException> remover;
private final ExceptionBiConsumer<OperationContext, ModelNode, OperationFailedException> installer;
MailSessionWriteAttributeHandler(AttributeDefinition attribute, ExceptionBiConsumer<OperationContext, ModelNode, OperationFailedException> remover, ExceptionBiConsumer<OperationContext, ModelNode, OperationFailedException> installer) {
super(List.of(attribute));
this.remover = remover;
this.installer = installer;
}
@Override
protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<Void> handback) throws OperationFailedException {
boolean updated = super.applyUpdateToRuntime(context, operation, attributeName, resolvedValue, currentValue, handback);
if (updated) {
PathAddress address = context.getCurrentAddress();
if (context.isResourceServiceRestartAllowed() && this.getAttributeDefinition(attributeName).getFlags().contains(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES) && context.markResourceRestarted(address, this)) {
this.remover.accept(context, context.getOriginalRootResource().navigate(address).getModel());
this.installer.accept(context, Resource.Tools.readModel(context.readResource(PathAddress.EMPTY_ADDRESS)));
// Returning false prevents going into reload required state
return false;
}
}
return updated;
}
@Override
protected void revertUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode valueToRestore, ModelNode resolvedValue, Void handback) throws OperationFailedException {
PathAddress address = context.getCurrentAddress();
if (context.isResourceServiceRestartAllowed() && this.getAttributeDefinition(attributeName).getFlags().contains(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES) && context.revertResourceRestarted(address, this)) {
this.remover.accept(context, context.readResource(PathAddress.EMPTY_ADDRESS, false).getModel());
this.installer.accept(context, Resource.Tools.readModel(context.getOriginalRootResource().navigate(address)));
}
}
}
| 4,130 | 53.355263 | 239 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailSubsystemParser2_0.java
|
/*
*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
* /
*/
package org.jboss.as.mail.extension;
import static org.jboss.as.controller.PersistentResourceXMLDescription.builder;
import org.jboss.as.controller.PersistentResourceXMLDescription;
import org.jboss.as.controller.PersistentResourceXMLParser;
/**
* @author Tomaz Cerar (c) 2013 Red Hat Inc.
*/
public class MailSubsystemParser2_0 extends PersistentResourceXMLParser {
private final PersistentResourceXMLDescription xmlDescription;
MailSubsystemParser2_0() {
xmlDescription = builder(MailExtension.SUBSYSTEM_PATH, Namespace.MAIL_2_0.getUriString())
.addChild(
builder(MailExtension.MAIL_SESSION_PATH)
.addAttributes(MailSessionDefinition.DEBUG, MailSessionDefinition.JNDI_NAME, MailSessionDefinition.FROM)
.addChild(
builder(MailSubsystemModel.SMTP_SERVER_PATH)
.addAttributes(MailServerDefinition.OUTBOUND_SOCKET_BINDING_REF, MailServerDefinition.SSL, MailServerDefinition.TLS, MailServerDefinition.USERNAME, MailServerDefinition.PASSWORD)
.setXmlElementName(MailSubsystemModel.SMTP_SERVER)
)
.addChild(
builder(MailSubsystemModel.POP3_SERVER_PATH)
.addAttributes(MailServerDefinition.OUTBOUND_SOCKET_BINDING_REF, MailServerDefinition.SSL, MailServerDefinition.TLS, MailServerDefinition.USERNAME, MailServerDefinition.PASSWORD)
.setXmlElementName(MailSubsystemModel.POP3_SERVER)
)
.addChild(
builder(MailSubsystemModel.IMAP_SERVER_PATH)
.addAttributes(MailServerDefinition.OUTBOUND_SOCKET_BINDING_REF, MailServerDefinition.SSL, MailServerDefinition.TLS, MailServerDefinition.USERNAME, MailServerDefinition.PASSWORD)
.setXmlElementName(MailSubsystemModel.IMAP_SERVER)
)
.addChild(
builder(MailSubsystemModel.CUSTOM_SERVER_PATH)
.addAttributes(MailServerDefinition.OUTBOUND_SOCKET_BINDING_REF_OPTIONAL, MailServerDefinition.SSL, MailServerDefinition.TLS, MailServerDefinition.USERNAME, MailServerDefinition.PASSWORD, MailServerDefinition.PROPERTIES)
.setXmlElementName(MailSubsystemModel.CUSTOM_SERVER)
)
)
.build();
}
@Override
public PersistentResourceXMLDescription getParserDescription() {
return xmlDescription;
}
}
| 4,020 | 52.613333 | 268 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailSessionDefinitionDescriptorProcessor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
import org.jboss.as.ee.resource.definition.ResourceDefinitionDescriptorProcessor;
import org.jboss.as.ee.resource.definition.ResourceDefinitionInjectionSource;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.metadata.javaee.spec.MailSessionMetaData;
import org.jboss.metadata.javaee.spec.MailSessionsMetaData;
import org.jboss.metadata.javaee.spec.RemoteEnvironment;
/**
* Deployment processor responsible for processing mail-session deployment descriptor elements
*
* @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc.
* @author Eduardo Martins
*
*/
public class MailSessionDefinitionDescriptorProcessor extends ResourceDefinitionDescriptorProcessor {
@Override
protected void processEnvironment(RemoteEnvironment environment, ResourceDefinitionInjectionSources injectionSources) throws DeploymentUnitProcessingException {
final MailSessionsMetaData metaDatas = environment.getMailSessions();
if (metaDatas != null) {
for(MailSessionMetaData metaData : metaDatas) {
injectionSources.addResourceDefinitionInjectionSource(getResourceDefinitionInjectionSource(metaData));
}
}
}
private ResourceDefinitionInjectionSource getResourceDefinitionInjectionSource(final MailSessionMetaData metaData) {
final SessionProvider provider = SessionProviderFactory.create(metaData);
return new MailSessionDefinitionInjectionSource(metaData.getName(), provider);
}
}
| 2,599 | 44.614035 | 164 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/CustomServerConfig.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
import java.util.Map;
import java.util.function.Supplier;
import org.jboss.as.network.OutboundSocketBinding;
/**
* @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2012 Red Hat Inc.
*/
final class CustomServerConfig extends ServerConfig {
private String protocol;
public CustomServerConfig(final String protocol, final Supplier<OutboundSocketBinding> socketBinding, Credentials credentials, boolean ssl, boolean tls, Map<String, String> properties) {
super(socketBinding, credentials, ssl, tls, properties);
this.protocol = protocol;
}
public String getProtocol() {
return protocol;
}
}
| 1,718 | 37.2 | 190 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailSubsystemModel.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
import org.jboss.as.controller.PathElement;
/**
* @author <a href="[email protected]">Tomaz Cerar</a>
* @created 26.7.11 15:21
*/
interface MailSubsystemModel {
String LOGIN = "login";
String SERVER_TYPE = "server";
String SMTP_SERVER = "smtp-server";
String POP3_SERVER = "pop3-server";
String IMAP_SERVER = "imap-server";
String CUSTOM_SERVER = "custom-server";
String MAIL_SESSION = "mail-session";
String LOGIN_USERNAME = "name";
String USER_NAME = "username";
String PASSWORD = "password";
String JNDI_NAME = "jndi-name";
String DEBUG = "debug";
String OUTBOUND_SOCKET_BINDING_REF = "outbound-socket-binding-ref";
String SSL = "ssl";
String TLS = "tls";
String FROM = "from";
String POP3 = "pop3";
String SMTP = "smtp";
String IMAP = "imap";
String NAME = "name";
String CUSTOM = "custom";
String PROPERTY = "property";
PathElement POP3_SERVER_PATH = PathElement.pathElement(SERVER_TYPE, POP3);
PathElement SMTP_SERVER_PATH = PathElement.pathElement(SERVER_TYPE, SMTP);
PathElement IMAP_SERVER_PATH = PathElement.pathElement(SERVER_TYPE, IMAP);
PathElement CUSTOM_SERVER_PATH = PathElement.pathElement(CUSTOM);
}
| 2,295 | 36.032258 | 78 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/Namespace.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
import java.util.HashMap;
import java.util.Map;
/**
* @author <a href="[email protected]">Tomaz Cerar</a>
*/
enum Namespace {
// must be first
UNKNOWN(null),
MAIL_1_0("urn:jboss:domain:mail:1.0"),
MAIL_1_1("urn:jboss:domain:mail:1.1"),
MAIL_1_2("urn:jboss:domain:mail:1.2"),
MAIL_2_0("urn:jboss:domain:mail:2.0"),
MAIL_3_0("urn:jboss:domain:mail:3.0"),
MAIL_4_0("urn:jboss:domain:mail:4.0");
/**
* The current namespace version.
*/
public static final Namespace CURRENT = MAIL_4_0;
private final String name;
Namespace(final String name) {
this.name = name;
}
/**
* Get the URI of this namespace.
*
* @return the URI
*/
public String getUriString() {
return name;
}
private static final Map<String, Namespace> MAP;
static {
final Map<String, Namespace> map = new HashMap<String, Namespace>();
for (Namespace namespace : values()) {
final String name = namespace.getUriString();
if (name != null) { map.put(name, namespace); }
}
MAP = map;
}
public static Namespace forUri(String uri) {
final Namespace element = MAP.get(uri);
return element == null ? UNKNOWN : element;
}
}
| 2,362 | 29.294872 | 76 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailServerRemove.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.RestartParentResourceRemoveHandler;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceName;
/**
* Remove attribute operation handler for attributes of the server resources.
* @author Paul Ferraro
*/
class MailServerRemove extends RestartParentResourceRemoveHandler {
MailServerRemove() {
super(MailSubsystemModel.MAIL_SESSION);
}
@Override
protected void recreateParentService(OperationContext context, PathAddress parentAddress, ModelNode parentModel) throws OperationFailedException {
MailSessionAdd.installSessionProviderService(context, parentAddress, parentModel);
}
@Override
protected ServiceName getParentServiceName(PathAddress parentAddress) {
return MailSessionDefinition.SESSION_CAPABILITY.getCapabilityServiceName(parentAddress).append("provider");
}
}
| 2,089 | 39.980392 | 150 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/ServerConfig.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.mail.extension;
import java.util.Map;
import java.util.function.Supplier;
import org.jboss.as.network.OutboundSocketBinding;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.value.InjectedValue;
import org.wildfly.common.function.ExceptionSupplier;
import org.wildfly.security.credential.PasswordCredential;
import org.wildfly.security.credential.source.CredentialSource;
import org.wildfly.security.password.interfaces.ClearPassword;
/**
* @author Tomaz Cerar
* @created 10.8.11 22:50
*/
class ServerConfig {
private final Supplier<OutboundSocketBinding> outgoingSocketBinding;
private final Credentials credentials;
private final InjectedValue<ExceptionSupplier<CredentialSource, Exception>> credentialSourceSupplierInjector = new InjectedValue<>();
private boolean sslEnabled = false;
private boolean tlsEnabled = false;
private final Map<String, String> properties;
public ServerConfig(final Supplier<OutboundSocketBinding> outgoingSocketBinding, final Credentials credentials, boolean ssl, boolean tls, Map<String, String> properties) {
this.outgoingSocketBinding = outgoingSocketBinding;
this.credentials = credentials;
this.sslEnabled = ssl;
this.tlsEnabled = tls;
this.properties = properties;
}
public OutboundSocketBinding getOutgoingSocketBinding() {
return (this.outgoingSocketBinding != null) ? this.outgoingSocketBinding.get() : null;
}
public Credentials getCredentials() {
ExceptionSupplier<CredentialSource, Exception> credentialSourceSupplier = credentialSourceSupplierInjector.getOptionalValue();
if (credentialSourceSupplier != null) {
try {
CredentialSource credentialSource = credentialSourceSupplier.get();
if (credentialSource == null) {
return credentials;
}
char[] password = credentialSource.getCredential(PasswordCredential.class).getPassword(ClearPassword.class).getPassword();
return new Credentials(credentials.getUsername(), new String(password));
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
return credentials;
}
}
public boolean isSslEnabled() {
return sslEnabled;
}
public boolean isTlsEnabled() {
return tlsEnabled;
}
public Map<String, String> getProperties() {
return properties;
}
public Injector<ExceptionSupplier<CredentialSource, Exception>> getCredentialSourceSupplierInjector() {
return credentialSourceSupplierInjector;
}
}
| 3,715 | 38.531915 | 175 |
java
|
null |
wildfly-main/mail/src/main/java/org/jboss/as/mail/extension/MailSubsystemParser4_0.java
|
/*
*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
* /
*/
package org.jboss.as.mail.extension;
import static org.jboss.as.controller.PersistentResourceXMLDescription.builder;
import org.jboss.as.controller.PersistentResourceXMLDescription;
import org.jboss.as.controller.PersistentResourceXMLParser;
/**
* @author Tomaz Cerar (c) 2017 Red Hat Inc.
*/
class MailSubsystemParser4_0 extends PersistentResourceXMLParser {
@Override
public PersistentResourceXMLDescription getParserDescription() {
return builder(MailExtension.SUBSYSTEM_PATH, Namespace.MAIL_4_0.getUriString())
.addChild(
builder(MailExtension.MAIL_SESSION_PATH)
.addAttributes(MailSessionDefinition.DEBUG, MailSessionDefinition.JNDI_NAME, MailSessionDefinition.FROM)
.addChild(
builder(MailSubsystemModel.SMTP_SERVER_PATH)
.addAttributes(MailServerDefinition.OUTBOUND_SOCKET_BINDING_REF, MailServerDefinition.SSL, MailServerDefinition.TLS, MailServerDefinition.USERNAME, MailServerDefinition.PASSWORD, MailServerDefinition.CREDENTIAL_REFERENCE)
.setXmlElementName(MailSubsystemModel.SMTP_SERVER)
)
.addChild(
builder(MailSubsystemModel.POP3_SERVER_PATH)
.addAttributes(MailServerDefinition.OUTBOUND_SOCKET_BINDING_REF, MailServerDefinition.SSL, MailServerDefinition.TLS, MailServerDefinition.USERNAME, MailServerDefinition.PASSWORD, MailServerDefinition.CREDENTIAL_REFERENCE)
.setXmlElementName(MailSubsystemModel.POP3_SERVER)
)
.addChild(
builder(MailSubsystemModel.IMAP_SERVER_PATH)
.addAttributes(MailServerDefinition.OUTBOUND_SOCKET_BINDING_REF, MailServerDefinition.SSL, MailServerDefinition.TLS, MailServerDefinition.USERNAME, MailServerDefinition.PASSWORD, MailServerDefinition.CREDENTIAL_REFERENCE)
.setXmlElementName(MailSubsystemModel.IMAP_SERVER)
)
.addChild(
builder(MailSubsystemModel.CUSTOM_SERVER_PATH)
.addAttributes(MailServerDefinition.OUTBOUND_SOCKET_BINDING_REF_OPTIONAL, MailServerDefinition.SSL, MailServerDefinition.TLS, MailServerDefinition.USERNAME, MailServerDefinition.PASSWORD, MailServerDefinition.CREDENTIAL_REFERENCE, MailServerDefinition.PROPERTIES)
.setXmlElementName(MailSubsystemModel.CUSTOM_SERVER)
)
)
.build();
}
}
| 4,037 | 58.382353 | 311 |
java
|
null |
wildfly-main/naming/src/test/java/org/jboss/as/naming/InitialContextFactoryTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.naming;
import static org.junit.Assert.assertTrue;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.spi.NamingManager;
import org.junit.Before;
import org.junit.Test;
/**
* @author John E. Bailey
*/
public class InitialContextFactoryTestCase {
@Before
public void init() {
NamingContext.setActiveNamingStore(new InMemoryNamingStore());
}
@Test
public void testInitialFactory() throws Exception {
// Test with sys prop
System.setProperty(Context.INITIAL_CONTEXT_FACTORY, InitialContextFactory.class.getName());
InitialContext initialContext = new InitialContext();
Context context = (Context) initialContext.lookup("");
assertTrue(context instanceof NamingContext);
// Test with builder
if (!NamingManager.hasInitialContextFactoryBuilder()) {
NamingManager.setInitialContextFactoryBuilder(new InitialContextFactoryBuilder());
}
initialContext = new InitialContext();
context = (Context) initialContext.lookup("");
assertTrue(context instanceof NamingContext);
}
@Test
public void testJavaContext() throws Exception {
System.setProperty(Context.INITIAL_CONTEXT_FACTORY, InitialContextFactory.class.getName());
System.setProperty(Context.URL_PKG_PREFIXES, "org.jboss.as.naming.interfaces");
InitialContext initialContext = new InitialContext();
Context context = (Context) initialContext.lookup("java:");
assertTrue(context instanceof NamingContext);
}
}
| 2,627 | 36.542857 | 99 |
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.