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/metrics/src/main/java/org/wildfly/extension/metrics/MetricsParser_1_0.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.metrics;
import static org.jboss.as.controller.PersistentResourceXMLDescription.builder;
import org.jboss.as.controller.PersistentResourceXMLDescription;
import org.jboss.as.controller.PersistentResourceXMLParser;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc.
*/
public class MetricsParser_1_0 extends PersistentResourceXMLParser {
/**
* The name space used for the {@code subsystem} element
*/
public static final String NAMESPACE = "urn:wildfly:metrics:1.0";
private static final PersistentResourceXMLDescription xmlDescription;
static {
xmlDescription = builder(MetricsExtension.SUBSYSTEM_PATH, NAMESPACE)
.addAttributes(
MetricsSubsystemDefinition.SECURITY_ENABLED,
MetricsSubsystemDefinition.EXPOSED_SUBSYSTEMS,
MetricsSubsystemDefinition.PREFIX)
.build();
}
@Override
public PersistentResourceXMLDescription getParserDescription() {
return xmlDescription;
}
}
| 2,125 | 38.37037 | 79 |
java
|
null |
wildfly-main/metrics/src/main/java/org/wildfly/extension/metrics/WildFlyMetricRegistryService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.metrics;
import static org.wildfly.extension.metrics.MetricsSubsystemDefinition.METRICS_REGISTRY_RUNTIME_CAPABILITY;
import java.io.IOException;
import java.util.function.Consumer;
import org.jboss.as.controller.OperationContext;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
import org.wildfly.extension.metrics._private.MetricsLogger;
import org.wildfly.extension.metrics.jmx.JmxMetricCollector;
/**
* Service to create a registry for WildFly (and JMX) metrics.
*/
public class WildFlyMetricRegistryService implements Service<WildFlyMetricRegistry> {
private final Consumer<WildFlyMetricRegistry> consumer;
private WildFlyMetricRegistry registry;
static void install(OperationContext context) {
ServiceBuilder<?> serviceBuilder = context.getServiceTarget().addService(METRICS_REGISTRY_RUNTIME_CAPABILITY.getCapabilityServiceName());
Consumer<WildFlyMetricRegistry> registry = serviceBuilder.provides(METRICS_REGISTRY_RUNTIME_CAPABILITY.getCapabilityServiceName());
serviceBuilder.setInstance(new WildFlyMetricRegistryService(registry)).install();
}
WildFlyMetricRegistryService(Consumer<WildFlyMetricRegistry> consumer) {
this.consumer = consumer;
}
@Override
public void start(StartContext context) {
registry = new WildFlyMetricRegistry();
// register metrics from JMX MBeans for base metrics
JmxMetricCollector jmxMetricCollector = new JmxMetricCollector(registry);
try {
jmxMetricCollector.init();
} catch (IOException e) {
throw MetricsLogger.LOGGER.failedInitializeJMXRegistrar(e);
}
consumer.accept(registry);
}
@Override
public void stop(StopContext context) {
consumer.accept(null);
registry.close();
registry = null;
}
@Override
public WildFlyMetricRegistry getValue() throws IllegalStateException, IllegalArgumentException {
return registry;
}
}
| 3,151 | 37.91358 | 145 |
java
|
null |
wildfly-main/metrics/src/main/java/org/wildfly/extension/metrics/_private/MetricsLogger.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.metrics._private;
import static org.jboss.logging.Logger.Level.INFO;
import static org.jboss.logging.Logger.Level.WARN;
import static org.jboss.logging.Logger.Level.ERROR;
import java.io.IOException;
import org.jboss.as.controller.PathAddress;
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;
/**
* Log messages for WildFly metrics Extension.
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc.
*/
@MessageLogger(projectCode = "WFLYMETRICS", length = 4)
public interface MetricsLogger extends BasicLogger {
/**
* A logger with the category {@code org.wildfly.extension.batch}.
*/
MetricsLogger LOGGER = Logger.getMessageLogger(MetricsLogger.class, "org.wildfly.extension.metrics");
/**
* Logs an informational message indicating the subsystem is being activated.
*/
@LogMessage(level = INFO)
@Message(id = 1, value = "Activating Base Metrics Subsystem")
void activatingSubsystem();
@Message(id = 2, value = "Failed to initialize metrics from JMX MBeans")
IllegalArgumentException failedInitializeJMXRegistrar(@Cause IOException e);
@LogMessage(level = WARN)
@Message(id = 3, value = "Unable to read attribute %s on %s: %s.")
void unableToReadAttribute(String attributeName, PathAddress address, String error);
@LogMessage(level = WARN)
@Message(id = 4, value = "Unable to convert attribute %s on %s to Double value.")
void unableToConvertAttribute(String attributeName, PathAddress address, @Cause Exception exception);
@LogMessage(level = ERROR)
@Message(id = 5, value = "Malformed name.")
void malformedName(@Cause Exception exception);
}
| 2,933 | 40.323944 | 105 |
java
|
null |
wildfly-main/metrics/src/main/java/org/wildfly/extension/metrics/deployment/DeploymentMetricService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.metrics.deployment;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEPLOYMENT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBDEPLOYMENT;
import static org.wildfly.extension.metrics.MetricsSubsystemDefinition.METRICS_REGISTRY_RUNTIME_CAPABILITY;
import static org.wildfly.extension.metrics.MetricsSubsystemDefinition.WILDFLY_COLLECTOR;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.function.Supplier;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.server.ServerService;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentCompleteServiceProcessor;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.msc.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
import org.wildfly.extension.metrics.MetricCollector;
import org.wildfly.extension.metrics.MetricRegistration;
import org.wildfly.extension.metrics.MetricRegistry;
public class DeploymentMetricService implements Service {
private final Resource rootResource;
private final ManagementResourceRegistration managementResourceRegistration;
private PathAddress deploymentAddress;
private final Supplier<MetricCollector> metricCollector;
private Supplier<MetricRegistry> metricRegistry;
private Supplier<Executor> managementExecutor;
private final boolean exposeAnySubsystem;
private final List<String> exposedSubsystems;
private final String prefix;
private MetricRegistration registration;
public static void install(ServiceTarget serviceTarget, DeploymentUnit deploymentUnit, Resource rootResource, ManagementResourceRegistration managementResourceRegistration, boolean exposeAnySubsystem, List<String> exposedSubsystems, String prefix) {
PathAddress deploymentAddress = createDeploymentAddressPrefix(deploymentUnit);
ServiceBuilder<?> sb = serviceTarget.addService(deploymentUnit.getServiceName().append("metrics"));
Supplier<MetricCollector> metricCollector = sb.requires(WILDFLY_COLLECTOR);
Supplier<MetricRegistry> metricRegistry = sb.requires(METRICS_REGISTRY_RUNTIME_CAPABILITY.getCapabilityServiceName());
Supplier<Executor> managementExecutor = sb.requires(ServerService.EXECUTOR_CAPABILITY.getCapabilityServiceName());
/*
* The deployment metric service depends on the deployment complete service name to ensure that the metrics from
* the deployment are collected and registered once the deployment services have all been properly installed.
*/
sb.requires(DeploymentCompleteServiceProcessor.serviceName(deploymentUnit.getServiceName()));
sb.setInstance(new DeploymentMetricService(rootResource, managementResourceRegistration, deploymentAddress, metricCollector, metricRegistry, managementExecutor,
exposeAnySubsystem, exposedSubsystems, prefix))
.install();
}
private DeploymentMetricService(Resource rootResource, ManagementResourceRegistration managementResourceRegistration, PathAddress deploymentAddress,
Supplier<MetricCollector> metricCollector, Supplier<MetricRegistry> metricRegistry,
Supplier<Executor> managementExecutor, boolean exposeAnySubsystem, List<String> exposedSubsystems, String prefix) {
this.rootResource = rootResource;
this.managementResourceRegistration = managementResourceRegistration;
this.deploymentAddress = deploymentAddress;
this.metricCollector = metricCollector;
this.metricRegistry = metricRegistry;
this.managementExecutor = managementExecutor;
this.exposeAnySubsystem = exposeAnySubsystem;
this.exposedSubsystems = exposedSubsystems;
this.prefix = prefix;
}
@Override
public void start(StartContext startContext) {
final Runnable task = new Runnable() {
@Override
public void run() {
registration = new MetricRegistration(metricRegistry.get());
metricCollector.get().collectResourceMetrics(rootResource,
managementResourceRegistration,
// prepend the deployment address to the subsystem resource address
address -> deploymentAddress.append(address),
exposeAnySubsystem, exposedSubsystems, prefix,
registration);
startContext.complete();
}
};
try {
managementExecutor.get().execute(task);
} catch (RejectedExecutionException e) {
task.run();
} finally {
startContext.asynchronous();
}
}
@Override
public void stop(StopContext stopContext) {
registration.unregister();
}
private static PathAddress createDeploymentAddressPrefix(DeploymentUnit deploymentUnit) {
if (deploymentUnit.getParent() == null) {
return PathAddress.pathAddress(DEPLOYMENT, deploymentUnit.getAttachment(Attachments.MANAGEMENT_NAME));
} else {
return createDeploymentAddressPrefix(deploymentUnit.getParent()).append(SUBDEPLOYMENT, deploymentUnit.getName());
}
}
}
| 6,689 | 48.555556 | 253 |
java
|
null |
wildfly-main/metrics/src/main/java/org/wildfly/extension/metrics/deployment/DeploymentMetricProcessor.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.metrics.deployment;
import java.util.List;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.server.deployment.DeploymentModelUtils;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.wildfly.extension.metrics.MetricCollector;
public class DeploymentMetricProcessor implements DeploymentUnitProcessor {
public static final AttachmentKey<MetricCollector> METRICS_COLLECTOR = AttachmentKey.create(MetricCollector.class);
private final boolean exposeAnySubsystem;
private final List<String> exposedSubsystems;
private final String prefix;
private Resource rootResource;
private ManagementResourceRegistration managementResourceRegistration;
public DeploymentMetricProcessor(boolean exposeAnySubsystem, List<String> exposedSubsystems, String prefix) {
this.exposeAnySubsystem = exposeAnySubsystem;
this.exposedSubsystems = exposedSubsystems;
this.prefix = prefix;
}
@Override
public void deploy(DeploymentPhaseContext phaseContext) {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
rootResource = deploymentUnit.getAttachment(DeploymentModelUtils.DEPLOYMENT_RESOURCE);
managementResourceRegistration = deploymentUnit.getAttachment(DeploymentModelUtils.MUTABLE_REGISTRATION_ATTACHMENT);
DeploymentMetricService.install(phaseContext.getServiceTarget(), deploymentUnit, rootResource, managementResourceRegistration,
exposeAnySubsystem, exposedSubsystems, prefix);
}
}
| 2,849 | 43.53125 | 134 |
java
|
null |
wildfly-main/metrics/src/main/java/org/wildfly/extension/metrics/jmx/JmxMetricMetadata.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.metrics.jmx;
import java.util.List;
import org.jboss.as.controller.client.helpers.MeasurementUnit;
import org.wildfly.extension.metrics.MetricID;
import org.wildfly.extension.metrics.MetricMetadata;
class JmxMetricMetadata implements MetricMetadata {
private final String name;
private final String description;
private final MeasurementUnit unit;
private final Type type;
private final String mbean;
private final MetricID metricID;
private List<String> tagsToFill;
private List<MetricTag> tags;
JmxMetricMetadata(String name, String description, MeasurementUnit unit, Type type, String mbean, List<String> tagsToFill, List<MetricTag> tags) {
this.name = name;
this.description = description;
this.unit = unit;
this.type = type;
this.mbean = mbean;
this.tagsToFill = tagsToFill;
this.tags = tags;
this.metricID = new MetricID(name, tags.toArray(new MetricTag[0]));
}
String getMBean() {
return mbean;
}
List<String> getTagsToFill() {
return tagsToFill;
}
@Override
public MetricID getMetricID() {
return metricID;
}
@Override
public String getMetricName() {
return name;
}
@Override
public MetricTag[] getTags() {
return tags.toArray(new MetricTag[0]);
}
@Override
public String getDescription() {
return description;
}
@Override
public Type getType() {
return type;
}
@Override
public MeasurementUnit getMeasurementUnit() {
return unit;
}
}
| 2,664 | 28.94382 | 150 |
java
|
null |
wildfly-main/metrics/src/main/java/org/wildfly/extension/metrics/jmx/JmxMetricCollector.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.metrics.jmx;
import static org.jboss.as.controller.client.helpers.MeasurementUnit.NONE;
import static org.wildfly.common.Assert.checkNotNullParam;
import static org.wildfly.extension.metrics._private.MetricsLogger.LOGGER;
import java.io.IOException;
import java.io.InputStream;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.OptionalDouble;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import org.jboss.as.controller.client.helpers.MeasurementUnit;
import org.wildfly.extension.metrics.Metric;
import org.wildfly.extension.metrics.MetricMetadata;
import org.wildfly.extension.metrics.MetricRegistry;
public class JmxMetricCollector {
private final MBeanServer mbs;
private MetricRegistry registry;
public JmxMetricCollector(MetricRegistry registry) {
this.registry = registry;
this.mbs = ManagementFactory.getPlatformMBeanServer();
}
public void init() throws IOException {
register("jmx-metrics.properties", registry);
}
private void register(String propertiesFile, MetricRegistry registry) throws IOException {
List<JmxMetricMetadata> configs = findMetadata(propertiesFile);
// expand multi mbeans
List<JmxMetricMetadata> expandedConfigs = new ArrayList<>();
Iterator<JmxMetricMetadata> iterator = configs.iterator();
while (iterator.hasNext()) {
JmxMetricMetadata metadata = iterator.next();
if (metadata.getTagsToFill().isEmpty()) {
continue;
}
try {
String[] split = metadata.getMBean().split("/");
String query = split[0];
String attribute = split[1];
Set<ObjectName> objectNames = mbs.queryNames(ObjectName.getInstance(query), null);
for (ObjectName objectName : objectNames) {
// fill the tags from the object names fields
List<MetricMetadata.MetricTag> tags = new ArrayList<>(metadata.getTagsToFill().size());
for (String key : metadata.getTagsToFill()) {
String value = objectName.getKeyProperty(key);
tags.add(new MetricMetadata.MetricTag(key, value));
}
expandedConfigs.add(new JmxMetricMetadata(metadata.getMetricName(),
metadata.getDescription(),
metadata.getMeasurementUnit(),
metadata.getType(),
objectName.getCanonicalName() + "/" + attribute,
Collections.emptyList(),
tags));
}
// now, it has been expanded, remove the "multi" mbean
iterator.remove();
} catch (MalformedObjectNameException e) {
LOGGER.malformedName(e);
}
}
configs.addAll(expandedConfigs);
for (JmxMetricMetadata config : configs) {
register(registry, config);
}
}
void register(MetricRegistry registry, JmxMetricMetadata metadata) {
Metric metric = new Metric() {
@Override
public OptionalDouble getValue() {
try {
return getValueFromMBean(mbs, metadata.getMBean());
} catch (Exception e) {
return OptionalDouble.empty();
}
}
};
registry.registerMetric(metric, metadata);
}
private List<JmxMetricMetadata> findMetadata(String propertiesFile) throws IOException {
try (
InputStream propertiesResource = getResource(propertiesFile)) {
if (propertiesResource == null) {
return Collections.emptyList();
}
return loadMetadataFromProperties(propertiesResource);
}
}
List<JmxMetricMetadata> loadMetadataFromProperties(InputStream propertiesResource) throws IOException {
Properties props = new Properties();
props.load(propertiesResource);
Map<String, List<MetricProperty>> parsedMetrics = props.entrySet()
.stream()
.map(MetricProperty::new)
.collect(Collectors.groupingBy(MetricProperty::getMetricName));
return parsedMetrics.entrySet()
.stream()
.map(this::metadataOf)
.sorted(Comparator.comparing(e -> e.getMetricName()))
.collect(Collectors.toList());
}
private InputStream getResource(String location) {
InputStream is = getClass().getResourceAsStream(location);
if (is == null) {
is = Thread.currentThread().getContextClassLoader().getResourceAsStream(location);
}
return is;
}
private JmxMetricMetadata metadataOf(Map.Entry<String, List<MetricProperty>> metadataEntry) {
String name = metadataEntry.getKey();
Map<String, String> entryProperties = new HashMap<>();
metadataEntry.getValue()
.forEach(
prop -> entryProperties.put(prop.propertyKey, prop.propertyValue));
List<String> tagsToFill = new ArrayList<>();
if (entryProperties.containsKey("tagsToFill")) {
tagsToFill = Arrays.asList(entryProperties.get("tagsToFill").split(","));
}
final MeasurementUnit unit = (entryProperties.get("unit") == null) ? NONE : MeasurementUnit.valueOf(entryProperties.get("unit").toUpperCase());
JmxMetricMetadata metadata = new JmxMetricMetadata(name,
entryProperties.get("description"),
unit,
MetricMetadata.Type.valueOf(entryProperties.get("type").toUpperCase()),
entryProperties.get("mbean"),
tagsToFill,
Collections.emptyList());
return metadata;
}
private static class MetricProperty {
MetricProperty(Map.Entry<Object, Object> keyValue) {
String key = (String) keyValue.getKey();
int propertyIdEnd = key.lastIndexOf('.');
metricName = key.substring(0, propertyIdEnd);
propertyKey = key.substring(propertyIdEnd + 1);
propertyValue = (String) keyValue.getValue();
}
String metricName;
String propertyKey;
String propertyValue;
String getMetricName() {
return metricName;
}
}
private static OptionalDouble getValueFromMBean(MBeanServer mbs, String mbeanExpression) {
checkNotNullParam("mbs", mbs);
checkNotNullParam("mbeanExpression", mbeanExpression);
if (!mbeanExpression.contains("/")) {
throw new IllegalArgumentException(mbeanExpression);
}
int slashIndex = mbeanExpression.indexOf('/');
String mbean = mbeanExpression.substring(0, slashIndex);
String attName = mbeanExpression.substring(slashIndex + 1);
String subItem = null;
if (attName.contains("#")) {
int hashIndex = attName.indexOf('#');
subItem = attName.substring(hashIndex + 1);
attName = attName.substring(0, hashIndex);
}
try {
ObjectName objectName = new ObjectName(mbean);
Object attribute = mbs.getAttribute(objectName, attName);
if (attribute instanceof Number) {
Number num = (Number) attribute;
return OptionalDouble.of(num.doubleValue());
} else if (attribute instanceof CompositeData) {
CompositeData compositeData = (CompositeData) attribute;
Number num = (Number) compositeData.get(subItem);
return OptionalDouble.of(num.doubleValue());
} else {
return OptionalDouble.empty();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 9,465 | 38.441667 | 151 |
java
|
null |
wildfly-main/jaxrs/src/test/java/org/jboss/as/jaxrs/JaxrsSubsystemTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jaxrs;
import java.io.IOException;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.junit.Test;
/**
* @author <a href="[email protected]">Kabir Khan</a>
*/
public class JaxrsSubsystemTestCase extends AbstractSubsystemBaseTest {
public JaxrsSubsystemTestCase() {
super(JaxrsExtension.SUBSYSTEM_NAME, new JaxrsExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
return "<subsystem xmlns=\"urn:jboss:domain:jaxrs:1.0\"/>";
}
@Override
protected String getSubsystemXsdPath() throws Exception {
return "schema/jboss-as-jaxrs_1_0.xsd";
}
@Test
@Override
public void testSubsystem() throws Exception {
standardSubsystemTest(null, false);
}
}
| 1,814 | 32.611111 | 71 |
java
|
null |
wildfly-main/jaxrs/src/test/java/org/jboss/as/jaxrs/JaxrsSubsystem20MinimalTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, 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.jaxrs;
import java.io.IOException;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
/**
* @author <a href="[email protected]">Kabir Khan</a>
* @author <a href="mailto:[email protected]>Jim Ma</a>
* @author <a href="mailto:[email protected]>Alessio Soldano</a>
* @author <a href="[email protected]>Ron Sigal</a>
*/
public class JaxrsSubsystem20MinimalTestCase extends AbstractSubsystemBaseTest {
public JaxrsSubsystem20MinimalTestCase() {
super(JaxrsExtension.SUBSYSTEM_NAME, new JaxrsExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource("jaxrs-2.0_minimal.xml");
}
@Override
protected String getSubsystemXsdPath() throws Exception {
return "schema/jboss-as-jaxrs_2_0.xsd";
}
@Override
public void testSubsystem() throws Exception {
standardSubsystemTest(null, false);
}
}
| 1,983 | 35.072727 | 80 |
java
|
null |
wildfly-main/jaxrs/src/test/java/org/jboss/as/jaxrs/JaxrsSubsystem30TestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, 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.jaxrs;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.List;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.model.test.FailedOperationTransformationConfig;
import org.jboss.as.model.test.ModelTestControllerVersion;
import org.jboss.as.model.test.ModelTestUtils;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.as.subsystem.test.KernelServicesBuilder;
import org.jboss.as.subsystem.test.LegacyKernelServicesInitializer;
import org.jboss.dmr.ModelNode;
import org.junit.Test;
/**
* @author <a href="mailto:[email protected]">James R. Perkins</a>
*/
public class JaxrsSubsystem30TestCase extends AbstractSubsystemBaseTest {
public JaxrsSubsystem30TestCase() {
super(JaxrsExtension.SUBSYSTEM_NAME, new JaxrsExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource("jaxrs.xml");
}
@Override
protected String getSubsystemXsdPath() throws Exception {
return "schema/jboss-as-jaxrs_3_0.xsd";
}
@Override
public void testSubsystem() throws Exception {
standardSubsystemTest(null);
}
@Test
public void testExpressions() throws Exception {
standardSubsystemTest("jaxrs-expressions.xml");
}
@Test
public void testRejectingTransformersEAP74() throws Exception {
FailedOperationTransformationConfig transformationConfig = new FailedOperationTransformationConfig();
transformationConfig.addFailedAttribute(PathAddress.pathAddress(JaxrsExtension.SUBSYSTEM_PATH),
new FailedOperationTransformationConfig.NewAttributesConfig(JaxrsAttribute.TRACING_TYPE, JaxrsAttribute.TRACING_THRESHOLD));
testRejectingTransformers(transformationConfig, ModelTestControllerVersion.EAP_7_4_0);
}
private void testRejectingTransformers(FailedOperationTransformationConfig transformationConfig, ModelTestControllerVersion controllerVersion) throws Exception {
ModelVersion subsystemModelVersion = controllerVersion.getSubsystemModelVersion(JaxrsExtension.SUBSYSTEM_NAME);
KernelServicesBuilder builder = createKernelServicesBuilder(createAdditionalInitialization());
LegacyKernelServicesInitializer kernelServicesInitializer = builder.createLegacyKernelServicesBuilder(createAdditionalInitialization(), controllerVersion, subsystemModelVersion)
.addMavenResourceURL("org.wildfly.core:wildfly-threads:" + controllerVersion.getCoreVersion())
.dontPersistXml();
kernelServicesInitializer.addMavenResourceURL("org.wildfly:wildfly-jaxrs:26.0.0.Final");
KernelServices kernelServices = builder.build();
assertTrue(kernelServices.isSuccessfulBoot());
assertTrue(kernelServices.getLegacyServices(subsystemModelVersion).isSuccessfulBoot());
List<ModelNode> operations = builder.parseXmlResource("jaxrs.xml");
ModelTestUtils.checkFailedTransformedBootOperations(kernelServices, subsystemModelVersion, operations, transformationConfig);
}
}
| 4,254 | 43.322917 | 185 |
java
|
null |
wildfly-main/jaxrs/src/test/java/org/jboss/as/jaxrs/JaxrsSubsystem20TestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, 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.jaxrs;
import java.io.IOException;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.junit.Test;
/**
* @author <a href="[email protected]">Kabir Khan</a>
* @author <a href="mailto:[email protected]>Jim Ma</a>
* @author <a href="mailto:[email protected]>Alessio Soldano</a>
* @author <a href="[email protected]>Ron Sigal</a>
*/
public class JaxrsSubsystem20TestCase extends AbstractSubsystemBaseTest {
public JaxrsSubsystem20TestCase() {
super(JaxrsExtension.SUBSYSTEM_NAME, new JaxrsExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource("jaxrs-2.0.xml");
}
@Override
protected String getSubsystemXsdPath() throws Exception {
return "schema/jboss-as-jaxrs_2_0.xsd";
}
@Override
public void testSubsystem() throws Exception {
standardSubsystemTest(null, false);
}
@Test
public void testExpressions() throws Exception {
standardSubsystemTest("jaxrs-2.0-expressions.xml", false);
}
}
| 2,121 | 33.786885 | 73 |
java
|
null |
wildfly-main/jaxrs/src/test/java/org/jboss/as/jaxrs/JaxrsMethodParameterProcessorTestCase.java
|
package org.jboss.as.jaxrs;
import org.jboss.as.jaxrs.deployment.JaxrsMethodParameterProcessor;
import org.jboss.as.jaxrs.deployment.ResteasyDeploymentData;
import org.jboss.as.jaxrs.rsources.SimpleClassLazyParamConverter;
import org.jboss.as.jaxrs.rsources.PrimitiveParamResource;
import org.jboss.as.jaxrs.rsources.SimpleClassParamConverterProvider;
import org.jboss.as.jaxrs.rsources.SimpleClassParameterizedTypeResource;
import org.jboss.as.jaxrs.rsources.SimpleFromStringProvider;
import org.jboss.as.jaxrs.rsources.SimpleFromStringResource;
import org.jboss.as.jaxrs.rsources.SimpleFromValueProvider;
import org.jboss.as.jaxrs.rsources.SimpleFromValueResource;
import org.jboss.as.jaxrs.rsources.SimpleValueOfProvider;
import org.jboss.as.jaxrs.rsources.SimpleClassParamConverterResource;
import org.jboss.as.jaxrs.rsources.SimpleValueOfResource;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.Set;
public class JaxrsMethodParameterProcessorTestCase {
private ResteasyDeploymentData resteasyDeploymentData;
private Set<String> resources;
private Set<String> providers;
@Before
public void before() {
resteasyDeploymentData = new ResteasyDeploymentData();
resources = resteasyDeploymentData.getScannedResourceClasses();
providers = resteasyDeploymentData.getScannedProviderClasses();
}
/**
* Check that a custom datatype is process by the ParamConverterProvider.
* The provider throws an exception by design.
*
* @throws Exception
*/
@Test
public void customParameterTest() throws Exception {
providers.clear();
resources.clear();
providers.add(SimpleClassParamConverterProvider.class.getName());
resources.add(SimpleClassParamConverterResource.class.getName());
JaxrsMethodParameterProcessor jProcessor = new JaxrsMethodParameterProcessor();
try {
jProcessor.testProcessor(Thread.currentThread().getContextClassLoader(),
resteasyDeploymentData);
} catch (Exception e) {
Assert.fail("Test failed. It should not have thrown an exception: " +e);
}
}
@Test
public void customParameterizedTypeTest() throws Exception {
providers.clear();
resources.clear();
providers.add(SimpleClassParamConverterProvider.class.getName());
resources.add(SimpleClassParameterizedTypeResource.class.getName());
JaxrsMethodParameterProcessor jProcessor = new JaxrsMethodParameterProcessor();
try {
jProcessor.testProcessor(Thread.currentThread().getContextClassLoader(),
resteasyDeploymentData);
} catch (Exception e) {
Assert.fail("Test failed. It should not have thrown an exception: " +e);
}
}
/**
* Check the primitive datatypes are not processed by any converter.
* @throws Exception
*/
@Test
public void primitiveParameterTest() throws Exception {
providers.clear();
resources.clear();
providers.add(SimpleClassParamConverterProvider.class.getName());
resources.add(PrimitiveParamResource.class.getName());
JaxrsMethodParameterProcessor jProcessor = new JaxrsMethodParameterProcessor();
try {
jProcessor.testProcessor(Thread.currentThread().getContextClassLoader(),
resteasyDeploymentData);
} catch (Exception e) {
Assert.fail("Test failed no exception should have been thrown");
}
}
@Test
public void fromValueTest() throws Exception {
providers.clear();
resources.clear();
providers.add(SimpleFromValueProvider.class.getName());
resources.add(SimpleFromValueResource.class.getName());
JaxrsMethodParameterProcessor jProcessor = new JaxrsMethodParameterProcessor();
try {
jProcessor.testProcessor(Thread.currentThread().getContextClassLoader(),
resteasyDeploymentData);
} catch (Exception e) {
Assert.fail("Test failed. It should not have thrown an exception: " +e);
}
}
@Test
public void fromStringTest() throws Exception {
providers.clear();
resources.clear();
providers.add(SimpleFromStringProvider.class.getName());
resources.add(SimpleFromStringResource.class.getName());
JaxrsMethodParameterProcessor jProcessor = new JaxrsMethodParameterProcessor();
try {
jProcessor.testProcessor(Thread.currentThread().getContextClassLoader(),
resteasyDeploymentData);
} catch (Exception e) {
Assert.fail("Test failed. It should not have thrown an exception: " +e);
}
}
@Test
public void valueOfTest() throws Exception {
providers.clear();
resources.clear();
providers.add(SimpleValueOfProvider.class.getName());
resources.add(SimpleValueOfResource.class.getName());
JaxrsMethodParameterProcessor jProcessor = new JaxrsMethodParameterProcessor();
try {
jProcessor.testProcessor(Thread.currentThread().getContextClassLoader(),
resteasyDeploymentData);
} catch (Exception e) {
Assert.fail("Test failed. It should not have thrown an exception: " +e);
}
}
@Test
public void lazyLoadAnnotationTest() throws Exception {
providers.clear();
resources.clear();
providers.add(SimpleClassLazyParamConverter.class.getName());
resources.add(SimpleClassParamConverterResource.class.getName());
JaxrsMethodParameterProcessor jProcessor = new JaxrsMethodParameterProcessor();
try {
jProcessor.testProcessor(Thread.currentThread().getContextClassLoader(),
resteasyDeploymentData);
} catch (Exception e) {
Assert.fail("Test failed. It should not have thrown an exception: " +e);
}
}
}
| 6,058 | 35.945122 | 87 |
java
|
null |
wildfly-main/jaxrs/src/test/java/org/jboss/as/jaxrs/rsources/SimpleClassLazyParamConverter.java
|
package org.jboss.as.jaxrs.rsources;
import jakarta.ws.rs.ext.ParamConverter;
@ParamConverter.Lazy
public class SimpleClassLazyParamConverter implements ParamConverter<SimpleClass> {
@Override
public SimpleClass fromString(String value) {
throw new RuntimeException("Force a failure");
}
@Override
public String toString(SimpleClass value) {
return value.toString();
}
}
| 414 | 23.411765 | 83 |
java
|
null |
wildfly-main/jaxrs/src/test/java/org/jboss/as/jaxrs/rsources/SimpleFromStringProvider.java
|
package org.jboss.as.jaxrs.rsources;
public class SimpleFromStringProvider {
public static String fromString(String s) {
throw new RuntimeException("Force error");
}
}
| 185 | 22.25 | 50 |
java
|
null |
wildfly-main/jaxrs/src/test/java/org/jboss/as/jaxrs/rsources/SimpleValueOfProvider.java
|
package org.jboss.as.jaxrs.rsources;
public class SimpleValueOfProvider {
public static String valueOf(String s) {
throw new RuntimeException("Force error");
}
}
| 180 | 19.111111 | 50 |
java
|
null |
wildfly-main/jaxrs/src/test/java/org/jboss/as/jaxrs/rsources/SimpleFromValueProvider.java
|
package org.jboss.as.jaxrs.rsources;
public class SimpleFromValueProvider {
public String fromValue(String s) {
throw new RuntimeException("Force error");
}
}
| 177 | 18.777778 | 50 |
java
|
null |
wildfly-main/jaxrs/src/test/java/org/jboss/as/jaxrs/rsources/SimpleClassParameterizedTypeResource.java
|
package org.jboss.as.jaxrs.rsources;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.QueryParam;
import java.util.List;
@Path("/parameterizedtype")
public class SimpleClassParameterizedTypeResource {
@GET
public void testQueryParam(@DefaultValue("101")
@QueryParam("111") List<SimpleClass> param) {
List<SimpleClass> xparam = param;
}
}
| 451 | 25.588235 | 76 |
java
|
null |
wildfly-main/jaxrs/src/test/java/org/jboss/as/jaxrs/rsources/PrimitiveParamResource.java
|
package org.jboss.as.jaxrs.rsources;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.QueryParam;
@Path("/primitive")
public class PrimitiveParamResource {
@GET
public String doGet(@QueryParam("boolean") @DefaultValue("true") boolean v) {
return "content";
}
@GET
public String doGet(@QueryParam("byte") @DefaultValue("127") byte v) {
return "content";
}
@GET
public String doGet(@QueryParam("short") @DefaultValue("32767") short v) {
return "content";
}
@GET
public String doGet(@QueryParam("int") @DefaultValue("2147483647") int v) {
return "content";
}
@GET
public String doGet(@QueryParam("long") @DefaultValue("9223372036854775807") long v) {
return "content";
}
@GET
public String doGet(@QueryParam("float") @DefaultValue("3.14159265") float v) {
return "content";
}
@GET
public String doGet(@QueryParam("double") @DefaultValue("3.14159265358979") double v) {
return "content";
}
@GET
public String doGet(@QueryParam("char") @DefaultValue("a") char v) {
return "content";
}
}
| 1,212 | 23.26 | 91 |
java
|
null |
wildfly-main/jaxrs/src/test/java/org/jboss/as/jaxrs/rsources/SimpleClass.java
|
package org.jboss.as.jaxrs.rsources;
public class SimpleClass {
private Integer value;
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
@Override
public String toString() {
return value.toString();
}
}
| 318 | 14.95 | 41 |
java
|
null |
wildfly-main/jaxrs/src/test/java/org/jboss/as/jaxrs/rsources/SimpleClassParamConverterProvider.java
|
package org.jboss.as.jaxrs.rsources;
import jakarta.ws.rs.ext.ParamConverter;
import jakarta.ws.rs.ext.ParamConverterProvider;
import jakarta.ws.rs.ext.Provider;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
@Provider
public class SimpleClassParamConverterProvider implements ParamConverterProvider {
@Override
public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType,
Annotation[] annotations) {
if (rawType.getName().equals(SimpleClass.class.getName())) {
return new ParamConverter<T>() {
@Override
public T fromString(String value) {
throw new RuntimeException("Force a failure");
}
@Override
public String toString(T value) {
return value.toString();
}
};
}
return null;
}
}
| 969 | 31.333333 | 82 |
java
|
null |
wildfly-main/jaxrs/src/test/java/org/jboss/as/jaxrs/rsources/SimpleFromValueResource.java
|
package org.jboss.as.jaxrs.rsources;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.QueryParam;
@Path("fromValue")
public class SimpleFromValueResource {
@GET
public String get(@DefaultValue("defaulFromValue")
@QueryParam("newValue") SimpleFromValueProvider p) {
return "done";
}
}
| 388 | 23.3125 | 74 |
java
|
null |
wildfly-main/jaxrs/src/test/java/org/jboss/as/jaxrs/rsources/SimpleClassParamConverterResource.java
|
package org.jboss.as.jaxrs.rsources;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.QueryParam;
@Path("/simpleclass")
public class SimpleClassParamConverterResource {
@GET
public void testQueryParam(@DefaultValue("101")
@QueryParam("111") SimpleClass param) {
SimpleClass xparam = param;
}
}
| 407 | 24.5 | 70 |
java
|
null |
wildfly-main/jaxrs/src/test/java/org/jboss/as/jaxrs/rsources/SimpleValueOfResource.java
|
package org.jboss.as.jaxrs.rsources;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.QueryParam;
@Path("valueof")
public class SimpleValueOfResource {
@GET
public String get(@DefaultValue("defaulValueOf")
@QueryParam("newValueOf") SimpleValueOfProvider p) {
return "done";
}
}
| 382 | 22.9375 | 74 |
java
|
null |
wildfly-main/jaxrs/src/test/java/org/jboss/as/jaxrs/rsources/SimpleFromStringResource.java
|
package org.jboss.as.jaxrs.rsources;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.QueryParam;
@Path("fromString")
public class SimpleFromStringResource {
@GET
public String get(@DefaultValue("defaulFromString")
@QueryParam("newString") SimpleFromStringProvider p) {
return "done";
}
}
| 393 | 23.625 | 76 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/JaxrsSubsystemParser_1_0.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2019, 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.jaxrs;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoAttributes;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoContent;
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.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLExtendedStreamReader;
public class JaxrsSubsystemParser_1_0 implements XMLStreamConstants, XMLElementReader<List<ModelNode>> {
/**
* {@inheritDoc}
*/
@Override
public void readElement(final XMLExtendedStreamReader reader, final List<ModelNode> list) throws XMLStreamException {
// Require no attributes or content
requireNoAttributes(reader);
requireNoContent(reader);
list.add(Util.createAddOperation(PathAddress.pathAddress(JaxrsExtension.SUBSYSTEM_PATH)));
}
}
| 2,043 | 39.88 | 121 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/JaxrsAnnotations.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.jaxrs;
import org.jboss.jandex.DotName;
/**
* Class that stores the {@link DotName}s of Jakarta RESTful Web Services annotations
*
* @author Stuart Douglas
*
*/
public enum JaxrsAnnotations {
CONSUMES("Consumes"),
COOKIE_PARAM("CookieParam"),
DEFAULT_VALUE("DefaultValue"),
DELETE("DELETE"),
ENCODED("Encoded"),
FORM_PARAM("FormParam"),
GET("GET"),
HEAD("HEAD"),
HEADER_PARAM("HeaderParam"),
HTTP_METHOD("HttpMethod"),
MATRIX_PARAM("MatrixParam"),
PATH("Path"),
PATH_PARAM("PathParam"),
POST("POST"),
PRODUCES("Produces"),
PUT("PUT"),
QUERY_PARAM("QueryParam"),
CONTEXT(Constants.JAVAX_WS_CORE,"Context"),
PROVIDER(Constants.JAVAX_WS_EXT,"Provider"),
APPLICATION_PATH("ApplicationPath");
private final String simpleName;
private final DotName dotName;
private JaxrsAnnotations(String simpleName) {
this.simpleName = simpleName;
this.dotName = DotName.createComponentized(Constants.JAVAX_WS_RS, simpleName);
}
private JaxrsAnnotations(DotName prefix,String simpleName) {
this.simpleName = simpleName;
this.dotName = DotName.createComponentized(prefix, simpleName);
}
// this can't go on the enum itself
private static class Constants {
public static final DotName JAVAX;
static {
// The odd split here of the namespace prefix is due to a custom rule in Batavia for this type
String p1 = "ja";
String p2;
try {
Class.forName("jakarta.ws.rs.ApplicationPath", false, JaxrsAnnotations.class.getClassLoader());
p2 = "karta";
} catch (ClassNotFoundException ignore) {
p2 = "vax";
}
JAVAX = DotName.createComponentized(null, p1 + p2);
}
public static final DotName JAVAX_WS = DotName.createComponentized(JAVAX, "ws");
public static final DotName JAVAX_WS_RS = DotName.createComponentized(JAVAX_WS, "rs");
public static final DotName JAVAX_WS_CORE = DotName.createComponentized(JAVAX_WS_RS, "core");
public static final DotName JAVAX_WS_EXT = DotName.createComponentized(JAVAX_WS_RS, "ext");
}
public DotName getDotName() {
return dotName;
}
public String getSimpleName() {
return simpleName;
}
}
| 3,408 | 33.785714 | 111 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/JacksonAnnotations.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2018, 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.jaxrs;
import org.jboss.jandex.DotName;
/**
* Class that stores the {@link DotName}s of Jackson annotations
*
* @author Alessio Soldano
*
*/
public enum JacksonAnnotations {
JacksonAnnotation("JacksonAnnotation"),
JsonAnyGetter("JsonAnyGetter"),
JsonAnySetter("JsonAnySetter"),
JsonAutoDetect("JsonAutoDetect"),
JsonBackReference("JsonBackReference"),
JsonCreator("JsonCreator"),
JsonGetter("JsonGetter"),
JsonIgnore("JsonIgnore"),
JsonIgnoreProperties("JsonIgnoreProperties"),
JsonIgnoreType("JsonIgnoreType"),
JsonManagedReference("JsonManagedReference"),
JsonProperty("JsonProperty"),
JsonPropertyOrder("JsonPropertyOrder"),
JsonRawValue("JsonRawValue"),
JsonSetter("JsonSetter"),
JsonSubTypes("JsonSubTypes"),
JsonTypeInfo("JsonTypeInfo"),
JsonTypeName("JsonTypeName"),
JsonUnwrapped("JsonUnwrapped"),
JsonValue("JsonValue"),
JsonWriteNullProperties("JsonWriteNullProperties");
private final String simpleName;
private final DotName dotName;
private JacksonAnnotations(String simpleName) {
this.simpleName = simpleName;
this.dotName = DotName.createComponentized(Constants.ANNOTATE, simpleName);
}
// this can't go on the enum itself
private static class Constants {
//org.codehaus.jackson.annotate
public static final DotName ORG = DotName.createComponentized(null, "org");
public static final DotName CODEHAUS = DotName.createComponentized(ORG, "codehaus");
public static final DotName JACKSON = DotName.createComponentized(CODEHAUS, "jackson");
public static final DotName ANNOTATE = DotName.createComponentized(JACKSON, "annotate");
}
public DotName getDotName() {
return dotName;
}
public String getSimpleName() {
return simpleName;
}
}
| 2,896 | 34.765432 | 96 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/Jackson2Annotations.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2018, 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.jaxrs;
import org.jboss.jandex.DotName;
/**
* Class that stores the {@link DotName}s of Jackson2 annotations
*
* @author Alessio Soldano
*
*/
public enum Jackson2Annotations {
JacksonAnnotation("JacksonAnnotation"),
JacksonInject("JacksonInject"),
JsonAnyGetter("JsonAnyGetter"),
JsonAnySetter("JsonAnySetter"),
JsonAutoDetect("JsonAutoDetect"),
JsonBackReference("JsonBackReference"),
JsonClassDescription("JsonClassDescription"),
JsonCreator("JsonCreator"),
JsonEnumDefaultValue("JsonEnumDefaultValue"),
JsonFilter("JsonFilter"),
JsonFormat("JsonFormat"),
JsonGetter("JsonGetter"),
JsonIdentityInfo("JsonIdentityInfo"),
JsonIdentityReference("JsonIdentityReference"),
JsonIgnore("JsonIgnore"),
JsonIgnoreProperties("JsonIgnoreProperties"),
JsonIgnoreType("JsonIgnoreType"),
JsonInclude("JsonInclude"),
JsonManagedReference("JsonManagedReference"),
JsonProperty("JsonProperty"),
JsonPropertyDescription("JsonPropertyDescription"),
JsonPropertyOrder("JsonPropertyOrder"),
JsonRawValue("JsonRawValue"),
JsonRootName("JsonRootName"),
JsonSetter("JsonSetter"),
JsonSubTypes("JsonSubTypes"),
JsonTypeId("JsonTypeId"),
JsonTypeInfo("JsonTypeInfo"),
JsonTypeName("JsonTypeName"),
JsonUnwrapped("JsonUnwrapped"),
JsonValue("JsonValue"),
JsonView("JsonView");
private final String simpleName;
private final DotName dotName;
private Jackson2Annotations(String simpleName) {
this.simpleName = simpleName;
this.dotName = DotName.createComponentized(Constants.ANNOTATION, simpleName);
}
// this can't go on the enum itself
private static class Constants {
public static final DotName COM = DotName.createComponentized(null, "com");
public static final DotName FASTERXML = DotName.createComponentized(COM, "fasterxml");
public static final DotName JACKSON = DotName.createComponentized(FASTERXML, "jackson");
public static final DotName ANNOTATION = DotName.createComponentized(JACKSON, "annotation");
}
public DotName getDotName() {
return dotName;
}
public String getSimpleName() {
return simpleName;
}
}
| 3,280 | 35.054945 | 100 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/JaxrsExtension.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.jaxrs;
import static org.jboss.as.jaxrs.logging.JaxrsLogger.JAXRS_LOGGER;
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.ResourceDescriptionResolver;
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;
/**
* Domain extension used to initialize the jaxrs subsystem.
*
* @author Stuart Douglas
* @author Emanuel Muckenhuber
*/
public class JaxrsExtension implements Extension {
public static final String SUBSYSTEM_NAME = "jaxrs";
static final ModelVersion CURRENT_MODEL_VERSION = ModelVersion.create(4, 0, 0);
private static final String RESOURCE_NAME = JaxrsExtension.class.getPackage().getName() + ".LocalDescriptions";
static PathElement SUBSYSTEM_PATH = PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, SUBSYSTEM_NAME);
static ResourceDescriptionResolver getResolver(final String... keyPrefix) {
StringBuilder prefix = new StringBuilder(SUBSYSTEM_NAME);
for (String kp : keyPrefix) {
prefix.append('.').append(kp);
}
return new StandardResourceDescriptionResolver(prefix.toString(), RESOURCE_NAME, JaxrsExtension.class.getClassLoader(), true, false);
}
/**
* {@inheritDoc}
*/
@Override
public void initialize(final ExtensionContext context) {
JAXRS_LOGGER.debug("Activating Jakarta RESTful Web Services Extension");
final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION);
final ManagementResourceRegistration registration = subsystem.registerSubsystemModel(new JaxrsSubsystemDefinition());
registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE);
ManagementResourceRegistration jaxrsResReg = subsystem.registerDeploymentModel(new JaxrsDeploymentDefinition());
jaxrsResReg.registerSubModel(new DeploymentRestResourcesDefintion());
subsystem.registerXMLElementWriter(JaxrsSubsystemParser_3_0::new);
}
/**
* {@inheritDoc}
*/
@Override
public void initializeParsers(final ExtensionParsingContext context) {
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, "urn:jboss:domain:jaxrs:1.0", JaxrsSubsystemParser_1_0::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, "urn:jboss:domain:jaxrs:2.0", JaxrsSubsystemParser_2_0::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, "urn:jboss:domain:jaxrs:3.0", JaxrsSubsystemParser_3_0::new);
}
}
| 4,075 | 46.395349 | 141 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/JaxrsSubsystemParser_3_0.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jaxrs;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoAttributes;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
import java.util.EnumSet;
import java.util.List;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.persistence.SubsystemMarshallingContext;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLElementWriter;
import org.jboss.staxmapper.XMLExtendedStreamReader;
import org.jboss.staxmapper.XMLExtendedStreamWriter;
/**
* @author <a href="mailto:[email protected]">Ron Sigal</a>
*/
public class JaxrsSubsystemParser_3_0 extends JaxrsSubsystemParser_2_0 implements XMLStreamConstants, XMLElementReader<List<ModelNode>>, XMLElementWriter<SubsystemMarshallingContext> {
private static final String NAMESPACE = "urn:jboss:domain:jaxrs:3.0";
@Override
public void readElement(final XMLExtendedStreamReader reader, final List<ModelNode> list) throws XMLStreamException {
final PathAddress address = PathAddress.pathAddress(JaxrsExtension.SUBSYSTEM_PATH);
final ModelNode subsystem = Util.createAddOperation(address);
list.add(subsystem);
requireNoAttributes(reader);
final EnumSet<JaxrsElement> encountered = EnumSet.noneOf(JaxrsElement.class);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final JaxrsElement element = JaxrsElement.forName(reader.getLocalName());
switch (element) {
case JAXRS_2_0_REQUEST_MATCHING:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.JAXRS_2_0_REQUEST_MATCHING);
break;
case RESTEASY_ADD_CHARSET:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_ADD_CHARSET);
break;
case RESTEASY_BUFFER_EXCEPTION_ENTITY:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_BUFFER_EXCEPTION_ENTITY);
break;
case RESTEASY_DISABLE_HTML_SANITIZER:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_DISABLE_HTML_SANITIZER);
break;
case RESTEASY_DISABLE_PROVIDERS:
handleList("class", reader, encountered, subsystem, JaxrsElement.RESTEASY_DISABLE_PROVIDERS);
break;
case RESTEASY_DOCUMENT_EXPAND_ENTITY_REFERENCES:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_DOCUMENT_EXPAND_ENTITY_REFERENCES);
break;
case RESTEASY_DOCUMENT_SECURE_DISABLE_DTDS:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_DOCUMENT_SECURE_DISABLE_DTDS);
break;
case RESTEASY_DOCUMENT_SECURE_PROCESSING_FEATURE:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_DOCUMENT_SECURE_PROCESSING_FEATURE);
break;
case RESTEASY_GZIP_MAX_INPUT:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_GZIP_MAX_INPUT);
break;
case RESTEASY_JNDI_RESOURCES:
handleList("jndi", reader, encountered, subsystem, JaxrsElement.RESTEASY_JNDI_RESOURCES);
break;
case RESTEASY_LANGUAGE_MAPPINGS:
handleMap(reader, encountered, subsystem, JaxrsElement.RESTEASY_LANGUAGE_MAPPINGS);
break;
case RESTEASY_MEDIA_TYPE_MAPPINGS:
handleMap(reader, encountered, subsystem, JaxrsElement.RESTEASY_MEDIA_TYPE_MAPPINGS);
break;
case RESTEASY_MEDIA_TYPE_PARAM_MAPPING:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_MEDIA_TYPE_PARAM_MAPPING);
break;
case RESTEASY_PREFER_JACKSON_OVER_JSONB:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_PREFER_JACKSON_OVER_JSONB);
break;
case RESTEASY_PROVIDERS:
handleList("class", reader, encountered, subsystem, JaxrsElement.RESTEASY_PROVIDERS);
break;
case RESTEASY_RFC7232_PRECONDITIONS:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_RFC7232_PRECONDITIONS);
break;
case RESTEASY_ROLE_BASED_SECURITY:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_ROLE_BASED_SECURITY);
break;
case RESTEASY_SECURE_RANDOM_MAX_USE:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_SECURE_RANDOM_MAX_USE);
break;
case RESTEASY_USE_BUILTIN_PROVIDERS:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_USE_BUILTIN_PROVIDERS);
break;
case RESTEASY_USE_CONTAINER_FORM_PARAMS:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_USE_CONTAINER_FORM_PARAMS);
break;
case RESTEASY_WIDER_REQUEST_MATCHING:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_WIDER_REQUEST_MATCHING);
break;
case TRACING_TYPE:
JaxrsAttribute.TRACING_TYPE.parseAndSetParameter(parseSimpleValue(reader, encountered, element), subsystem, reader);
break;
case TRACING_THRESHOLD:
JaxrsAttribute.TRACING_THRESHOLD.parseAndSetParameter(parseSimpleValue(reader, encountered, element), subsystem, reader);
break;
default:
throw unexpectedElement(reader);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void writeContent(final XMLExtendedStreamWriter streamWriter, final SubsystemMarshallingContext context) throws XMLStreamException {
context.startSubsystemElement(NAMESPACE, false);
ModelNode subsystem = context.getModelNode();
for (AttributeDefinition attr : JaxrsAttribute.ATTRIBUTES) {
attr.getMarshaller().marshallAsElement(attr, subsystem, true, streamWriter);
}
streamWriter.writeEndElement();
}
protected String parseSimpleValue(final XMLExtendedStreamReader reader,
final EnumSet<JaxrsElement> encountered,
final JaxrsElement element) throws XMLStreamException {
if (!encountered.add(element)) {
throw unexpectedElement(reader);
}
return parseElementNoAttributes(reader);
}
}
| 8,359 | 44.68306 | 184 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/JaxrsSubsystemDefinition.java
|
/*
* Copyright (C) 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 library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.jboss.as.jaxrs;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.ReloadRequiredRemoveStepHandler;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.RuntimePackageDependency;
/**
*
* @author <a href="mailto:[email protected]">Emmanuel Hugonnet</a> (c) 2014 Red Hat, inc.
*/
public class JaxrsSubsystemDefinition extends SimpleResourceDefinition {
public static final String RESTEASY_ATOM = "org.jboss.resteasy.resteasy-atom-provider";
public static final String RESTEASY_CDI = "org.jboss.resteasy.resteasy-cdi";
public static final String RESTEASY_CLIENT_MICROPROFILE = "org.jboss.resteasy.resteasy-client-microprofile";
public static final String RESTEASY_CRYPTO = "org.jboss.resteasy.resteasy-crypto";
public static final String RESTEASY_VALIDATOR = "org.jboss.resteasy.resteasy-validator-provider";
public static final String RESTEASY_CLIENT = "org.jboss.resteasy.resteasy-client";
public static final String RESTEASY_CLIENT_API = "org.jboss.resteasy.resteasy-client-api";
public static final String RESTEASY_CORE = "org.jboss.resteasy.resteasy-core";
public static final String RESTEASY_CORE_SPI = "org.jboss.resteasy.resteasy-core-spi";
public static final String RESTEASY_JAXB = "org.jboss.resteasy.resteasy-jaxb-provider";
public static final String RESTEASY_JACKSON2 = "org.jboss.resteasy.resteasy-jackson2-provider";
public static final String RESTEASY_JSON_P_PROVIDER = "org.jboss.resteasy.resteasy-json-p-provider";
public static final String RESTEASY_JSON_B_PROVIDER = "org.jboss.resteasy.resteasy-json-binding-provider";
public static final String RESTEASY_JSAPI = "org.jboss.resteasy.resteasy-jsapi";
public static final String RESTEASY_MULTIPART = "org.jboss.resteasy.resteasy-multipart-provider";
public static final String RESTEASY_TRACING = "org.jboss.resteasy.resteasy-tracing-api";
public static final String JACKSON_DATATYPE_JDK8 = "com.fasterxml.jackson.datatype.jackson-datatype-jdk8";
public static final String JACKSON_DATATYPE_JSR310 = "com.fasterxml.jackson.datatype.jackson-datatype-jsr310";
public static final String JAXB_API = "jakarta.xml.bind.api";
public static final String JSON_API = "jakarta.json.api";
public static final String JAXRS_API = "jakarta.ws.rs.api";
public static final String MP_REST_CLIENT = "org.eclipse.microprofile.restclient";
JaxrsSubsystemDefinition() {
super(new Parameters(JaxrsExtension.SUBSYSTEM_PATH, JaxrsExtension.getResolver())
.setAddHandler(new JaxrsSubsystemAdd(JaxrsAttribute.ATTRIBUTES))
.setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE));
}
@Override
public void registerAttributes(ManagementResourceRegistration registration) {
OperationStepHandler handler = new JaxrsParamHandler(JaxrsAttribute.ATTRIBUTES);
for (AttributeDefinition definition : JaxrsAttribute.ATTRIBUTES) {
registration.registerReadWriteAttribute(definition, null, handler);
}
}
@Override
public void registerAdditionalRuntimePackages(ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerAdditionalRuntimePackages(RuntimePackageDependency.passive(RESTEASY_CDI),
RuntimePackageDependency.passive(RESTEASY_VALIDATOR),
RuntimePackageDependency.passive(RESTEASY_JSON_B_PROVIDER),
RuntimePackageDependency.required(JAXRS_API),
RuntimePackageDependency.required(JAXB_API),
RuntimePackageDependency.required(JSON_API),
RuntimePackageDependency.optional(RESTEASY_ATOM),
RuntimePackageDependency.required(RESTEASY_CORE),
RuntimePackageDependency.required(RESTEASY_CORE_SPI),
// The deprecated module should be activated if present for cases when other modules depend on this
RuntimePackageDependency.optional("org.jboss.resteasy.resteasy-jaxrs"),
RuntimePackageDependency.optional(RESTEASY_JAXB),
RuntimePackageDependency.optional(RESTEASY_JACKSON2),
RuntimePackageDependency.optional(RESTEASY_JSON_P_PROVIDER),
RuntimePackageDependency.optional(RESTEASY_JSAPI),
RuntimePackageDependency.optional(RESTEASY_MULTIPART),
RuntimePackageDependency.optional(RESTEASY_TRACING),
RuntimePackageDependency.optional(RESTEASY_CRYPTO),
RuntimePackageDependency.optional(JACKSON_DATATYPE_JDK8),
RuntimePackageDependency.optional(JACKSON_DATATYPE_JSR310),
// The following ones are optional dependencies located in org.jboss.as.jaxrs module.xml
// To be provisioned, they need to be explicitly added as optional packages.
RuntimePackageDependency.optional("org.jboss.resteasy.resteasy-spring"));
}
}
| 6,189 | 59.097087 | 119 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/JaxrsParamHandler.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jaxrs;
import org.jboss.as.controller.AbstractWriteAttributeHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.dmr.ModelNode;
/**
* An AbstractWriteAttributeHandler extension for updating basic RESTEasy config attributes
*
* @author <a href="mailto:[email protected]">Alessio Soldano</a>
* @author <a href="mailto:[email protected]">Jim Ma</a>
* @author <a href="mailto:[email protected]">Ron Sigal</a>
*/
final class JaxrsParamHandler extends AbstractWriteAttributeHandler<Void> {
public JaxrsParamHandler(final AttributeDefinition... definitions) {
super(definitions);
}
@Override
protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName,
ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<Void> handbackHolder)
throws OperationFailedException {
// Currently all attributes are set as context parameters and therefore require a reload or at least a re-deploy
return !isSameValue(context, resolvedValue, currentValue, attributeName);
}
private boolean isSameValue(OperationContext context, ModelNode resolvedValue, ModelNode currentValue, String attributeName)
throws OperationFailedException {
if (resolvedValue.equals(getAttributeDefinition(attributeName).resolveValue(context, currentValue))) {
return true;
}
if (!currentValue.isDefined()) {
return resolvedValue.equals(getAttributeDefinition(attributeName).getDefaultValue());
}
return false;
}
@Override
protected void revertUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName,
ModelNode valueToRestore, ModelNode valueToRevert, Void handback) throws OperationFailedException {
// Nothing to do, as nothing was changed
}
}
| 3,062 | 43.391304 | 128 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/JaxrsServerConfig.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jaxrs;
import java.util.LinkedHashMap;
import java.util.Map;
import org.jboss.dmr.ModelNode;
/**
* @author <a href="mailto:[email protected]">Ron Sigal</a>
*/
public class JaxrsServerConfig {
private ModelNode jaxrs20RequestMatching;
private ModelNode resteasyAddCharset;
private ModelNode resteasyBufferExceptionEntity;
private ModelNode resteasyDisableHtmlSanitizer;
private ModelNode resteasyDisableProviders;
private ModelNode resteasyDocumentExpandEntityReferences;
private ModelNode resteasyDocumentSecureProcessingFeature;
private ModelNode resteasyGzipMaxInput;
private ModelNode resteasyJndiResources;
private ModelNode resteasyLanguageMappings;
private ModelNode resteasyMediaTypeMappings;
private ModelNode resteasyMediaTypeParamMapping;
private ModelNode resteasyPreferJacksonOverJsonB;
private ModelNode resteasyProviders;
private ModelNode resteasyRFC7232Preconditions;
private ModelNode resteasyRoleBasedSecurity;
private ModelNode resteasySecureDisableDTDs;
private ModelNode resteasySecureRandomMaxUse;
private ModelNode resteasyUseBuiltinProviders;
private ModelNode resteasyUseContainerFormParams;
private ModelNode resteasyWiderRequestMatching;
private final Map<String, String> contextParameters;
public JaxrsServerConfig() {
contextParameters = new LinkedHashMap<>();
}
/**
* Adds the value to the context parameters.
*
* @param name the name of the context parameter
* @param value the value for the context parameter
*
* @return this configuration
*/
protected JaxrsServerConfig putContextParameter(final String name, final String value) {
contextParameters.put(name, value);
return this;
}
/**
* Returns a copy of the context parameters.
*
* @return the context parameters
*/
public Map<String, String> getContextParameters() {
return Map.copyOf(contextParameters);
}
public ModelNode isJaxrs20RequestMatching() {
return jaxrs20RequestMatching;
}
public void setJaxrs20RequestMatching(ModelNode jaxrs20RequestMatching) {
this.jaxrs20RequestMatching = jaxrs20RequestMatching;
}
public ModelNode isResteasyAddCharset() {
return resteasyAddCharset;
}
public void setResteasyAddCharset(ModelNode resteasyAddCharset) {
this.resteasyAddCharset = resteasyAddCharset;
}
public ModelNode isResteasyBufferExceptionEntity() {
return resteasyBufferExceptionEntity;
}
public void setResteasyBufferExceptionEntity(ModelNode resteasyBufferExceptionEntity) {
this.resteasyBufferExceptionEntity = resteasyBufferExceptionEntity;
}
public ModelNode isResteasyDisableHtmlSanitizer() {
return resteasyDisableHtmlSanitizer;
}
public void setResteasyDisableHtmlSanitizer(ModelNode resteasyDisableHtmlSanitizer) {
this.resteasyDisableHtmlSanitizer = resteasyDisableHtmlSanitizer;
}
public ModelNode getResteasyDisableProviders() {
return resteasyDisableProviders;
}
public void setResteasyDisableProviders(ModelNode resteasyDisableProviders) {
this.resteasyDisableProviders = resteasyDisableProviders;
}
@Deprecated
public ModelNode isResteasyDocumentExpandEntityReferences() {
return resteasyDocumentExpandEntityReferences;
}
@Deprecated
public void setResteasyDocumentExpandEntityReferences(ModelNode resteasyDocumentExpandEntityReferences) {
this.resteasyDocumentExpandEntityReferences = resteasyDocumentExpandEntityReferences;
}
public ModelNode isResteasyDocumentSecureProcessingFeature() {
return resteasyDocumentSecureProcessingFeature;
}
public void setResteasyDocumentSecureProcessingFeature(ModelNode resteasyDocumentSecureProcessingFeature) {
this.resteasyDocumentSecureProcessingFeature = resteasyDocumentSecureProcessingFeature;
}
public ModelNode getResteasyGzipMaxInput() {
return resteasyGzipMaxInput;
}
public void setResteasyGzipMaxInput(ModelNode resteasyGzipMaxInput) {
this.resteasyGzipMaxInput = resteasyGzipMaxInput;
}
public ModelNode getResteasyJndiResources() {
return resteasyJndiResources;
}
public void setResteasyJndiResources(ModelNode resteasyJndiResources) {
this.resteasyJndiResources = resteasyJndiResources;
}
public ModelNode getResteasyLanguageMappings() {
return resteasyLanguageMappings;
}
public void setResteasyLanguageMappings(ModelNode resteasyLanguageMappings) {
this.resteasyLanguageMappings = resteasyLanguageMappings;
}
public ModelNode getResteasyMediaTypeMappings() {
return resteasyMediaTypeMappings;
}
public void setResteasyMediaTypeMappings(ModelNode resteasyMediaTypeMappings) {
this.resteasyMediaTypeMappings = resteasyMediaTypeMappings;
}
public ModelNode getResteasyMediaTypeParamMapping() {
return resteasyMediaTypeParamMapping;
}
public void setResteasyMediaTypeParamMapping(ModelNode resteasyMediaTypeParamMapping) {
this.resteasyMediaTypeParamMapping = resteasyMediaTypeParamMapping;
}
public ModelNode isResteasyPreferJacksonOverJsonB() {
return resteasyPreferJacksonOverJsonB;
}
public void setResteasyPreferJacksonOverJsonB(ModelNode resteasyPreferJacksonOverJsonB) {
this.resteasyPreferJacksonOverJsonB = resteasyPreferJacksonOverJsonB;
}
public ModelNode getResteasyProviders() {
return resteasyProviders;
}
public void setResteasyProviders(ModelNode resteasyProviders) {
this.resteasyProviders = resteasyProviders;
}
public ModelNode isResteasyRFC7232Preconditions() {
return resteasyRFC7232Preconditions;
}
public void setResteasyRFC7232Preconditions(ModelNode resteasyRFC7232Preconditions) {
this.resteasyRFC7232Preconditions = resteasyRFC7232Preconditions;
}
public ModelNode isResteasyRoleBasedSecurity() {
return resteasyRoleBasedSecurity;
}
public void setResteasyRoleBasedSecurity(ModelNode resteasyRoleBasedSecurity) {
this.resteasyRoleBasedSecurity = resteasyRoleBasedSecurity;
}
@Deprecated
public ModelNode isResteasySecureDisableDTDs() {
return resteasySecureDisableDTDs;
}
@Deprecated
public void setResteasySecureDisableDTDs(ModelNode resteasySecureDisableDTDs) {
this.resteasySecureDisableDTDs = resteasySecureDisableDTDs;
}
public ModelNode getResteasySecureRandomMaxUse() {
return resteasySecureRandomMaxUse;
}
public void setResteasySecureRandomMaxUse(ModelNode resteasySecureRandomMaxUse) {
this.resteasySecureRandomMaxUse = resteasySecureRandomMaxUse;
}
public ModelNode isResteasyUseBuiltinProviders() {
return resteasyUseBuiltinProviders;
}
public void setResteasyUseBuiltinProviders(ModelNode resteasyUseBuiltinProviders) {
this.resteasyUseBuiltinProviders = resteasyUseBuiltinProviders;
}
public ModelNode isResteasyUseContainerFormParams() {
return resteasyUseContainerFormParams;
}
public void setResteasyUseContainerFormParams(ModelNode resteasyUseContainerFormParams) {
this.resteasyUseContainerFormParams = resteasyUseContainerFormParams;
}
public ModelNode isResteasyWiderRequestMatching() {
return resteasyWiderRequestMatching;
}
public void setResteasyWiderRequestMatching(ModelNode resteasyWiderRequestMatching) {
this.resteasyWiderRequestMatching = resteasyWiderRequestMatching;
}
}
| 8,737 | 39.64186 | 111 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/JaxrsSubsystemAdd.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.jaxrs;
import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME;
import org.jboss.as.controller.AbstractBoottimeAddStepHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.jaxrs.deployment.JaxrsAnnotationProcessor;
import org.jboss.as.jaxrs.deployment.JaxrsCdiIntegrationProcessor;
import org.jboss.as.jaxrs.deployment.JaxrsComponentDeployer;
import org.jboss.as.jaxrs.deployment.JaxrsDependencyProcessor;
import org.jboss.as.jaxrs.deployment.JaxrsIntegrationProcessor;
import org.jboss.as.jaxrs.deployment.JaxrsMethodParameterProcessor;
import org.jboss.as.jaxrs.deployment.JaxrsScanningProcessor;
import org.jboss.as.jaxrs.deployment.JaxrsSpringProcessor;
import org.jboss.as.jaxrs.logging.JaxrsLogger;
import org.jboss.as.server.AbstractDeploymentChainStep;
import org.jboss.as.server.DeploymentProcessorTarget;
import org.jboss.as.server.deployment.Phase;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.resteasy.spi.ResteasyDeployment;
/**
* The jaxrs subsystem add update handler.
*
* @author Stuart Douglas
* @author <a href="mailto:[email protected]">Ron Sigal</a>
*/
class JaxrsSubsystemAdd extends AbstractBoottimeAddStepHandler {
static final JaxrsSubsystemAdd INSTANCE = new JaxrsSubsystemAdd();
JaxrsSubsystemAdd(AttributeDefinition... attributes) {
super(attributes);
}
protected void performBoottime(final OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException {
final ServiceTarget serviceTarget = context.getServiceTarget();
JaxrsLogger.JAXRS_LOGGER.resteasyVersion(ResteasyDeployment.class.getPackage().getImplementationVersion());
context.addStep(new AbstractDeploymentChainStep() {
public void execute(DeploymentProcessorTarget processorTarget) {
processorTarget.addDeploymentProcessor(JaxrsExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_JAXRS_ANNOTATIONS, new JaxrsAnnotationProcessor());
processorTarget.addDeploymentProcessor(JaxrsExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_JAXRS_SPRING, new JaxrsSpringProcessor(serviceTarget));
processorTarget.addDeploymentProcessor(JaxrsExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_JAXRS, new JaxrsDependencyProcessor());
processorTarget.addDeploymentProcessor(JaxrsExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_JAXRS_SCANNING, new JaxrsScanningProcessor());
processorTarget.addDeploymentProcessor(JaxrsExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_JAXRS_COMPONENT, new JaxrsComponentDeployer());
CapabilityServiceSupport capabilities = context.getCapabilityServiceSupport();
if (capabilities.hasCapability(WELD_CAPABILITY_NAME)) {
processorTarget.addDeploymentProcessor(JaxrsExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_JAXRS_CDI_INTEGRATION, new JaxrsCdiIntegrationProcessor());
}
processorTarget.addDeploymentProcessor(JaxrsExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_JAXRS_METHOD_PARAMETER, new JaxrsMethodParameterProcessor());
processorTarget.addDeploymentProcessor(JaxrsExtension.SUBSYSTEM_NAME, Phase.INSTALL, Phase.INSTALL_JAXRS_DEPLOYMENT, new JaxrsIntegrationProcessor());
}
}, OperationContext.Stage.RUNTIME);
JaxrsServerConfig serverConfig = createServerConfig(operation, context);
JaxrsServerConfigService.install(serviceTarget, serverConfig);
}
private static JaxrsServerConfig createServerConfig(ModelNode configuration, OperationContext context) throws OperationFailedException {
final JaxrsServerConfig config = new JaxrsServerConfig();
if (configuration.hasDefined(JaxrsConstants.JAXRS_2_0_REQUEST_MATCHING)) {
config.setJaxrs20RequestMatching(JaxrsAttribute.JAXRS_2_0_REQUEST_MATCHING.resolveModelAttribute(context, configuration));
}
if (configuration.hasDefined(JaxrsConstants.RESTEASY_ADD_CHARSET)) {
config.setResteasyAddCharset(JaxrsAttribute.RESTEASY_ADD_CHARSET.resolveModelAttribute(context, configuration));
}
if (configuration.hasDefined(JaxrsConstants.RESTEASY_BUFFER_EXCEPTION_ENTITY)) {
config.setResteasyBufferExceptionEntity(JaxrsAttribute.RESTEASY_BUFFER_EXCEPTION_ENTITY.resolveModelAttribute(context, configuration));
}
if (configuration.hasDefined(JaxrsConstants.RESTEASY_DISABLE_HTML_SANITIZER)) {
config.setResteasyDisableHtmlSanitizer(JaxrsAttribute.RESTEASY_DISABLE_HTML_SANITIZER.resolveModelAttribute(context, configuration));
}
if (configuration.hasDefined(JaxrsConstants.RESTEASY_DISABLE_PROVIDERS)) {
config.setResteasyDisableProviders(JaxrsAttribute.RESTEASY_DISABLE_PROVIDERS.resolveModelAttribute(context, configuration));
}
if (configuration.hasDefined(JaxrsConstants.RESTEASY_DOCUMENT_EXPAND_ENTITY_REFERENCES)) {
config.setResteasyDocumentExpandEntityReferences(JaxrsAttribute.RESTEASY_DOCUMENT_EXPAND_ENTITY_REFERENCES.resolveModelAttribute(context, configuration));
}
if (configuration.hasDefined(JaxrsConstants.RESTEASY_DOCUMENT_SECURE_DISABLE_DTDS)) {
config.setResteasySecureDisableDTDs(JaxrsAttribute.RESTEASY_DOCUMENT_SECURE_DISABLE_DTDS.resolveModelAttribute(context, configuration));
}
if (configuration.hasDefined(JaxrsConstants.RESTEASY_DOCUMENT_SECURE_PROCESSING_FEATURE)) {
config.setResteasyDocumentSecureProcessingFeature(JaxrsAttribute.RESTEASY_DOCUMENT_SECURE_PROCESSING_FEATURE.resolveModelAttribute(context, configuration));
}
if (configuration.hasDefined(JaxrsConstants.RESTEASY_GZIP_MAX_INPUT)) {
config.setResteasyGzipMaxInput(JaxrsAttribute.RESTEASY_GZIP_MAX_INPUT.resolveModelAttribute(context, configuration));
}
if (configuration.hasDefined(JaxrsConstants.RESTEASY_JNDI_RESOURCES)) {
config.setResteasyJndiResources(JaxrsAttribute.RESTEASY_JNDI_RESOURCES.resolveModelAttribute(context, configuration));
}
if (configuration.hasDefined(JaxrsConstants.RESTEASY_LANGUAGE_MAPPINGS)) {
config.setResteasyLanguageMappings(JaxrsAttribute.RESTEASY_LANGUAGE_MAPPINGS.resolveModelAttribute(context, configuration));
}
if (configuration.hasDefined(JaxrsConstants.RESTEASY_MEDIA_TYPE_MAPPINGS)) {
config.setResteasyMediaTypeMappings(JaxrsAttribute.RESTEASY_MEDIA_TYPE_MAPPINGS.resolveModelAttribute(context, configuration));
}
if (configuration.hasDefined(JaxrsConstants.RESTEASY_MEDIA_TYPE_PARAM_MAPPING)) {
config.setResteasyMediaTypeParamMapping(JaxrsAttribute.RESTEASY_MEDIA_TYPE_PARAM_MAPPING.resolveModelAttribute(context, configuration));
}
if (configuration.hasDefined(JaxrsConstants.RESTEASY_PREFER_JACKSON_OVER_JSONB)) {
config.setResteasyPreferJacksonOverJsonB(JaxrsAttribute.RESTEASY_PREFER_JACKSON_OVER_JSONB.resolveModelAttribute(context, configuration));
}
if (configuration.hasDefined(JaxrsConstants.RESTEASY_PROVIDERS)) {
config.setResteasyProviders(JaxrsAttribute.RESTEASY_PROVIDERS.resolveModelAttribute(context, configuration));
}
if (configuration.hasDefined(JaxrsConstants.RESTEASY_RFC7232_PRECONDITIONS)) {
config.setResteasyRFC7232Preconditions(JaxrsAttribute.RESTEASY_RFC7232_PRECONDITIONS.resolveModelAttribute(context, configuration));
}
if (configuration.hasDefined(JaxrsConstants.RESTEASY_ROLE_BASED_SECURITY)) {
config.setResteasyRoleBasedSecurity(JaxrsAttribute.RESTEASY_ROLE_BASED_SECURITY.resolveModelAttribute(context, configuration));
}
if (configuration.hasDefined(JaxrsConstants.RESTEASY_SECURE_RANDOM_MAX_USE)) {
config.setResteasySecureRandomMaxUse(JaxrsAttribute.RESTEASY_SECURE_RANDOM_MAX_USE.resolveModelAttribute(context, configuration));
}
if (configuration.hasDefined(JaxrsConstants.RESTEASY_USE_BUILTIN_PROVIDERS)) {
config.setResteasyUseBuiltinProviders(JaxrsAttribute.RESTEASY_USE_BUILTIN_PROVIDERS.resolveModelAttribute(context, configuration));
}
if (configuration.hasDefined(JaxrsConstants.RESTEASY_USE_CONTAINER_FORM_PARAMS)) {
config.setResteasyUseContainerFormParams(JaxrsAttribute.RESTEASY_USE_CONTAINER_FORM_PARAMS.resolveModelAttribute(context, configuration));
}
if (configuration.hasDefined(JaxrsConstants.RESTEASY_WIDER_REQUEST_MATCHING)) {
config.setResteasyWiderRequestMatching(JaxrsAttribute.RESTEASY_WIDER_REQUEST_MATCHING.resolveModelAttribute(context, configuration));
}
if (configuration.hasDefined(JaxrsAttribute.TRACING_THRESHOLD.getName())) {
config.putContextParameter("resteasy.server.tracing.threshold", JaxrsAttribute.TRACING_THRESHOLD.resolveModelAttribute(context, configuration).asString());
}
if (configuration.hasDefined(JaxrsAttribute.TRACING_TYPE.getName())) {
config.putContextParameter("resteasy.server.tracing.type", JaxrsAttribute.TRACING_TYPE.resolveModelAttribute(context, configuration).asString());
}
return config;
}
}
| 10,712 | 64.323171 | 186 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/JaxrsSubsystemParser_2_0.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jaxrs;
import static org.jboss.as.controller.parsing.ParseUtils.requireAttributes;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoAttributes;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
import java.util.EnumSet;
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.PropertiesAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* @author <a href="mailto:[email protected]">Ron Sigal</a>
*/
public class JaxrsSubsystemParser_2_0 implements XMLStreamConstants, XMLElementReader<List<ModelNode>> {
@Override
public void readElement(final XMLExtendedStreamReader reader, final List<ModelNode> list) throws XMLStreamException {
final PathAddress address = PathAddress.pathAddress(JaxrsExtension.SUBSYSTEM_PATH);
final ModelNode subsystem = Util.createAddOperation(address);
list.add(subsystem);
requireNoAttributes(reader);
final EnumSet<JaxrsElement> encountered = EnumSet.noneOf(JaxrsElement.class);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final JaxrsElement element = JaxrsElement.forName(reader.getLocalName());
switch (element) {
case JAXRS_2_0_REQUEST_MATCHING:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.JAXRS_2_0_REQUEST_MATCHING);
break;
case RESTEASY_ADD_CHARSET:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_ADD_CHARSET);
break;
case RESTEASY_BUFFER_EXCEPTION_ENTITY:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_BUFFER_EXCEPTION_ENTITY);
break;
case RESTEASY_DISABLE_HTML_SANITIZER:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_DISABLE_HTML_SANITIZER);
break;
case RESTEASY_DISABLE_PROVIDERS:
handleList("class", reader, encountered, subsystem, JaxrsElement.RESTEASY_DISABLE_PROVIDERS);
break;
case RESTEASY_DOCUMENT_EXPAND_ENTITY_REFERENCES:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_DOCUMENT_EXPAND_ENTITY_REFERENCES);
break;
case RESTEASY_DOCUMENT_SECURE_DISABLE_DTDS:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_DOCUMENT_SECURE_DISABLE_DTDS);
break;
case RESTEASY_DOCUMENT_SECURE_PROCESSING_FEATURE:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_DOCUMENT_SECURE_PROCESSING_FEATURE);
break;
case RESTEASY_GZIP_MAX_INPUT:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_GZIP_MAX_INPUT);
break;
case RESTEASY_JNDI_RESOURCES:
handleList("jndi", reader, encountered, subsystem, JaxrsElement.RESTEASY_JNDI_RESOURCES);
break;
case RESTEASY_LANGUAGE_MAPPINGS:
handleMap(reader, encountered, subsystem, JaxrsElement.RESTEASY_LANGUAGE_MAPPINGS);
break;
case RESTEASY_MEDIA_TYPE_MAPPINGS:
handleMap(reader, encountered, subsystem, JaxrsElement.RESTEASY_MEDIA_TYPE_MAPPINGS);
break;
case RESTEASY_MEDIA_TYPE_PARAM_MAPPING:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_MEDIA_TYPE_PARAM_MAPPING);
break;
case RESTEASY_PREFER_JACKSON_OVER_JSONB:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_PREFER_JACKSON_OVER_JSONB);
break;
case RESTEASY_PROVIDERS:
handleList("class", reader, encountered, subsystem, JaxrsElement.RESTEASY_PROVIDERS);
break;
case RESTEASY_RFC7232_PRECONDITIONS:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_RFC7232_PRECONDITIONS);
break;
case RESTEASY_ROLE_BASED_SECURITY:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_ROLE_BASED_SECURITY);
break;
case RESTEASY_SECURE_RANDOM_MAX_USE:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_SECURE_RANDOM_MAX_USE);
break;
case RESTEASY_USE_BUILTIN_PROVIDERS:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_USE_BUILTIN_PROVIDERS);
break;
case RESTEASY_USE_CONTAINER_FORM_PARAMS:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_USE_CONTAINER_FORM_PARAMS);
break;
case RESTEASY_WIDER_REQUEST_MATCHING:
handleSimpleElement(reader, encountered, subsystem, JaxrsElement.RESTEASY_WIDER_REQUEST_MATCHING);
break;
default:
throw unexpectedElement(reader);
}
}
}
protected void handleSimpleElement(final XMLExtendedStreamReader reader,
final EnumSet<JaxrsElement> encountered,
final ModelNode subsystem,
final JaxrsElement element) throws XMLStreamException {
if (!encountered.add(element)) {
throw unexpectedElement(reader);
}
final String name = element.getLocalName();
final String value = parseElementNoAttributes(reader);
final SimpleAttributeDefinition attribute = (SimpleAttributeDefinition) JaxrsConstants.nameToAttributeMap.get(name);
attribute.parseAndSetParameter(value, subsystem, reader);
}
protected void handleList(final String tag,
final XMLExtendedStreamReader reader,
final EnumSet<JaxrsElement> encountered,
final ModelNode subsystem,
final JaxrsElement element) throws XMLStreamException {
if (!encountered.add(element)) {
throw unexpectedElement(reader);
}
final String name = element.getLocalName();
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
if (!tag.equals(reader.getLocalName())) {
throw unexpectedElement(reader);
}
String value = parseElementNoAttributes(reader);
subsystem.get(name).add(value);
}
}
protected void handleMap(final XMLExtendedStreamReader reader,
final EnumSet<JaxrsElement> encountered,
final ModelNode subsystem,
final JaxrsElement element) throws XMLStreamException {
if (!encountered.add(element)) {
throw unexpectedElement(reader);
}
final String name = element.getLocalName();
final PropertiesAttributeDefinition attribute = (PropertiesAttributeDefinition) JaxrsConstants.nameToAttributeMap.get(name);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
if (!"entry".equals(reader.getLocalName())) {
throw unexpectedElement(reader);
}
final String[] array = requireAttributes(reader, "key");
if (array.length != 1) {
throw unexpectedElement(reader);
}
String value = reader.getElementText().trim();
attribute.parseAndAddParameterElement(array[0], value, subsystem, reader);
}
}
protected String parseElementNoAttributes(final XMLExtendedStreamReader reader) throws XMLStreamException {
requireNoAttributes(reader);
return reader.getElementText().trim();
}
}
| 9,443 | 43.758294 | 132 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/JaxrsDeploymentDefinition.java
|
/*
* Copyright (C) 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 library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.jboss.as.jaxrs;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.wildfly.extension.undertow.DeploymentDefinition.CONTEXT_ROOT;
import static org.wildfly.extension.undertow.DeploymentDefinition.SERVER;
import static org.wildfly.extension.undertow.DeploymentDefinition.VIRTUAL_HOST;
import io.undertow.servlet.handlers.ServletHandler;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import jakarta.servlet.Servlet;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.ObjectTypeAttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleListAttributeDefinition;
import org.jboss.as.controller.SimpleOperationDefinition;
import org.jboss.as.controller.SimpleOperationDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.msc.service.ServiceController;
import org.jboss.resteasy.spi.ResourceInvoker;
import org.jboss.resteasy.core.ResourceMethodInvoker;
import org.jboss.resteasy.core.ResourceMethodRegistry;
import org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher;
import org.wildfly.extension.undertow.UndertowExtension;
import org.wildfly.extension.undertow.UndertowService;
import org.wildfly.extension.undertow.deployment.UndertowDeploymentService;
/**
*
* @author <a href="mailto:[email protected]">Emmanuel Hugonnet</a> (c) 2014 Red Hat, inc.
*/
public class JaxrsDeploymentDefinition extends SimpleResourceDefinition {
public static final String SHOW_RESOURCES = "show-resources";
public static final AttributeDefinition CLASSNAME
= new SimpleAttributeDefinitionBuilder("resource-class", ModelType.STRING, true).setStorageRuntime().build();
public static final AttributeDefinition PATH
= new SimpleAttributeDefinitionBuilder("resource-path", ModelType.STRING, true).setStorageRuntime().build();
public static final AttributeDefinition METHOD
= new SimpleAttributeDefinitionBuilder("jaxrs-resource-method", ModelType.STRING, false).setStorageRuntime().build();
public static final AttributeDefinition METHODS
= new SimpleListAttributeDefinition.Builder("resource-methods", METHOD).setStorageRuntime().build();
public static final ObjectTypeAttributeDefinition JAXRS_RESOURCE
= new ObjectTypeAttributeDefinition.Builder("jaxrs-resource", CLASSNAME, PATH, METHODS).setStorageRuntime().build();
JaxrsDeploymentDefinition() {
super(new Parameters(JaxrsExtension.SUBSYSTEM_PATH, JaxrsExtension.getResolver()).setFeature(false).setRuntime(true));
}
@Override
public void registerOperations(ManagementResourceRegistration resourceRegistration) {
super.registerOperations(resourceRegistration);
resourceRegistration.registerOperationHandler(ShowJaxrsResourcesHandler.DEFINITION, new ShowJaxrsResourcesHandler());
}
private static class ShowJaxrsResourcesHandler implements OperationStepHandler {
public static final SimpleOperationDefinition DEFINITION = new SimpleOperationDefinitionBuilder(SHOW_RESOURCES,
JaxrsExtension.getResolver("deployment"))
.setReadOnly()
.setRuntimeOnly()
.setReplyType(ModelType.LIST)
.setDeprecated(ModelVersion.create(2, 0, 0))
.setReplyParameters(JAXRS_RESOURCE).build();
void handle(ModelNode response, String contextRootPath, Collection<String> servletMappings, String mapping, List<ResourceInvoker> resources) {
for (ResourceInvoker resourceInvoker : resources) {
if (ResourceMethodInvoker.class.isAssignableFrom(resourceInvoker.getClass())) {
ResourceMethodInvoker resource = (ResourceMethodInvoker) resourceInvoker;
final ModelNode node = new ModelNode();
node.get(CLASSNAME.getName()).set(resource.getResourceClass().getCanonicalName());
node.get(PATH.getName()).set(mapping);
for (String servletMapping : servletMappings) {
String method = formatMethod(resource, servletMapping, mapping, contextRootPath);
for (final String httpMethod : resource.getHttpMethods()) {
node.get(METHODS.getName()).add(String.format(method, httpMethod));
}
}
response.add(node);
}
}
}
private String formatMethod(ResourceMethodInvoker resource, String servletMapping, String path, String contextRootPath) {
StringBuilder builder = new StringBuilder();
builder.append("%1$s ");
String servletPath = servletMapping.replaceAll("\\*", "");
if(servletPath.charAt(0) == '/') {
servletPath = servletPath.substring(1);
}
builder.append(contextRootPath).append('/').append(servletPath).append(path);
builder.append(" - ").append(resource.getResourceClass().getCanonicalName()).append('.').append(resource.getMethod().getName()).append('(');
if (resource.getMethod().getParameterCount() > 0) {
builder.append("...");
}
builder.append(')');
return builder.toString().replaceAll("//", "/");
}
@Override
public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException {
final PathAddress address = PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR));
//Getting Undertow deployment Model to access Servlet informations.
final ModelNode subModel = context.readResourceFromRoot(address.subAddress(0, address.size() - 1).append(
SUBSYSTEM, UndertowExtension.SUBSYSTEM_NAME), false).getModel();
final String host = VIRTUAL_HOST.resolveModelAttribute(context, subModel).asString();
final String contextPath = CONTEXT_ROOT.resolveModelAttribute(context, subModel).asString();
final String server = SERVER.resolveModelAttribute(context, subModel).asString();
final ServiceController<?> controller = context.getServiceRegistry(false).getService(UndertowService.deploymentServiceName(server, host, contextPath));
final UndertowDeploymentService deploymentService = (UndertowDeploymentService) controller.getService();
try {
deploymentService.getDeployment().createThreadSetupAction((exchange, ctxObject) -> {
Servlet resteasyServlet = null;
for (Map.Entry<String, ServletHandler> servletHandler : deploymentService.getDeployment().getServlets().getServletHandlers().entrySet()) {
if (HttpServletDispatcher.class.isAssignableFrom(servletHandler.getValue().getManagedServlet().getServletInfo().getServletClass())) {
resteasyServlet = servletHandler.getValue().getManagedServlet().getServlet().getInstance();
break;
}
}
if (resteasyServlet != null) {
final Collection<String> servletMappings = resteasyServlet.getServletConfig().getServletContext().getServletRegistration(resteasyServlet.getServletConfig().getServletName()).getMappings();
final ResourceMethodRegistry registry = (ResourceMethodRegistry) ((HttpServletDispatcher) resteasyServlet).getDispatcher().getRegistry();
context.addStep((context1, operation1) -> {
if (registry != null) {
final ModelNode response = new ModelNode();
for (Map.Entry<String, List<ResourceInvoker>> resource : registry.getBounded().entrySet()) {
handle(response, contextPath, servletMappings, resource.getKey(), resource.getValue());
}
context1.getResult().set(response);
}
}, OperationContext.Stage.RUNTIME);
}
return null;
}).call(null, null);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
}
| 9,970 | 56.304598 | 212 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/JaxrsElement.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.jaxrs;
import java.util.HashMap;
import java.util.Map;
/**
* Jaxrs configuration elements.
*
* @author <a href="mailto:[email protected]">Alessio Soldano</a>
* @author <a href="mailto:[email protected]">Richard Opalka</a>
* @author <a href="mailto:[email protected]">Ron Sigal</a>
*/
enum JaxrsElement {
UNKNOWN(null),
JAXRS_2_0_REQUEST_MATCHING(JaxrsConstants.JAXRS_2_0_REQUEST_MATCHING),
RESTEASY_ADD_CHARSET(JaxrsConstants.RESTEASY_ADD_CHARSET),
RESTEASY_BUFFER_EXCEPTION_ENTITY(JaxrsConstants.RESTEASY_BUFFER_EXCEPTION_ENTITY),
RESTEASY_DISABLE_HTML_SANITIZER(JaxrsConstants.RESTEASY_DISABLE_HTML_SANITIZER),
RESTEASY_DISABLE_PROVIDERS(JaxrsConstants.RESTEASY_DISABLE_PROVIDERS),
@Deprecated
RESTEASY_DOCUMENT_EXPAND_ENTITY_REFERENCES(JaxrsConstants.RESTEASY_DOCUMENT_EXPAND_ENTITY_REFERENCES),
@Deprecated
RESTEASY_DOCUMENT_SECURE_DISABLE_DTDS(JaxrsConstants.RESTEASY_DOCUMENT_SECURE_DISABLE_DTDS),
RESTEASY_DOCUMENT_SECURE_PROCESSING_FEATURE(JaxrsConstants.RESTEASY_DOCUMENT_SECURE_PROCESSING_FEATURE),
RESTEASY_GZIP_MAX_INPUT(JaxrsConstants.RESTEASY_GZIP_MAX_INPUT),
RESTEASY_JNDI_RESOURCES(JaxrsConstants.RESTEASY_JNDI_RESOURCES),
RESTEASY_LANGUAGE_MAPPINGS(JaxrsConstants.RESTEASY_LANGUAGE_MAPPINGS),
RESTEASY_MEDIA_TYPE_MAPPINGS(JaxrsConstants.RESTEASY_MEDIA_TYPE_MAPPINGS),
RESTEASY_MEDIA_TYPE_PARAM_MAPPING(JaxrsConstants.RESTEASY_MEDIA_TYPE_PARAM_MAPPING),
RESTEASY_PREFER_JACKSON_OVER_JSONB(JaxrsConstants.RESTEASY_PREFER_JACKSON_OVER_JSONB),
RESTEASY_PROVIDERS(JaxrsConstants.RESTEASY_PROVIDERS),
RESTEASY_RFC7232_PRECONDITIONS(JaxrsConstants.RESTEASY_RFC7232_PRECONDITIONS),
RESTEASY_ROLE_BASED_SECURITY(JaxrsConstants.RESTEASY_ROLE_BASED_SECURITY),
RESTEASY_SECURE_RANDOM_MAX_USE(JaxrsConstants.RESTEASY_SECURE_RANDOM_MAX_USE),
RESTEASY_USE_BUILTIN_PROVIDERS(JaxrsConstants.RESTEASY_USE_BUILTIN_PROVIDERS),
RESTEASY_USE_CONTAINER_FORM_PARAMS(JaxrsConstants.RESTEASY_USE_CONTAINER_FORM_PARAMS),
RESTEASY_WIDER_REQUEST_MATCHING(JaxrsConstants.RESTEASY_WIDER_REQUEST_MATCHING),
TRACING_TYPE(JaxrsAttribute.TRACING_TYPE.getName()),
TRACING_THRESHOLD(JaxrsAttribute.TRACING_THRESHOLD.getName()),
;
private final String name;
private JaxrsElement(final String name) {
this.name = name;
}
private static final Map<String, JaxrsElement> MAP;
static {
final Map<String, JaxrsElement> map = new HashMap<String, JaxrsElement>();
for (final JaxrsElement element : values()) {
final String name = element.getLocalName();
if (name != null)
map.put(name, element);
}
MAP = map;
}
static JaxrsElement forName(final String localName) {
final JaxrsElement element = MAP.get(localName);
return element == null ? UNKNOWN : element;
}
/**
* Get the local name of this element.
*
* @return the local name
*/
String getLocalName() {
return name;
}
}
| 4,087 | 42.031579 | 108 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/JaxrsAttribute.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2019, 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.jaxrs;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.DefaultAttributeMarshaller;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PropertiesAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.StringListAttributeDefinition;
import org.jboss.as.controller.access.constraint.SensitivityClassification;
import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition;
import org.jboss.as.controller.operations.validation.ModelTypeValidator;
import org.jboss.as.controller.operations.validation.StringAllowedValuesValidator;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.dmr.Property;
/**
* Jaxrs configuration attributes.
*
* @author <a href="mailto:[email protected]">Ron Sigal</a>
*/
public abstract class JaxrsAttribute {
public static final String RESTEASY_PARAMETER_GROUP = "resteasy";
/*
* All users can read see and read the attribute. However, users must have explicit permissions to write the
* constrained by this constraint.
*/
private static final SensitiveTargetAccessConstraintDefinition TRACING_MANAGEMENT_CONSTRAINT = new SensitiveTargetAccessConstraintDefinition(
new SensitivityClassification(JaxrsExtension.SUBSYSTEM_NAME, "tracing-management", false, false, true)
);
public static final SimpleAttributeDefinition JAXRS_2_0_REQUEST_MATCHING = new SimpleAttributeDefinitionBuilder(JaxrsConstants.JAXRS_2_0_REQUEST_MATCHING, ModelType.BOOLEAN)
.setRequired(false)
.setAllowExpression(true)
.setValidator(new ModelTypeValidator(ModelType.BOOLEAN, false))
.setDefaultValue(ModelNode.FALSE)
.setAttributeGroup(RESTEASY_PARAMETER_GROUP)
.build();
public static final SimpleAttributeDefinition RESTEASY_ADD_CHARSET = new SimpleAttributeDefinitionBuilder(JaxrsConstants.RESTEASY_ADD_CHARSET, ModelType.BOOLEAN)
.setRequired(false)
.setAllowExpression(true)
.setValidator(new ModelTypeValidator(ModelType.BOOLEAN, false))
.setDefaultValue(ModelNode.TRUE)
.setAttributeGroup(RESTEASY_PARAMETER_GROUP)
.build();
public static final SimpleAttributeDefinition RESTEASY_BUFFER_EXCEPTION_ENTITY = new SimpleAttributeDefinitionBuilder(JaxrsConstants.RESTEASY_BUFFER_EXCEPTION_ENTITY, ModelType.BOOLEAN)
.setRequired(false)
.setAllowExpression(true)
.setValidator(new ModelTypeValidator(ModelType.BOOLEAN, false))
.setDefaultValue(ModelNode.TRUE)
.setAttributeGroup(RESTEASY_PARAMETER_GROUP)
.build();
public static final SimpleAttributeDefinition RESTEASY_DISABLE_HTML_SANITIZER = new SimpleAttributeDefinitionBuilder(JaxrsConstants.RESTEASY_DISABLE_HTML_SANITIZER, ModelType.BOOLEAN)
.setRequired(false)
.setAllowExpression(true)
.setValidator(new ModelTypeValidator(ModelType.BOOLEAN, false))
.setDefaultValue(ModelNode.FALSE)
.setAttributeGroup(RESTEASY_PARAMETER_GROUP)
.build();
public static final StringListAttributeDefinition RESTEASY_DISABLE_PROVIDERS = new StringListAttributeDefinition.Builder(JaxrsConstants.RESTEASY_DISABLE_PROVIDERS)
.setRequired(false)
.setAllowExpression(true)
.setAllowDuplicates(false)
.setAttributeGroup(RESTEASY_PARAMETER_GROUP)
.setAttributeMarshaller(ListMarshaller.INSTANCE)
.build();
@Deprecated
public static final SimpleAttributeDefinition RESTEASY_DOCUMENT_EXPAND_ENTITY_REFERENCES = new SimpleAttributeDefinitionBuilder(JaxrsConstants.RESTEASY_DOCUMENT_EXPAND_ENTITY_REFERENCES, ModelType.BOOLEAN)
.setRequired(false)
.setAllowExpression(true)
.setValidator(new ModelTypeValidator(ModelType.BOOLEAN, false))
.setDefaultValue(ModelNode.FALSE)
.setAttributeGroup(RESTEASY_PARAMETER_GROUP)
.setDeprecated(ModelVersion.create(3, 0, 0), true)
.build();
@Deprecated
public static final SimpleAttributeDefinition RESTEASY_DOCUMENT_SECURE_DISABLE_DTDS = new SimpleAttributeDefinitionBuilder(JaxrsConstants.RESTEASY_DOCUMENT_SECURE_DISABLE_DTDS, ModelType.BOOLEAN)
.setRequired(false)
.setAllowExpression(true)
.setValidator(new ModelTypeValidator(ModelType.BOOLEAN, false))
.setDefaultValue(ModelNode.TRUE)
.setAttributeGroup(RESTEASY_PARAMETER_GROUP)
.setDeprecated(ModelVersion.create(3, 0, 0), true)
.build();
public static final SimpleAttributeDefinition RESTEASY_DOCUMENT_SECURE_PROCESSING_FEATURE = new SimpleAttributeDefinitionBuilder(JaxrsConstants.RESTEASY_DOCUMENT_SECURE_PROCESSING_FEATURE, ModelType.BOOLEAN)
.setRequired(false)
.setAllowExpression(true)
.setValidator(new ModelTypeValidator(ModelType.BOOLEAN, false))
.setDefaultValue(ModelNode.TRUE)
.setAttributeGroup(RESTEASY_PARAMETER_GROUP)
.build();
public static final SimpleAttributeDefinition RESTEASY_GZIP_MAX_INPUT = new SimpleAttributeDefinitionBuilder(JaxrsConstants.RESTEASY_GZIP_MAX_INPUT, ModelType.INT)
.setRequired(false)
.setAllowExpression(true)
.setValidator(new ModelTypeValidator(ModelType.INT, false))
.setDefaultValue(new ModelNode(10000000))
.setAttributeGroup(RESTEASY_PARAMETER_GROUP)
.build();
public static final StringListAttributeDefinition RESTEASY_JNDI_RESOURCES = new StringListAttributeDefinition.Builder(JaxrsConstants.RESTEASY_JNDI_RESOURCES)
.setRequired(false)
.setAllowExpression(true)
.setAttributeGroup(RESTEASY_PARAMETER_GROUP)
.setAttributeMarshaller(ListMarshaller.INSTANCE)
.build();
public static final PropertiesAttributeDefinition RESTEASY_LANGUAGE_MAPPINGS = new PropertiesAttributeDefinition.Builder(JaxrsConstants.RESTEASY_LANGUAGE_MAPPINGS, true)
.setRequired(false)
.setAllowExpression(true)
.setAttributeGroup(RESTEASY_PARAMETER_GROUP)
.setAttributeMarshaller(MapMarshaller.INSTANCE)
.build();
public static final PropertiesAttributeDefinition RESTEASY_MEDIA_TYPE_MAPPINGS = new PropertiesAttributeDefinition.Builder(JaxrsConstants.RESTEASY_MEDIA_TYPE_MAPPINGS, true)
.setRequired(false)
.setAllowExpression(true)
.setAttributeGroup(RESTEASY_PARAMETER_GROUP)
.setAttributeMarshaller(MapMarshaller.INSTANCE)
.build();
public static final SimpleAttributeDefinition RESTEASY_MEDIA_TYPE_PARAM_MAPPING = new SimpleAttributeDefinitionBuilder(JaxrsConstants.RESTEASY_MEDIA_TYPE_PARAM_MAPPING, ModelType.STRING)
.setRequired(false)
.setAllowExpression(true)
.setValidator(new ModelTypeValidator(ModelType.STRING, true))
.setAttributeGroup(RESTEASY_PARAMETER_GROUP)
.build();
public static final SimpleAttributeDefinition RESTEASY_PREFER_JACKSON_OVER_JSONB = new SimpleAttributeDefinitionBuilder(JaxrsConstants.RESTEASY_PREFER_JACKSON_OVER_JSONB, ModelType.BOOLEAN)
.setRequired(false)
.setAllowExpression(true)
.setValidator(new ModelTypeValidator(ModelType.BOOLEAN, false))
.setDefaultValue(ModelNode.FALSE)
.setAttributeGroup(RESTEASY_PARAMETER_GROUP)
.build();
public static final StringListAttributeDefinition RESTEASY_PROVIDERS = new StringListAttributeDefinition.Builder(JaxrsConstants.RESTEASY_PROVIDERS)
.setRequired(false)
.setAllowExpression(true)
.setAllowDuplicates(false)
.setAttributeGroup(RESTEASY_PARAMETER_GROUP)
.setAttributeMarshaller(ListMarshaller.INSTANCE)
.build();
public static final SimpleAttributeDefinition RESTEASY_RFC7232_PRECONDITIONS = new SimpleAttributeDefinitionBuilder(JaxrsConstants.RESTEASY_RFC7232_PRECONDITIONS, ModelType.BOOLEAN)
.setRequired(false)
.setAllowExpression(true)
.setValidator(new ModelTypeValidator(ModelType.BOOLEAN, false))
.setDefaultValue(ModelNode.FALSE)
.setAttributeGroup(RESTEASY_PARAMETER_GROUP)
.build();
public static final SimpleAttributeDefinition RESTEASY_ROLE_BASED_SECURITY = new SimpleAttributeDefinitionBuilder(JaxrsConstants.RESTEASY_ROLE_BASED_SECURITY, ModelType.BOOLEAN)
.setRequired(false)
.setAllowExpression(true)
.setValidator(new ModelTypeValidator(ModelType.BOOLEAN, false))
.setDefaultValue(ModelNode.FALSE)
.setAttributeGroup(RESTEASY_PARAMETER_GROUP)
.build();
public static final SimpleAttributeDefinition RESTEASY_SECURE_RANDOM_MAX_USE = new SimpleAttributeDefinitionBuilder(JaxrsConstants.RESTEASY_SECURE_RANDOM_MAX_USE, ModelType.INT)
.setRequired(false)
.setAllowExpression(true)
.setValidator(new ModelTypeValidator(ModelType.INT, false))
.setDefaultValue(new ModelNode(100))
.setAttributeGroup(RESTEASY_PARAMETER_GROUP)
.build();
public static final SimpleAttributeDefinition RESTEASY_USE_BUILTIN_PROVIDERS = new SimpleAttributeDefinitionBuilder(JaxrsConstants.RESTEASY_USE_BUILTIN_PROVIDERS, ModelType.BOOLEAN)
.setRequired(false)
.setAllowExpression(true)
.setValidator(new ModelTypeValidator(ModelType.BOOLEAN, false))
.setDefaultValue(ModelNode.TRUE)
.setAttributeGroup(RESTEASY_PARAMETER_GROUP)
.build();
public static final SimpleAttributeDefinition RESTEASY_USE_CONTAINER_FORM_PARAMS = new SimpleAttributeDefinitionBuilder(JaxrsConstants.RESTEASY_USE_CONTAINER_FORM_PARAMS, ModelType.BOOLEAN)
.setRequired(false)
.setAllowExpression(true)
.setValidator(new ModelTypeValidator(ModelType.BOOLEAN, false))
.setDefaultValue(ModelNode.FALSE)
.setAttributeGroup(RESTEASY_PARAMETER_GROUP)
.build();
public static final SimpleAttributeDefinition RESTEASY_WIDER_REQUEST_MATCHING = new SimpleAttributeDefinitionBuilder(JaxrsConstants.RESTEASY_WIDER_REQUEST_MATCHING, ModelType.BOOLEAN)
.setRequired(false)
.setAllowExpression(true)
.setValidator(new ModelTypeValidator(ModelType.BOOLEAN, false))
.setDefaultValue(ModelNode.FALSE)
.setAttributeGroup(RESTEASY_PARAMETER_GROUP)
.build();
static final SimpleAttributeDefinition TRACING_TYPE = SimpleAttributeDefinitionBuilder.create("tracing-type", ModelType.STRING)
.addAccessConstraint(TRACING_MANAGEMENT_CONSTRAINT)
.setAllowExpression(true)
.setAttributeGroup("tracing")
.setDefaultValue(new ModelNode("OFF"))
.setRequired(false)
.setValidator(new StringAllowedValuesValidator("OFF", "ON_DEMAND", "ALL"))
.build();
static final SimpleAttributeDefinition TRACING_THRESHOLD = SimpleAttributeDefinitionBuilder.create("tracing-threshold", ModelType.STRING)
.addAccessConstraint(TRACING_MANAGEMENT_CONSTRAINT)
.setAllowExpression(true)
.setAttributeGroup("tracing")
.setDefaultValue(new ModelNode("SUMMARY"))
.setRequired(false)
.setValidator(new StringAllowedValuesValidator("SUMMARY", "TRACE", "VERBOSE"))
.build();
public static final AttributeDefinition[] ATTRIBUTES = new AttributeDefinition[] {
JAXRS_2_0_REQUEST_MATCHING,
RESTEASY_ADD_CHARSET,
RESTEASY_BUFFER_EXCEPTION_ENTITY,
RESTEASY_DISABLE_HTML_SANITIZER,
RESTEASY_DISABLE_PROVIDERS,
RESTEASY_DOCUMENT_EXPAND_ENTITY_REFERENCES,
RESTEASY_DOCUMENT_SECURE_DISABLE_DTDS,
RESTEASY_DOCUMENT_SECURE_PROCESSING_FEATURE,
RESTEASY_GZIP_MAX_INPUT,
RESTEASY_JNDI_RESOURCES,
RESTEASY_LANGUAGE_MAPPINGS,
RESTEASY_MEDIA_TYPE_MAPPINGS,
RESTEASY_MEDIA_TYPE_PARAM_MAPPING,
RESTEASY_PREFER_JACKSON_OVER_JSONB,
RESTEASY_PROVIDERS,
RESTEASY_RFC7232_PRECONDITIONS,
RESTEASY_ROLE_BASED_SECURITY,
RESTEASY_SECURE_RANDOM_MAX_USE,
RESTEASY_USE_BUILTIN_PROVIDERS,
RESTEASY_USE_CONTAINER_FORM_PARAMS,
RESTEASY_WIDER_REQUEST_MATCHING,
TRACING_TYPE,
TRACING_THRESHOLD,
};
public static final AttributeDefinition[] simpleAttributesArray = new AttributeDefinition[] {
JAXRS_2_0_REQUEST_MATCHING,
RESTEASY_ADD_CHARSET,
RESTEASY_BUFFER_EXCEPTION_ENTITY,
RESTEASY_DISABLE_HTML_SANITIZER,
RESTEASY_DOCUMENT_EXPAND_ENTITY_REFERENCES,
RESTEASY_DOCUMENT_SECURE_DISABLE_DTDS,
RESTEASY_DOCUMENT_SECURE_PROCESSING_FEATURE,
RESTEASY_GZIP_MAX_INPUT,
RESTEASY_MEDIA_TYPE_PARAM_MAPPING,
RESTEASY_PREFER_JACKSON_OVER_JSONB,
RESTEASY_RFC7232_PRECONDITIONS,
RESTEASY_ROLE_BASED_SECURITY,
RESTEASY_SECURE_RANDOM_MAX_USE,
RESTEASY_USE_BUILTIN_PROVIDERS,
RESTEASY_USE_CONTAINER_FORM_PARAMS,
RESTEASY_WIDER_REQUEST_MATCHING,
TRACING_TYPE,
TRACING_THRESHOLD,
};
public static final AttributeDefinition[] listAttributeArray = new AttributeDefinition[] {
RESTEASY_DISABLE_PROVIDERS,
RESTEASY_PROVIDERS
};
public static final AttributeDefinition[] jndiAttributesArray = new AttributeDefinition[] {
RESTEASY_JNDI_RESOURCES
};
public static final AttributeDefinition[] mapAttributeArray = new AttributeDefinition[] {
RESTEASY_LANGUAGE_MAPPINGS,
RESTEASY_MEDIA_TYPE_MAPPINGS
};
public static final Set<AttributeDefinition> SIMPLE_ATTRIBUTES = new HashSet<>(Arrays. asList(simpleAttributesArray));
public static final Set<AttributeDefinition> LIST_ATTRIBUTES = new HashSet<>(Arrays. asList(listAttributeArray));
public static final Set<AttributeDefinition> JNDI_ATTRIBUTES = new HashSet<>(Arrays. asList(jndiAttributesArray));
public static final Set<AttributeDefinition> MAP_ATTRIBUTES = new HashSet<>(Arrays. asList(mapAttributeArray));
private static class ListMarshaller extends DefaultAttributeMarshaller {
static final ListMarshaller INSTANCE = new ListMarshaller();
@Override
public void marshallAsElement(final AttributeDefinition attribute, final ModelNode resourceModel, final boolean marshallDefault, final XMLStreamWriter writer) throws XMLStreamException {
if (isMarshallable(attribute, resourceModel, marshallDefault)) {
writer.writeStartElement(attribute.getXmlName());
List<ModelNode> list = resourceModel.get(attribute.getName()).asList();
for (ModelNode node : list) {
String child = "class";
if (JNDI_ATTRIBUTES.contains(attribute)) {
child = "jndi";
}
writer.writeStartElement(child);
writer.writeCharacters(node.asString().trim());
writer.writeEndElement();
}
writer.writeEndElement();
}
}
}
private static class MapMarshaller extends DefaultAttributeMarshaller {
static final MapMarshaller INSTANCE = new MapMarshaller();
@Override
public void marshallAsElement(final AttributeDefinition attribute, final ModelNode resourceModel, final boolean marshallDefault, final XMLStreamWriter writer) throws XMLStreamException {
if (isMarshallable(attribute, resourceModel, marshallDefault)) {
writer.writeStartElement(attribute.getXmlName());
List<ModelNode> list = resourceModel.get(attribute.getName()).asList();
for (ModelNode node : list) {
Property property = node.asProperty();
writer.writeStartElement("entry");
writer.writeAttribute("key", property.getName());
writer.writeCharacters(property.getValue().asString().trim());
writer.writeEndElement();
}
writer.writeEndElement();
}
}
}
}
| 18,139 | 49.670391 | 211 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/DeploymentRestResourcesDefintion.java
|
/*
* Copyright (C) 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 library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.jboss.as.jaxrs;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.wildfly.extension.undertow.DeploymentDefinition.CONTEXT_ROOT;
import static org.wildfly.extension.undertow.DeploymentDefinition.SERVER;
import static org.wildfly.extension.undertow.DeploymentDefinition.VIRTUAL_HOST;
import io.undertow.server.HttpServerExchange;
import io.undertow.servlet.api.ThreadSetupHandler;
import io.undertow.servlet.handlers.ServletHandler;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import jakarta.ws.rs.CookieParam;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.FormParam;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.MatrixParam;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.ObjectListAttributeDefinition;
import org.jboss.as.controller.ObjectTypeAttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleListAttributeDefinition;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.OperationContext.AttachmentKey;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.jaxrs.logging.JaxrsLogger;
import org.jboss.as.server.Services;
import org.jboss.as.server.moduleservice.ServiceModuleLoader;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.logmanager.Level;
import org.jboss.modules.Module;
import org.jboss.msc.service.ServiceController;
import org.jboss.resteasy.spi.ResourceInvoker;
import org.jboss.resteasy.core.ResourceLocatorInvoker;
import org.jboss.resteasy.core.ResourceMethodInvoker;
import org.jboss.resteasy.core.ResourceMethodRegistry;
import org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher;
import org.jboss.resteasy.spi.metadata.ResourceBuilder;
import org.jboss.resteasy.spi.metadata.ResourceClass;
import org.jboss.resteasy.spi.metadata.ResourceLocator;
import org.jboss.resteasy.spi.metadata.ResourceMethod;
import org.wildfly.extension.undertow.UndertowExtension;
import org.wildfly.extension.undertow.UndertowService;
import org.wildfly.extension.undertow.deployment.UndertowDeploymentService;
/**
* @author <a href="mailto:[email protected]">Lin Gao</a>
*/
@SuppressWarnings("deprecation")
public class DeploymentRestResourcesDefintion extends SimpleResourceDefinition {
public static final String REST_RESOURCE_NAME = "rest-resource";
public static final AttributeDefinition RESOURCE_CLASS = new SimpleAttributeDefinitionBuilder("resource-class",
ModelType.STRING, true).setStorageRuntime().build();
public static final AttributeDefinition RESOURCE_PATH = new SimpleAttributeDefinitionBuilder("resource-path", ModelType.STRING, true)
.setStorageRuntime().build();
public static final AttributeDefinition RESOURCE_METHOD = new SimpleAttributeDefinitionBuilder("resource-method",
ModelType.STRING, false).setStorageRuntime().build();
public static final AttributeDefinition RESOURCE_METHODS = new SimpleListAttributeDefinition.Builder("resource-methods", RESOURCE_METHOD)
.setStorageRuntime().build();
public static final AttributeDefinition CONSUME = new SimpleAttributeDefinitionBuilder("consume", ModelType.STRING, true)
.setStorageRuntime().build();
public static final AttributeDefinition CONSUMES = new SimpleListAttributeDefinition.Builder("consumes", CONSUME)
.setStorageRuntime().build();
public static final AttributeDefinition PRODUCE = new SimpleAttributeDefinitionBuilder("produce", ModelType.STRING, true)
.setStorageRuntime().build();
public static final AttributeDefinition PRODUCES = new SimpleListAttributeDefinition.Builder("produces", PRODUCE)
.setStorageRuntime().build();
public static final AttributeDefinition JAVA_METHOD = new SimpleAttributeDefinitionBuilder("java-method", ModelType.STRING,
true).setStorageRuntime().build();
public static final ObjectTypeAttributeDefinition RESOURCE_PATH_GRP = new ObjectTypeAttributeDefinition.Builder(
"rest-resource-path-group", RESOURCE_PATH, CONSUMES, PRODUCES, JAVA_METHOD, RESOURCE_METHODS).build();
public static final ObjectListAttributeDefinition RESOURCE_PATHS = new ObjectListAttributeDefinition.Builder(
"rest-resource-paths", RESOURCE_PATH_GRP).build();
public static final ObjectTypeAttributeDefinition SUB_RESOURCE_LOCATOR = new ObjectTypeAttributeDefinition.Builder(
"sub-resource-locator-group", RESOURCE_CLASS, RESOURCE_PATH, CONSUMES, PRODUCES, JAVA_METHOD, RESOURCE_METHODS).build();
public static final ObjectListAttributeDefinition SUB_RESOURCE_LOCATORS = new ObjectListAttributeDefinition.Builder(
"sub-resource-locators", SUB_RESOURCE_LOCATOR).build();
private AttachmentKey<Map<PathAddress, UndertowDeploymentService>> undertowDeployServiceKey = AttachmentKey.create(Map.class);
private AttachmentKey<Map<PathAddress, Module>> deploymentModuleKey = AttachmentKey.create(Map.class);
private AttachmentKey<Map<String, ResourceMeta>> resourceMetaKey = AttachmentKey.create(Map.class);
DeploymentRestResourcesDefintion() {
super(PathElement.pathElement(REST_RESOURCE_NAME), JaxrsExtension.getResolver("deployment"));
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerMetric(RESOURCE_CLASS, new AbstractRestResReadHandler() {
@Override
void handleAttribute(String className, List<JaxrsResourceMethodDescription> methodInvokers,
List<JaxrsResourceLocatorDescription> locatorIncokers, Collection<String> servletMappings,
ModelNode response) {
response.set(className);
}
});
resourceRegistration.registerMetric(RESOURCE_PATHS, new AbstractRestResReadHandler() {
@Override
void handleAttribute(String className, List<JaxrsResourceMethodDescription> methodInvokers,
List<JaxrsResourceLocatorDescription> locatorIncokers, Collection<String> servletMappings,
ModelNode response) {
for (JaxrsResourceMethodDescription methodDesc: methodInvokers) {
response.add(methodDesc.toModelNode());
}
}
});
resourceRegistration.registerMetric(SUB_RESOURCE_LOCATORS, new AbstractRestResReadHandler() {
@Override
void handleAttribute(String className, List<JaxrsResourceMethodDescription> methodInvokers,
List<JaxrsResourceLocatorDescription> locatorIncokers, Collection<String> servletMappings,
ModelNode response) {
for (JaxrsResourceLocatorDescription methodDesc: locatorIncokers) {
response.add(methodDesc.toModelNode());
}
}
});
}
abstract class AbstractRestResReadHandler implements OperationStepHandler {
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
PathAddress address = context.getCurrentAddress();
String clsName = address.getLastElement().getValue();
final PathAddress parentAddress = address.getParent();
final ModelNode subModel = context.readResourceFromRoot(parentAddress.subAddress(0, parentAddress.size() - 1).append(SUBSYSTEM, UndertowExtension.SUBSYSTEM_NAME), false).getModel();
final String host = VIRTUAL_HOST.resolveModelAttribute(context, subModel).asString();
final String contextPath = CONTEXT_ROOT.resolveModelAttribute(context, subModel).asString();
final String server = SERVER.resolveModelAttribute(context, subModel).asString();
Map<PathAddress, UndertowDeploymentService> deploymentServiceMap = context.getAttachment(undertowDeployServiceKey);
if (deploymentServiceMap == null) {
deploymentServiceMap = Collections.synchronizedMap(new HashMap<PathAddress, UndertowDeploymentService>());
context.attach(undertowDeployServiceKey, deploymentServiceMap);
}
UndertowDeploymentService undertowDeploymentService = deploymentServiceMap.get(parentAddress);
if (undertowDeploymentService == null) {
final ServiceController<?> controller = context.getServiceRegistry(false).getService(UndertowService.deploymentServiceName(server, host, contextPath));
undertowDeploymentService = (UndertowDeploymentService) controller.getService();
deploymentServiceMap.put(parentAddress, undertowDeploymentService);
}
final UndertowDeploymentService deploymentService = undertowDeploymentService;
Map<String, ResourceMeta> resourceMetaMap = context.getAttachment(resourceMetaKey);
if (resourceMetaMap == null) {
resourceMetaMap = Collections.synchronizedMap(new HashMap<String, ResourceMeta>());
context.attach(resourceMetaKey, resourceMetaMap);
}
ResourceMeta resMeta = resourceMetaMap.get(clsName);
if (resMeta == null) {
resMeta = new ResourceMeta();
resourceMetaMap.put(clsName, resMeta);
}
final ResourceMeta resourceMeta = resMeta;
try {
if(deploymentService.getDeployment() == null) {
return;
}
deploymentService.getDeployment().createThreadSetupAction(new ThreadSetupHandler.Action<Object, Object>() {
@Override
public Object call(HttpServerExchange exchange, Object ctxObject) throws Exception {
List<HttpServletDispatcher> resteasyServlets = new ArrayList<>();
for (Map.Entry<String, ServletHandler> servletHandler : deploymentService.getDeployment().getServlets().getServletHandlers().entrySet()) {
if (HttpServletDispatcher.class.isAssignableFrom(servletHandler.getValue().getManagedServlet().getServletInfo().getServletClass())) {
resteasyServlets.add((HttpServletDispatcher) servletHandler.getValue().getManagedServlet().getServlet().getInstance());
}
}
if (!resteasyServlets.isEmpty()) {
context.addStep(new OperationStepHandler() {
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
final ModelNode response = new ModelNode();
List<JaxrsResourceMethodDescription> resMethodInvokers = resourceMeta.methodInvokers;
List<JaxrsResourceLocatorDescription> resLocatorInvokers = resourceMeta.resLocatorInvokers;
for (HttpServletDispatcher resteasyServlet: resteasyServlets) {
final Collection<String> servletMappings = resteasyServlet.getServletConfig().getServletContext().getServletRegistration(resteasyServlet.getServletConfig().getServletName()).getMappings();
if (!resourceMeta.metaComplete) {
resourceMeta.metaComplete = true;
final ResourceMethodRegistry registry = (ResourceMethodRegistry) resteasyServlet.getDispatcher().getRegistry();
for (Map.Entry<String, List<ResourceInvoker>> resource : registry.getBounded().entrySet()) {
String mapping = resource.getKey();
List<ResourceInvoker> resouceInvokers = resource.getValue();
for (ResourceInvoker resourceInvoker : resouceInvokers) {
if (ResourceMethodInvoker.class.isAssignableFrom(resourceInvoker.getClass())) {
ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker) resourceInvoker;
Class<?> resClass = methodInvoker.getResourceClass();
if (resClass.getCanonicalName().equals(clsName)) {
JaxrsResourceMethodDescription resMethodDesc = resMethodDescription(methodInvoker, contextPath, mapping, servletMappings, clsName);
resMethodInvokers.add(resMethodDesc);
} else if (resClass.isInterface()){
Class<?> resClsInModel = getResourceClassInModel(clsName, context);
if (resClass.isAssignableFrom(resClsInModel)) {
JaxrsResourceMethodDescription resMethodDesc = resMethodDescription(methodInvoker, contextPath, mapping, servletMappings, clsName);
resMethodInvokers.add(resMethodDesc);
}
}
} else if (ResourceLocatorInvoker.class.isAssignableFrom(resourceInvoker.getClass())) {
ResourceLocatorInvoker locatorInvoker = (ResourceLocatorInvoker) resourceInvoker;
Class<?> resLocatorClass = locatorInvoker.getMethod().getDeclaringClass();
if (clsName.equals(resLocatorClass.getCanonicalName())) {
ResourceClass resClass = ResourceBuilder.locatorFromAnnotations(locatorInvoker.getMethod().getReturnType());
JaxrsResourceLocatorDescription resLocatorDesc = resLocatorDescription(resClass, contextPath, mapping, servletMappings, new ArrayList<Class<?>>());
resLocatorInvokers.add(resLocatorDesc);
} else if (resLocatorClass.isInterface()) {
Class<?> resClsInModel = getResourceClassInModel(clsName, context);
if (resLocatorClass.isAssignableFrom(resClsInModel)) {
ResourceClass resClass = ResourceBuilder.locatorFromAnnotations(locatorInvoker.getMethod().getReturnType());
JaxrsResourceLocatorDescription resLocatorDesc = resLocatorDescription(resClass, contextPath, mapping, servletMappings, new ArrayList<Class<?>>());
resLocatorInvokers.add(resLocatorDesc);
}
}
}
}
}
Collections.sort(resMethodInvokers);
Collections.sort(resLocatorInvokers);
}
handleAttribute(clsName, resMethodInvokers, resLocatorInvokers, servletMappings, response);
}
context.getResult().set(response);
}
private Class<?> getResourceClassInModel(String clsName, OperationContext context) throws OperationFailedException{
try {
Map<PathAddress, Module> deploymentModuleMap = context.getAttachment(deploymentModuleKey);
if (deploymentModuleMap == null) {
deploymentModuleMap = Collections.synchronizedMap(new HashMap<PathAddress, Module>());
context.attach(deploymentModuleKey, deploymentModuleMap);
}
Module deployModule = deploymentModuleMap.get(parentAddress);
if (deployModule == null) {
final StringBuilder sb = new StringBuilder(ModelDescriptionConstants.DEPLOYMENT);
sb.append(".");
String deployRuntimeName = address.getElement(0).getValue();
final ModelNode deployModel = context.readResourceFromRoot(address.subAddress(0, 1)).getModel();
if (deployModel.isDefined() && deployModel.hasDefined(ModelDescriptionConstants.RUNTIME_NAME)) {
deployRuntimeName = deployModel.get(ModelDescriptionConstants.RUNTIME_NAME).asString();
}
sb.append(deployRuntimeName);
if (address.size() > 1 && address.getElement(1).getKey().equals(ModelDescriptionConstants.SUBDEPLOYMENT)) {
sb.append(".");
sb.append(address.getElement(1).getValue());
}
String moduleName = sb.toString();
ServiceModuleLoader srvModuleLoader = (ServiceModuleLoader) context.getServiceRegistry(false).getRequiredService(Services.JBOSS_SERVICE_MODULE_LOADER).getValue();
deployModule = srvModuleLoader.loadModule(moduleName);
deploymentModuleMap.put(parentAddress, deployModule);
}
return Class.forName(clsName, false, deployModule.getClassLoader());
} catch (Exception e) {
throw new OperationFailedException(e);
}
}
}, OperationContext.Stage.RUNTIME);
}
return null;
}
}).call(null, null);
} catch (Exception ex) {
//WFLY-10222 we don't want a failure to read the attribute to break everything
JaxrsLogger.JAXRS_LOGGER.failedToReadAttribute(ex, address, operation.get(NAME));
context.addResponseWarning(Level.WARN, ex.getMessage());
}
}
abstract void handleAttribute(String className, List<JaxrsResourceMethodDescription> methodInvokers,
List<JaxrsResourceLocatorDescription> locatorIncokers, Collection<String> servletMappings, ModelNode response);
}
private class ResourceMeta {
private List<JaxrsResourceMethodDescription> methodInvokers;
private List<JaxrsResourceLocatorDescription> resLocatorInvokers;
private boolean metaComplete = false;
private ResourceMeta() {
this.methodInvokers = new ArrayList<>();
this.resLocatorInvokers = new ArrayList<>();
}
}
private JaxrsResourceLocatorDescription resLocatorDescription(ResourceClass resClass, String contextPath, String mapping,
Collection<String> servletMappings, List<Class<?>> resolvedCls) {
JaxrsResourceLocatorDescription locatorRes = new JaxrsResourceLocatorDescription();
locatorRes.resourceClass = resClass.getClazz();
resolvedCls.add(resClass.getClazz());
for (ResourceMethod resMethod : resClass.getResourceMethods()) {
JaxrsResourceMethodDescription jaxrsRes = new JaxrsResourceMethodDescription();
jaxrsRes.consumeTypes = resMethod.getConsumes();
jaxrsRes.contextPath = contextPath;
jaxrsRes.httpMethods = resMethod.getHttpMethods();
jaxrsRes.method = resMethod.getMethod();
jaxrsRes.produceTypes = resMethod.getProduces();
jaxrsRes.resourceClass = resClass.getClazz().getCanonicalName();
String resPath = new StringBuilder(mapping).append("/").append(resMethod.getFullpath()).toString().replace("//", "/");
jaxrsRes.resourcePath = resPath;
jaxrsRes.servletMappings = servletMappings;
addMethodParameters(jaxrsRes, resMethod.getMethod());
locatorRes.methodsDescriptions.add(jaxrsRes);
}
for (ResourceLocator resLocator: resClass.getResourceLocators()) {
Class<?> clz = resLocator.getReturnType();
if (clz.equals(resClass.getClazz())) {
break;
}
if (resolvedCls.contains(clz)) {
break;
} else {
resolvedCls.add(clz);
}
ResourceClass subResClass = ResourceBuilder.locatorFromAnnotations(clz);
String subMapping = new StringBuilder(mapping).append("/").append(resLocator.getFullpath()).toString().replace("//", "/");
JaxrsResourceLocatorDescription inner = resLocatorDescription(subResClass, contextPath, subMapping, servletMappings, resolvedCls);
if (inner.containsMethodResources()) {
locatorRes.subLocatorDescriptions.add(inner);
}
}
return locatorRes;
}
private JaxrsResourceMethodDescription resMethodDescription(ResourceMethodInvoker methodInvoker, String contextPath,
String mapping, Collection<String> servletMappings, String clsName) {
JaxrsResourceMethodDescription jaxrsRes = new JaxrsResourceMethodDescription();
jaxrsRes.consumeTypes = methodInvoker.getConsumes();
jaxrsRes.contextPath = contextPath;
jaxrsRes.httpMethods = methodInvoker.getHttpMethods();
jaxrsRes.method = methodInvoker.getMethod();
jaxrsRes.produceTypes = methodInvoker.getProduces();
jaxrsRes.resourceClass = clsName;
jaxrsRes.resourcePath = mapping;
jaxrsRes.servletMappings = servletMappings;
addMethodParameters(jaxrsRes, methodInvoker.getMethod());
return jaxrsRes;
}
private void addMethodParameters(JaxrsResourceMethodDescription jaxrsRes, Method method) {
for (Parameter param : method.getParameters()) {
ParamInfo paramInfo = new ParamInfo();
paramInfo.cls = param.getType();
paramInfo.defaultValue = null;
paramInfo.name = null;
paramInfo.type = null;
Annotation annotation;
if ((annotation = param.getAnnotation(PathParam.class)) != null) {
PathParam pathParam = (PathParam) annotation;
paramInfo.name = pathParam.value();
paramInfo.type = "@" + PathParam.class.getSimpleName();
} else if ((annotation = param.getAnnotation(QueryParam.class)) != null) {
QueryParam queryParam = (QueryParam) annotation;
paramInfo.name = queryParam.value();
paramInfo.type = "@" + QueryParam.class.getSimpleName();
} else if ((annotation = param.getAnnotation(HeaderParam.class)) != null) {
HeaderParam headerParam = (HeaderParam) annotation;
paramInfo.name = headerParam.value();
paramInfo.type = "@" + HeaderParam.class.getSimpleName();
} else if ((annotation = param.getAnnotation(CookieParam.class)) != null) {
CookieParam cookieParam = (CookieParam) annotation;
paramInfo.name = cookieParam.value();
paramInfo.type = "@" + CookieParam.class.getSimpleName();
} else if ((annotation = param.getAnnotation(MatrixParam.class)) != null) {
MatrixParam matrixParam = (MatrixParam) annotation;
paramInfo.name = matrixParam.value();
paramInfo.type = "@" + MatrixParam.class.getSimpleName();
} else if ((annotation = param.getAnnotation(FormParam.class)) != null) {
FormParam formParam = (FormParam) annotation;
paramInfo.name = formParam.value();
paramInfo.type = "@" + FormParam.class.getSimpleName();
}
if (paramInfo.name == null) {
paramInfo.name = param.getName();
}
if ((annotation = param.getAnnotation(DefaultValue.class)) != null) {
DefaultValue defaultValue = (DefaultValue) annotation;
paramInfo.defaultValue = defaultValue.value();
}
jaxrsRes.parameters.add(paramInfo);
}
}
private static class JaxrsResourceLocatorDescription implements Comparable<JaxrsResourceLocatorDescription> {
private Class<?> resourceClass;
private List<JaxrsResourceMethodDescription> methodsDescriptions = new ArrayList<>();
private List<JaxrsResourceLocatorDescription> subLocatorDescriptions = new ArrayList<>();
@Override
public int compareTo(JaxrsResourceLocatorDescription o) {
return resourceClass.getCanonicalName().compareTo(o.resourceClass.getCanonicalName());
}
public ModelNode toModelNode() {
ModelNode node = new ModelNode();
node.get(RESOURCE_CLASS.getName()).set(resourceClass.getCanonicalName());
ModelNode resPathNode = node.get(RESOURCE_PATHS.getName());
Collections.sort(methodsDescriptions);
for (JaxrsResourceMethodDescription methodRes : methodsDescriptions) {
resPathNode.add(methodRes.toModelNode());
}
ModelNode subResNode = node.get(SUB_RESOURCE_LOCATORS.getName());
Collections.sort(subLocatorDescriptions);
for (JaxrsResourceLocatorDescription subLocator : subLocatorDescriptions) {
subResNode.add(subLocator.toModelNode());
}
return node;
}
private boolean containsMethodResources() {
if (!this.methodsDescriptions.isEmpty()) {
return true;
}
for (JaxrsResourceLocatorDescription p : this.subLocatorDescriptions) {
if (p.containsMethodResources()) {
return true;
}
}
return false;
}
}
private static class JaxrsResourceMethodDescription implements Comparable<JaxrsResourceMethodDescription> {
private String resourceClass;
private String resourcePath;
private Method method;
private List<ParamInfo> parameters = new ArrayList<>();
private Set<String> httpMethods = Collections.emptySet();
private MediaType[] consumeTypes;
private MediaType[] produceTypes;
private Collection<String> servletMappings = Collections.emptyList();
private String contextPath;
@Override
public int compareTo(JaxrsResourceMethodDescription other) {
int result = this.resourcePath.compareTo(other.resourcePath);
if (result == 0) {
result = this.resourceClass.compareTo(other.resourceClass);
}
if (result == 0) {
result = this.method.getName().compareTo(other.method.getName());
}
return result;
}
ModelNode toModelNode() {
ModelNode node = new ModelNode();
node.get(RESOURCE_PATH.getName()).set(resourcePath);
ModelNode consumeNode = node.get(CONSUMES.getName());
if (consumeTypes != null && consumeTypes.length > 0) {
for (MediaType consume : consumeTypes) {
consumeNode.add(consume.toString());
}
}
ModelNode produceNode = node.get(PRODUCES.getName());
if (produceTypes != null && produceTypes.length > 0) {
for (MediaType produce : produceTypes) {
produceNode.add(produce.toString());
}
}
node.get(JAVA_METHOD.getName()).set(formatJavaMethod());
for (final String servletMapping : servletMappings) {
for (final String httpMethod : httpMethods) {
node.get(RESOURCE_METHODS.getName()).add(httpMethod + " " + formatPath(servletMapping, contextPath, resourcePath));
}
}
return node;
}
private String formatPath(String servletMapping, String ctxPath, String resPath) {
StringBuilder sb = new StringBuilder();
String servletPath = servletMapping.replaceAll("\\*", "");
if (servletPath.charAt(0) == '/') {
servletPath = servletPath.substring(1);
}
sb.append(ctxPath).append('/').append(servletPath).append(resPath);
return sb.toString().replace("//", "/");
}
private String formatJavaMethod() {
StringBuilder sb = new StringBuilder();
sb.append(method.getReturnType().getCanonicalName()).append(" ").append(resourceClass)
.append(".").append(method.getName()).append('(');
int i = 0;
for (ParamInfo param : this.parameters) {
if (param.type != null) {
sb.append(param.type).append(" ");
}
sb.append(param.cls.getCanonicalName()).append(" ").append(param.name);
if (param.defaultValue != null) {
sb.append(" = '");
sb.append(param.defaultValue);
sb.append("'");
}
if (++i < this.parameters.size()) {
sb.append(", ");
}
}
sb.append(")");
return sb.toString();
}
}
private static class ParamInfo {
private String name;
private Class<?> cls;
private String type; // @PathParam, or @CookieParam, or @QueryParam, etc
private String defaultValue;
}
}
| 33,027 | 57.353357 | 228 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/JaxrsServerConfigService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jaxrs;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* WS server config service.
*
* @author <a href="[email protected]">Alessio Soldano</a>
* @author <a href="mailto:[email protected]">Richard Opalka</a>
* @author <a href="mailto:[email protected]">Jim Ma</a>
* @author <a href="mailto:[email protected]">Ron Sigal</a>
*/
public final class JaxrsServerConfigService implements Service<JaxrsServerConfig> {
public static final ServiceName JAXRS_SERVICE = ServiceName.JBOSS.append("jaxrs");
public static final ServiceName CONFIG_SERVICE = JAXRS_SERVICE.append("config");
private final JaxrsServerConfig serverConfig;
private JaxrsServerConfigService(final JaxrsServerConfig serverConfig) {
this.serverConfig = serverConfig;
}
@Override
public void start(final StartContext context) throws StartException {
}
@Override
public void stop(final StopContext context) {
}
public static ServiceController<?> install(final ServiceTarget serviceTarget, final JaxrsServerConfig serverConfig) {
final ServiceBuilder<?> builder = serviceTarget.addService(CONFIG_SERVICE);
builder.setInstance(new JaxrsServerConfigService(serverConfig));
return builder.install();
}
public JaxrsServerConfig getJaxrsServerConfig() {
return serverConfig;
}
@Override
public JaxrsServerConfig getValue() throws IllegalStateException, IllegalArgumentException {
return serverConfig;
}
}
| 2,846 | 36.96 | 121 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/ResteasyExtensionTransformerRegistration.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jaxrs;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.transform.ExtensionTransformerRegistration;
import org.jboss.as.controller.transform.SubsystemTransformerRegistration;
import org.jboss.as.controller.transform.description.ChainedTransformationDescriptionBuilder;
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.as.controller.transform.description.TransformationDescriptionBuilder;
import org.kohsuke.MetaInfServices;
/**
* @author <a href="mailto:[email protected]">James R. Perkins</a>
*/
@MetaInfServices
public class ResteasyExtensionTransformerRegistration implements ExtensionTransformerRegistration {
private static final ModelVersion VERSION_3_0_0 = ModelVersion.create(3, 0, 0);
@Override
public String getSubsystemName() {
return JaxrsExtension.SUBSYSTEM_NAME;
}
@Override
public void registerTransformers(final SubsystemTransformerRegistration subsystemRegistration) {
ChainedTransformationDescriptionBuilder builder = TransformationDescriptionBuilder.Factory.createChainedSubystemInstance(subsystemRegistration.getCurrentSubsystemVersion());
registerV3Transformers(builder.createBuilder(JaxrsExtension.CURRENT_MODEL_VERSION, VERSION_3_0_0));
builder.buildAndRegister(subsystemRegistration, new ModelVersion[] {VERSION_3_0_0, JaxrsExtension.CURRENT_MODEL_VERSION});
}
private static void registerV3Transformers(ResourceTransformationDescriptionBuilder subsystem) {
subsystem.getAttributeBuilder()
.setDiscard(DiscardAttributeChecker.DEFAULT_VALUE, JaxrsAttribute.TRACING_TYPE, JaxrsAttribute.TRACING_THRESHOLD)
.addRejectCheck(RejectAttributeChecker.DEFINED, JaxrsAttribute.TRACING_TYPE, JaxrsAttribute.TRACING_THRESHOLD);
}
}
| 3,054 | 47.492063 | 181 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/JaxrsConstants.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2019, 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.jaxrs;
import java.util.HashMap;
import java.util.Map;
import org.jboss.as.controller.AttributeDefinition;
public class JaxrsConstants {
public static final String JAXRS_2_0_REQUEST_MATCHING = "jaxrs-2-0-request-matching";
public static final String RESTEASY_ADD_CHARSET = "resteasy-add-charset";
public static final String RESTEASY_BUFFER_EXCEPTION_ENTITY = "resteasy-buffer-exception-entity";
public static final String RESTEASY_DISABLE_HTML_SANITIZER = "resteasy-disable-html-sanitizer";
public static final String RESTEASY_DISABLE_PROVIDERS = "resteasy-disable-providers";
@Deprecated
public static final String RESTEASY_DOCUMENT_EXPAND_ENTITY_REFERENCES = "resteasy-document-expand-entity-references";
@Deprecated
public static final String RESTEASY_DOCUMENT_SECURE_DISABLE_DTDS = "resteasy-document-secure-disableDTDs";
public static final String RESTEASY_DOCUMENT_SECURE_PROCESSING_FEATURE = "resteasy-document-secure-processing-feature";
public static final String RESTEASY_GZIP_MAX_INPUT = "resteasy-gzip-max-input";
public static final String RESTEASY_JNDI_RESOURCES = "resteasy-jndi-resources";
public static final String RESTEASY_LANGUAGE_MAPPINGS = "resteasy-language-mappings";
public static final String RESTEASY_MEDIA_TYPE_MAPPINGS = "resteasy-media-type-mappings";
public static final String RESTEASY_MEDIA_TYPE_PARAM_MAPPING = "resteasy-media-type-param-mapping";
public static final String RESTEASY_PREFER_JACKSON_OVER_JSONB = "resteasy-prefer-jackson-over-jsonb";
public static final String RESTEASY_PROVIDERS = "resteasy-providers";
public static final String RESTEASY_RFC7232_PRECONDITIONS = "resteasy-rfc7232preconditions";
public static final String RESTEASY_ROLE_BASED_SECURITY = "resteasy-role-based-security";
public static final String RESTEASY_SECURE_RANDOM_MAX_USE = "resteasy-secure-random-max-use";
public static final String RESTEASY_USE_BUILTIN_PROVIDERS = "resteasy-use-builtin-providers";
public static final String RESTEASY_USE_CONTAINER_FORM_PARAMS = "resteasy-use-container-form-params";
public static final String RESTEASY_WIDER_REQUEST_MATCHING = "resteasy-wider-request-matching";
public static final Map<String, AttributeDefinition> nameToAttributeMap = new HashMap<String,AttributeDefinition> ();
static {
nameToAttributeMap.put(JAXRS_2_0_REQUEST_MATCHING, JaxrsAttribute.JAXRS_2_0_REQUEST_MATCHING);
nameToAttributeMap.put(RESTEASY_ADD_CHARSET, JaxrsAttribute.RESTEASY_ADD_CHARSET);
nameToAttributeMap.put(RESTEASY_BUFFER_EXCEPTION_ENTITY, JaxrsAttribute.RESTEASY_BUFFER_EXCEPTION_ENTITY);
nameToAttributeMap.put(RESTEASY_DISABLE_HTML_SANITIZER, JaxrsAttribute.RESTEASY_DISABLE_HTML_SANITIZER);
nameToAttributeMap.put(RESTEASY_DISABLE_PROVIDERS, JaxrsAttribute.RESTEASY_DISABLE_PROVIDERS);
nameToAttributeMap.put(RESTEASY_DOCUMENT_EXPAND_ENTITY_REFERENCES, JaxrsAttribute.RESTEASY_DOCUMENT_EXPAND_ENTITY_REFERENCES);
nameToAttributeMap.put(RESTEASY_DOCUMENT_SECURE_DISABLE_DTDS, JaxrsAttribute.RESTEASY_DOCUMENT_SECURE_DISABLE_DTDS);
nameToAttributeMap.put(RESTEASY_DOCUMENT_SECURE_PROCESSING_FEATURE, JaxrsAttribute.RESTEASY_DOCUMENT_SECURE_PROCESSING_FEATURE);
nameToAttributeMap.put(RESTEASY_GZIP_MAX_INPUT, JaxrsAttribute.RESTEASY_GZIP_MAX_INPUT);
nameToAttributeMap.put(RESTEASY_JNDI_RESOURCES, JaxrsAttribute.RESTEASY_JNDI_RESOURCES);
nameToAttributeMap.put(RESTEASY_LANGUAGE_MAPPINGS, JaxrsAttribute.RESTEASY_LANGUAGE_MAPPINGS);
nameToAttributeMap.put(RESTEASY_MEDIA_TYPE_MAPPINGS, JaxrsAttribute.RESTEASY_MEDIA_TYPE_MAPPINGS);
nameToAttributeMap.put(RESTEASY_MEDIA_TYPE_PARAM_MAPPING, JaxrsAttribute.RESTEASY_MEDIA_TYPE_PARAM_MAPPING);
nameToAttributeMap.put(RESTEASY_PREFER_JACKSON_OVER_JSONB, JaxrsAttribute.RESTEASY_PREFER_JACKSON_OVER_JSONB);
nameToAttributeMap.put(RESTEASY_PROVIDERS, JaxrsAttribute.RESTEASY_PROVIDERS);
nameToAttributeMap.put(RESTEASY_RFC7232_PRECONDITIONS, JaxrsAttribute.RESTEASY_RFC7232_PRECONDITIONS);
nameToAttributeMap.put(RESTEASY_ROLE_BASED_SECURITY, JaxrsAttribute.RESTEASY_ROLE_BASED_SECURITY);
nameToAttributeMap.put(RESTEASY_SECURE_RANDOM_MAX_USE, JaxrsAttribute.RESTEASY_SECURE_RANDOM_MAX_USE);
nameToAttributeMap.put(RESTEASY_USE_BUILTIN_PROVIDERS, JaxrsAttribute.RESTEASY_USE_BUILTIN_PROVIDERS);
nameToAttributeMap.put(RESTEASY_USE_CONTAINER_FORM_PARAMS, JaxrsAttribute.RESTEASY_USE_CONTAINER_FORM_PARAMS);
nameToAttributeMap.put(RESTEASY_WIDER_REQUEST_MATCHING, JaxrsAttribute.RESTEASY_WIDER_REQUEST_MATCHING);
}
}
| 5,721 | 70.525 | 136 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/logging/JaxrsLogger.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jaxrs.logging;
import static org.jboss.logging.Logger.Level.ERROR;
import static org.jboss.logging.Logger.Level.INFO;
import static org.jboss.logging.Logger.Level.WARN;
import java.util.List;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.jaxrs.deployment.JaxrsSpringProcessor;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.dmr.ModelNode;
import org.jboss.jandex.AnnotationTarget;
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>
*/
@SuppressWarnings("deprecation")
@MessageLogger(projectCode = "WFLYRS", length = 4)
public interface JaxrsLogger extends BasicLogger {
/**
* A logger with the category {@code org.jboss.jaxrs}.
*/
JaxrsLogger JAXRS_LOGGER = Logger.getMessageLogger(JaxrsLogger.class, "org.jboss.as.jaxrs");
/**
* Logs a warning message indicating the annotation, represented by the {@code annotation} parameter, not on Class,
* represented by the {@code target} parameter.
*
* @param annotation the missing annotation.
* @param target the target.
*/
@LogMessage(level = WARN)
@Message(id = 1, value = "%s annotation not on Class: %s")
void classAnnotationNotFound(String annotation, AnnotationTarget target);
/**
* Logs a warning message indicating the annotation, represented by the {@code annotation} parameter, not on Class
* or Method, represented by the {@code target} parameter.
*
* @param annotation the missing annotation.
* @param target the target.
*/
@LogMessage(level = WARN)
@Message(id = 2, value = "%s annotation not on Class or Method: %s")
void classOrMethodAnnotationNotFound(String annotation, AnnotationTarget target);
/**
* Logs an error message indicating more than one mapping found for Jakarta RESTful Web Services servlet, represented by the
* {@code servletName} parameter, the second mapping, represented by the {@code pattern} parameter, will not work.
*
* @param servletName the name of the servlet.
* @param pattern the pattern.
*/
@LogMessage(level = ERROR)
@Message(id = 3, value = "More than one mapping found for Jakarta RESTful Web Services servlet: %s the second mapping %s will not work")
void moreThanOneServletMapping(String servletName, String pattern);
// /**
// * Logs a warning message indicating no servlet mappings found for the Jakarta RESTful Web Services application, represented by the
// * {@code servletName} parameter, either annotate with {@link jakarta.ws.rs.ApplicationPath @ApplicationPath} or add
// * a {@code servlet-mapping} in the web.xml.
// *
// * @param servletName the servlet name.
// */
// @LogMessage(level = WARN)
// @Message(id = 4, value = "No Servlet mappings found for Jakarta RESTful Web Services application: %s either annotate it with @ApplicationPath or add a servlet-mapping in web.xml")
// void noServletMappingFound(String servletName);
//
// /**
// * Logs a warning message indicating that {@code resteasy.scan} was found in the {@code web.xml} and is not
// * necessary.
// */
// @LogMessage(level = WARN)
// @Message(id = 5, value = "%s found and ignored in web.xml. This is not necessary, as Resteasy will use the container integration in the JAX-RS 1.1 specification in section 2.3.2")
// void resteasyScanWarning(String param);
/**
* Creates an exception indicating the Jakarta RESTful Web Services application class could not be loaded.
*
* @param cause the cause of the error.
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 6, value = "Could not load Jakarta RESTful Web Services Application class")
DeploymentUnitProcessingException cannotLoadApplicationClass(@Cause Throwable cause);
// /**
// * Creates an exception indicating more than one application class found in deployment.
// *
// * @param app1 the first application.
// * @param app2 the second application.
// * @return a {@link DeploymentUnitProcessingException} for the error.
// */
// @Message(id = 7, value = "More than one Application class found in deployment %s and %s")
// DeploymentUnitProcessingException moreThanOneApplicationClassFound(Class<? extends Application> app1, Class<? extends Application> app2);
//
// /**
// * A message indicating only one Jakarta RESTful Web Services application class is allowed.
// *
// * @param sb a builder with application classes.
// * @return the message.
// */
// @Message(id = 8, value = "Only one Jakarta RESTful Web Services Application Class allowed. %s")
// String onlyOneApplicationClassAllowed(StringBuilder sb);
//
// /**
// * A message indicating the incorrect mapping config.
// *
// * @return the message.
// */
// @Message(id = 9, value = "Please use either @ApplicationPath or servlet mapping for url path config.")
// String conflictUrlMapping();
/**
* Jakarta RESTful Web Services resource @Path annotation is on a class or interface that is not a view
*
*
* @param type The class with the annotation
* @param ejbName The ejb
* @return the exception
*/
@Message(id = 10, value = "Jakarta RESTful Web Services resource %s does not correspond to a view on the Jakarta Enterprise Beans %s. @Path annotations can only be placed on classes or interfaces that represent a local, remote or no-interface view of an Jakarta Enterprise Beans.")
DeploymentUnitProcessingException typeNameNotAnEjbView(List<Class<?>> type, String ejbName);
@Message(id = 11, value = "Invalid value for parameter %s: %s")
DeploymentUnitProcessingException invalidParamValue(String param, String value);
@Message(id = 12, value = "No spring integration jar found")
DeploymentUnitProcessingException noSpringIntegrationJar();
@LogMessage(level = WARN)
@Message(id = 13, value = "The context param " + JaxrsSpringProcessor.DISABLE_PROPERTY + " is deprecated, and will be removed in a future release. Please use " + JaxrsSpringProcessor.ENABLE_PROPERTY + " instead")
void disablePropertyDeprecated();
@LogMessage(level = ERROR)
@Message(id = 14, value = "Failed to register management view for REST resource class: %s")
void failedToRegisterManagementViewForRESTResources(String resClass, @Cause Exception e);
@LogMessage(level = WARN)
@Message(id = 15, value = "No Servlet declaration found for Jakarta RESTful Web Services application. In %s either provide a class that extends jakarta.ws.rs.core.Application or declare a servlet class in web.xml.")
void noServletDeclaration(String archiveName);
@LogMessage(level = INFO)
@Message(id = 16, value = "RESTEasy version %s")
void resteasyVersion(String version);
@LogMessage(level = WARN)
@Message(id = 17, value = "Failed to read attribute from Jakarta RESTful Web Services deployment at %s with name %s")
void failedToReadAttribute(@Cause Exception ex, PathAddress address, ModelNode modelNode);
@LogMessage(level = WARN)
@Message(id = 18, value = "Explicit usage of Jackson annotation in a Jakarta RESTful Web Services deployment; the system will disable Jakarta JSON Binding processing for the current deployment. Consider setting the '%s' property to 'false' to restore Jakarta JSON Binding.")
void jacksonAnnotationDetected(String property);
@LogMessage(level = WARN)
@Message(id = 19, value = "Error converting default value %s for parameter %s in method %s using param converter %s. Exception: %s : %s")
void paramConverterFailed(String defaultValue, String param, String method,
String paramConverter, String exceptionClass,
String exceptionMsg);
@LogMessage(level = WARN)
@Message(id = 20, value = "\"Error converting default value %s for parameter %s in method %s using method %s. Exception: %s : %s\"")
void baseTypeMethodFailed(String defaultValue, String param, String method,
String converterMethod, String exceptionClass,
String exceptionMsg);
@LogMessage(level = ERROR)
@Message(id = 21, value = "%s %s")
void classIntrospectionFailure(String clazz, String msg);
@Message(id = 22, value = "\"Parameter %s is not a list\"")
OperationFailedException parameterNotList(String param);
@Message(id = 23, value = "Illegal value for parameter %s: %s")
String illegalArgument(String name, String value);
@LogMessage(level = WARN)
@Message(id = 29, value = "The RESTEasy tracing API has been enabled for deployment \"%s\" and is not meant for production.")
void tracingEnabled(String deploymentName);
@Message(id = 30, value = "Invalid ConfigurationFactory found %s")
IllegalStateException invalidConfigurationFactory(Class<?> factory);
@LogMessage(level = WARN)
@Message(id = 31, value = "Failed to load RESTEasy MicroProfile Configuration: %s")
void failedToLoadConfigurationFactory(String msg);
}
| 10,640 | 47.368182 | 285 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/deployment/JaxrsAnnotationProcessor.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.jaxrs.deployment;
import org.jboss.as.jaxrs.JaxrsAnnotations;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.annotation.CompositeIndex;
import static org.jboss.as.ee.weld.InjectionTargetDefiningAnnotations.INJECTION_TARGET_DEFINING_ANNOTATIONS;
/**
* Looks for jaxrs annotations in war deployments
*
* @author Stuart Douglas
*/
public class JaxrsAnnotationProcessor implements DeploymentUnitProcessor {
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (deploymentUnit.getParent() == null) {
//register resource, provider and application as Jakarta Contexts and Dependency Injection annotation defining types
deploymentUnit.addToAttachmentList(INJECTION_TARGET_DEFINING_ANNOTATIONS, JaxrsAnnotations.PROVIDER.getDotName());
deploymentUnit.addToAttachmentList(INJECTION_TARGET_DEFINING_ANNOTATIONS, JaxrsAnnotations.PATH.getDotName());
}
final CompositeIndex index = deploymentUnit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
for (final JaxrsAnnotations annotation : JaxrsAnnotations.values()) {
if (!index.getAnnotations(annotation.getDotName()).isEmpty()) {
JaxrsDeploymentMarker.mark(deploymentUnit);
return;
}
}
}
@Override
public void undeploy(DeploymentUnit deploymentUnit) {
if (deploymentUnit.getParent() == null) {
deploymentUnit.getAttachmentList(INJECTION_TARGET_DEFINING_ANNOTATIONS).remove(JaxrsAnnotations.PROVIDER.getDotName());
deploymentUnit.getAttachmentList(INJECTION_TARGET_DEFINING_ANNOTATIONS).remove(JaxrsAnnotations.PATH.getDotName());
}
}
}
| 3,158 | 44.128571 | 131 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/deployment/JaxrsDeploymentMarker.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.jaxrs.deployment;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.server.deployment.DeploymentUnit;
/**
* Marker for Jakarta RESTful Web Services deployments
*
* @author Stuart Douglas
*/
public class JaxrsDeploymentMarker {
private static final AttachmentKey<Boolean> ATTACHMENT_KEY = AttachmentKey.create(Boolean.class);
public static void mark(DeploymentUnit deployment) {
if (deployment.getParent() != null) {
deployment.getParent().putAttachment(ATTACHMENT_KEY, true);
} else {
deployment.putAttachment(ATTACHMENT_KEY, true);
}
}
//This actually tells whether the deployment unit is potentially part of a Jakarta RESTful Web Services deployment;
//in practice, we might not be dealing with a Jakarta RESTful Web Services deployment (it depends on which/where
//Jakarta RESTful Web Services annotations are found in the deployment, especially if it's an EAR one)
public static boolean isJaxrsDeployment(DeploymentUnit deploymentUnit) {
DeploymentUnit deployment = deploymentUnit.getParent() == null ? deploymentUnit : deploymentUnit.getParent();
Boolean val = deployment.getAttachment(ATTACHMENT_KEY);
return val != null && val;
}
}
| 2,311 | 43.461538 | 119 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/deployment/ResteasyContextHandleFactory.java
|
/*
* Copyright 2021 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.jaxrs.deployment;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map;
import jakarta.enterprise.concurrent.ContextService;
import org.jboss.as.ee.concurrent.handle.ContextHandleFactory;
import org.jboss.as.ee.concurrent.handle.ResetContextHandle;
import org.jboss.as.ee.concurrent.handle.SetupContextHandle;
import org.jboss.resteasy.core.ResteasyContext;
/**
* A context factory for propagating the RESTEasy context for managed threads.
*
* @author <a href="mailto:[email protected]">James R. Perkins</a>
*/
class ResteasyContextHandleFactory implements ContextHandleFactory {
private static final String NAME = "RESTEASY";
static ResteasyContextHandleFactory INSTANCE = new ResteasyContextHandleFactory();
private ResteasyContextHandleFactory() {
}
@Override
public SetupContextHandle saveContext(final ContextService contextService, final Map<String, String> contextObjectProperties) {
return new ResteasySetupContextHandle();
}
@Override
public int getChainPriority() {
return 900;
}
@Override
public String getName() {
return NAME;
}
@Override
public void writeSetupContextHandle(final SetupContextHandle contextHandle, final ObjectOutputStream out) {
}
@Override
public SetupContextHandle readSetupContextHandle(final ObjectInputStream in) {
return new ResteasySetupContextHandle();
}
private static class ResteasySetupContextHandle implements SetupContextHandle {
private final Map<Class<?>, Object> currentContext;
private ResteasySetupContextHandle() {
this.currentContext = ResteasyContext.getContextDataMap();
}
@Override
public ResetContextHandle setup() throws IllegalStateException {
ResteasyContext.pushContextDataMap(currentContext);
return new ResetContextHandle() {
@Override
public void reset() {
ResteasyContext.removeContextDataLevel();
}
@Override
public String getFactoryName() {
return NAME;
}
};
}
@Override
public String getFactoryName() {
return NAME;
}
}
}
| 2,945 | 30.340426 | 131 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/deployment/JaxrsMethodParameterProcessor.java
|
package org.jboss.as.jaxrs.deployment;
import org.jboss.as.ee.structure.DeploymentType;
import org.jboss.as.ee.structure.DeploymentTypeMarker;
import org.jboss.as.jaxrs.JaxrsAnnotations;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.annotation.CompositeIndex;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.Index;
import org.jboss.jandex.Indexer;
import org.jboss.modules.Module;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.ext.ParamConverter;
import jakarta.ws.rs.ext.ParamConverterProvider;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.jboss.as.jaxrs.logging.JaxrsLogger.JAXRS_LOGGER;
/**
* This class addresses the spec requirement of pre-processing resource
* method parameters with DefaultValue annotations at application deployment
* time.
* (section 3.2 of the Jakarta RESTful Web Services 2.1 specification)
*/
public class JaxrsMethodParameterProcessor implements DeploymentUnitProcessor {
private final DotName PARAM_CONVERTER_PROVIDER_DOTNAME =
DotName.createSimple("jakarta.ws.rs.ext.ParamConverterProvider");
private final DotName PARAM_CONVERTER_DOTNAME =
DotName.createSimple("jakarta.ws.rs.ext.ParamConverter");
private final DotName PARAM_CONVERTER_LAZY_DOTNAME =
DotName.createSimple("jakarta.ws.rs.ext.ParamConverter$Lazy");
private final DotName DEFAULT_VALUE_DOTNAME =
DotName.createSimple("jakarta.ws.rs.DefaultValue");
@Override
public void deploy(DeploymentPhaseContext phaseContext)
throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (!JaxrsDeploymentMarker.isJaxrsDeployment(deploymentUnit)) {
return;
}
if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) {
return;
}
final ResteasyDeploymentData resteasy = deploymentUnit.getAttachment(
JaxrsAttachments.RESTEASY_DEPLOYMENT_DATA);
if (resteasy == null) {
return;
}
final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
final CompositeIndex index = deploymentUnit.getAttachment(
Attachments.COMPOSITE_ANNOTATION_INDEX);
processData(index, module.getClassLoader(), resteasy, false);
}
/**
*
* @param index
* @param classLoader
* @param resteasy
* @param isFromUnitTest
* @throws DeploymentUnitProcessingException
*/
private void processData(final CompositeIndex index, final ClassLoader classLoader,
ResteasyDeploymentData resteasy, boolean isFromUnitTest)
throws DeploymentUnitProcessingException {
List<ParamDetail> detailList = getResouceClasses(index, classLoader,
resteasy.getScannedResourceClasses(), isFromUnitTest);
if (!detailList.isEmpty()) {
HashMap<String, List<Validator>> paramConverterMap =
getParamConverters(index, classLoader,
resteasy.getScannedProviderClasses(), isFromUnitTest);
validateDefaultValues(detailList, paramConverterMap);
}
}
/**
* Process all parameter DefaulValue objects. Flag all parameters with
* missing and invalid converters.
*
* @param detailList
* @param paramConverterMap
*/
private void validateDefaultValues(List<ParamDetail> detailList,
HashMap<String, List<Validator>> paramConverterMap)
throws DeploymentUnitProcessingException {
for(ParamDetail detail : detailList) {
// check param converter for specific return type
List<Validator> validators = paramConverterMap.get(
detail.parameter.getName());
if (validators == null) {
// check for paramConverterProvider
validators = paramConverterMap.get(Object.class.getName());
}
boolean isCheckClazzMethods = true;
if (validators != null) {
for (Validator v : validators) {
if (!v.isLazyLoad()) {
try {
Object obj = v.verify(detail);
if (obj != null) {
isCheckClazzMethods = false;
break;
}
} catch (Exception e) {
JAXRS_LOGGER.paramConverterFailed(detail.defaultValue.value(),
detail.parameter.getSimpleName(),
detail.method.toString(),
v.toString(), e.getClass().getName(),
e.getMessage());
}
}
}
}
if (isCheckClazzMethods) {
Class baseType = detail.parameter;
Method valueOf = null;
// constructor rule
try {
Constructor<?> ctor = baseType.getConstructor(String.class);
if (Modifier.isPublic(ctor.getModifiers())) {
continue; // success move to next detail
}
} catch (NoSuchMethodException ignored) { }
// method fromValue(String.class) rule
try {
Method fromValue = baseType.getDeclaredMethod("fromValue", String.class);
if (Modifier.isPublic(fromValue.getModifiers())) {
for (Annotation ann : baseType.getAnnotations()) {
if (ann.annotationType().getName()
.equals("jakarta.xml.bind.annotation.XmlEnum")) {
valueOf = fromValue;
}
}
validateBaseType(fromValue, detail.defaultValue.value(), detail);
continue; // success move to next detail
}
} catch (NoSuchMethodException ignoredA) { }
// method fromString(String.class) rule
Method fromString = null;
try {
fromString = baseType.getDeclaredMethod("fromString", String.class);
if (Modifier.isStatic(fromString.getModifiers())) {
validateBaseType(fromString, detail.defaultValue.value(), detail);
continue; // success move to next detail
}
} catch (NoSuchMethodException ignoredB) {
}
// method valueof(String.class) rule
try {
valueOf = baseType.getDeclaredMethod("valueOf", String.class);
if (Modifier.isStatic(valueOf.getModifiers())) {
validateBaseType(valueOf, detail.defaultValue.value(), detail);
continue; // success move to next detail
}
} catch (NoSuchMethodException ignored) {
}
}
}
}
/**
* Create a list of ParamConverters and ParamConverterProviders present
* in the application.
*
* When running unitTest the classes must be indexed. In normal deployment
* the indexing is already done.
*
* @param index
* @param classLoader
* @return
*/
private HashMap<String, List<Validator>> getParamConverters(
final CompositeIndex index, final ClassLoader classLoader,
Set<String> knownProviderClasses, boolean isFromUnitTest) {
HashMap<String, List<Validator>> paramConverterMap = new HashMap<>();
List<Validator> converterProviderList = new ArrayList<>();
paramConverterMap.put(Object.class.getName(), converterProviderList);
Set<ClassInfo> paramConverterSet = new HashSet<ClassInfo>();
if(isFromUnitTest) {
Indexer indexer = new Indexer();
for (String className : knownProviderClasses) {
try {
String pathName = className.replace(".", File.separator);
InputStream stream = classLoader.getResourceAsStream(
pathName + ".class");
indexer.index(stream);
stream.close();
} catch (IOException e) {
JAXRS_LOGGER.classIntrospectionFailure(e.getClass().getName(),
e.getMessage());
}
}
Index tmpIndex = indexer.complete();
List<ClassInfo> paramConverterList =
tmpIndex.getKnownDirectImplementors(PARAM_CONVERTER_DOTNAME);
List<ClassInfo> paramConverterProviderList =
tmpIndex.getKnownDirectImplementors(PARAM_CONVERTER_PROVIDER_DOTNAME);
paramConverterSet.addAll(paramConverterList);
paramConverterSet.addAll(paramConverterProviderList);
} else {
for (String clazzName : knownProviderClasses) {
ClassInfo classInfo = index.getClassByName(DotName.createSimple(clazzName));
if (classInfo != null) {
List<DotName> intfNamesList = classInfo.interfaceNames();
for (DotName dotName : intfNamesList) {
if (dotName.compareTo(PARAM_CONVERTER_DOTNAME) == 0
|| dotName.compareTo(PARAM_CONVERTER_PROVIDER_DOTNAME) == 0) {
paramConverterSet.add(classInfo);
break;
}
}
}
}
}
for (ClassInfo classInfo : paramConverterSet) {
Class<?> clazz = null;
Method method = null;
try {
String clazzName = classInfo.name().toString();
if (clazzName.endsWith("$1")) {
clazzName = clazzName.substring(0, clazzName.length()-2);
}
clazz = classLoader.loadClass(clazzName);
Constructor<?> ctor = clazz.getConstructor();
Object object = ctor.newInstance();
List<AnnotationInstance> lazyLoadAnnotations =classInfo
.annotationsMap().get(PARAM_CONVERTER_LAZY_DOTNAME);
if (object instanceof ParamConverterProvider) {
ParamConverterProvider pcpObj = (ParamConverterProvider) object;
method = pcpObj.getClass().getMethod(
"getConverter",
Class.class,
Type.class,
Annotation[].class);
converterProviderList.add(new ConverterProvider(pcpObj, method, lazyLoadAnnotations));
}
if (object instanceof ParamConverter) {
ParamConverter pc = (ParamConverter) object;
method = getFromStringMethod(pc.getClass());
Class<?> returnClazz = method.getReturnType();
List<Validator> verifiers = paramConverterMap.get(returnClazz.getName());
PConverter pConverter = new PConverter(pc, method, lazyLoadAnnotations);
if (verifiers == null){
List<Validator> vList = new ArrayList<>();
vList.add(pConverter);
paramConverterMap.put(returnClazz.getName(), vList);
} else {
verifiers.add(pConverter);
}
}
} catch(NoSuchMethodException nsne) {
JAXRS_LOGGER.classIntrospectionFailure(nsne.getClass().getName(),
nsne.getMessage());
} catch (Exception e) {
JAXRS_LOGGER.classIntrospectionFailure(e.getClass().getName(),
e.getMessage());
}
}
return paramConverterMap;
}
private Method getFromStringMethod(final Class clazz) {
Method method = null;
try {
method = clazz.getMethod("fromString", String.class);
}catch(NoSuchMethodException nsme) {
JAXRS_LOGGER.classIntrospectionFailure(nsme.getClass().getName(),
nsme.getMessage());
}
return method;
}
/**
* Create list of objects that represents resource method parameters with a
* DefaultValue annontation assigned to it.
*
* When running unitTest the classes must be indexed. In normal deployment
* the indexing is already done.
*
* @param index
* @param classLoader
* @return
*/
private ArrayList<ParamDetail> getResouceClasses(final CompositeIndex index,
final ClassLoader classLoader,
Set<String> knownResourceClasses,
boolean isFromUnitTest) {
ArrayList<ParamDetail> detailList = new ArrayList<>();
ArrayList<String> classNameArr = new ArrayList<>();
if (isFromUnitTest) {
for (String className : knownResourceClasses) {
try {
String pathName = className.replace(".", File.separator);
InputStream stream = classLoader.getResourceAsStream(pathName + ".class");
ClassInfo classInfo = Index.singleClass(stream);
List<AnnotationInstance> defaultValuesList =
classInfo.annotationsMap().get(DEFAULT_VALUE_DOTNAME);
if (!defaultValuesList.isEmpty()) {
classNameArr.add((classInfo).name().toString());
}
stream.close();
} catch (IOException e) {
JAXRS_LOGGER.classIntrospectionFailure(e.getClass().getName(),
e.getMessage());
}
}
} else {
for (String clazzName : knownResourceClasses) {
ClassInfo classInfo = index.getClassByName(DotName.createSimple(clazzName));
if (classInfo != null) {
Map<DotName, List<AnnotationInstance>> annotationsMap =
classInfo.annotationsMap();
if (annotationsMap != null && !annotationsMap.isEmpty()) {
List<AnnotationInstance> xInstance = annotationsMap.get(
JaxrsAnnotations.PATH.getDotName());
List<AnnotationInstance> xdefaultValuesList =
annotationsMap.get(DEFAULT_VALUE_DOTNAME);
if ((xInstance != null && !xInstance.isEmpty()) &&
(xdefaultValuesList != null && !xdefaultValuesList.isEmpty())) {
classNameArr.add((classInfo).name().toString());
}
}
}
}
}
// resource classes with @DefaultValue
// find methods and method params with @DefaultValue
for (String className : classNameArr) {
Class<?> clazz = null;
try {
clazz = classLoader.loadClass(className);
for (Method method : clazz.getMethods()) {
if (clazz == method.getDeclaringClass()) {
Type[] genParamTypeArr = method.getGenericParameterTypes();
Annotation[][] annotationMatrix = method.getParameterAnnotations();
for (int j = 0; j < genParamTypeArr.length; j++) {
DefaultValue defaultValue = lookupDefaultValueAnn(annotationMatrix[j]);
if (defaultValue != null) {
Class paramClazz = checkParamType(genParamTypeArr[j],
method, j, classLoader);
if (paramClazz != null) {
detailList.add(new ParamDetail(method,
defaultValue, paramClazz, annotationMatrix[j]));
}
}
}
}
}
} catch (ClassNotFoundException e) {
JAXRS_LOGGER.classIntrospectionFailure(e.getClass().getName(),
e.getMessage());
}
}
return detailList;
}
/**
* Take steps to properly identify the parameter's data type
* @param genParamType
* @param method
* @param paramPos
* @param classLoader
* @return
*/
private Class checkParamType(Type genParamType, final Method method,
final int paramPos, final ClassLoader classLoader){
Class paramClazz = null;
if (genParamType instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType) genParamType;
Type[] actualTypeArgs = pType.getActualTypeArguments();
// skip Map types. Don't know how to set default value for these
if (actualTypeArgs.length == 1) {
try {
paramClazz = classLoader.loadClass(actualTypeArgs[0].getTypeName());
} catch (Exception ee) {
JAXRS_LOGGER.classIntrospectionFailure(ee.getClass().getName(),
ee.getMessage());
}
}
} else {
Class<?>[] paramArr = method.getParameterTypes();
if (paramArr[paramPos].isArray()) {
Class compClazz = paramArr[paramPos].getComponentType();
if (!compClazz.isPrimitive()) {
paramClazz = compClazz;
}
} else {
if (!paramArr[paramPos].isPrimitive()) {
paramClazz = paramArr[paramPos];
}
}
}
return paramClazz;
}
/**
* Extract a DefaultValue annotation from the list of parameter annotations
* @param annotationArr
* @return
*/
private DefaultValue lookupDefaultValueAnn(Annotation[] annotationArr) {
for (Annotation ann : annotationArr) {
if (ann instanceof DefaultValue) {
return (DefaultValue)ann;
}
}
return null;
}
/**
* Data structure for passing around related parameter information
*/
private class ParamDetail {
public Method method;
public DefaultValue defaultValue;
public Class parameter;
public Annotation[] annotations;
public ParamDetail(Method method, DefaultValue defaultValue, Class parameter,
Annotation[] annotations) {
this.method = method;
this.defaultValue = defaultValue;
this.parameter = parameter;
this.annotations = annotations;
}
}
private interface Validator {
public Object verify(ParamDetail detail) throws Exception;
public boolean isLazyLoad();
}
/**
* ParamConverterProvider's getConverter method used for validation
*/
private class ConverterProvider implements Validator {
private ParamConverterProvider pcp;
private ParamConverter pc = null;
private Method method;
private boolean isLazyLoad = false;
public ConverterProvider(ParamConverterProvider pcp, Method method,
List<AnnotationInstance> lazyAnnotations) {
this.pcp = pcp;
this.method = method;
if (lazyAnnotations != null && !lazyAnnotations.isEmpty()) {
isLazyLoad = true;
}
}
public boolean isLazyLoad() {
return isLazyLoad;
}
public Object verify(ParamDetail detail) throws Exception {
Object obj = method.invoke(pcp,
detail.parameter,
detail.parameter.getComponentType(),
detail.annotations);
if (obj instanceof ParamConverter) {
this.pc = (ParamConverter) obj;
return pc.fromString(detail.defaultValue.value());
}
return obj;
}
@Override
public String toString() {
if (pc == null) {
return pcp.getClass().getName();
}
return pc.getClass().getName();
}
}
/**
* ParamConverter's method fromString used for validation
*/
private class PConverter implements Validator {
private ParamConverter pc;
private Method method;
private boolean isLazyLoad = false;
public PConverter(ParamConverter pc, Method method,
List<AnnotationInstance> lazyAnnotations) {
this.pc = pc;
this.method = method;
if (lazyAnnotations != null && !lazyAnnotations.isEmpty()) {
isLazyLoad = true;
}
}
public boolean isLazyLoad() {
return isLazyLoad;
}
public Object verify(ParamDetail detail) throws Exception {
Object obj = method.invoke(pc, detail.defaultValue.value());
return obj;
}
@Override
public String toString() {
return pc.getClass().getName();
}
}
/**
* Confirm the method can handle the default value without throwing
* and exception.
*
* @param method
* @param defaultValue
*/
private void validateBaseType(Method method, String defaultValue, ParamDetail detail)
throws DeploymentUnitProcessingException {
if (defaultValue != null) {
try {
method.invoke(method.getDeclaringClass(), defaultValue);
} catch (Exception e) {
JAXRS_LOGGER.baseTypeMethodFailed(defaultValue,
detail.parameter.getSimpleName(), detail.method.toString(),
method.toString(), e.getClass().getName(),
e.getMessage());
}
}
}
/**
* Method allows unit-test to provide processing data.
* @param resteasyDeploymentData
*/
public void testProcessor(final ClassLoader classLoader,
final ResteasyDeploymentData resteasyDeploymentData)
throws DeploymentUnitProcessingException {
processData(null, classLoader, resteasyDeploymentData, true);
}
}
| 23,849 | 37.970588 | 106 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/deployment/JaxrsSpringProcessor.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.jaxrs.deployment;
import org.jboss.as.jaxrs.logging.JaxrsLogger;
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.ModuleRootMarker;
import org.jboss.as.server.deployment.module.MountHandle;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.as.server.deployment.module.TempFileProviderService;
import org.jboss.as.web.common.WarMetaData;
import org.jboss.metadata.javaee.spec.ParamValueMetaData;
import org.jboss.metadata.web.jboss.JBossServletMetaData;
import org.jboss.metadata.web.jboss.JBossWebMetaData;
import org.jboss.metadata.web.spec.ListenerMetaData;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.vfs.VFS;
import org.jboss.vfs.VFSUtils;
import org.jboss.vfs.VirtualFile;
import java.io.Closeable;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* Recognize Spring deployment and add the Jakarta RESTful Web Services integration to it
*/
public class JaxrsSpringProcessor implements DeploymentUnitProcessor {
private static final String JAR_LOCATION = "resteasy-spring-jar";
private static final ModuleIdentifier MODULE = ModuleIdentifier.create("org.jboss.resteasy.resteasy-spring");
public static final String SPRING_LISTENER = "org.jboss.resteasy.plugins.spring.SpringContextLoaderListener";
public static final String SPRING_SERVLET = "org.springframework.web.servlet.DispatcherServlet";
@Deprecated
public static final String DISABLE_PROPERTY = "org.jboss.as.jaxrs.disableSpringIntegration";
public static final String ENABLE_PROPERTY = "org.jboss.as.jaxrs.enableSpringIntegration";
public static final String SERVICE_NAME = "resteasy-spring-integration-resource-root";
private final ServiceTarget serviceTarget;
private VirtualFile resourceRoot;
public JaxrsSpringProcessor(ServiceTarget serviceTarget) {
this.serviceTarget = serviceTarget;
}
/**
* Lookup Seam integration resource loader.
*
* @return the Seam integration resource loader
* @throws DeploymentUnitProcessingException
* for any error
*/
protected synchronized VirtualFile getResteasySpringVirtualFile() throws DeploymentUnitProcessingException {
if(resourceRoot != null) {
return resourceRoot;
}
try {
Module module = Module.getBootModuleLoader().loadModule(MODULE);
URL fileUrl = module.getClassLoader().getResource(JAR_LOCATION);
if (fileUrl == null) {
throw JaxrsLogger.JAXRS_LOGGER.noSpringIntegrationJar();
}
File dir = new File(fileUrl.toURI());
File file = null;
for (String jar : dir.list()) {
if (jar.endsWith(".jar")) {
file = new File(dir, jar);
break;
}
}
if (file == null) {
throw JaxrsLogger.JAXRS_LOGGER.noSpringIntegrationJar();
}
VirtualFile vf = VFS.getChild(file.toURI());
final Closeable mountHandle = VFS.mountZip(file, vf, TempFileProviderService.provider());
Service<Closeable> mountHandleService = new Service<Closeable>() {
public void start(StartContext startContext) throws StartException {
}
public void stop(StopContext stopContext) {
VFSUtils.safeClose(mountHandle);
}
public Closeable getValue() throws IllegalStateException, IllegalArgumentException {
return mountHandle;
}
};
ServiceBuilder<Closeable> builder = serviceTarget.addService(ServiceName.JBOSS.append(SERVICE_NAME),
mountHandleService);
builder.setInitialMode(ServiceController.Mode.ACTIVE).install();
resourceRoot = vf;
return resourceRoot;
} catch (Exception e) {
throw new DeploymentUnitProcessingException(e);
}
}
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (deploymentUnit.getParent() != null) {
return;
}
final List<DeploymentUnit> deploymentUnits = new ArrayList<DeploymentUnit>();
deploymentUnits.add(deploymentUnit);
deploymentUnits.addAll(deploymentUnit.getAttachmentList(Attachments.SUB_DEPLOYMENTS));
boolean found = false;
for (DeploymentUnit unit : deploymentUnits) {
WarMetaData warMetaData = unit.getAttachment(WarMetaData.ATTACHMENT_KEY);
if (warMetaData == null) {
continue;
}
JBossWebMetaData md = warMetaData.getMergedJBossWebMetaData();
if (md == null) {
continue;
}
if (md.getContextParams() != null) {
boolean skip = false;
for (ParamValueMetaData prop : md.getContextParams()) {
if (prop.getParamName().equals(ENABLE_PROPERTY)) {
boolean explicitEnable = Boolean.parseBoolean(prop.getParamValue());
if (explicitEnable) {
found = true;
} else {
skip = true;
}
break;
} else if (prop.getParamName().equals(DISABLE_PROPERTY) && "true".equals(prop.getParamValue())) {
skip = true;
JaxrsLogger.JAXRS_LOGGER.disablePropertyDeprecated();
break;
}
}
if (skip) {
continue;
}
}
if (md.getListeners() != null) {
for (ListenerMetaData listener : md.getListeners()) {
if (SPRING_LISTENER.equals(listener.getListenerClass())) {
found = true;
break;
}
}
}
if (md.getServlets() != null) {
for (JBossServletMetaData servlet : md.getServlets()) {
if (SPRING_SERVLET.equals(servlet.getServletClass())) {
found = true;
break;
}
}
}
if (found) {
try {
MountHandle mh = MountHandle.create(null); // actual close is done by the MSC service above
ResourceRoot resourceRoot = new ResourceRoot(getResteasySpringVirtualFile(), mh);
ModuleRootMarker.mark(resourceRoot);
deploymentUnit.addToAttachmentList(Attachments.RESOURCE_ROOTS, resourceRoot);
} catch (Exception e) {
throw new DeploymentUnitProcessingException(e);
}
return;
}
}
}
}
| 8,814 | 41.177033 | 117 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/deployment/JaxrsIntegrationProcessor.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.jaxrs.deployment;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.ee.structure.DeploymentType;
import org.jboss.as.ee.structure.DeploymentTypeMarker;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentResourceSupport;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.annotation.CompositeIndex;
import org.jboss.as.server.deployment.module.ModuleDependency;
import org.jboss.as.server.deployment.module.ModuleSpecification;
import org.jboss.as.web.common.WarMetaData;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.jandex.DotName;
import org.jboss.metadata.javaee.spec.ParamValueMetaData;
import org.jboss.metadata.web.jboss.JBossServletMetaData;
import org.jboss.metadata.web.jboss.JBossServletsMetaData;
import org.jboss.metadata.web.jboss.JBossWebMetaData;
import org.jboss.metadata.web.spec.FilterMetaData;
import org.jboss.metadata.web.spec.ServletMappingMetaData;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceRegistry;
import org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher;
import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters;
import org.wildfly.security.manager.WildFlySecurityManager;
import static org.jboss.as.jaxrs.logging.JaxrsLogger.JAXRS_LOGGER;
import org.jboss.as.jaxrs.DeploymentRestResourcesDefintion;
import org.jboss.as.jaxrs.Jackson2Annotations;
import org.jboss.as.jaxrs.JacksonAnnotations;
import org.jboss.as.jaxrs.JaxrsAttribute;
import org.jboss.as.jaxrs.JaxrsConstants;
import org.jboss.as.jaxrs.JaxrsExtension;
import org.jboss.as.jaxrs.JaxrsServerConfig;
import org.jboss.as.jaxrs.JaxrsServerConfigService;
/**
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @author Stuart Douglas
* @author <a href="mailto:[email protected]">Ron Sigal</a>
*/
public class JaxrsIntegrationProcessor implements DeploymentUnitProcessor {
private static final String JAX_RS_SERVLET_NAME = "jakarta.ws.rs.core.Application";
private static final String SERVLET_INIT_PARAM = "jakarta.ws.rs.Application";
public static final String RESTEASY_SCAN = "resteasy.scan";
public static final String RESTEASY_SCAN_RESOURCES = "resteasy.scan.resources";
public static final String RESTEASY_SCAN_PROVIDERS = "resteasy.scan.providers";
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (!JaxrsDeploymentMarker.isJaxrsDeployment(deploymentUnit)) {
return;
}
if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) {
return;
}
final DeploymentUnit parent = deploymentUnit.getParent() == null ? deploymentUnit : deploymentUnit.getParent();
final WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
final JBossWebMetaData webdata = warMetaData.getMergedJBossWebMetaData();
setConfigParameters(phaseContext, webdata);
final ResteasyDeploymentData resteasy = deploymentUnit.getAttachment(JaxrsAttachments.RESTEASY_DEPLOYMENT_DATA);
if (resteasy == null)
return;
// Set up the configuration factory
final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
if (module != null) {
final CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
final WildFlyConfigurationFactory configurationFactory = WildFlyConfigurationFactory.getInstance();
configurationFactory.register(module.getClassLoader(), support.hasCapability("org.wildfly.microprofile.config"));
}
final List<ParamValueMetaData> params = webdata.getContextParams();
boolean entityExpandEnabled = false;
if (params != null) {
Iterator<ParamValueMetaData> it = params.iterator();
while (it.hasNext()) {
final ParamValueMetaData param = it.next();
if(param.getParamName().equals(ResteasyContextParameters.RESTEASY_EXPAND_ENTITY_REFERENCES)) {
entityExpandEnabled = true;
}
}
}
//don't expand entity references by default
if(!entityExpandEnabled) {
setContextParameter(webdata, ResteasyContextParameters.RESTEASY_EXPAND_ENTITY_REFERENCES, "false");
}
final Map<ModuleIdentifier, ResteasyDeploymentData> attachmentMap = parent.getAttachment(JaxrsAttachments.ADDITIONAL_RESTEASY_DEPLOYMENT_DATA);
final List<ResteasyDeploymentData> additionalData = new ArrayList<ResteasyDeploymentData>();
final ModuleSpecification moduleSpec = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);
if (moduleSpec != null && attachmentMap != null) {
final Set<ModuleIdentifier> identifiers = new HashSet<ModuleIdentifier>();
for (ModuleDependency dep : moduleSpec.getAllDependencies()) {
//make sure we don't double up
if (!identifiers.contains(dep.getIdentifier())) {
identifiers.add(dep.getIdentifier());
if (attachmentMap.containsKey(dep.getIdentifier())) {
additionalData.add(attachmentMap.get(dep.getIdentifier()));
}
}
}
resteasy.merge(additionalData);
}
if (!resteasy.getScannedResourceClasses().isEmpty()) {
StringBuilder buf = null;
for (String resource : resteasy.getScannedResourceClasses()) {
if (buf == null) {
buf = new StringBuilder();
buf.append(resource);
} else {
buf.append(",").append(resource);
}
}
String resources = buf.toString();
JAXRS_LOGGER.debugf("Adding Jakarta RESTful Web Services resource classes: %s", resources);
setContextParameter(webdata, ResteasyContextParameters.RESTEASY_SCANNED_RESOURCES, resources);
}
if (!resteasy.getScannedProviderClasses().isEmpty()) {
StringBuilder buf = null;
for (String provider : resteasy.getScannedProviderClasses()) {
if (buf == null) {
buf = new StringBuilder();
buf.append(provider);
} else {
buf.append(",").append(provider);
}
}
String providers = buf.toString();
JAXRS_LOGGER.debugf("Adding Jakarta RESTful Web Services provider classes: %s", providers);
setContextParameter(webdata, ResteasyContextParameters.RESTEASY_SCANNED_PROVIDERS, providers);
}
if (!resteasy.getScannedJndiComponentResources().isEmpty()) {
StringBuilder buf = null;
for (String resource : resteasy.getScannedJndiComponentResources()) {
if (buf == null) {
buf = new StringBuilder();
buf.append(resource);
} else {
buf.append(",").append(resource);
}
}
String providers = buf.toString();
JAXRS_LOGGER.debugf("Adding Jakarta RESTful Web Services jndi component resource classes: %s", providers);
setContextParameter(webdata, ResteasyContextParameters.RESTEASY_SCANNED_JNDI_RESOURCES, providers);
}
if (!resteasy.isUnwrappedExceptionsParameterSet()) {
setContextParameter(webdata, ResteasyContextParameters.RESTEASY_UNWRAPPED_EXCEPTIONS, "jakarta.ejb.EJBException");
}
if (findContextParam(webdata, ResteasyContextParameters.RESTEASY_PREFER_JACKSON_OVER_JSONB) == null) {
final String prop = WildFlySecurityManager.getPropertyPrivileged(ResteasyContextParameters.RESTEASY_PREFER_JACKSON_OVER_JSONB, null);
if (prop != null) {
setContextParameter(webdata, ResteasyContextParameters.RESTEASY_PREFER_JACKSON_OVER_JSONB, prop);
} else {
setContextParameter(webdata, ResteasyContextParameters.RESTEASY_PREFER_JACKSON_OVER_JSONB, Boolean.toString(hasJacksonAnnotations(deploymentUnit)));
}
}
boolean managementAdded = false;
if (!resteasy.getScannedApplicationClasses().isEmpty() || resteasy.hasBootClasses() || resteasy.isDispatcherCreated()) {
addManagement(deploymentUnit, resteasy);
managementAdded = true;
}
// Check for the existence of the "resteasy.server.tracing.type" context parameter. If set to ALL or ON_DEMAND
// log a warning message.
final String value = webdata.getContextParams().stream()
.filter(contextValue -> "resteasy.server.tracing.type".equals(contextValue.getParamName()))
.map(ParamValueMetaData::getParamValue)
.findFirst()
.orElse(null);
if (value != null && !"OFF".equals(value)) {
JAXRS_LOGGER.tracingEnabled(deploymentUnit.getName());
}
if (resteasy.hasBootClasses() || resteasy.isDispatcherCreated())
return;
// ignore any non-annotated Application class that doesn't have a servlet mapping
Set<Class<? extends Application>> applicationClassSet = new HashSet<>();
for (Class<? extends Application> clazz : resteasy.getScannedApplicationClasses()) {
if (clazz.isAnnotationPresent(ApplicationPath.class) || servletMappingsExist(webdata, clazz.getName())) {
applicationClassSet.add(clazz);
}
}
// add default servlet
if (applicationClassSet.isEmpty()) {
JBossServletMetaData servlet = new JBossServletMetaData();
servlet.setName(JAX_RS_SERVLET_NAME);
servlet.setServletClass(HttpServlet30Dispatcher.class.getName());
servlet.setAsyncSupported(true);
addServlet(webdata, servlet);
setServletMappingPrefix(webdata, JAX_RS_SERVLET_NAME, servlet);
} else {
for (Class<? extends Application> applicationClass : applicationClassSet) {
String servletName = null;
servletName = applicationClass.getName();
JBossServletMetaData servlet = new JBossServletMetaData();
// must load on startup for services like JSAPI to work
servlet.setLoadOnStartup("" + 0);
servlet.setName(servletName);
servlet.setServletClass(HttpServlet30Dispatcher.class.getName());
servlet.setAsyncSupported(true);
setServletInitParam(servlet, SERVLET_INIT_PARAM, applicationClass.getName());
addServlet(webdata, servlet);
if (!servletMappingsExist(webdata, servletName)) {
try {
//no mappings, add our own
List<String> patterns = new ArrayList<String>();
//for some reason the spec requires this to be decoded
String pathValue = URLDecoder.decode(applicationClass.getAnnotation(ApplicationPath.class).value().trim(), "UTF-8");
if (!pathValue.startsWith("/")) {
pathValue = "/" + pathValue;
}
String prefix = pathValue;
if (pathValue.endsWith("/")) {
pathValue += "*";
} else {
pathValue += "/*";
}
patterns.add(pathValue);
setServletInitParam(servlet, "resteasy.servlet.mapping.prefix", prefix);
ServletMappingMetaData mapping = new ServletMappingMetaData();
mapping.setServletName(servletName);
mapping.setUrlPatterns(patterns);
if (webdata.getServletMappings() == null) {
webdata.setServletMappings(new ArrayList<ServletMappingMetaData>());
}
webdata.getServletMappings().add(mapping);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
} else {
setServletMappingPrefix(webdata, servletName, servlet);
}
}
}
if (!managementAdded && webdata.getServletMappings() != null) {
for (ServletMappingMetaData servletMapMeta: webdata.getServletMappings()) {
if (JAX_RS_SERVLET_NAME.equals(servletMapMeta.getServletName())) {
addManagement(deploymentUnit, resteasy);
break;
}
}
}
// suppress warning for EAR deployments, as we can't easily tell here the app is properly declared
if (deploymentUnit.getParent() == null && (webdata.getServletMappings() == null || webdata.getServletMappings().isEmpty())) {
JAXRS_LOGGER.noServletDeclaration(deploymentUnit.getName());
}
}
private void addManagement(DeploymentUnit deploymentUnit, ResteasyDeploymentData resteasy) {
Set<String> classes = resteasy.getScannedResourceClasses();
for (String jndiComp : resteasy.getScannedJndiComponentResources()) {
String[] jndiCompArray = jndiComp.split(";");
classes.add(jndiCompArray[1]); // REST as Jakarta Enterprise Beans are added into jndiComponents
}
List<String> rootRestClasses = new ArrayList<>(classes);
Collections.sort(rootRestClasses);
for (String componentClass : rootRestClasses) {
try {
final DeploymentResourceSupport deploymentResourceSupport = deploymentUnit
.getAttachment(org.jboss.as.server.deployment.Attachments.DEPLOYMENT_RESOURCE_SUPPORT);
deploymentResourceSupport.getDeploymentSubModel(JaxrsExtension.SUBSYSTEM_NAME,
PathElement.pathElement(DeploymentRestResourcesDefintion.REST_RESOURCE_NAME, componentClass));
} catch (Exception e) {
JAXRS_LOGGER.failedToRegisterManagementViewForRESTResources(componentClass, e);
}
}
}
protected void setServletInitParam(JBossServletMetaData servlet, String name, String value) {
ParamValueMetaData param = new ParamValueMetaData();
param.setParamName(name);
param.setParamValue(value);
List<ParamValueMetaData> params = servlet.getInitParam();
if (params == null) {
params = new ArrayList<ParamValueMetaData>();
servlet.setInitParam(params);
}
params.add(param);
}
private boolean hasJacksonAnnotations(DeploymentUnit deploymentUnit) {
final CompositeIndex index = deploymentUnit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
for (Jackson2Annotations a : Jackson2Annotations.values())
{
if (checkAnnotation(a.getDotName(), index)) {
return true;
}
}
for (JacksonAnnotations a : JacksonAnnotations.values())
{
if (checkAnnotation(a.getDotName(), index)) {
return true;
}
}
return false;
}
private boolean checkAnnotation(DotName name, CompositeIndex index) {
List<?> list = index.getAnnotations(name);
if (list != null && !list.isEmpty()) {
JAXRS_LOGGER.jacksonAnnotationDetected(ResteasyContextParameters.RESTEASY_PREFER_JACKSON_OVER_JSONB);
return true;
}
return false;
}
private void setServletMappingPrefix(JBossWebMetaData webdata, String servletName, JBossServletMetaData servlet) {
final List<ServletMappingMetaData> mappings = webdata.getServletMappings();
if (mappings != null) {
boolean mappingSet = false;
for (final ServletMappingMetaData mapping : mappings) {
if (mapping.getServletName().equals(servletName)
&& mapping.getUrlPatterns() != null) {
for (String pattern : mapping.getUrlPatterns()) {
if (mappingSet) {
JAXRS_LOGGER.moreThanOneServletMapping(servletName, pattern);
} else {
mappingSet = true;
String realPattern = pattern;
if (realPattern.endsWith("*")) {
realPattern = realPattern.substring(0, realPattern.length() - 1);
}
setServletInitParam(servlet, "resteasy.servlet.mapping.prefix", realPattern);
}
}
}
}
}
}
private void addServlet(JBossWebMetaData webdata, JBossServletMetaData servlet) {
if (webdata.getServlets() == null) {
webdata.setServlets(new JBossServletsMetaData());
}
webdata.getServlets().add(servlet);
}
@Override
public void undeploy(DeploymentUnit context) {
//Clear the type cache in jackson databind
//see https://issues.jboss.org/browse/WFLY-7037
//see https://github.com/FasterXML/jackson-databind/issues/1363
//we use reflection to avoid a non optional dependency on jackson
try {
Module module = context.getAttachment(Attachments.MODULE);
Class<?> typeFactoryClass = module.getClassLoader().loadClass("com.fasterxml.jackson.databind.type.TypeFactory");
Method defaultInstanceMethod = typeFactoryClass.getMethod("defaultInstance");
Object typeFactory = defaultInstanceMethod.invoke(null);
Method clearCache = typeFactoryClass.getDeclaredMethod("clearCache");
clearCache.invoke(typeFactory);
// Remove the deployment from the registered configuration factory
if (JaxrsDeploymentMarker.isJaxrsDeployment(context)) {
WildFlyConfigurationFactory.getInstance().unregister(module.getClassLoader());
}
} catch (Exception e) {
JAXRS_LOGGER.debugf("Failed to clear class utils LRU map");
}
}
protected void setFilterInitParam(FilterMetaData filter, String name, String value) {
ParamValueMetaData param = new ParamValueMetaData();
param.setParamName(name);
param.setParamValue(value);
List<ParamValueMetaData> params = filter.getInitParam();
if (params == null) {
params = new ArrayList<ParamValueMetaData>();
filter.setInitParam(params);
}
params.add(param);
}
public static ParamValueMetaData findContextParam(JBossWebMetaData webdata, String name) {
List<ParamValueMetaData> params = webdata.getContextParams();
if (params == null)
return null;
for (ParamValueMetaData param : params) {
if (param.getParamName().equals(name)) {
return param;
}
}
return null;
}
public static ParamValueMetaData findInitParam(JBossWebMetaData webdata, String name) {
JBossServletsMetaData servlets = webdata.getServlets();
if (servlets == null)
return null;
for (JBossServletMetaData servlet : servlets) {
List<ParamValueMetaData> initParams = servlet.getInitParam();
if (initParams != null) {
for (ParamValueMetaData param : initParams) {
if (param.getParamName().equals(name)) {
return param;
}
}
}
}
return null;
}
public static boolean servletMappingsExist(JBossWebMetaData webdata, String servletName) {
List<ServletMappingMetaData> mappings = webdata.getServletMappings();
if (mappings == null)
return false;
for (ServletMappingMetaData mapping : mappings) {
if (mapping.getServletName().equals(servletName)) {
return true;
}
}
return false;
}
public static void setContextParameter(JBossWebMetaData webdata, String name, String value) {
ParamValueMetaData param = new ParamValueMetaData();
String resteasyName = name;
if (resteasyName.equals(JaxrsConstants.RESTEASY_PREFER_JACKSON_OVER_JSONB)) {
resteasyName = ResteasyContextParameters.RESTEASY_PREFER_JACKSON_OVER_JSONB;
} else {
resteasyName = resteasyName.replace("-", ".");
}
param.setParamName(resteasyName);
param.setParamValue(value);
List<ParamValueMetaData> params = webdata.getContextParams();
if (params == null) {
params = new ArrayList<ParamValueMetaData>();
webdata.setContextParams(params);
}
params.add(param);
}
private void setConfigParameters(DeploymentPhaseContext phaseContext, JBossWebMetaData webdata) {
ServiceRegistry registry = phaseContext.getServiceRegistry();
ServiceName name = JaxrsServerConfigService.CONFIG_SERVICE;
@SuppressWarnings("deprecation")
JaxrsServerConfig config =(JaxrsServerConfig) registry.getRequiredService(name).getValue();
ModelNode modelNode;
if (isTransmittable(JaxrsAttribute.JAXRS_2_0_REQUEST_MATCHING, modelNode = config.isJaxrs20RequestMatching())) {
setContextParameter(webdata, JaxrsConstants.JAXRS_2_0_REQUEST_MATCHING, modelNode.asString());
}
if (isTransmittable(JaxrsAttribute.RESTEASY_ADD_CHARSET, modelNode = config.isResteasyAddCharset())) {
setContextParameter(webdata, JaxrsConstants.RESTEASY_ADD_CHARSET, modelNode.asString());
}
if (isTransmittable(JaxrsAttribute.RESTEASY_BUFFER_EXCEPTION_ENTITY, modelNode = config.isResteasyBufferExceptionEntity())) {
setContextParameter(webdata, JaxrsConstants.RESTEASY_BUFFER_EXCEPTION_ENTITY, modelNode.asString());
}
if (isTransmittable(JaxrsAttribute.RESTEASY_DISABLE_HTML_SANITIZER, modelNode = config.isResteasyDisableHtmlSanitizer())) {
setContextParameter(webdata, JaxrsConstants.RESTEASY_DISABLE_HTML_SANITIZER, modelNode.asString());
}
if (isSubstantiveList(modelNode = config.getResteasyDisableProviders())) {
setContextParameter(webdata, JaxrsConstants.RESTEASY_DISABLE_PROVIDERS, convertListToString(modelNode));
}
if (isTransmittable(JaxrsAttribute.RESTEASY_DOCUMENT_EXPAND_ENTITY_REFERENCES, modelNode = config.isResteasyDocumentExpandEntityReferences())) {
setContextParameter(webdata, JaxrsConstants.RESTEASY_DOCUMENT_EXPAND_ENTITY_REFERENCES, modelNode.asString());
}
if (isTransmittable(JaxrsAttribute.RESTEASY_DOCUMENT_SECURE_DISABLE_DTDS, modelNode = config.isResteasySecureDisableDTDs())) {
setContextParameter(webdata, JaxrsConstants.RESTEASY_DOCUMENT_SECURE_DISABLE_DTDS, modelNode.asString());
}
if (isTransmittable(JaxrsAttribute.RESTEASY_DOCUMENT_SECURE_PROCESSING_FEATURE, modelNode = config.isResteasyDocumentSecureProcessingFeature())) {
setContextParameter(webdata, JaxrsConstants.RESTEASY_DOCUMENT_SECURE_PROCESSING_FEATURE, modelNode.asString());
}
if (isTransmittable(JaxrsAttribute.RESTEASY_GZIP_MAX_INPUT, modelNode = config.getResteasyGzipMaxInput())) {
setContextParameter(webdata, JaxrsConstants.RESTEASY_GZIP_MAX_INPUT, modelNode.asString());
}
if (isSubstantiveList(modelNode = config.getResteasyJndiResources())) {
setContextParameter(webdata, JaxrsConstants.RESTEASY_JNDI_RESOURCES, convertListToString(modelNode));
}
if (isSubstantiveList(modelNode = config.getResteasyLanguageMappings())) {
setContextParameter(webdata, JaxrsConstants.RESTEASY_LANGUAGE_MAPPINGS, convertMapToString(modelNode));
}
if (isSubstantiveList(modelNode = config.getResteasyMediaTypeMappings())) {
setContextParameter(webdata, JaxrsConstants.RESTEASY_MEDIA_TYPE_MAPPINGS, convertMapToString(modelNode));
}
if (isTransmittable(JaxrsAttribute.RESTEASY_MEDIA_TYPE_PARAM_MAPPING, modelNode = config.getResteasyMediaTypeParamMapping())) {
setContextParameter(webdata, JaxrsConstants.RESTEASY_MEDIA_TYPE_PARAM_MAPPING, modelNode.asString());
}
if (isTransmittable(JaxrsAttribute.RESTEASY_PREFER_JACKSON_OVER_JSONB, modelNode = config.isResteasyPreferJacksonOverJsonB())) {
setContextParameter(webdata, JaxrsConstants.RESTEASY_PREFER_JACKSON_OVER_JSONB, modelNode.asString());
}
if (isSubstantiveList(modelNode = config.getResteasyProviders())) {
setContextParameter(webdata, JaxrsConstants.RESTEASY_PROVIDERS, convertListToString(modelNode));
}
if (isTransmittable(JaxrsAttribute.RESTEASY_RFC7232_PRECONDITIONS, modelNode = config.isResteasyRFC7232Preconditions())) {
setContextParameter(webdata, JaxrsConstants.RESTEASY_RFC7232_PRECONDITIONS, modelNode.asString());
}
if (isTransmittable(JaxrsAttribute.RESTEASY_ROLE_BASED_SECURITY, modelNode = config.isResteasyRoleBasedSecurity())) {
setContextParameter(webdata, JaxrsConstants.RESTEASY_ROLE_BASED_SECURITY, modelNode.asString());
}
if (isTransmittable(JaxrsAttribute.RESTEASY_SECURE_RANDOM_MAX_USE, modelNode = config.getResteasySecureRandomMaxUse())) {
setContextParameter(webdata, JaxrsConstants.RESTEASY_SECURE_RANDOM_MAX_USE, modelNode.asString());
}
if (isTransmittable(JaxrsAttribute.RESTEASY_USE_BUILTIN_PROVIDERS, modelNode = config.isResteasyUseBuiltinProviders())) {
setContextParameter(webdata, JaxrsConstants.RESTEASY_USE_BUILTIN_PROVIDERS, modelNode.asString());
}
if (isTransmittable(JaxrsAttribute.RESTEASY_USE_CONTAINER_FORM_PARAMS, modelNode = config.isResteasyUseContainerFormParams())) {
setContextParameter(webdata, JaxrsConstants.RESTEASY_USE_CONTAINER_FORM_PARAMS, modelNode.asString());
}
if (isTransmittable(JaxrsAttribute.RESTEASY_WIDER_REQUEST_MATCHING, modelNode = config.isResteasyWiderRequestMatching())) {
setContextParameter(webdata, JaxrsConstants.RESTEASY_WIDER_REQUEST_MATCHING, modelNode.asString());
}
// Add the context parameters
config.getContextParameters().forEach((key, value) -> setContextParameter(webdata, key, value));
}
/**
* Send value to RESTEasy only if it's not null, empty string, or the default value.
*/
private boolean isTransmittable(AttributeDefinition attribute, ModelNode modelNode) {
if (modelNode == null || ModelType.UNDEFINED.equals(modelNode.getType())) {
return false;
}
String value = modelNode.asString();
if ("".equals(value.trim())) {
return false;
}
return !value.equals(attribute.getDefaultValue() != null ? attribute.getDefaultValue().asString() : null);
}
/**
* List attributes can be reset to white space, but RESTEasy's ConfigurationBootstrap doesn't handle
* empty maps appropriately at present.
*/
private boolean isSubstantiveList(ModelNode modelNode) {
if (modelNode == null || ModelType.UNDEFINED.equals(modelNode.getType())) {
return false;
}
return !modelNode.asList().isEmpty();
}
private String convertListToString(ModelNode modelNode) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (ModelNode value : modelNode.asList()) {
if (first) {
first = false;
} else {
sb.append(",");
}
sb.append(value.asString());
}
return sb.toString();
}
private String convertMapToString(ModelNode modelNode) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String key : modelNode.keys()) {
ModelNode value = modelNode.get(key);
if (first) {
first = false;
} else {
sb.append(",");
}
sb.append(key + ":" + value.asString());
}
return sb.toString();
}
}
| 30,716 | 47.679873 | 164 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/deployment/JaxrsComponentDeployer.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.jaxrs.deployment;
import static org.jboss.as.jaxrs.logging.JaxrsLogger.JAXRS_LOGGER;
import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME;
import java.util.Arrays;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.ee.component.Attachments;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.ee.component.ViewDescription;
import org.jboss.as.ee.managedbean.component.ManagedBeanComponentDescription;
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.resteasy.util.GetRestful;
/**
* Integrates Jakarta RESTful Web Services with managed beans and Jakarta Enterprise Beans's
*
* @author Stuart Douglas
*/
public class JaxrsComponentDeployer implements DeploymentUnitProcessor {
/**
* We use hard coded class names to avoid a direct dependency on Jakarta Enterprise Beans
*
* This allows the use of Jakarta RESTful Web Services in cut down servers without Jakarta Enterprise Beans
*
* Kinda yuck, but there is not really any alternative if we want don't want the dependency
*/
private static final String SESSION_BEAN_DESCRIPTION_CLASS_NAME = "org.jboss.as.ejb3.component.session.SessionBeanComponentDescription";
private static final String STATEFUL_SESSION_BEAN_DESCRIPTION_CLASS_NAME = "org.jboss.as.ejb3.component.stateful.StatefulComponentDescription";
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final Module module = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.MODULE);
if (module == null) {
return;
}
final ResteasyDeploymentData resteasy = deploymentUnit.getAttachment(JaxrsAttachments.RESTEASY_DEPLOYMENT_DATA);
if (resteasy == null) {
return;
}
// Set up the context for managed threads
phaseContext.getDeploymentUnit().addToAttachmentList(Attachments.ADDITIONAL_FACTORIES, ResteasyContextHandleFactory.INSTANCE);
// right now I only support resources
if (!resteasy.isScanResources()) return;
final EEModuleDescription moduleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION);
if (moduleDescription == null) {
return;
}
final ClassLoader loader = module.getClassLoader();
final CapabilityServiceSupport support = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.CAPABILITY_SERVICE_SUPPORT);
boolean partOfWeldDeployment = false;
if (support.hasCapability(WELD_CAPABILITY_NAME)) {
partOfWeldDeployment = support.getOptionalCapabilityRuntimeAPI(WELD_CAPABILITY_NAME, WeldCapability.class).get()
.isPartOfWeldDeployment(deploymentUnit);
}
for (final ComponentDescription component : moduleDescription.getComponentDescriptions()) {
Class<?> componentClass = null;
try {
componentClass = loader.loadClass(component.getComponentClassName());
} catch (ClassNotFoundException e) {
throw new DeploymentUnitProcessingException(e);
}
if (!GetRestful.isRootResource(componentClass)) continue;
if (isInstanceOf(component, SESSION_BEAN_DESCRIPTION_CLASS_NAME)) {
if (isInstanceOf(component, STATEFUL_SESSION_BEAN_DESCRIPTION_CLASS_NAME)) {
//using SFSB's as Jakarta RESTful Web Services endpoints is not recommended, but if people really want to do it they can
JAXRS_LOGGER.debugf("Stateful session bean %s is being used as a Jakarta RESTful Web Services endpoint, this is not recommended", component.getComponentName());
if (partOfWeldDeployment) {
//if possible just let CDI handle the integration
continue;
}
}
Class<?>[] jaxrsType = GetRestful.getSubResourceClasses(componentClass);
final String jndiName;
if (component.getViews().size() == 1) {
//only 1 view, just use the simple JNDI name
jndiName = "java:app/" + moduleDescription.getModuleName() + "/" + component.getComponentName();
} else {
boolean found = false;
String foundType = null;
for (final ViewDescription view : component.getViews()) {
for (Class<?> subResource : jaxrsType) {
if (view.getViewClassName().equals(subResource.getName())) {
foundType = subResource.getName();
found = true;
break;
}
}
if (found) {
break;
}
}
if (!found) {
throw JAXRS_LOGGER.typeNameNotAnEjbView(Arrays.asList(jaxrsType), component.getComponentName());
}
jndiName = "java:app/" + moduleDescription.getModuleName() + "/" + component.getComponentName() + "!" + foundType;
}
JAXRS_LOGGER.debugf("Found Jakarta RESTful Web Services Managed Bean: %s local jndi jaxRsTypeName: %s", component.getComponentClassName(), jndiName);
StringBuilder buf = new StringBuilder();
buf.append(jndiName).append(";").append(component.getComponentClassName()).append(";").append("true");
resteasy.getScannedJndiComponentResources().add(buf.toString());
// make sure its removed from list
resteasy.getScannedResourceClasses().remove(component.getComponentClassName());
} else if (component instanceof ManagedBeanComponentDescription) {
String jndiName = "java:app/" + moduleDescription.getModuleName() + "/" + component.getComponentName();
JAXRS_LOGGER.debugf("Found Jakarta RESTful Web Services Managed Bean: %s local jndi name: %s", component.getComponentClassName(), jndiName);
StringBuilder buf = new StringBuilder();
buf.append(jndiName).append(";").append(component.getComponentClassName()).append(";").append("true");
resteasy.getScannedJndiComponentResources().add(buf.toString());
// make sure its removed from list
resteasy.getScannedResourceClasses().remove(component.getComponentClassName());
}
}
}
private boolean isInstanceOf(ComponentDescription component, String className) {
Class<?> c = component.getClass();
while (c != Object.class && c != null) {
if(c.getName().equals(className)) {
return true;
}
c = c.getSuperclass();
}
return false;
}
}
| 8,529 | 48.022989 | 180 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/deployment/JaxrsAttachments.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.jaxrs.deployment;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.modules.ModuleIdentifier;
import java.util.Map;
/**
* Jaxrs attachments
*
* @author Stuart Douglas
*
*/
public class JaxrsAttachments {
public static final AttachmentKey<ResteasyDeploymentData> RESTEASY_DEPLOYMENT_DATA = AttachmentKey.create(ResteasyDeploymentData.class);
public static final AttachmentKey<Map<ModuleIdentifier, ResteasyDeploymentData>> ADDITIONAL_RESTEASY_DEPLOYMENT_DATA = AttachmentKey.create(Map.class);
}
| 1,570 | 37.317073 | 155 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/deployment/JaxrsScanningProcessor.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.jaxrs.deployment;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import jakarta.ws.rs.core.Application;
import org.jboss.as.jaxrs.JaxrsAnnotations;
import org.jboss.as.jaxrs.logging.JaxrsLogger;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.annotation.CompositeIndex;
import org.jboss.as.web.common.WarMetaData;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.MethodInfo;
import org.jboss.metadata.javaee.spec.ParamValueMetaData;
import org.jboss.metadata.web.jboss.JBossWebMetaData;
import org.jboss.metadata.web.spec.FilterMetaData;
import org.jboss.metadata.web.spec.ServletMetaData;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoadException;
import org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher;
import org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrapClasses;
import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters;
import static org.jboss.as.jaxrs.logging.JaxrsLogger.JAXRS_LOGGER;
import static org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters.RESTEASY_SCAN;
import static org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters.RESTEASY_SCAN_PROVIDERS;
import static org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters.RESTEASY_SCAN_RESOURCES;
/**
* Processor that finds Jakarta RESTful Web Services classes in the deployment
*
* @author Stuart Douglas
*/
public class JaxrsScanningProcessor implements DeploymentUnitProcessor {
private static final DotName DECORATOR = DotName.createSimple("jakarta.decorator.Decorator");
public static final DotName APPLICATION = DotName.createSimple(Application.class.getName());
private static final String ORG_APACHE_CXF = "org.apache.cxf";
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (!JaxrsDeploymentMarker.isJaxrsDeployment(deploymentUnit)) {
return;
}
final DeploymentUnit parent = deploymentUnit.getParent() == null ? deploymentUnit : deploymentUnit.getParent();
final Map<ModuleIdentifier, ResteasyDeploymentData> deploymentData;
if (deploymentUnit.getParent() == null) {
deploymentData = Collections.synchronizedMap(new HashMap<ModuleIdentifier, ResteasyDeploymentData>());
deploymentUnit.putAttachment(JaxrsAttachments.ADDITIONAL_RESTEASY_DEPLOYMENT_DATA, deploymentData);
} else {
deploymentData = parent.getAttachment(JaxrsAttachments.ADDITIONAL_RESTEASY_DEPLOYMENT_DATA);
}
final ModuleIdentifier moduleIdentifier = deploymentUnit.getAttachment(Attachments.MODULE_IDENTIFIER);
ResteasyDeploymentData resteasyDeploymentData = new ResteasyDeploymentData();
final WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
try {
if (warMetaData == null) {
resteasyDeploymentData.setScanAll(true);
scan(deploymentUnit, module.getClassLoader(), resteasyDeploymentData);
deploymentData.put(moduleIdentifier, resteasyDeploymentData);
} else {
scanWebDeployment(deploymentUnit, warMetaData.getMergedJBossWebMetaData(), module.getClassLoader(), resteasyDeploymentData);
scan(deploymentUnit, module.getClassLoader(), resteasyDeploymentData);
// When BootStrap classes are present and no Application subclass declared
// must check context param for Application subclass declaration
if (resteasyDeploymentData.getScannedResourceClasses().isEmpty() &&
!resteasyDeploymentData.isDispatcherCreated() &&
hasBootClasses(warMetaData.getMergedJBossWebMetaData())) {
checkOtherParams(deploymentUnit, warMetaData.getMergedJBossWebMetaData(), module.getClassLoader(), resteasyDeploymentData);
}
}
deploymentUnit.putAttachment(JaxrsAttachments.RESTEASY_DEPLOYMENT_DATA, resteasyDeploymentData);
} catch (ModuleLoadException e) {
throw new DeploymentUnitProcessingException(e);
}
}
private void checkOtherParams(final DeploymentUnit du,
final JBossWebMetaData webdata,
final ClassLoader classLoader,
final ResteasyDeploymentData resteasyDeploymentData)
throws DeploymentUnitProcessingException{
HashSet<String> appClazzList = new HashSet<>();
List<ParamValueMetaData> contextParamList = webdata.getContextParams();
if (contextParamList !=null) {
for(ParamValueMetaData param: contextParamList) {
if ("jakarta.ws.rs.core.Application".equals(param.getParamName())) {
appClazzList.add(param.getParamValue());
}
}
}
if (webdata.getServlets() != null) {
for (ServletMetaData servlet : webdata.getServlets()) {
List<ParamValueMetaData> initParamList = servlet.getInitParam();
if (initParamList != null) {
for(ParamValueMetaData param: initParamList) {
if ("jakarta.ws.rs.core.Application".equals(param.getParamName())) {
appClazzList.add(param.getParamValue());
}
}
}
}
}
processDeclaredApplicationClasses(du, appClazzList, webdata, classLoader, resteasyDeploymentData);
}
private void processDeclaredApplicationClasses(final DeploymentUnit du,
final Set<String> appClazzList,
final JBossWebMetaData webdata,
final ClassLoader classLoader,
final ResteasyDeploymentData resteasyDeploymentData)
throws DeploymentUnitProcessingException {
final CompositeIndex index = du.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
List<AnnotationInstance> resources = index.getAnnotations(JaxrsAnnotations.PATH.getDotName());
Map<String, ClassInfo> resourceMap = new HashMap<>(resources.size());
if (resources != null) {
for (AnnotationInstance a: resources) {
if (a.target() instanceof ClassInfo) {
resourceMap.put(((ClassInfo)a.target()).name().toString(),
(ClassInfo)a.target());
}
}
}
for (String clazzName: appClazzList) {
Class<?> clazz = null;
try {
clazz = classLoader.loadClass(clazzName);
} catch (ClassNotFoundException e) {
throw new DeploymentUnitProcessingException(e);
}
if (Application.class.isAssignableFrom(clazz)) {
try {
Application appClazz = (Application) clazz.newInstance();
Set<Class<?>> declClazzs = appClazz.getClasses();
Set<Object> declSingletons = appClazz.getSingletons();
HashSet<Class<?>> clazzSet = new HashSet<>();
if (declClazzs != null) {
clazzSet.addAll(declClazzs);
}
if (declSingletons != null) {
for (Object obj : declSingletons) {
clazzSet.add((Class) obj);
}
}
Set<String> scannedResourceClasses = resteasyDeploymentData.getScannedResourceClasses();
for (Class<?> cClazz : clazzSet) {
if (cClazz.isAnnotationPresent(jakarta.ws.rs.Path.class)) {
final ClassInfo info = resourceMap.get(cClazz.getName());
if (info != null) {
if (info.annotationsMap().containsKey(DECORATOR)) {
//we do not add decorators as resources
//we can't pick up on programatically added decorators, but that is such an edge case it should not really matter
continue;
}
if (!Modifier.isInterface(info.flags())) {
scannedResourceClasses.add(info.name().toString());
}
}
}
}
} catch (Exception e) {
JAXRS_LOGGER.cannotLoadApplicationClass(e);
}
}
}
}
public static final Set<String> BOOT_CLASSES = new HashSet<String>();
static {
Collections.addAll(BOOT_CLASSES, ResteasyBootstrapClasses.BOOTSTRAP_CLASSES);
}
/**
* If any servlet/filter classes are declared, then we probably don't want to scan.
*/
protected boolean hasBootClasses(JBossWebMetaData webdata) throws DeploymentUnitProcessingException {
if (webdata.getServlets() != null) {
for (ServletMetaData servlet : webdata.getServlets()) {
String servletClass = servlet.getServletClass();
if (BOOT_CLASSES.contains(servletClass))
return true;
}
}
if (webdata.getFilters() != null) {
for (FilterMetaData filter : webdata.getFilters()) {
if (BOOT_CLASSES.contains(filter.getFilterClass()))
return true;
}
}
return false;
}
protected void scanWebDeployment(final DeploymentUnit du, final JBossWebMetaData webdata, final ClassLoader classLoader, final ResteasyDeploymentData resteasyDeploymentData) throws DeploymentUnitProcessingException {
// If there is a resteasy boot class in web.xml, then the default should be to not scan
// make sure this call happens before checkDeclaredApplicationClassAsServlet!!!
boolean hasBoot = hasBootClasses(webdata);
resteasyDeploymentData.setBootClasses(hasBoot);
Class<?> declaredApplicationClass = checkDeclaredApplicationClassAsServlet(webdata, classLoader);
// Assume that checkDeclaredApplicationClassAsServlet created the dispatcher
if (declaredApplicationClass != null) {
resteasyDeploymentData.setDispatcherCreated(true);
// Instigate creation of resteasy configuration switches for
// found provider and resource classes
resteasyDeploymentData.setScanProviders(true);
resteasyDeploymentData.setScanResources(true);
}
// set scanning on only if there are no boot classes
if (!hasBoot && !webdata.isMetadataComplete()) {
resteasyDeploymentData.setScanAll(true);
resteasyDeploymentData.setScanProviders(true);
resteasyDeploymentData.setScanResources(true);
}
// check resteasy configuration flags
List<ParamValueMetaData> contextParams = webdata.getContextParams();
if (contextParams != null) {
for (ParamValueMetaData param : contextParams) {
if (param.getParamName().equals(RESTEASY_SCAN)) {
resteasyDeploymentData.setScanAll(valueOf(RESTEASY_SCAN, param.getParamValue()));
} else if (param.getParamName().equals(ResteasyContextParameters.RESTEASY_SCAN_PROVIDERS)) {
resteasyDeploymentData.setScanProviders(valueOf(RESTEASY_SCAN_PROVIDERS, param.getParamValue()));
} else if (param.getParamName().equals(RESTEASY_SCAN_RESOURCES)) {
resteasyDeploymentData.setScanResources(valueOf(RESTEASY_SCAN_RESOURCES, param.getParamValue()));
} else if (param.getParamName().equals(ResteasyContextParameters.RESTEASY_UNWRAPPED_EXCEPTIONS)) {
resteasyDeploymentData.setUnwrappedExceptionsParameterSet(true);
}
}
}
}
protected void scan(final DeploymentUnit du, final ClassLoader classLoader, final ResteasyDeploymentData resteasyDeploymentData)
throws DeploymentUnitProcessingException, ModuleLoadException {
final CompositeIndex index = du.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
if (!resteasyDeploymentData.shouldScan()) {
return;
}
if (!resteasyDeploymentData.isDispatcherCreated()) {
final Set<ClassInfo> applicationClasses = index.getAllKnownSubclasses(APPLICATION);
try {
for (ClassInfo c : applicationClasses) {
if (Modifier.isAbstract(c.flags())) continue;
@SuppressWarnings("unchecked")
Class<? extends Application> scanned = (Class<? extends Application>) classLoader.loadClass(c.name().toString());
resteasyDeploymentData.getScannedApplicationClasses().add(scanned);
}
} catch (ClassNotFoundException e) {
throw JaxrsLogger.JAXRS_LOGGER.cannotLoadApplicationClass(e);
}
}
List<AnnotationInstance> resources = null;
List<AnnotationInstance> providers = null;
if (resteasyDeploymentData.isScanResources()) {
resources = index.getAnnotations(JaxrsAnnotations.PATH.getDotName());
}
if (resteasyDeploymentData.isScanProviders()) {
providers = index.getAnnotations(JaxrsAnnotations.PROVIDER.getDotName());
}
if ((resources == null || resources.isEmpty()) && (providers == null || providers.isEmpty()))
return;
final Set<ClassInfo> pathInterfaces = new HashSet<ClassInfo>();
if (resources != null) {
for (AnnotationInstance e : resources) {
final ClassInfo info;
if (e.target() instanceof ClassInfo) {
info = (ClassInfo) e.target();
} else if (e.target() instanceof MethodInfo) {
//ignore
continue;
} else {
JAXRS_LOGGER.classOrMethodAnnotationNotFound("@Path", e.target());
continue;
}
if(info.name().toString().startsWith(ORG_APACHE_CXF)) {
//do not add CXF classes
//see WFLY-9752
continue;
}
if(info.annotationsMap().containsKey(DECORATOR)) {
//we do not add decorators as resources
//we can't pick up on programatically added decorators, but that is such an edge case it should not really matter
continue;
}
if (!Modifier.isInterface(info.flags())) {
resteasyDeploymentData.getScannedResourceClasses().add(info.name().toString());
} else {
pathInterfaces.add(info);
}
}
}
if (providers != null) {
for (AnnotationInstance e : providers) {
if (e.target() instanceof ClassInfo) {
ClassInfo info = (ClassInfo) e.target();
if(info.name().toString().startsWith(ORG_APACHE_CXF)) {
//do not add CXF classes
//see WFLY-9752
continue;
}
if(info.annotationsMap().containsKey(DECORATOR)) {
//we do not add decorators as providers
//we can't pick up on programatically added decorators, but that is such an edge case it should not really matter
continue;
}
if (!Modifier.isInterface(info.flags())) {
resteasyDeploymentData.getScannedProviderClasses().add(info.name().toString());
}
} else {
JAXRS_LOGGER.classAnnotationNotFound("@Provider", e.target());
}
}
}
// look for all implementations of interfaces annotated @Path
for (final ClassInfo iface : pathInterfaces) {
final Set<ClassInfo> implementors = index.getAllKnownImplementors(iface.name());
for (final ClassInfo implementor : implementors) {
if(implementor.name().toString().startsWith(ORG_APACHE_CXF)) {
//do not add CXF classes
//see WFLY-9752
continue;
}
if(implementor.annotationsMap().containsKey(DECORATOR)) {
//we do not add decorators as resources
//we can't pick up on programatically added decorators, but that is such an edge case it should not really matter
continue;
}
resteasyDeploymentData.getScannedResourceClasses().add(implementor.name().toString());
}
}
}
protected Class<?> checkDeclaredApplicationClassAsServlet(JBossWebMetaData webData,
ClassLoader classLoader) throws DeploymentUnitProcessingException {
if (webData.getServlets() == null)
return null;
for (ServletMetaData servlet : webData.getServlets()) {
String servletClass = servlet.getServletClass();
if (servletClass == null)
continue;
Class<?> clazz = null;
try {
clazz = classLoader.loadClass(servletClass);
} catch (ClassNotFoundException e) {
throw new DeploymentUnitProcessingException(e);
}
if (Application.class.isAssignableFrom(clazz)) {
servlet.setServletClass(HttpServlet30Dispatcher.class.getName());
servlet.setAsyncSupported(true);
ParamValueMetaData param = new ParamValueMetaData();
param.setParamName("jakarta.ws.rs.Application");
param.setParamValue(servletClass);
List<ParamValueMetaData> params = servlet.getInitParam();
if (params == null) {
params = new ArrayList<ParamValueMetaData>();
servlet.setInitParam(params);
}
params.add(param);
return clazz;
}
}
return null;
}
private boolean valueOf(String paramName, String value) throws DeploymentUnitProcessingException {
if (value == null) {
throw JaxrsLogger.JAXRS_LOGGER.invalidParamValue(paramName, value);
}
if (value.toLowerCase(Locale.ENGLISH).equals("true")) {
return true;
} else if (value.toLowerCase(Locale.ENGLISH).equals("false")) {
return false;
} else {
throw JaxrsLogger.JAXRS_LOGGER.invalidParamValue(paramName, value);
}
}
}
| 21,097 | 45.884444 | 220 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/deployment/ResteasyDeploymentData.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.jaxrs.deployment;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import jakarta.ws.rs.core.Application;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* @author <a href="mailto:[email protected]">Bill Burke</a>
*/
public class ResteasyDeploymentData {
private boolean scanAll;
private boolean scanResources;
private boolean scanProviders;
private boolean dispatcherCreated;
private final Set<String> scannedResourceClasses = new LinkedHashSet<String>();
private final Set<String> scannedProviderClasses = new LinkedHashSet<String>();
private List<Class<? extends Application>> scannedApplicationClasses = new ArrayList<>();
private boolean bootClasses;
private boolean unwrappedExceptionsParameterSet;
private final Set<String> scannedJndiComponentResources = new LinkedHashSet<String>();
/**
* Merges a list of additional Jakarta RESTful Web Services deployment data with this lot of deployment data.
*
* @param deploymentData
*/
public void merge(final List<ResteasyDeploymentData> deploymentData) throws DeploymentUnitProcessingException {
for (ResteasyDeploymentData data : deploymentData) {
scannedApplicationClasses.addAll(data.getScannedApplicationClasses());
if (scanResources) {
scannedResourceClasses.addAll(data.getScannedResourceClasses());
scannedJndiComponentResources.addAll(data.getScannedJndiComponentResources());
}
if (scanProviders) {
scannedProviderClasses.addAll(data.getScannedProviderClasses());
}
}
}
public Set<String> getScannedJndiComponentResources() {
return scannedJndiComponentResources;
}
public boolean isDispatcherCreated() {
return dispatcherCreated;
}
public void setDispatcherCreated(boolean dispatcherCreated) {
this.dispatcherCreated = dispatcherCreated;
}
public List<Class<? extends Application>> getScannedApplicationClasses() {
return scannedApplicationClasses;
}
public boolean hasBootClasses() {
return bootClasses;
}
public void setBootClasses(boolean bootClasses) {
this.bootClasses = bootClasses;
}
public boolean shouldScan() {
return scanAll || scanResources || scanProviders;
}
public boolean isScanAll() {
return scanAll;
}
public void setScanAll(boolean scanAll) {
if (scanAll) {
scanResources = true;
scanProviders = true;
}
this.scanAll = scanAll;
}
public boolean isScanResources() {
return scanResources;
}
public void setScanResources(boolean scanResources) {
this.scanResources = scanResources;
}
public boolean isScanProviders() {
return scanProviders;
}
public void setScanProviders(boolean scanProviders) {
this.scanProviders = scanProviders;
}
public Set<String> getScannedResourceClasses() {
return scannedResourceClasses;
}
public Set<String> getScannedProviderClasses() {
return scannedProviderClasses;
}
public boolean isUnwrappedExceptionsParameterSet() {
return unwrappedExceptionsParameterSet;
}
public void setUnwrappedExceptionsParameterSet(boolean unwrappedExceptionsParameterSet) {
this.unwrappedExceptionsParameterSet = unwrappedExceptionsParameterSet;
}
}
| 4,602 | 32.115108 | 115 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/deployment/WildFlyConfigurationFactory.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jaxrs.deployment;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.jboss.as.jaxrs.logging.JaxrsLogger;
import org.jboss.resteasy.spi.ResteasyConfiguration;
import org.jboss.resteasy.spi.config.Configuration;
import org.jboss.resteasy.spi.config.ConfigurationFactory;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* @author <a href="mailto:[email protected]">James R. Perkins</a>
*/
public class WildFlyConfigurationFactory implements ConfigurationFactory {
private static final ConfigurationFactory DEFAULT = () -> Integer.MAX_VALUE;
private final Map<ClassLoader, ConfigurationFactory> delegates;
public WildFlyConfigurationFactory() {
delegates = new ConcurrentHashMap<>();
}
static WildFlyConfigurationFactory getInstance() {
final ConfigurationFactory result = ConfigurationFactory.getInstance();
if (!(result instanceof WildFlyConfigurationFactory)) {
throw JaxrsLogger.JAXRS_LOGGER.invalidConfigurationFactory(result == null ? null : result.getClass());
}
return (WildFlyConfigurationFactory) result;
}
void register(final ClassLoader classLoader, final boolean useMpConfig) {
delegates.put(classLoader, createDelegate(classLoader, useMpConfig));
}
void unregister(final ClassLoader classLoader) {
delegates.remove(classLoader);
}
@Override
public Configuration getConfiguration() {
return getDelegate().getConfiguration();
}
@Override
public Configuration getConfiguration(final ResteasyConfiguration config) {
return getDelegate().getConfiguration(config);
}
@Override
public int priority() {
return 0;
}
private ConfigurationFactory getDelegate() {
return delegates.getOrDefault(WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(), DEFAULT);
}
private static ConfigurationFactory createDelegate(final ClassLoader classLoader, final boolean useMpConfig) {
if (useMpConfig) {
// Safely load this and have a default. This way we won't fail using RESTEasy.
try {
final Constructor<? extends ConfigurationFactory> constructor =
getMpConfigFactory(classLoader).getConstructor();
return constructor.newInstance();
} catch (NoSuchMethodException | InvocationTargetException | InstantiationException |
IllegalAccessException | ClassNotFoundException e) {
JaxrsLogger.JAXRS_LOGGER.failedToLoadConfigurationFactory(e.getMessage());
}
}
return DEFAULT;
}
@SuppressWarnings("unchecked")
private static Class<? extends ConfigurationFactory> getMpConfigFactory(final ClassLoader classLoader) throws ClassNotFoundException {
return (Class<? extends ConfigurationFactory>) Class.forName("org.jboss.resteasy.microprofile.config.ConfigConfigurationFactory", false, classLoader);
}
}
| 4,164 | 39.436893 | 158 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/deployment/JaxrsCdiIntegrationProcessor.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.jaxrs.deployment;
import static org.jboss.as.jaxrs.logging.JaxrsLogger.JAXRS_LOGGER;
import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME;
import java.util.ArrayList;
import java.util.List;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.ee.structure.DeploymentType;
import org.jboss.as.ee.structure.DeploymentTypeMarker;
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.web.common.WarMetaData;
import org.jboss.as.weld.WeldCapability;
import org.jboss.metadata.javaee.spec.ParamValueMetaData;
import org.jboss.metadata.web.jboss.JBossWebMetaData;
import org.jboss.modules.Module;
/**
* @author Stuart Douglas
*/
public class JaxrsCdiIntegrationProcessor implements DeploymentUnitProcessor {
public static final String CDI_INJECTOR_FACTORY_CLASS = "org.jboss.resteasy.cdi.CdiInjectorFactory";
@Override
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
if (!JaxrsDeploymentMarker.isJaxrsDeployment(deploymentUnit)) {
return;
}
if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) {
return;
}
final WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
final JBossWebMetaData webdata = warMetaData.getMergedJBossWebMetaData();
try {
final CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
if (support.hasCapability(WELD_CAPABILITY_NAME)) {
final WeldCapability api = support.getOptionalCapabilityRuntimeAPI(WELD_CAPABILITY_NAME, WeldCapability.class).get();
if (api.isWeldDeployment(deploymentUnit)) {
// don't set this param if Jakarta Contexts and Dependency Injection is not in classpath
module.getClassLoader().loadClass(CDI_INJECTOR_FACTORY_CLASS);
JAXRS_LOGGER.debug("Found Jakarta Contexts and Dependency Injection, adding injector factory class");
setContextParameter(webdata, "resteasy.injector.factory", CDI_INJECTOR_FACTORY_CLASS);
}
}
} catch (ClassNotFoundException ignored) {
}
}
public static void setContextParameter(JBossWebMetaData webdata, String name, String value) {
ParamValueMetaData param = new ParamValueMetaData();
param.setParamName(name);
param.setParamValue(value);
List<ParamValueMetaData> params = webdata.getContextParams();
if (params == null) {
params = new ArrayList<ParamValueMetaData>();
webdata.setContextParams(params);
}
params.add(param);
}
}
| 4,242 | 43.663158 | 133 |
java
|
null |
wildfly-main/jaxrs/src/main/java/org/jboss/as/jaxrs/deployment/JaxrsDependencyProcessor.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.jaxrs.deployment;
import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME;
import java.util.ArrayList;
import java.util.List;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
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 static org.jboss.as.jaxrs.JaxrsSubsystemDefinition.JACKSON_DATATYPE_JDK8;
import static org.jboss.as.jaxrs.JaxrsSubsystemDefinition.JACKSON_DATATYPE_JSR310;
import static org.jboss.as.jaxrs.JaxrsSubsystemDefinition.JAXB_API;
import static org.jboss.as.jaxrs.JaxrsSubsystemDefinition.JAXRS_API;
import static org.jboss.as.jaxrs.JaxrsSubsystemDefinition.JSON_API;
import static org.jboss.as.jaxrs.JaxrsSubsystemDefinition.MP_REST_CLIENT;
import static org.jboss.as.jaxrs.JaxrsSubsystemDefinition.RESTEASY_ATOM;
import static org.jboss.as.jaxrs.JaxrsSubsystemDefinition.RESTEASY_CDI;
import static org.jboss.as.jaxrs.JaxrsSubsystemDefinition.RESTEASY_CLIENT;
import static org.jboss.as.jaxrs.JaxrsSubsystemDefinition.RESTEASY_CLIENT_API;
import static org.jboss.as.jaxrs.JaxrsSubsystemDefinition.RESTEASY_CLIENT_MICROPROFILE;
import static org.jboss.as.jaxrs.JaxrsSubsystemDefinition.RESTEASY_CRYPTO;
import static org.jboss.as.jaxrs.JaxrsSubsystemDefinition.RESTEASY_JACKSON2;
import static org.jboss.as.jaxrs.JaxrsSubsystemDefinition.RESTEASY_JAXB;
import static org.jboss.as.jaxrs.JaxrsSubsystemDefinition.RESTEASY_CORE;
import static org.jboss.as.jaxrs.JaxrsSubsystemDefinition.RESTEASY_CORE_SPI;
import static org.jboss.as.jaxrs.JaxrsSubsystemDefinition.RESTEASY_JSAPI;
import static org.jboss.as.jaxrs.JaxrsSubsystemDefinition.RESTEASY_JSON_B_PROVIDER;
import static org.jboss.as.jaxrs.JaxrsSubsystemDefinition.RESTEASY_JSON_P_PROVIDER;
import static org.jboss.as.jaxrs.JaxrsSubsystemDefinition.RESTEASY_MULTIPART;
import static org.jboss.as.jaxrs.JaxrsSubsystemDefinition.RESTEASY_VALIDATOR;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.as.weld.WeldCapability;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoader;
import org.jboss.modules.filter.PathFilters;
import org.jboss.vfs.VirtualFile;
/**
* Deployment processor which adds a module dependencies for modules needed for Jakarta RESTful Web Services deployments.
*
* @author Stuart Douglas
*/
public class JaxrsDependencyProcessor implements DeploymentUnitProcessor {
private static final String CLIENT_BUILDER = "META-INF/services/jakarta.ws.rs.client.ClientBuilder";
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);
boolean deploymentBundlesClientBuilder = isClientBuilderInDeployment(deploymentUnit);
final ModuleLoader moduleLoader = Module.getBootModuleLoader();
addDependency(moduleSpecification, moduleLoader, JAXRS_API, false, false);
addDependency(moduleSpecification, moduleLoader, JAXB_API, false, false);
addDependency(moduleSpecification, moduleLoader, JSON_API, false, false);
//we need to add these from all deployments, as they could be using the Jakarta RESTful Web Services client
addDependency(moduleSpecification, moduleLoader, RESTEASY_ATOM, true, false);
addDependency(moduleSpecification, moduleLoader, RESTEASY_VALIDATOR, true, false);
addDependency(moduleSpecification, moduleLoader, RESTEASY_CLIENT, true, deploymentBundlesClientBuilder);
addDependency(moduleSpecification, moduleLoader, RESTEASY_CLIENT_API, true, deploymentBundlesClientBuilder);
addDependency(moduleSpecification, moduleLoader, RESTEASY_CORE, true, deploymentBundlesClientBuilder);
addDependency(moduleSpecification, moduleLoader, RESTEASY_CORE_SPI, true, deploymentBundlesClientBuilder);
addDependency(moduleSpecification, moduleLoader, RESTEASY_CLIENT_MICROPROFILE, true, false);
addDependency(moduleSpecification, moduleLoader, RESTEASY_JAXB, true, false);
addDependency(moduleSpecification, moduleLoader, RESTEASY_JACKSON2, true, false);
addDependency(moduleSpecification, moduleLoader, RESTEASY_JSON_P_PROVIDER, true, false);
addDependency(moduleSpecification, moduleLoader, RESTEASY_JSON_B_PROVIDER, true, false);
addDependency(moduleSpecification, moduleLoader, RESTEASY_JSAPI, true, false);
addDependency(moduleSpecification, moduleLoader, RESTEASY_MULTIPART, true, false);
addDependency(moduleSpecification, moduleLoader, RESTEASY_CRYPTO, true, false);
addDependency(moduleSpecification, moduleLoader, JACKSON_DATATYPE_JDK8, true, false);
addDependency(moduleSpecification, moduleLoader, JACKSON_DATATYPE_JSR310, true, false);
final CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
if (support.hasCapability(WELD_CAPABILITY_NAME)) {
final WeldCapability api = support.getOptionalCapabilityRuntimeAPI(WELD_CAPABILITY_NAME, WeldCapability.class).get();
if (api.isPartOfWeldDeployment(deploymentUnit)) {
addDependency(moduleSpecification, moduleLoader, RESTEASY_CDI, true, false);
}
}
if (support.hasCapability("org.wildfly.microprofile.config")) {
addDependency(moduleSpecification, moduleLoader, MP_REST_CLIENT, true, false);
addDependency(moduleSpecification, moduleLoader, "org.jboss.resteasy.microprofile.config", true, false);
}
}
private boolean isClientBuilderInDeployment(DeploymentUnit deploymentUnit) {
ResourceRoot root = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
List<ResourceRoot> roots = new ArrayList<>(deploymentUnit.getAttachmentList(Attachments.RESOURCE_ROOTS));
roots.add(root);
for(ResourceRoot r : roots) {
VirtualFile file = r.getRoot().getChild(CLIENT_BUILDER);
if(file.exists()) {
return true;
}
}
return false;
}
private void addDependency(ModuleSpecification moduleSpecification, ModuleLoader moduleLoader,
ModuleIdentifier moduleIdentifier, boolean optional, boolean deploymentBundelesClientBuilder) {
addDependency(moduleSpecification, moduleLoader, moduleIdentifier.toString(), optional, deploymentBundelesClientBuilder);
}
private void addDependency(ModuleSpecification moduleSpecification, ModuleLoader moduleLoader,
String moduleIdentifier, boolean optional, boolean deploymentBundelesClientBuilder) {
ModuleDependency dependency = new ModuleDependency(moduleLoader, moduleIdentifier, optional, false, true, false);
if(deploymentBundelesClientBuilder) {
dependency.addImportFilter(PathFilters.is(CLIENT_BUILDER), false);
}
moduleSpecification.addSystemDependency(dependency);
}
}
| 8,539 | 57.095238 | 129 |
java
|
null |
wildfly-main/microprofile/lra/participant/src/test/java/org/wildfly/extension/microprofile/lra/participant/MicroprofileLRAParticipantSubsystemTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.participant;
import org.jboss.as.subsystem.test.AbstractSubsystemSchemaTest;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.EnumSet;
@RunWith(Parameterized.class)
public class MicroprofileLRAParticipantSubsystemTestCase extends AbstractSubsystemSchemaTest<MicroProfileLRAParticipantSubsystemSchema> {
@Parameterized.Parameters
public static Iterable<MicroProfileLRAParticipantSubsystemSchema> parameters() {
return EnumSet.allOf(MicroProfileLRAParticipantSubsystemSchema.class);
}
public MicroprofileLRAParticipantSubsystemTestCase(MicroProfileLRAParticipantSubsystemSchema schema) {
super(MicroProfileLRAParticipantExtension.SUBSYSTEM_NAME, new MicroProfileLRAParticipantExtension(), schema, MicroProfileLRAParticipantExtension.CURRENT_SCHEMA);
}
}
| 1,905 | 43.325581 | 169 |
java
|
null |
wildfly-main/microprofile/lra/participant/src/main/java/org/wildfly/extension/microprofile/lra/participant/MicroProfileLRAParticipantAdd.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.participant;
import org.jboss.as.controller.AbstractBoottimeAddStepHandler;
import org.jboss.as.controller.CapabilityServiceBuilder;
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;
import org.jboss.msc.service.ServiceController;
import org.wildfly.extension.microprofile.lra.participant._private.MicroProfileLRAParticipantLogger;
import org.wildfly.extension.microprofile.lra.participant.deployment.LRAParticipantDeploymentDependencyProcessor;
import org.wildfly.extension.microprofile.lra.participant.deployment.LRAParticipantDeploymentSetupProcessor;
import org.wildfly.extension.microprofile.lra.participant.deployment.LRAParticipantJaxrsDeploymentUnitProcessor;
import org.wildfly.extension.microprofile.lra.participant.service.LRAParticipantService;
import org.wildfly.extension.undertow.Capabilities;
import org.wildfly.extension.undertow.Host;
import org.wildfly.extension.undertow.UndertowService;
import java.util.Arrays;
import java.util.function.Supplier;
import static org.jboss.as.controller.OperationContext.Stage.RUNTIME;
import static org.wildfly.extension.microprofile.lra.participant.MicroProfileLRAParticipantExtension.SUBSYSTEM_NAME;
import static org.wildfly.extension.microprofile.lra.participant.MicroProfileLRAParticipantSubsystemDefinition.ATTRIBUTES;
import static org.wildfly.extension.microprofile.lra.participant.MicroProfileLRAParticipantSubsystemDefinition.COORDINATOR_URL_PROP;
class MicroProfileLRAParticipantAdd extends AbstractBoottimeAddStepHandler {
MicroProfileLRAParticipantAdd() {
super(Arrays.asList(ATTRIBUTES));
}
@Override
protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
super.performBoottime(context, operation, model);
final String url = MicroProfileLRAParticipantSubsystemDefinition.LRA_COORDINATOR_URL.resolveModelAttribute(context, model).asString();
System.setProperty(COORDINATOR_URL_PROP, url);
context.addStep(new AbstractDeploymentChainStep() {
public void execute(DeploymentProcessorTarget processorTarget) {
// TODO Put these into Phase.java https://issues.redhat.com/browse/WFCORE-5559
final int STRUCTURE_MICROPROFILE_LRA_PARTICIPANT = 0x2400;
final int DEPENDENCIES_MICROPROFILE_LRA_PARTICIPANT = 0x18D0;
processorTarget.addDeploymentProcessor(SUBSYSTEM_NAME, Phase.STRUCTURE, STRUCTURE_MICROPROFILE_LRA_PARTICIPANT, new LRAParticipantDeploymentSetupProcessor());
processorTarget.addDeploymentProcessor(SUBSYSTEM_NAME, Phase.DEPENDENCIES, DEPENDENCIES_MICROPROFILE_LRA_PARTICIPANT, new LRAParticipantDeploymentDependencyProcessor());
processorTarget.addDeploymentProcessor(SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_JAXRS_SCANNING, new LRAParticipantJaxrsDeploymentUnitProcessor());
}
}, RUNTIME);
registerParticipantProxyService(context, model);
MicroProfileLRAParticipantLogger.LOGGER.activatingSubsystem(url);
}
private void registerParticipantProxyService(final OperationContext context, final ModelNode model) throws OperationFailedException {
CapabilityServiceBuilder<?> builder = context.getCapabilityServiceTarget()
.addCapability(MicroProfileLRAParticipantSubsystemDefinition.LRA_PARTICIPANT_CAPABILITY);
builder.requiresCapability(Capabilities.CAPABILITY_UNDERTOW, UndertowService.class);
String serverModelValue = MicroProfileLRAParticipantSubsystemDefinition.PROXY_SERVER.resolveModelAttribute(context, model).asString();
String hostModelValue = MicroProfileLRAParticipantSubsystemDefinition.PROXY_HOST.resolveModelAttribute(context, model).asString();
Supplier<Host> hostSupplier = builder.requiresCapability(Capabilities.CAPABILITY_HOST, Host.class, serverModelValue, hostModelValue);
final LRAParticipantService lraParticipantProxyService = new LRAParticipantService(hostSupplier);
builder.setInstance(lraParticipantProxyService);
builder.setInitialMode(ServiceController.Mode.ACTIVE).install();
}
}
| 5,483 | 56.726316 | 185 |
java
|
null |
wildfly-main/microprofile/lra/participant/src/main/java/org/wildfly/extension/microprofile/lra/participant/MicroProfileLRAParticipantSubsystemSchema.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.participant;
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;
import static org.jboss.as.controller.PersistentResourceXMLDescription.builder;
/**
* Enumerates the supported schemas of the MicroProfile LRA participant subsystem.
* @author Paul Ferraro
*/
enum MicroProfileLRAParticipantSubsystemSchema implements PersistentSubsystemSchema<MicroProfileLRAParticipantSubsystemSchema> {
VERSION_1_0(1),
;
private final VersionedNamespace<IntVersion, MicroProfileLRAParticipantSubsystemSchema> namespace;
MicroProfileLRAParticipantSubsystemSchema(int major) {
this.namespace = SubsystemSchema.createSubsystemURN(MicroProfileLRAParticipantExtension.SUBSYSTEM_NAME, new IntVersion(major));
}
@Override
public VersionedNamespace<IntVersion, MicroProfileLRAParticipantSubsystemSchema> getNamespace() {
return this.namespace;
}
@Override
public PersistentResourceXMLDescription getXMLDescription() {
return builder(MicroProfileLRAParticipantSubsystemDefinition.PATH, this.namespace)
.addAttributes(MicroProfileLRAParticipantSubsystemDefinition.ATTRIBUTES)
.build();
}
}
| 2,447 | 42.714286 | 135 |
java
|
null |
wildfly-main/microprofile/lra/participant/src/main/java/org/wildfly/extension/microprofile/lra/participant/MicroProfileLRAParticipantSubsystemModel.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.participant;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.SubsystemModel;
/**
* Enumerates the supported model versions of the MicroProfile LRA participant subsystem.
* @author Paul Ferraro
*/
enum MicroProfileLRAParticipantSubsystemModel implements SubsystemModel {
VERSION_1_0_0(1),
;
private final ModelVersion version;
MicroProfileLRAParticipantSubsystemModel(int major) {
this.version = ModelVersion.create(major);
}
@Override
public ModelVersion getVersion() {
return this.version;
}
}
| 1,649 | 34.869565 | 89 |
java
|
null |
wildfly-main/microprofile/lra/participant/src/main/java/org/wildfly/extension/microprofile/lra/participant/CommonAttributes.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.participant;
interface CommonAttributes {
String LRA_COORDINATOR_URL = "lra-coordinator-url";
String DEFAULT_COORDINATOR_URL = "http://localhost:8080/lra-coordinator/lra-coordinator";
String PROXY_SERVER = "proxy-server";
String PROXY_HOST = "proxy-host";
}
| 1,346 | 42.451613 | 93 |
java
|
null |
wildfly-main/microprofile/lra/participant/src/main/java/org/wildfly/extension/microprofile/lra/participant/MicroProfileLRAParticipantExtension.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.participant;
import org.jboss.as.controller.Extension;
import org.jboss.as.controller.ExtensionContext;
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.operations.common.GenericSubsystemDescribeHandler;
import org.jboss.as.controller.parsing.ExtensionParsingContext;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import java.util.EnumSet;
import java.util.List;
public class MicroProfileLRAParticipantExtension implements Extension {
/**
* The name of our subsystem within the model.
*/
static final String SUBSYSTEM_NAME = "microprofile-lra-participant";
private static final MicroProfileLRAParticipantSubsystemModel CURRENT_MODEL = MicroProfileLRAParticipantSubsystemModel.VERSION_1_0_0;
static final MicroProfileLRAParticipantSubsystemSchema CURRENT_SCHEMA = MicroProfileLRAParticipantSubsystemSchema.VERSION_1_0;
private final PersistentResourceXMLDescription currentDescription = CURRENT_SCHEMA.getXMLDescription();
@Override
public void initialize(ExtensionContext extensionContext) {
final SubsystemRegistration sr = extensionContext.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL.getVersion());
sr.registerXMLElementWriter(new PersistentResourceXMLDescriptionWriter(this.currentDescription));
final ManagementResourceRegistration root = sr.registerSubsystemModel(new MicroProfileLRAParticipantSubsystemDefinition());
root.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE, false);
}
@Override
public void initializeParsers(ExtensionParsingContext context) {
for (MicroProfileLRAParticipantSubsystemSchema schema : EnumSet.allOf(MicroProfileLRAParticipantSubsystemSchema.class)) {
XMLElementReader<List<ModelNode>> reader = (schema == CURRENT_SCHEMA) ? new PersistentResourceXMLDescriptionReader(this.currentDescription) : schema;
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, schema.getNamespace().getUri(), reader);
}
}
}
| 3,448 | 48.985507 | 161 |
java
|
null |
wildfly-main/microprofile/lra/participant/src/main/java/org/wildfly/extension/microprofile/lra/participant/Namespace.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.participant;
import java.util.HashMap;
import java.util.Map;
enum Namespace {
// must be first
UNKNOWN(null),
LRA_PARTICIPANT_1_0("urn:wildfly:microprofile-lra-participant:1.0"),
;
/**
* The current namespace version.
*/
public static final Namespace CURRENT = LRA_PARTICIPANT_1_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<>();
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,119 | 29.285714 | 72 |
java
|
null |
wildfly-main/microprofile/lra/participant/src/main/java/org/wildfly/extension/microprofile/lra/participant/MicroProfileLRAParticipantSubsystemDefinition.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.participant;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.PersistentResourceDefinition;
import org.jboss.as.controller.ReloadRequiredRemoveStepHandler;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.descriptions.ParentResourceDescriptionResolver;
import org.jboss.as.controller.descriptions.SubsystemResourceDescriptionResolver;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.wildfly.extension.undertow.Constants;
import java.util.Arrays;
import java.util.Collection;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.wildfly.extension.microprofile.lra.participant.MicroProfileLRAParticipantExtension.SUBSYSTEM_NAME;
public class MicroProfileLRAParticipantSubsystemDefinition extends PersistentResourceDefinition {
static final PathElement PATH = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME);
static final ParentResourceDescriptionResolver RESOLVER = new SubsystemResourceDescriptionResolver(SUBSYSTEM_NAME, MicroProfileLRAParticipantExtension.class);
private static final String LRA_PARTICIPANT_CAPABILITY_NAME = "org.wildfly.microprofile.lra.participant";
public static final String COORDINATOR_URL_PROP = "lra.coordinator.url";
static final RuntimeCapability<Void> LRA_PARTICIPANT_CAPABILITY = RuntimeCapability.Builder
.of(LRA_PARTICIPANT_CAPABILITY_NAME)
.setServiceType(Void.class)
.build();
static final SimpleAttributeDefinition LRA_COORDINATOR_URL =
new SimpleAttributeDefinitionBuilder(CommonAttributes.LRA_COORDINATOR_URL, ModelType.STRING, true)
.setRequired(false)
.setDefaultValue(new ModelNode(CommonAttributes.DEFAULT_COORDINATOR_URL))
.setAllowExpression(true)
.setXmlName(CommonAttributes.LRA_COORDINATOR_URL)
.setRestartAllServices()
.build();
static final SimpleAttributeDefinition PROXY_SERVER =
new SimpleAttributeDefinitionBuilder(CommonAttributes.PROXY_SERVER, ModelType.STRING, true)
.setAllowExpression(true)
.setXmlName(CommonAttributes.PROXY_SERVER)
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.setDefaultValue(new ModelNode(Constants.DEFAULT_SERVER))
.build();
static final SimpleAttributeDefinition PROXY_HOST =
new SimpleAttributeDefinitionBuilder(CommonAttributes.PROXY_HOST, ModelType.STRING, true)
.setAllowExpression(true)
.setXmlName(CommonAttributes.PROXY_HOST)
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.setDefaultValue(new ModelNode(Constants.DEFAULT_HOST))
.build();
static final AttributeDefinition[] ATTRIBUTES = {LRA_COORDINATOR_URL, PROXY_SERVER, PROXY_HOST};
MicroProfileLRAParticipantSubsystemDefinition() {
super(new Parameters(PATH, RESOLVER)
.setAddHandler(new MicroProfileLRAParticipantAdd())
.setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE)
.setCapabilities(LRA_PARTICIPANT_CAPABILITY));
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return Arrays.asList(ATTRIBUTES);
}
}
| 4,607 | 46.020408 | 162 |
java
|
null |
wildfly-main/microprofile/lra/participant/src/main/java/org/wildfly/extension/microprofile/lra/participant/service/LRAParticipantService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.participant.service;
import static org.wildfly.extension.microprofile.lra.participant.MicroProfileLRAParticipantSubsystemDefinition.COORDINATOR_URL_PROP;
import io.undertow.servlet.api.Deployment;
import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.DeploymentManager;
import io.undertow.servlet.api.ServletContainer;
import io.undertow.servlet.api.ServletInfo;
import jakarta.servlet.ServletException;
import org.jboss.msc.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher;
import org.wildfly.extension.microprofile.lra.participant._private.MicroProfileLRAParticipantLogger;
import org.wildfly.extension.microprofile.lra.participant.jaxrs.LRAParticipantApplication;
import org.wildfly.extension.undertow.Host;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
public final class LRAParticipantService implements Service {
public static final String CONTEXT_PATH = "/lra-participant-narayana-proxy";
private static final String DEPLOYMENT_NAME = "LRA Participant Proxy";
private final Supplier<Host> undertow;
private volatile DeploymentManager deploymentManager = null;
private volatile Deployment deployment = null;
public LRAParticipantService(Supplier<Host> undertow) {
this.undertow = undertow;
}
@Override
public synchronized void start(final StartContext context) throws StartException {
deployParticipantProxy();
}
@Override
public synchronized void stop(final StopContext context) {
try {
undeployServlet();
} finally {
// If we are stopping the server is either shutting down or reloading.
// In case it's a reload and this subsystem will not be installed after the reload,
// clear the lra.coordinator.url prop so it doesn't affect the reloaded server.
// If the subsystem is still in the config, the add op handler will set it again.
// TODO perhaps set the property in this service's start and have LRAParticipantDeploymentDependencyProcessor
// add a dep on this service to the next DeploymentUnitPhaseService (thus ensuring the prop
// is set before any deployment begins creating services).
System.clearProperty(COORDINATOR_URL_PROP);
}
}
private void deployParticipantProxy() {
undeployServlet();
final Map<String, String> initialParameters = new HashMap<>();
initialParameters.put("jakarta.ws.rs.Application", LRAParticipantApplication.class.getName());
MicroProfileLRAParticipantLogger.LOGGER.startingParticipantProxy(CONTEXT_PATH);
final DeploymentInfo participantProxyDeploymentInfo = getDeploymentInfo(DEPLOYMENT_NAME, CONTEXT_PATH, initialParameters);
deployServlet(participantProxyDeploymentInfo);
}
private DeploymentInfo getDeploymentInfo(final String name, final String contextPath, final Map<String, String> initialParameters) {
final DeploymentInfo deploymentInfo = new DeploymentInfo();
deploymentInfo.setClassLoader(LRAParticipantApplication.class.getClassLoader());
deploymentInfo.setContextPath(contextPath);
deploymentInfo.setDeploymentName(name);
// JAX-RS setup
ServletInfo restEasyServlet = new ServletInfo("RESTEasy", HttpServletDispatcher.class).addMapping("/*");
deploymentInfo.addServlets(restEasyServlet);
for (Map.Entry<String, String> entry : initialParameters.entrySet()) {
deploymentInfo.addInitParameter(entry.getKey(), entry.getValue());
}
return deploymentInfo;
}
private void deployServlet(final DeploymentInfo deploymentInfo) {
deploymentManager = ServletContainer.Factory.newInstance().addDeployment(deploymentInfo);
deploymentManager.deploy();
deployment = deploymentManager.getDeployment();
try {
undertow.get()
.registerDeployment(deployment, deploymentManager.start());
} catch (ServletException e) {
deployment = null;
}
}
private void undeployServlet() {
if (deploymentManager != null) {
if (deployment != null) {
undertow.get()
.unregisterDeployment(deployment);
deployment = null;
}
try {
deploymentManager.stop();
} catch (ServletException e) {
MicroProfileLRAParticipantLogger.LOGGER.failedStoppingParticipant(CONTEXT_PATH, e);
} finally {
deploymentManager.undeploy();
}
deploymentManager = null;
}
}
}
| 5,938 | 42.036232 | 136 |
java
|
null |
wildfly-main/microprofile/lra/participant/src/main/java/org/wildfly/extension/microprofile/lra/participant/_private/MicroProfileLRAParticipantLogger.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.participant._private;
import jakarta.servlet.ServletException;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
import org.wildfly.extension.microprofile.lra.participant.service.LRAParticipantService;
import static org.jboss.logging.Logger.Level.ERROR;
import static org.jboss.logging.Logger.Level.INFO;
import static org.jboss.logging.Logger.Level.WARN;
/**
* Log messages for WildFly microprofile-lra-participant Extension.
*/
@MessageLogger(projectCode = "WFLYTXLRAPARTICIPANT", length = 4)
public interface MicroProfileLRAParticipantLogger extends BasicLogger {
MicroProfileLRAParticipantLogger LOGGER = Logger.getMessageLogger(MicroProfileLRAParticipantLogger.class, "org.wildfly.extension.microprofile.lra.participant");
/**
* Logs an informational message indicating the subsystem is being activated.
*/
@LogMessage(level = INFO)
@Message(id = 1, value = "Activating MicroProfile LRA Participant Subsystem with system property (lra.coordinator.url) value as %s")
void activatingSubsystem(String url);
@LogMessage(level = INFO)
@Message(id = 2, value = "Starting Narayana MicroProfile LRA Participant Proxy available at path %s" + LRAParticipantService.CONTEXT_PATH)
void startingParticipantProxy(String path);
@LogMessage(level = WARN)
@Message(id = 3, value = "The CDI marker file cannot be created")
void cannotCreateCDIMarkerFile(@Cause Throwable e);
@LogMessage(level = ERROR)
@Message(id = 4, value = "Failed to stop Narayana MicroProfile LRA Participant Proxy at path %s/" + LRAParticipantService.CONTEXT_PATH)
void failedStoppingParticipant(String path, @Cause ServletException cause);
}
| 2,962 | 44.584615 | 164 |
java
|
null |
wildfly-main/microprofile/lra/participant/src/main/java/org/wildfly/extension/microprofile/lra/participant/deployment/LRAParticipantDeploymentDependencyProcessor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.participant.deployment;
import io.narayana.lra.client.internal.proxy.nonjaxrs.LRACDIExtension;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
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.as.server.deployment.module.ModuleDependency;
import org.jboss.as.server.deployment.module.ModuleSpecification;
import org.jboss.as.weld.WeldCapability;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleLoader;
import org.jboss.modules.filter.PathFilters;
import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME;
public class LRAParticipantDeploymentDependencyProcessor implements DeploymentUnitProcessor {
@Override
public void deploy(DeploymentPhaseContext phaseContext) {
DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (LRAAnnotationsUtil.isNotLRADeployment(deploymentUnit)) {
return;
}
addModuleDependencies(deploymentUnit);
}
@Override
public void undeploy(DeploymentUnit context) {
}
private void addModuleDependencies(DeploymentUnit deploymentUnit) {
final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);
final ModuleLoader moduleLoader = Module.getBootModuleLoader();
moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, "org.eclipse.microprofile.lra.api", false, false, false, false));
ModuleDependency lraParticipantDependency = new ModuleDependency(moduleLoader, "org.jboss.narayana.rts.lra-participant", false, false, true, false);
lraParticipantDependency.addImportFilter(PathFilters.getMetaInfFilter(), true);
moduleSpecification.addSystemDependency(lraParticipantDependency);
moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, "org.jboss.jandex", false, false, true, false));
moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, "org.jboss.as.weld.common", false, false, true, false));
moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, "org.jboss.resteasy.resteasy-cdi", false, false, true, false));
final CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
if (support.hasCapability(WELD_CAPABILITY_NAME)) {
support.getOptionalCapabilityRuntimeAPI(WELD_CAPABILITY_NAME, WeldCapability.class).get()
.registerExtensionInstance(new LRACDIExtension(), deploymentUnit);
}
}
}
| 3,827 | 50.04 | 156 |
java
|
null |
wildfly-main/microprofile/lra/participant/src/main/java/org/wildfly/extension/microprofile/lra/participant/deployment/LRAParticipantDeploymentSetupProcessor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.participant.deployment;
import org.jboss.as.ee.structure.DeploymentType;
import org.jboss.as.ee.structure.DeploymentTypeMarker;
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.vfs.VirtualFile;
import org.wildfly.extension.microprofile.lra.participant._private.MicroProfileLRAParticipantLogger;
import java.io.IOException;
public class LRAParticipantDeploymentSetupProcessor implements DeploymentUnitProcessor {
// CDI markers do declare deployment being a CDI project
private static final String WEB_INF_BEANS_XML = "WEB-INF/beans.xml";
private static final String META_INF_BEANS_XML = "META-INF/beans.xml";
@Override
public void deploy(DeploymentPhaseContext phaseContext) {
DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (LRAAnnotationsUtil.isNotLRADeployment(deploymentUnit)) {
return;
}
addBeanXml(deploymentUnit);
}
@Override
public void undeploy(DeploymentUnit context) {
}
private void addBeanXml(DeploymentUnit deploymentUnit) {
VirtualFile beanXmlVFile;
if (DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) {
beanXmlVFile = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot().getChild(WEB_INF_BEANS_XML);
} else {
beanXmlVFile = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot().getChild(META_INF_BEANS_XML);
}
if (!beanXmlVFile.exists()) {
try {
boolean isCreated = beanXmlVFile.getPhysicalFile().createNewFile();
MicroProfileLRAParticipantLogger.LOGGER.debugf("The CDI marker file '%s' %s created",
beanXmlVFile.getPhysicalFile(), (isCreated ? "was" : "was NOT"));
} catch (IOException ioe) {
MicroProfileLRAParticipantLogger.LOGGER.cannotCreateCDIMarkerFile(ioe);
}
}
}
}
| 3,198 | 42.22973 | 124 |
java
|
null |
wildfly-main/microprofile/lra/participant/src/main/java/org/wildfly/extension/microprofile/lra/participant/deployment/LRAParticipantJaxrsDeploymentUnitProcessor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.participant.deployment;
import io.narayana.lra.client.internal.proxy.nonjaxrs.LRAParticipantResource;
import io.narayana.lra.filter.ClientLRARequestFilter;
import io.narayana.lra.filter.ClientLRAResponseFilter;
import io.narayana.lra.filter.ServerLRAFilter;
import org.jboss.as.jaxrs.deployment.JaxrsAttachments;
import org.jboss.as.jaxrs.deployment.ResteasyDeploymentData;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
public class LRAParticipantJaxrsDeploymentUnitProcessor implements DeploymentUnitProcessor {
@Override
public void deploy(DeploymentPhaseContext phaseContext) {
DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (LRAAnnotationsUtil.isNotLRADeployment(deploymentUnit)) {
return;
}
final ResteasyDeploymentData resteasyDeploymentData = deploymentUnit.getAttachment(JaxrsAttachments.RESTEASY_DEPLOYMENT_DATA);
if (resteasyDeploymentData != null) {
resteasyDeploymentData.getScannedResourceClasses().add(LRAParticipantResource.class.getName());
resteasyDeploymentData.getScannedProviderClasses().add(ServerLRAFilter.class.getName());
resteasyDeploymentData.getScannedProviderClasses().add(ClientLRARequestFilter.class.getName());
resteasyDeploymentData.getScannedProviderClasses().add(ClientLRAResponseFilter.class.getName());
}
}
@Override
public void undeploy(DeploymentUnit context) {
}
}
| 2,667 | 45.807018 | 134 |
java
|
null |
wildfly-main/microprofile/lra/participant/src/main/java/org/wildfly/extension/microprofile/lra/participant/deployment/LRAAnnotationsUtil.java
|
package org.wildfly.extension.microprofile.lra.participant.deployment;
import org.eclipse.microprofile.lra.annotation.AfterLRA;
import org.eclipse.microprofile.lra.annotation.Compensate;
import org.eclipse.microprofile.lra.annotation.Complete;
import org.eclipse.microprofile.lra.annotation.Forget;
import org.eclipse.microprofile.lra.annotation.Status;
import org.eclipse.microprofile.lra.annotation.ws.rs.LRA;
import org.eclipse.microprofile.lra.annotation.ws.rs.Leave;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.annotation.CompositeIndex;
import org.jboss.jandex.DotName;
public class LRAAnnotationsUtil {
private static final DotName[] LRA_ANNOTATIONS = {
DotName.createSimple(LRA.class),
DotName.createSimple(Complete.class),
DotName.createSimple(Compensate.class),
DotName.createSimple(Status.class),
DotName.createSimple(Forget.class),
DotName.createSimple(Leave.class),
DotName.createSimple(AfterLRA.class)
};
public static boolean isNotLRADeployment(DeploymentUnit deploymentUnit) {
final CompositeIndex compositeIndex = deploymentUnit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
if (compositeIndex == null) {
return true;
}
return !isLRAAnnotationsPresent(compositeIndex);
}
private static boolean isLRAAnnotationsPresent(CompositeIndex compositeIndex) {
for (DotName annotation : LRA_ANNOTATIONS) {
if (compositeIndex.getAnnotations(annotation).size() > 0) {
return true;
}
}
return false;
}
}
| 1,711 | 36.217391 | 115 |
java
|
null |
wildfly-main/microprofile/lra/participant/src/main/java/org/wildfly/extension/microprofile/lra/participant/jaxrs/LRAParticipantApplication.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.participant.jaxrs;
import io.narayana.lra.client.internal.proxy.nonjaxrs.LRAParticipantResource;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@ApplicationPath("/")
public class LRAParticipantApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
return new HashSet<>(List.of(LRAParticipantResource.class));
}
}
| 1,534 | 36.439024 | 77 |
java
|
null |
wildfly-main/microprofile/lra/coordinator/src/test/java/org/wildfly/extension/microprofile/lra/coordinator/MicroprofileLRACoordinatorSubsystemTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.coordinator;
import org.jboss.as.subsystem.test.AbstractSubsystemSchemaTest;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.EnumSet;
@RunWith(Parameterized.class)
public class MicroprofileLRACoordinatorSubsystemTestCase extends AbstractSubsystemSchemaTest<MicroProfileLRACoordinatorSubsystemSchema> {
@Parameterized.Parameters
public static Iterable<MicroProfileLRACoordinatorSubsystemSchema> parameters() {
return EnumSet.allOf(MicroProfileLRACoordinatorSubsystemSchema.class);
}
public MicroprofileLRACoordinatorSubsystemTestCase(MicroProfileLRACoordinatorSubsystemSchema schema) {
super(MicroProfileLRACoordinatorExtension.SUBSYSTEM_NAME, new MicroProfileLRACoordinatorExtension(), schema, MicroProfileLRACoordinatorExtension.CURRENT_SCHEMA);
}
}
| 1,905 | 43.325581 | 169 |
java
|
null |
wildfly-main/microprofile/lra/coordinator/src/main/java/org/wildfly/extension/microprofile/lra/coordinator/MicroProfileLRACoordinatorSubsystemSchema.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.coordinator;
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;
import static org.jboss.as.controller.PersistentResourceXMLDescription.builder;
/**
* Enumerates the supported schemas of the MicroProfile LRA coordinator subsystem.
*
* @author Paul Ferraro
*/
public enum MicroProfileLRACoordinatorSubsystemSchema implements PersistentSubsystemSchema<MicroProfileLRACoordinatorSubsystemSchema> {
VERSION_1_0(1),
;
private final VersionedNamespace<IntVersion, MicroProfileLRACoordinatorSubsystemSchema> namespace;
MicroProfileLRACoordinatorSubsystemSchema(int major) {
this.namespace = SubsystemSchema.createSubsystemURN(MicroProfileLRACoordinatorExtension.SUBSYSTEM_NAME, new IntVersion(major));
}
@Override
public VersionedNamespace<IntVersion, MicroProfileLRACoordinatorSubsystemSchema> getNamespace() {
return this.namespace;
}
@Override
public PersistentResourceXMLDescription getXMLDescription() {
return builder(MicroProfileLRACoordinatorSubsystemDefinition.PATH, this.namespace)
.addAttributes(MicroProfileLRACoordinatorSubsystemDefinition.ATTRIBUTES)
.build();
}
}
| 2,459 | 40.694915 | 135 |
java
|
null |
wildfly-main/microprofile/lra/coordinator/src/main/java/org/wildfly/extension/microprofile/lra/coordinator/MicroProfileLRACoordinatorSubsystemModel.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.coordinator;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.SubsystemModel;
/**
* Enumerates the supported model versions of the MicroProfile LRA coordinator subsystem.
* @author Paul Ferraro
*/
public enum MicroProfileLRACoordinatorSubsystemModel implements SubsystemModel {
VERSION_1_0_0(1),
;
private final ModelVersion version;
MicroProfileLRACoordinatorSubsystemModel(int major) {
this.version = ModelVersion.create(major);
}
@Override
public ModelVersion getVersion() {
return this.version;
}
}
| 1,656 | 35.021739 | 89 |
java
|
null |
wildfly-main/microprofile/lra/coordinator/src/main/java/org/wildfly/extension/microprofile/lra/coordinator/MicroProfileLRACoordinatorExtension.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.coordinator;
import org.jboss.as.controller.Extension;
import org.jboss.as.controller.ExtensionContext;
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.operations.common.GenericSubsystemDescribeHandler;
import org.jboss.as.controller.parsing.ExtensionParsingContext;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import java.util.EnumSet;
import java.util.List;
public class MicroProfileLRACoordinatorExtension implements Extension {
/**
* The name of our subsystem within the model.
*/
static final String SUBSYSTEM_NAME = "microprofile-lra-coordinator";
private static final MicroProfileLRACoordinatorSubsystemModel CURRENT_MODEL = MicroProfileLRACoordinatorSubsystemModel.VERSION_1_0_0;
static final MicroProfileLRACoordinatorSubsystemSchema CURRENT_SCHEMA = MicroProfileLRACoordinatorSubsystemSchema.VERSION_1_0;
private final PersistentResourceXMLDescription currentDescription = CURRENT_SCHEMA.getXMLDescription();
@Override
public void initialize(ExtensionContext extensionContext) {
final SubsystemRegistration subsystem = extensionContext.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL.getVersion());
subsystem.registerXMLElementWriter(new PersistentResourceXMLDescriptionWriter(this.currentDescription));
final ManagementResourceRegistration registration = subsystem.registerSubsystemModel(new MicroProfileLRACoordinatorSubsystemDefinition());
registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE);
}
@Override
public void initializeParsers(ExtensionParsingContext context) {
for (MicroProfileLRACoordinatorSubsystemSchema schema : EnumSet.allOf(MicroProfileLRACoordinatorSubsystemSchema.class)) {
XMLElementReader<List<ModelNode>> reader = (schema == CURRENT_SCHEMA) ? new PersistentResourceXMLDescriptionReader(this.currentDescription) : schema;
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, schema.getNamespace().getUri(), reader);
}
}
}
| 3,476 | 50.132353 | 161 |
java
|
null |
wildfly-main/microprofile/lra/coordinator/src/main/java/org/wildfly/extension/microprofile/lra/coordinator/MicroProfileLRACoordinatorAdd.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.coordinator;
import org.jboss.as.controller.AbstractBoottimeAddStepHandler;
import org.jboss.as.controller.CapabilityServiceBuilder;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceController;
import org.jboss.tm.XAResourceRecoveryRegistry;
import org.wildfly.extension.microprofile.lra.coordinator._private.MicroProfileLRACoordinatorLogger;
import org.wildfly.extension.microprofile.lra.coordinator.service.LRACoordinatorService;
import org.wildfly.extension.microprofile.lra.coordinator.service.LRARecoveryService;
import org.wildfly.extension.undertow.Capabilities;
import org.wildfly.extension.undertow.Host;
import org.wildfly.extension.undertow.UndertowService;
import java.util.Arrays;
import java.util.function.Supplier;
import static org.wildfly.extension.microprofile.lra.coordinator.MicroProfileLRACoordinatorSubsystemDefinition.ATTRIBUTES;
class MicroProfileLRACoordinatorAdd extends AbstractBoottimeAddStepHandler {
MicroProfileLRACoordinatorAdd() {
super(Arrays.asList(ATTRIBUTES));
}
@Override
protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
super.performBoottime(context, operation, model);
registerRecoveryService(context);
registerCoordinatorService(context, model);
MicroProfileLRACoordinatorLogger.LOGGER.activatingSubsystem();
}
private void registerCoordinatorService(final OperationContext context, final ModelNode model) throws OperationFailedException {
CapabilityServiceBuilder builder = context.getCapabilityServiceTarget()
.addCapability(MicroProfileLRACoordinatorSubsystemDefinition.LRA_COORDINATOR_CAPABILITY);
builder.requiresCapability(Capabilities.CAPABILITY_UNDERTOW, UndertowService.class);
String serverModelValue = MicroProfileLRACoordinatorSubsystemDefinition.SERVER.resolveModelAttribute(context, model).asString();
String hostModelValue = MicroProfileLRACoordinatorSubsystemDefinition.HOST.resolveModelAttribute(context, model).asString();
Supplier<Host> hostSupplier = builder.requiresCapability(Capabilities.CAPABILITY_HOST, Host.class, serverModelValue, hostModelValue);
final LRACoordinatorService lraCoordinatorService = new LRACoordinatorService(hostSupplier);
builder.requiresCapability(MicroProfileLRACoordinatorSubsystemDefinition.LRA_RECOVERY_SERVICE_CAPABILITY_NAME, null);
builder.setInstance(lraCoordinatorService);
builder.setInitialMode(ServiceController.Mode.ACTIVE).install();
}
private void registerRecoveryService(final OperationContext context) {
CapabilityServiceBuilder builder = context.getCapabilityServiceTarget().addCapability(
MicroProfileLRACoordinatorSubsystemDefinition.LRA_RECOVERY_SERVICE_CAPABILITY);
builder.provides(MicroProfileLRACoordinatorSubsystemDefinition.LRA_RECOVERY_SERVICE_CAPABILITY);
// JTA is required to be loaded before the LRA recovery setup
builder.requiresCapability(MicroProfileLRACoordinatorSubsystemDefinition.REF_JTA_RECOVERY_CAPABILITY, XAResourceRecoveryRegistry.class);
final LRARecoveryService lraRecoveryService = new LRARecoveryService();
builder.setInstance(lraRecoveryService);
builder.setInitialMode(ServiceController.Mode.ACTIVE).install();
}
}
| 4,572 | 50.965909 | 144 |
java
|
null |
wildfly-main/microprofile/lra/coordinator/src/main/java/org/wildfly/extension/microprofile/lra/coordinator/MicroProfileLRACoordinatorSubsystemDefinition.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.coordinator;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.ReloadRequiredRemoveStepHandler;
import org.jboss.as.controller.ReloadRequiredWriteAttributeHandler;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.descriptions.ParentResourceDescriptionResolver;
import org.jboss.as.controller.descriptions.SubsystemResourceDescriptionResolver;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.wildfly.extension.undertow.Constants;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.wildfly.extension.microprofile.lra.coordinator.MicroProfileLRACoordinatorExtension.SUBSYSTEM_NAME;
public class MicroProfileLRACoordinatorSubsystemDefinition extends SimpleResourceDefinition {
static final PathElement PATH = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME);
static final ParentResourceDescriptionResolver RESOLVER = new SubsystemResourceDescriptionResolver(SUBSYSTEM_NAME, MicroProfileLRACoordinatorExtension.class);
static final String LRA_COORDINATOR_CAPABILITY_NAME = "org.wildfly.microprofile.lra.coordinator";
static final String LRA_RECOVERY_SERVICE_CAPABILITY_NAME = "org.wildfly.microprofile.lra.recovery";
static final String REF_JTA_RECOVERY_CAPABILITY = "org.wildfly.transactions.xa-resource-recovery-registry";
static final RuntimeCapability<Void> LRA_COORDINATOR_CAPABILITY = RuntimeCapability.Builder
.of(LRA_COORDINATOR_CAPABILITY_NAME)
.setServiceType(Void.class)
.build();
static final RuntimeCapability<Void> LRA_RECOVERY_SERVICE_CAPABILITY = RuntimeCapability.Builder
.of(LRA_RECOVERY_SERVICE_CAPABILITY_NAME)
.setServiceType(Void.class)
.build();
static final SimpleAttributeDefinition SERVER =
new SimpleAttributeDefinitionBuilder(CommonAttributes.SERVER, ModelType.STRING, true)
.setAllowExpression(true)
.setXmlName(CommonAttributes.SERVER)
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.setDefaultValue(new ModelNode(Constants.DEFAULT_SERVER))
.build();
static final SimpleAttributeDefinition HOST =
new SimpleAttributeDefinitionBuilder(CommonAttributes.HOST, ModelType.STRING, true)
.setAllowExpression(true)
.setXmlName(CommonAttributes.HOST)
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.setDefaultValue(new ModelNode(Constants.DEFAULT_HOST))
.build();
static final AttributeDefinition[] ATTRIBUTES = {SERVER, HOST};
MicroProfileLRACoordinatorSubsystemDefinition() {
super(new Parameters(PATH, RESOLVER)
.setAddHandler(new MicroProfileLRACoordinatorAdd())
.setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE)
.setCapabilities(LRA_COORDINATOR_CAPABILITY, LRA_RECOVERY_SERVICE_CAPABILITY));
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerReadWriteAttribute(SERVER, null, new ReloadRequiredWriteAttributeHandler(SERVER));
resourceRegistration.registerReadWriteAttribute(HOST, null, new ReloadRequiredWriteAttributeHandler(HOST));
}
}
| 4,757 | 49.617021 | 162 |
java
|
null |
wildfly-main/microprofile/lra/coordinator/src/main/java/org/wildfly/extension/microprofile/lra/coordinator/CommonAttributes.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.coordinator;
interface CommonAttributes {
String SERVER = "server";
String HOST = "host";
}
| 1,170 | 42.37037 | 70 |
java
|
null |
wildfly-main/microprofile/lra/coordinator/src/main/java/org/wildfly/extension/microprofile/lra/coordinator/service/LRACoordinatorService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.coordinator.service;
import io.undertow.servlet.api.Deployment;
import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.DeploymentManager;
import io.undertow.servlet.api.ServletContainer;
import io.undertow.servlet.api.ServletInfo;
import org.jboss.msc.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher;
import org.wildfly.extension.microprofile.lra.coordinator._private.MicroProfileLRACoordinatorLogger;
import org.wildfly.extension.microprofile.lra.coordinator.jaxrs.LRACoordinatorApp;
import org.wildfly.extension.undertow.Host;
import jakarta.servlet.ServletException;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
public final class LRACoordinatorService implements Service {
public static final String CONTEXT_PATH = "/lra-coordinator";
private static final String DEPLOYMENT_NAME = "LRA Coordinator";
private final Supplier<Host> undertow;
private volatile DeploymentManager deploymentManager = null;
private volatile Deployment deployment = null;
public LRACoordinatorService(Supplier<Host> undertow) {
this.undertow = undertow;
}
@Override
public synchronized void start(final StartContext context) throws StartException {
deployCoordinator();
}
@Override
public synchronized void stop(final StopContext context) {
undeployServlet();
}
private void deployCoordinator() {
undeployServlet();
final Map<String, String> initialParameters = new HashMap<>();
initialParameters.put("jakarta.ws.rs.Application", LRACoordinatorApp.class.getName());
MicroProfileLRACoordinatorLogger.LOGGER.startingCoordinator(CONTEXT_PATH);
final DeploymentInfo coordinatorDeploymentInfo = getDeploymentInfo(DEPLOYMENT_NAME, CONTEXT_PATH, initialParameters);
deployServlet(coordinatorDeploymentInfo);
}
private DeploymentInfo getDeploymentInfo(final String name, final String contextPath, final Map<String, String> initialParameters) {
final DeploymentInfo deploymentInfo = new DeploymentInfo();
deploymentInfo.setClassLoader(LRACoordinatorApp.class.getClassLoader());
deploymentInfo.setContextPath(contextPath);
deploymentInfo.setDeploymentName(name);
// JAX-RS setup
ServletInfo restEasyServlet = new ServletInfo("RESTEasy", HttpServletDispatcher.class).addMapping("/*");
deploymentInfo.addServlets(restEasyServlet);
for (Map.Entry<String, String> entry : initialParameters.entrySet()) {
deploymentInfo.addInitParameter(entry.getKey(), entry.getValue());
}
return deploymentInfo;
}
private void deployServlet(final DeploymentInfo deploymentInfo) {
deploymentManager = ServletContainer.Factory.newInstance().addDeployment(deploymentInfo);
deploymentManager.deploy();
deployment = deploymentManager.getDeployment();
try {
undertow.get()
.registerDeployment(deployment, deploymentManager.start());
} catch (ServletException e) {
deployment = null;
}
}
private void undeployServlet() {
if (deploymentManager != null) {
if (deployment != null) {
undertow.get()
.unregisterDeployment(deployment);
deployment = null;
}
try {
deploymentManager.stop();
} catch (ServletException e) {
MicroProfileLRACoordinatorLogger.LOGGER.failedStoppingCoordinator(CONTEXT_PATH, e);
} finally {
deploymentManager.undeploy();
}
deploymentManager = null;
}
}
}
| 4,968 | 38.752 | 136 |
java
|
null |
wildfly-main/microprofile/lra/coordinator/src/main/java/org/wildfly/extension/microprofile/lra/coordinator/service/LRARecoveryService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.coordinator.service;
import com.arjuna.ats.arjuna.recovery.RecoveryManager;
import io.narayana.lra.coordinator.internal.Implementations;
import io.narayana.lra.coordinator.internal.LRARecoveryModule;
import org.jboss.logging.Logger;
import org.jboss.msc.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.wildfly.extension.microprofile.lra.coordinator._private.MicroProfileLRACoordinatorLogger;
import org.wildfly.security.manager.WildFlySecurityManager;
public class LRARecoveryService implements Service {
private static final Logger log = Logger.getLogger(LRARecoveryService.class);
private volatile LRARecoveryModule lraRecoveryModule;
@Override
public synchronized void start(final StartContext context) throws StartException {
// installing LRA recovery types
Implementations.install();
final ClassLoader loader = LRARecoveryService.class.getClassLoader();
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(loader);
try {
try {
lraRecoveryModule = LRARecoveryModule.getInstance();
// verify if the getInstance has added the module else could be removed meanwhile and adding explicitly
if(RecoveryManager.manager().getModules().stream()
.noneMatch(rm -> rm instanceof LRARecoveryModule)) {
RecoveryManager.manager().addModule(lraRecoveryModule);
}
} catch (Exception e) {
throw MicroProfileLRACoordinatorLogger.LOGGER.lraRecoveryServiceFailedToStart();
}
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged((ClassLoader) null);
}
}
@Override
public synchronized void stop(final StopContext context) {
Implementations.uninstall();
if (lraRecoveryModule != null) {
final RecoveryManager recoveryManager = RecoveryManager.manager();
try {
recoveryManager.removeModule(lraRecoveryModule, false);
} catch (Exception e) {
log.debugf("Cannot remove LRA recovery module %s while stopping %s",
lraRecoveryModule.getClass().getName(), LRARecoveryService.class.getName());
}
}
}
}
| 3,465 | 43.435897 | 119 |
java
|
null |
wildfly-main/microprofile/lra/coordinator/src/main/java/org/wildfly/extension/microprofile/lra/coordinator/_private/MicroProfileLRACoordinatorLogger.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.coordinator._private;
import io.narayana.lra.LRAConstants;
import jakarta.servlet.ServletException;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
import org.jboss.msc.service.StartException;
import static org.jboss.logging.Logger.Level.ERROR;
import static org.jboss.logging.Logger.Level.INFO;
/**
* Log messages for WildFly microprofile-lra-coordinator Extension.
*/
@MessageLogger(projectCode = "WFLYTXLRACOORD", length = 4)
public interface MicroProfileLRACoordinatorLogger extends BasicLogger {
MicroProfileLRACoordinatorLogger LOGGER = Logger.getMessageLogger(MicroProfileLRACoordinatorLogger.class, "org.wildfly.extension.microprofile.lra.coordinator");
/**
* Logs an informational message indicating the subsystem is being activated.
*/
@LogMessage(level = INFO)
@Message(id = 1, value = "Activating MicroProfile LRA Coordinator Subsystem")
void activatingSubsystem();
/**
* Creates an exception indicating that the LRA recovery service failed to start.
*
* @return a {@link org.jboss.msc.service.StartException} for the error.
*/
@Message(id = 2, value = "LRA recovery service start failed")
StartException lraRecoveryServiceFailedToStart();
@LogMessage(level = INFO)
@Message(id = 3, value = "Starting Narayana MicroProfile LRA Coordinator available at path %s/" + LRAConstants.COORDINATOR_PATH_NAME)
void startingCoordinator(String path);
@LogMessage(level = ERROR)
@Message(id = 4, value = "Failed to stop Narayana MicroProfile LRA Coordinator at path %s/" + LRAConstants.COORDINATOR_PATH_NAME)
void failedStoppingCoordinator(String path, @Cause ServletException cause);
}
| 2,967 | 42.014493 | 164 |
java
|
null |
wildfly-main/microprofile/lra/coordinator/src/main/java/org/wildfly/extension/microprofile/lra/coordinator/jaxrs/LRACoordinatorApp.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.lra.coordinator.jaxrs;
import io.narayana.lra.coordinator.api.Coordinator;
import io.narayana.lra.coordinator.api.CoordinatorContainerFilter;
import jakarta.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
public class LRACoordinatorApp extends Application {
private final Set<Class<?>> classes = new HashSet<>();
private final Set<Object> singletons = new HashSet<>();
public LRACoordinatorApp() {
classes.add(Coordinator.class);
singletons.add(new CoordinatorContainerFilter());
}
@Override
public Set<Class<?>> getClasses() {
return classes;
}
@Override
public Set<Object> getSingletons() {
return singletons;
}
}
| 1,784 | 34.7 | 70 |
java
|
null |
wildfly-main/microprofile/jwt-smallrye/src/test/java/org/wildfly/extension/microprofile/jwt/smallrye/MicroProfileJWTSubsystemTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.extension.microprofile.jwt.smallrye;
import java.util.EnumSet;
import java.util.Properties;
import org.jboss.as.subsystem.test.AbstractSubsystemSchemaTest;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
* Subsystem parsing test case.
*
* <a href="mailto:[email protected]">Darran Lofthouse</a>
*/
@RunWith(Parameterized.class)
public class MicroProfileJWTSubsystemTestCase extends AbstractSubsystemSchemaTest<MicroProfileJWTSubsystemSchema> {
@Parameters
public static Iterable<MicroProfileJWTSubsystemSchema> parameters() {
return EnumSet.allOf(MicroProfileJWTSubsystemSchema.class);
}
public MicroProfileJWTSubsystemTestCase(MicroProfileJWTSubsystemSchema schema) {
super(MicroProfileJWTExtension.SUBSYSTEM_NAME, new MicroProfileJWTExtension(), schema, MicroProfileJWTSubsystemSchema.CURRENT);
}
@Override
protected String getSubsystemXmlPathPattern() {
// Exclude subsystem name from pattern
return "subsystem_%2$d_%3$d.xml";
}
@Override
protected Properties getResolvedProperties() {
return System.getProperties();
}
}
| 1,935 | 33.571429 | 135 |
java
|
null |
wildfly-main/microprofile/jwt-smallrye/src/main/java/org/wildfly/extension/microprofile/jwt/smallrye/MicroProfileSubsystemDefinition.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.extension.microprofile.jwt.smallrye;
import static org.wildfly.extension.microprofile.jwt.smallrye.Capabilities.CONFIG_CAPABILITY_NAME;
import static org.wildfly.extension.microprofile.jwt.smallrye.Capabilities.EE_SECURITY_CAPABILITY_NAME;
import static org.wildfly.extension.microprofile.jwt.smallrye.Capabilities.ELYTRON_CAPABILITY_NAME;
import static org.wildfly.extension.microprofile.jwt.smallrye.Capabilities.JWT_CAPABILITY_NAME;
import static org.wildfly.extension.microprofile.jwt.smallrye.Capabilities.WELD_CAPABILITY_NAME;
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.SimpleResourceDefinition;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.RuntimePackageDependency;
/**
* Root subsystem definition for the MicroProfile JWT subsystem using SmallRye JWT.
*
* <a href="mailto:[email protected]">Darran Lofthouse</a>
*/
class MicroProfileSubsystemDefinition extends PersistentResourceDefinition {
static final String EE_SECURITY_IMPL = "org.wildfly.security.jakarta.security";
static final RuntimeCapability<Void> CONFIG_CAPABILITY =
RuntimeCapability.Builder.of(JWT_CAPABILITY_NAME)
.setServiceType(Void.class)
.addRequirements(CONFIG_CAPABILITY_NAME, EE_SECURITY_CAPABILITY_NAME,
ELYTRON_CAPABILITY_NAME, WELD_CAPABILITY_NAME)
.build();
protected MicroProfileSubsystemDefinition() {
super(new SimpleResourceDefinition.Parameters(MicroProfileJWTExtension.SUBSYSTEM_PATH, MicroProfileJWTExtension.SUBSYSTEM_RESOLVER)
.setAddHandler(new MicroProfileJWTSubsystemAdd())
.setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE)
.setCapabilities(CONFIG_CAPABILITY)
.setAdditionalPackages(RuntimePackageDependency.required(EE_SECURITY_IMPL))
);
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return Collections.emptySet();
}
@Override
public void registerOperations(ManagementResourceRegistration resourceRegistration) {
super.registerOperations(resourceRegistration);
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
}
}
| 3,345 | 41.897436 | 139 |
java
|
null |
wildfly-main/microprofile/jwt-smallrye/src/main/java/org/wildfly/extension/microprofile/jwt/smallrye/JwtDependencyProcessor.java
|
/*
* Copyright 2019 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.extension.microprofile.jwt.smallrye;
import static org.wildfly.extension.microprofile.jwt.smallrye.MicroProfileSubsystemDefinition.EE_SECURITY_IMPL;
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;
/**
* A {link {@link DeploymentUnitProcessor} to add the required dependencies to activate MicroProfile JWT.
*
* @author <a href="mailto:[email protected]">Darran Lofthouse</a>
*/
class JwtDependencyProcessor implements DeploymentUnitProcessor {
private static final String EE_SECURITY_API = "jakarta.security.enterprise.api";
private static final String MP_JWT_API = "org.eclipse.microprofile.jwt.auth.api";
private static final String SMALLRYE_JWT = "io.smallrye.jwt";
private static final String ELYTRON_JWT = "org.wildfly.security.elytron-jwt";
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (!JwtDeploymentMarker.isJWTDeployment(deploymentUnit)) {
return;
}
ModuleLoader moduleLoader = Module.getBootModuleLoader();
ModuleSpecification moduleSpec = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);
moduleSpec.addSystemDependency(new ModuleDependency(moduleLoader, EE_SECURITY_API, false, false, true, false));
moduleSpec.addSystemDependency(new ModuleDependency(moduleLoader, EE_SECURITY_IMPL, false, false, true, false));
moduleSpec.addSystemDependency(new ModuleDependency(moduleLoader, MP_JWT_API, false, false, true, false));
moduleSpec.addSystemDependency(new ModuleDependency(moduleLoader, SMALLRYE_JWT, false, false, true, false));
moduleSpec.addSystemDependency(new ModuleDependency(moduleLoader, ELYTRON_JWT, false, false, true, false));
}
}
| 2,910 | 48.338983 | 120 |
java
|
null |
wildfly-main/microprofile/jwt-smallrye/src/main/java/org/wildfly/extension/microprofile/jwt/smallrye/MicroProfileJWTExtension.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.extension.microprofile.jwt.smallrye;
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;
/**
* A {@link Extension} to add support for MicroProfile JWT using SmallRye JWT.
*
* <a href="mailto:[email protected]">Darran Lofthouse</a>
*/
public class MicroProfileJWTExtension implements Extension {
/**
* The name of our subsystem within the model.
*/
public static final String SUBSYSTEM_NAME = "microprofile-jwt-smallrye";
protected static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME);
static final ParentResourceDescriptionResolver SUBSYSTEM_RESOLVER = new SubsystemResourceDescriptionResolver(SUBSYSTEM_NAME, MicroProfileJWTExtension.class);
protected static final ModelVersion VERSION_1_0_0 = ModelVersion.create(1, 0, 0);
private static final ModelVersion CURRENT_MODEL_VERSION = VERSION_1_0_0;
private final PersistentResourceXMLDescription currentDescription = MicroProfileJWTSubsystemSchema.CURRENT.getXMLDescription();
@Override
public void initialize(ExtensionContext context) {
final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION);
subsystem.registerXMLElementWriter(new PersistentResourceXMLDescriptionWriter(this.currentDescription));
final ManagementResourceRegistration registration = subsystem.registerSubsystemModel(new MicroProfileSubsystemDefinition());
registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE);
}
@Override
public void initializeParsers(ExtensionParsingContext context) {
for (MicroProfileJWTSubsystemSchema schema : EnumSet.allOf(MicroProfileJWTSubsystemSchema.class)) {
XMLElementReader<List<ModelNode>> reader = (schema == MicroProfileJWTSubsystemSchema.CURRENT) ? new PersistentResourceXMLDescriptionReader(this.currentDescription) : schema;
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, schema.getNamespace().getUri(), reader);
}
}
}
| 3,805 | 45.414634 | 185 |
java
|
null |
wildfly-main/microprofile/jwt-smallrye/src/main/java/org/wildfly/extension/microprofile/jwt/smallrye/Capabilities.java
|
/*
* Copyright 2019 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.extension.microprofile.jwt.smallrye;
/**
* Class to hold the capabilities as used or exposed by this subsystem.
*
* @author <a href="mailto:[email protected]">Darran Lofthouse</a>
*/
class Capabilities {
/*
* Our Capabilities
*/
static final String JWT_CAPABILITY_NAME = "org.wildfly.microprofile.jwt";
/*
* External Capabilities
*/
static final String CONFIG_CAPABILITY_NAME = "org.wildfly.microprofile.config";
static final String EE_SECURITY_CAPABILITY_NAME = "org.wildfly.ee.security";
static final String ELYTRON_CAPABILITY_NAME = "org.wildfly.security.elytron";
static final String WELD_CAPABILITY_NAME = "org.wildfly.weld";
}
| 1,319 | 28.333333 | 83 |
java
|
null |
wildfly-main/microprofile/jwt-smallrye/src/main/java/org/wildfly/extension/microprofile/jwt/smallrye/MicroProfileJWTSubsystemAdd.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.extension.microprofile.jwt.smallrye;
import org.jboss.as.controller.AbstractBoottimeAddStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationContext.Stage;
import org.jboss.as.server.AbstractDeploymentChainStep;
import org.jboss.as.server.DeploymentProcessorTarget;
import org.jboss.as.server.deployment.Phase;
import org.jboss.dmr.ModelNode;
import org.wildfly.extension.microprofile.jwt.smallrye._private.MicroProfileJWTLogger;
/**
* Add handler for the MicroProfile JWT subsystem.
*
* <a href="mailto:[email protected]">Darran Lofthouse</a>
*/
class MicroProfileJWTSubsystemAdd extends AbstractBoottimeAddStepHandler {
MicroProfileJWTSubsystemAdd() {
}
@Override
public void performBoottime(OperationContext context, ModelNode operation, ModelNode model) {
MicroProfileJWTLogger.ROOT_LOGGER.activatingSubsystem();
if (context.isNormalServer()) {
context.addStep(new AbstractDeploymentChainStep() {
@Override
protected void execute(DeploymentProcessorTarget processorTarget) {
processorTarget.addDeploymentProcessor(MicroProfileJWTExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_MICROPROFILE_JWT_DETECTION, new JwtActivationProcessor());
processorTarget.addDeploymentProcessor(MicroProfileJWTExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_MICROPROFILE_JWT, new JwtDependencyProcessor());
}
}, Stage.RUNTIME);
}
}
}
| 2,291 | 38.517241 | 187 |
java
|
null |
wildfly-main/microprofile/jwt-smallrye/src/main/java/org/wildfly/extension/microprofile/jwt/smallrye/MicroProfileJWTSubsystemSchema.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.jwt.smallrye;
import static org.jboss.as.controller.PersistentResourceXMLDescription.builder;
import org.jboss.as.controller.PersistentResourceXMLDescription;
import org.jboss.as.controller.PersistentSubsystemSchema;
import org.jboss.as.controller.SubsystemSchema;
import org.jboss.as.controller.xml.VersionedNamespace;
import org.jboss.staxmapper.IntVersion;
/**
* Enumerates the supported subsystem namespaces of the MicroProfile JWT subsystem.
* @author Paul Ferraro
*/
public enum MicroProfileJWTSubsystemSchema implements PersistentSubsystemSchema<MicroProfileJWTSubsystemSchema> {
VERSION_1_0(1),
;
static final MicroProfileJWTSubsystemSchema CURRENT = VERSION_1_0;
private final VersionedNamespace<IntVersion, MicroProfileJWTSubsystemSchema> namespace;
MicroProfileJWTSubsystemSchema(int major) {
this.namespace = SubsystemSchema.createSubsystemURN(MicroProfileJWTExtension.SUBSYSTEM_NAME, new IntVersion(major));
}
@Override
public VersionedNamespace<IntVersion, MicroProfileJWTSubsystemSchema> getNamespace() {
return this.namespace;
}
@Override
public PersistentResourceXMLDescription getXMLDescription() {
return builder(MicroProfileJWTExtension.SUBSYSTEM_PATH, this.namespace).build();
}
}
| 2,352 | 38.881356 | 124 |
java
|
null |
wildfly-main/microprofile/jwt-smallrye/src/main/java/org/wildfly/extension/microprofile/jwt/smallrye/JwtActivationProcessor.java
|
/*
* Copyright 2019 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.extension.microprofile.jwt.smallrye;
import static org.wildfly.extension.microprofile.jwt.smallrye._private.MicroProfileJWTLogger.ROOT_LOGGER;
import java.util.List;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.annotation.CompositeIndex;
import org.jboss.as.server.security.VirtualDomainMarkerUtility;
import org.jboss.as.web.common.WarMetaData;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.AnnotationTarget.Kind;
import org.jboss.jandex.AnnotationValue;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.metadata.web.jboss.JBossWebMetaData;
import org.jboss.metadata.web.spec.LoginConfigMetaData;
/**
* A {@link DeploymentUnitProcessor} to detect if MicroProfile JWT should be activated.
*
* @author <a href="mailto:[email protected]">Darran Lofthouse</a>
*/
class JwtActivationProcessor implements DeploymentUnitProcessor {
private static final String AUTH_METHOD = "authMethod";
private static final String REALM_NAME = "realmName";
private static final String JWT_AUTH_METHOD = "MP-JWT";
private static final DotName APPLICATION_DOT_NAME = DotName.createSimple("jakarta.ws.rs.core.Application");
private static final DotName LOGIN_CONFIG_DOT_NAME = DotName.createSimple("org.eclipse.microprofile.auth.LoginConfig");
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
if (warMetaData == null) {
return;
}
JBossWebMetaData mergedMetaData = warMetaData.getMergedJBossWebMetaData();
LoginConfigMetaData loginConfig = mergedMetaData != null ? mergedMetaData.getLoginConfig() : null;
if (loginConfig != null && !JWT_AUTH_METHOD.equals(loginConfig.getAuthMethod())) {
// An auth-method has been defined, this is not MP-JWT
return;
}
if (loginConfig == null) {
final CompositeIndex index = deploymentUnit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
List<AnnotationInstance> annotations = index.getAnnotations(LOGIN_CONFIG_DOT_NAME);
for (AnnotationInstance annotation : annotations) {
// First we must be sure the annotation is on an Application class.
AnnotationTarget target = annotation.target();
if (target.kind() == Kind.CLASS
&& extendsApplication(target.asClass(), index)) {
loginConfig = new LoginConfigMetaData();
AnnotationValue authMethodValue = annotation.value(AUTH_METHOD);
if (authMethodValue == null) {
throw ROOT_LOGGER.noAuthMethodSpecified();
}
loginConfig.setAuthMethod(authMethodValue.asString());
AnnotationValue realmNameValue = annotation.value(REALM_NAME);
if (realmNameValue != null) {
loginConfig.setRealmName(realmNameValue.asString());
}
mergedMetaData.setLoginConfig(loginConfig);
break;
}
ROOT_LOGGER.loginConfigInvalidTarget(target.toString());
}
}
if (loginConfig != null && JWT_AUTH_METHOD.equals(loginConfig.getAuthMethod())) {
ROOT_LOGGER.tracef("Activating JWT for deployment %s.", deploymentUnit.getName());
JwtDeploymentMarker.mark(deploymentUnit);
VirtualDomainMarkerUtility.virtualDomainRequired(deploymentUnit);
}
}
private boolean extendsApplication(ClassInfo classInfo, CompositeIndex index) {
if (classInfo == null) {
return false;
}
DotName superType = classInfo.superName();
if (superType == null) {
return false;
} else if (APPLICATION_DOT_NAME.equals(superType)) {
return true;
}
return extendsApplication(index.getClassByName(superType), index);
}
}
| 5,159 | 41.295082 | 123 |
java
|
null |
wildfly-main/microprofile/jwt-smallrye/src/main/java/org/wildfly/extension/microprofile/jwt/smallrye/JwtDeploymentMarker.java
|
/*
* Copyright 2019 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.extension.microprofile.jwt.smallrye;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.server.deployment.DeploymentUnit;
/**
* Utility class for marking a deployment as a JWT deployment.
*
* @author <a href="mailto:[email protected]">Darran Lofthouse</a>
*/
class JwtDeploymentMarker {
private static final AttachmentKey<Boolean> ATTACHMENT_KEY = AttachmentKey.create(Boolean.class);
public static void mark(DeploymentUnit deployment) {
toRoot(deployment).putAttachment(ATTACHMENT_KEY, true);
}
public static boolean isJWTDeployment(DeploymentUnit deployment) {
Boolean val = toRoot(deployment).getAttachment(ATTACHMENT_KEY);
return val != null && val;
}
private static DeploymentUnit toRoot(final DeploymentUnit deployment) {
DeploymentUnit result = deployment;
DeploymentUnit parent = result.getParent();
while (parent != null) {
result = parent;
parent = result.getParent();
}
return result;
}
}
| 1,675 | 31.230769 | 101 |
java
|
null |
wildfly-main/microprofile/jwt-smallrye/src/main/java/org/wildfly/extension/microprofile/jwt/smallrye/_private/MicroProfileJWTLogger.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.extension.microprofile.jwt.smallrye._private;
import static org.jboss.logging.Logger.Level.INFO;
import static org.jboss.logging.Logger.Level.WARN;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
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;
/**
*
* <a href="mailto:[email protected]">Darran Lofthouse</a>
*/
@MessageLogger(projectCode = "WFLYJWT", length = 4)
public interface MicroProfileJWTLogger extends BasicLogger {
/**
* The root logger with a category of the package name.
*/
MicroProfileJWTLogger ROOT_LOGGER = Logger.getMessageLogger(MicroProfileJWTLogger.class, "org.wildfly.extension.microprofile.jwt.smallrye");
/**
* Logs an informational message indicating the naming subsystem is being activated.
*/
@LogMessage(level = INFO)
@Message(id = 1, value = "Activating MicroProfile JWT Subsystem")
void activatingSubsystem();
@LogMessage(level = WARN)
@Message(id = 2, value = "@LoginConfig annotation detected on invalid target \"%s\".")
void loginConfigInvalidTarget(String target);
@Message(id = 3, value = "No `authMethod` specified on the @LoginConfig annotation.")
DeploymentUnitProcessingException noAuthMethodSpecified();
}
| 2,150 | 36.736842 | 144 |
java
|
null |
wildfly-main/microprofile/metrics-smallrye/src/test/java/org/wildfly/extension/microprofile/metrics/Subsystem_2_0_ParsingTestCase.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.microprofile.metrics;
import java.io.IOException;
import java.util.Properties;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc.
*/
public class Subsystem_2_0_ParsingTestCase extends AbstractSubsystemBaseTest {
public Subsystem_2_0_ParsingTestCase() {
super(MicroProfileMetricsExtension.SUBSYSTEM_NAME, new MicroProfileMetricsExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource("subsystem_2_0.xml");
}
@Override
protected String getSubsystemXsdPath() throws IOException {
return "schema/wildfly-microprofile-metrics-smallrye_2_0.xsd";
}
@Override
protected Properties getResolvedProperties() {
return System.getProperties();
}
@Override
protected AdditionalInitialization createAdditionalInitialization() {
return AdditionalInitialization.ADMIN_ONLY_HC;
}
}
| 2,125 | 33.290323 | 95 |
java
|
null |
wildfly-main/microprofile/metrics-smallrye/src/test/java/org/wildfly/extension/microprofile/metrics/Subsystem_1_0_ParsingTestCase.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.microprofile.metrics;
import java.io.IOException;
import java.util.Properties;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.jboss.as.subsystem.test.KernelServices;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc.
*/
public class Subsystem_1_0_ParsingTestCase extends AbstractSubsystemBaseTest {
public Subsystem_1_0_ParsingTestCase() {
super(MicroProfileMetricsExtension.SUBSYSTEM_NAME, new MicroProfileMetricsExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource("subsystem_1_0.xml");
}
@Override
protected String getSubsystemXsdPath() throws IOException {
return "schema/wildfly-microprofile-metrics-smallrye_1_0.xsd";
}
protected Properties getResolvedProperties() {
return System.getProperties();
}
@Override
protected KernelServices standardSubsystemTest(String configId, boolean compareXml) throws Exception {
return super.standardSubsystemTest(configId, false);
}
@Override
protected AdditionalInitialization createAdditionalInitialization() {
return AdditionalInitialization.ADMIN_ONLY_HC;
}
}
| 2,350 | 34.621212 | 106 |
java
|
null |
wildfly-main/microprofile/metrics-smallrye/src/main/java/org/wildfly/extension/microprofile/metrics/MicroProfileMetricsExtension.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.microprofile.metrics;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import java.util.Collections;
import java.util.Set;
import org.jboss.as.controller.ExtensionContext;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.PersistentResourceXMLParser;
import org.jboss.as.controller.SubsystemRegistration;
import org.jboss.as.controller.descriptions.ResourceDescriptionResolver;
import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver;
import org.jboss.as.controller.extension.AbstractLegacyExtension;
import org.jboss.as.controller.parsing.ExtensionParsingContext;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc.
*/
public class MicroProfileMetricsExtension extends AbstractLegacyExtension {
static final String EXTENSION_NAME = "org.wildfly.extension.microprofile.metrics.smallrye";
/**
* The name of our subsystem within the model.
*/
public static final String SUBSYSTEM_NAME = "microprofile-metrics-smallrye";
protected static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME);
private static final String RESOURCE_NAME = MicroProfileMetricsExtension.class.getPackage().getName() + ".LocalDescriptions";
protected static final ModelVersion VERSION_1_0_0 = ModelVersion.create(1, 0, 0);
protected static final ModelVersion VERSION_2_0_0 = ModelVersion.create(2, 0, 0);
private static final ModelVersion CURRENT_MODEL_VERSION = VERSION_2_0_0;
private static final PersistentResourceXMLParser CURRENT_PARSER = new MicroProfileMetricsParser_2_0();
static ResourceDescriptionResolver getResourceDescriptionResolver(final String... keyPrefix) {
return getResourceDescriptionResolver(true, keyPrefix);
}
static ResourceDescriptionResolver getResourceDescriptionResolver(final boolean useUnprefixedChildTypes, final String... keyPrefix) {
StringBuilder prefix = new StringBuilder();
for (String kp : keyPrefix) {
if (prefix.length() > 0) {
prefix.append('.');
}
prefix.append(kp);
}
return new StandardResourceDescriptionResolver(prefix.toString(), RESOURCE_NAME, MicroProfileMetricsExtension.class.getClassLoader(), true, useUnprefixedChildTypes);
}
public MicroProfileMetricsExtension() {
super(EXTENSION_NAME, SUBSYSTEM_NAME);
}
@Override
protected Set<ManagementResourceRegistration> initializeLegacyModel(final ExtensionContext context) {
final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION);
subsystem.registerXMLElementWriter(CURRENT_PARSER);
final ManagementResourceRegistration registration = subsystem.registerSubsystemModel(new MicroProfileMetricsSubsystemDefinition());
return Collections.singleton(registration);
}
@Override
public void initializeLegacyParsers(ExtensionParsingContext context) {
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, MicroProfileMetricsParser_1_0.NAMESPACE, MicroProfileMetricsParser_1_0::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, MicroProfileMetricsParser_2_0.NAMESPACE, CURRENT_PARSER);
}
}
| 4,482 | 44.282828 | 173 |
java
|
null |
wildfly-main/microprofile/metrics-smallrye/src/main/java/org/wildfly/extension/microprofile/metrics/MicroProfileMetricsParser_2_0.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.microprofile.metrics;
import static org.jboss.as.controller.PersistentResourceXMLDescription.builder;
import org.jboss.as.controller.PersistentResourceXMLDescription;
import org.jboss.as.controller.PersistentResourceXMLParser;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc.
*/
public class MicroProfileMetricsParser_2_0 extends PersistentResourceXMLParser {
/**
* The name space used for the {@code subsystem} element
*/
public static final String NAMESPACE = "urn:wildfly:microprofile-metrics-smallrye:2.0";
private static final PersistentResourceXMLDescription xmlDescription;
static {
xmlDescription = builder(MicroProfileMetricsExtension.SUBSYSTEM_PATH, NAMESPACE)
.addAttributes(
MicroProfileMetricsSubsystemDefinition.SECURITY_ENABLED,
MicroProfileMetricsSubsystemDefinition.EXPOSED_SUBSYSTEMS,
MicroProfileMetricsSubsystemDefinition.PREFIX)
.build();
}
@Override
public PersistentResourceXMLDescription getParserDescription() {
return xmlDescription;
}
}
| 2,221 | 39.4 | 91 |
java
|
null |
wildfly-main/microprofile/metrics-smallrye/src/main/java/org/wildfly/extension/microprofile/metrics/MigrateOperation.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.microprofile.metrics;
import static org.jboss.as.controller.OperationContext.Stage.MODEL;
import static org.jboss.as.controller.PathAddress.pathAddress;
import static org.jboss.as.controller.PathElement.pathElement;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXTENSION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.wildfly.extension.microprofile.metrics.MicroProfileMetricsExtension.EXTENSION_NAME;
import static org.wildfly.extension.microprofile.metrics.MicroProfileMetricsExtension.SUBSYSTEM_NAME;
import static org.wildfly.extension.microprofile.metrics._private.MicroProfileMetricsLogger.ROOT_LOGGER;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.RunningMode;
import org.jboss.as.controller.SimpleMapAttributeDefinition;
import org.jboss.as.controller.SimpleOperationDefinitionBuilder;
import org.jboss.as.controller.StringListAttributeDefinition;
import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition;
import org.jboss.as.controller.descriptions.ResourceDescriptionResolver;
import org.jboss.as.controller.operations.MultistepUtil;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
public class MigrateOperation implements OperationStepHandler {
private static final PathAddress MP_METRICS_EXTENSION_ELEMENT = pathAddress(pathElement(EXTENSION, EXTENSION_NAME));
private static final PathAddress MP_METRICS_SUBSYSTEM_ELEMENT = pathAddress(pathElement(SUBSYSTEM, SUBSYSTEM_NAME));
private static final String MIGRATE = "migrate";
private static final String MIGRATION_WARNINGS = "migration-warnings";
private static final String MIGRATION_ERROR = "migration-error";
private static final String MIGRATION_OPERATIONS = "migration-operations";
private static final String DESCRIBE_MIGRATION = "describe-migration";
static final StringListAttributeDefinition MIGRATION_WARNINGS_ATTR =
new StringListAttributeDefinition.Builder(MIGRATION_WARNINGS)
.setRequired(false)
.build();
static final SimpleMapAttributeDefinition MIGRATION_ERROR_ATTR =
new SimpleMapAttributeDefinition.Builder(MIGRATION_ERROR, ModelType.OBJECT, true)
.setValueType(ModelType.OBJECT)
.setRequired(false)
.build();
private final boolean describe;
private MigrateOperation(boolean describe) {
this.describe = describe;
}
static void registerOperations(ManagementResourceRegistration registry, ResourceDescriptionResolver resourceDescriptionResolver) {
registry.registerOperationHandler(new SimpleOperationDefinitionBuilder(MIGRATE, resourceDescriptionResolver)
.setReplyParameters(MIGRATION_WARNINGS_ATTR, MIGRATION_ERROR_ATTR)
.setAccessConstraints(SensitiveTargetAccessConstraintDefinition.READ_WHOLE_CONFIG)
.build(),
new MigrateOperation(false));
registry.registerOperationHandler(new SimpleOperationDefinitionBuilder(DESCRIBE_MIGRATION, resourceDescriptionResolver)
.setReplyParameters(MIGRATION_WARNINGS_ATTR, MIGRATION_ERROR_ATTR)
.setAccessConstraints(SensitiveTargetAccessConstraintDefinition.READ_WHOLE_CONFIG)
.setReadOnly()
.build(),
new MigrateOperation(true));
}
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
if (!describe && context.getRunningMode() != RunningMode.ADMIN_ONLY) {
throw ROOT_LOGGER.migrateOperationAllowedOnlyInAdminOnly();
}
final PathAddress subsystemsAddress = context.getCurrentAddress().getParent();
final Map<PathAddress, ModelNode> migrateOperations = new LinkedHashMap<>();
context.addStep((operationContext, modelNode) -> {
removeMicroProfileMetrics(subsystemsAddress.append(MP_METRICS_SUBSYSTEM_ELEMENT), migrateOperations);
if (describe) {
// :describe-migration operation
// for describe-migration operation, do nothing and return the list of operations that would
// be executed in the composite operation
final Collection<ModelNode> values = migrateOperations.values();
ModelNode result = new ModelNode();
result.get(MIGRATION_OPERATIONS).set(values);
result.get(MIGRATION_WARNINGS).set(new ModelNode().setEmptyList());
context.getResult().set(result);
} else {
// :migrate operation
// invoke an OSH on a composite operation with all the migration operations
final Map<PathAddress, ModelNode> migrateOpResponses = migrateSubsystems(context, migrateOperations);
context.completeStep((resultAction, context1, operation1) -> {
final ModelNode result = new ModelNode();
result.get(MIGRATION_WARNINGS).set(new ModelNode().setEmptyList());
if (resultAction == OperationContext.ResultAction.ROLLBACK) {
for (Map.Entry<PathAddress, ModelNode> entry : migrateOpResponses.entrySet()) {
if (entry.getValue().hasDefined(FAILURE_DESCRIPTION)) {
ModelNode desc = new ModelNode();
desc.get(OP).set(migrateOperations.get(entry.getKey()));
desc.get(RESULT).set(entry.getValue());
result.get(MIGRATION_ERROR).set(desc);
break;
}
}
context1.getFailureDescription().set(new ModelNode(ROOT_LOGGER.migrationFailed()));
}
context1.getResult().set(result);
});
}
}, MODEL);
}
private void removeMicroProfileMetrics(final PathAddress address,
final Map<PathAddress, ModelNode> migrateOperations) {
migrateOperations.put(address, Util.createRemoveOperation(address));
migrateOperations.put(MP_METRICS_EXTENSION_ELEMENT, Util.createRemoveOperation(MP_METRICS_EXTENSION_ELEMENT));
}
private Map<PathAddress, ModelNode> migrateSubsystems(OperationContext context,
final Map<PathAddress,
ModelNode> migrationOperations) throws OperationFailedException {
final Map<PathAddress, ModelNode> result = new LinkedHashMap<>();
MultistepUtil.recordOperationSteps(context, migrationOperations, result);
return result;
}
}
| 8,690 | 52.319018 | 134 |
java
|
null |
wildfly-main/microprofile/metrics-smallrye/src/main/java/org/wildfly/extension/microprofile/metrics/MicroProfileMetricsSubsystemDefinition.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.microprofile.metrics;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.ModelOnlyAddStepHandler;
import org.jboss.as.controller.ModelOnlyResourceDefinition;
import org.jboss.as.controller.ReloadRequiredRemoveStepHandler;
import org.jboss.as.controller.ReloadRequiredWriteAttributeHandler;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.StringListAttributeDefinition;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.wildfly.extension.metrics.MetricsSubsystemDefinition;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc.
*/
public class MicroProfileMetricsSubsystemDefinition extends ModelOnlyResourceDefinition {
static final String MP_CONFIG = "org.wildfly.microprofile.config";
static final String METRICS_HTTP_CONTEXT_CAPABILITY = "org.wildfly.extension.metrics.http-context";
static final RuntimeCapability<Void> MICROPROFILE_METRICS_HTTP_SECURITY_CAPABILITY =
RuntimeCapability.Builder.of(MetricsSubsystemDefinition.METRICS_HTTP_SECURITY_CAPABILITY, Boolean.class)
.build();
static final RuntimeCapability<Void> MICROPROFILE_METRICS_SCAN =
RuntimeCapability.Builder.of(MetricsSubsystemDefinition.METRICS_SCAN_CAPABILITY)
.addRequirements(METRICS_HTTP_CONTEXT_CAPABILITY, MP_CONFIG)
.build();
static final AttributeDefinition SECURITY_ENABLED = SimpleAttributeDefinitionBuilder.create("security-enabled", ModelType.BOOLEAN)
.setDefaultValue(ModelNode.TRUE)
.setRequired(false)
.setRestartAllServices()
.setAllowExpression(true)
.build();
static final StringListAttributeDefinition EXPOSED_SUBSYSTEMS = new StringListAttributeDefinition.Builder("exposed-subsystems")
.setRequired(false)
.setRestartAllServices()
.build();
static final AttributeDefinition PREFIX = SimpleAttributeDefinitionBuilder.create("prefix", ModelType.STRING)
.setRequired(false)
.setRestartAllServices()
.setAllowExpression(true)
.build();
static final AttributeDefinition[] ATTRIBUTES = {SECURITY_ENABLED, EXPOSED_SUBSYSTEMS, PREFIX};
protected MicroProfileMetricsSubsystemDefinition() {
super(new SimpleResourceDefinition.Parameters(MicroProfileMetricsExtension.SUBSYSTEM_PATH,
MicroProfileMetricsExtension.getResourceDescriptionResolver(MicroProfileMetricsExtension.SUBSYSTEM_NAME))
.setAddHandler(new ModelOnlyAddStepHandler(ATTRIBUTES))
.setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE)
.setCapabilities(MICROPROFILE_METRICS_HTTP_SECURITY_CAPABILITY, MICROPROFILE_METRICS_SCAN));
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
for (AttributeDefinition att : ATTRIBUTES) {
resourceRegistration.registerReadWriteAttribute(att, null,
new ReloadRequiredWriteAttributeHandler(ATTRIBUTES));
}
}
@Override
public void registerOperations(ManagementResourceRegistration resourceRegistration) {
super.registerOperations(resourceRegistration);
MigrateOperation.registerOperations(resourceRegistration, getResourceDescriptionResolver());
}
}
| 4,697 | 47.43299 | 134 |
java
|
null |
wildfly-main/microprofile/metrics-smallrye/src/main/java/org/wildfly/extension/microprofile/metrics/MicroProfileMetricsParser_1_0.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.microprofile.metrics;
import static org.jboss.as.controller.PersistentResourceXMLDescription.builder;
import org.jboss.as.controller.PersistentResourceXMLDescription;
import org.jboss.as.controller.PersistentResourceXMLParser;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc.
*/
public class MicroProfileMetricsParser_1_0 extends PersistentResourceXMLParser {
/**
* The name space used for the {@code subsystem} element
*/
public static final String NAMESPACE = "urn:wildfly:microprofile-metrics-smallrye:1.0";
private static final PersistentResourceXMLDescription xmlDescription;
static {
xmlDescription = builder(MicroProfileMetricsExtension.SUBSYSTEM_PATH, NAMESPACE)
.addAttribute(MicroProfileMetricsSubsystemDefinition.SECURITY_ENABLED)
.addAttribute(MicroProfileMetricsSubsystemDefinition.EXPOSED_SUBSYSTEMS)
.build();
}
@Override
public PersistentResourceXMLDescription getParserDescription() {
return xmlDescription;
}
}
| 2,130 | 39.207547 | 91 |
java
|
null |
wildfly-main/microprofile/metrics-smallrye/src/main/java/org/wildfly/extension/microprofile/metrics/_private/MicroProfileMetricsLogger.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.microprofile.metrics._private;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
/**
* Log messages for WildFly microprofile-metrics-smallrye Extension.
*
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc.
*/
@MessageLogger(projectCode = "WFLYMPMETRICS", length = 4)
public interface MicroProfileMetricsLogger extends BasicLogger {
/**
* A logger with the category {@code org.wildfly.extension.batch}.
*/
MicroProfileMetricsLogger ROOT_LOGGER = Logger.getMessageLogger(MicroProfileMetricsLogger.class,
"org.wildfly.extension.microprofile.metrics.smallrye");
// no longer used
// @LogMessage(level = INFO)
// @Message(id = 1, value = "Activating MicroProfile Metrics Subsystem")
// void activatingSubsystem();
// no longer used
// @Message(id = 2, value = "Failed to initialize metrics from JMX MBeans")
// IllegalArgumentException failedInitializeJMXRegistrar(@Cause IOException e);
// no longer used
// @Message(id = 3, value = "Unable to read attribute %s on %s: %s.")
// IllegalStateException unableToReadAttribute(String attributeName, PathAddress address, String error);
// no longer used
// @Message(id = 4, value = "Unable to convert attribute %s on %s to Double value.")
// IllegalStateException unableToConvertAttribute(String attributeName, PathAddress address, @Cause Exception exception);
// no longer used
// @Message(id = 5, value = "Metric attribute %s on %s is undefined and will not be exposed.")
// IllegalStateException undefinedMetric(String attributeName, PathAddress address);
// no longer used
// @Message(id = 6, value = "The metric was unavailable")
// IllegalStateException metricUnavailable();
//7, 8 and 9 are taken downstream
/*
@Message(id = 7, value = "")
OperationFailedException seeDownstream();
@Message(id = 8, value = "")
String seeDownstream();
@Message(id = 9, value = "")
OperationFailedException seeDownstream();
*/
@Message(id = 10, value = "The migrate operation cannot be performed. The server must be in admin-only mode.")
OperationFailedException migrateOperationAllowedOnlyInAdminOnly();
@Message(id = 11, value = "Migration failed. See results for more details.")
String migrationFailed();
}
| 3,572 | 39.602273 | 125 |
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.