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/microprofile/fault-tolerance-smallrye/extension/src/test/java/org/wildfly/extension/microprofile/faulttolerance/MicroProfileFaultToleranceModelTest.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.microprofile.faulttolerance; import static org.junit.runners.Parameterized.Parameters; import java.util.EnumSet; import org.jboss.as.subsystem.test.AbstractSubsystemSchemaTest; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; /** * @author Radoslav Husar */ @RunWith(value = Parameterized.class) public class MicroProfileFaultToleranceModelTest extends AbstractSubsystemSchemaTest<MicroProfileFaultToleranceSchema> { @Parameters public static Iterable<MicroProfileFaultToleranceSchema> parameters() { return EnumSet.allOf(MicroProfileFaultToleranceSchema.class); } public MicroProfileFaultToleranceModelTest(MicroProfileFaultToleranceSchema testSchema) { super(MicroProfileFaultToleranceExtension.SUBSYSTEM_NAME, new MicroProfileFaultToleranceExtension(), testSchema, MicroProfileFaultToleranceSchema.CURRENT); } @Override protected String getSubsystemXmlPathPattern() { // Exclude subsystem name from pattern return "subsystem_%2$d_%3$d.xml"; } }
2,098
38.603774
163
java
null
wildfly-main/microprofile/fault-tolerance-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/faulttolerance/MicroProfileFaultToleranceModel.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.microprofile.faulttolerance; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.SubsystemModel; /** * Enumeration of supported versions of management model. * * @author Radoslav Husar */ public enum MicroProfileFaultToleranceModel implements SubsystemModel { VERSION_1_0_0(1, 0, 0), // WildFly 19-present ; static final MicroProfileFaultToleranceModel CURRENT = VERSION_1_0_0; private final ModelVersion version; MicroProfileFaultToleranceModel(int major, int minor, int micro) { this.version = ModelVersion.create(major, minor, micro); } @Override public ModelVersion getVersion() { return this.version; } }
1,749
34.714286
73
java
null
wildfly-main/microprofile/fault-tolerance-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/faulttolerance/MicroProfileFaultToleranceSchema.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.microprofile.faulttolerance; 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; /** * Enumeration of supported subsystem schemas. * * @author Radoslav Husar */ public enum MicroProfileFaultToleranceSchema implements PersistentSubsystemSchema<MicroProfileFaultToleranceSchema> { VERSION_1_0(1, 0), // WildFly 19-present ; public static final MicroProfileFaultToleranceSchema CURRENT = VERSION_1_0; private final VersionedNamespace<IntVersion, MicroProfileFaultToleranceSchema> namespace; MicroProfileFaultToleranceSchema(int major, int minor) { this.namespace = SubsystemSchema.createSubsystemURN(MicroProfileFaultToleranceExtension.SUBSYSTEM_NAME, new IntVersion(major, minor)); } @Override public VersionedNamespace<IntVersion, MicroProfileFaultToleranceSchema> getNamespace() { return this.namespace; } @Override public PersistentResourceXMLDescription getXMLDescription() { return builder(MicroProfileFaultToleranceResourceDefinition.PATH, this.namespace).build(); } }
2,404
39.762712
142
java
null
wildfly-main/microprofile/fault-tolerance-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/faulttolerance/MicroProfileFaultToleranceServiceHandler.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.microprofile.faulttolerance; import static org.wildfly.extension.microprofile.faulttolerance.MicroProfileFaultToleranceLogger.ROOT_LOGGER; import java.util.function.Consumer; import org.jboss.as.clustering.controller.ResourceServiceHandler; import org.jboss.as.controller.OperationContext; import org.jboss.as.server.DeploymentProcessorTarget; import org.jboss.as.server.deployment.Phase; import org.jboss.dmr.ModelNode; import org.wildfly.extension.microprofile.faulttolerance.deployment.MicroProfileFaultToleranceDependenciesProcessor; import org.wildfly.extension.microprofile.faulttolerance.deployment.MicroProfileFaultToleranceDeploymentProcessor; /** * @author Radoslav Husar */ public class MicroProfileFaultToleranceServiceHandler implements ResourceServiceHandler, Consumer<DeploymentProcessorTarget> { @Override public void installServices(OperationContext context, ModelNode model) { ROOT_LOGGER.activatingSubsystem(); } @Override public void removeServices(OperationContext context, ModelNode model) { } @Override public void accept(DeploymentProcessorTarget deploymentProcessorTarget) { deploymentProcessorTarget.addDeploymentProcessor(MicroProfileFaultToleranceExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_MICROPROFILE_FAULT_TOLERANCE, new MicroProfileFaultToleranceDependenciesProcessor()); deploymentProcessorTarget.addDeploymentProcessor(MicroProfileFaultToleranceExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_MICROPROFILE_FAULT_TOLERANCE, new MicroProfileFaultToleranceDeploymentProcessor()); } }
2,676
45.155172
233
java
null
wildfly-main/microprofile/fault-tolerance-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/faulttolerance/MicroProfileFaultToleranceExtension.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.microprofile.faulttolerance; import org.jboss.as.clustering.controller.PersistentSubsystemExtension; import org.jboss.as.controller.descriptions.ParentResourceDescriptionResolver; import org.jboss.as.controller.descriptions.SubsystemResourceDescriptionResolver; /** * Extension that registers the microprofile fault tolerance subsystem * @author Radoslav Husar */ public class MicroProfileFaultToleranceExtension extends PersistentSubsystemExtension<MicroProfileFaultToleranceSchema> { static final String SUBSYSTEM_NAME = "microprofile-fault-tolerance-smallrye"; static final ParentResourceDescriptionResolver SUBSYSTEM_RESOLVER = new SubsystemResourceDescriptionResolver(SUBSYSTEM_NAME, MicroProfileFaultToleranceExtension.class); public MicroProfileFaultToleranceExtension() { super(SUBSYSTEM_NAME, MicroProfileFaultToleranceModel.CURRENT, MicroProfileFaultToleranceResourceDefinition::new, MicroProfileFaultToleranceSchema.CURRENT); } }
2,026
47.261905
172
java
null
wildfly-main/microprofile/fault-tolerance-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/faulttolerance/MicroProfileFaultToleranceResourceDefinition.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.microprofile.faulttolerance; import org.jboss.as.clustering.controller.DeploymentChainContributingResourceRegistrar; import org.jboss.as.clustering.controller.ManagementResourceRegistration; import org.jboss.as.clustering.controller.ResourceDescriptor; import org.jboss.as.clustering.controller.SubsystemRegistration; import org.jboss.as.clustering.controller.SubsystemResourceDefinition; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler; /** * @author Radoslav Husar */ public class MicroProfileFaultToleranceResourceDefinition extends SubsystemResourceDefinition { static final PathElement PATH = pathElement(MicroProfileFaultToleranceExtension.SUBSYSTEM_NAME); enum Capability implements org.jboss.as.clustering.controller.Capability { MICROPROFILE_FAULT_TOLERANCE("org.wildfly.microprofile.fault-tolerance"), ; private final RuntimeCapability<Void> definition; Capability(String name) { this.definition = RuntimeCapability.Builder.of(name) .addRequirements("org.wildfly.microprofile.config") .build(); } @Override public RuntimeCapability<?> getDefinition() { return this.definition; } } protected MicroProfileFaultToleranceResourceDefinition() { super(PATH, MicroProfileFaultToleranceExtension.SUBSYSTEM_RESOLVER); } @Override public void register(SubsystemRegistration parentRegistration) { ManagementResourceRegistration registration = parentRegistration.registerSubsystemModel(this); registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE); ResourceDescriptor descriptor = new ResourceDescriptor(this.getResourceDescriptionResolver()) .addCapabilities(Capability.class) ; MicroProfileFaultToleranceServiceHandler handler = new MicroProfileFaultToleranceServiceHandler(); new DeploymentChainContributingResourceRegistrar(descriptor, handler, handler).register(registration); } }
3,297
42.973333
132
java
null
wildfly-main/microprofile/fault-tolerance-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/faulttolerance/MicroProfileFaultToleranceLogger.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.microprofile.faulttolerance; import static org.jboss.logging.Logger.Level.INFO; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * @author Radoslav Husar */ @MessageLogger(projectCode = "WFLYMPFTEXT", length = 4) public interface MicroProfileFaultToleranceLogger extends BasicLogger { MicroProfileFaultToleranceLogger ROOT_LOGGER = Logger.getMessageLogger(MicroProfileFaultToleranceLogger.class, MicroProfileFaultToleranceLogger.class.getPackage().getName()); @LogMessage(level = INFO) @Message(id = 1, value = "Activating MicroProfile Fault Tolerance subsystem.") void activatingSubsystem(); @LogMessage(level = INFO) @Message(id = 2, value = "MicroProfile Fault Tolerance subsystem with use '%s' metrics provider.") void metricsProvider(String metricsProvider); }
2,030
39.62
178
java
null
wildfly-main/microprofile/fault-tolerance-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/faulttolerance/deployment/MicroProfileFaultToleranceDeploymentProcessor.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.microprofile.faulttolerance.deployment; import static org.wildfly.extension.microprofile.faulttolerance.MicroProfileFaultToleranceLogger.ROOT_LOGGER; import java.util.Set; import io.smallrye.faulttolerance.FaultToleranceExtension; import io.smallrye.faulttolerance.metrics.MetricsIntegration; 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.weld.Capabilities; import org.jboss.as.weld.WeldCapability; /** * This {@link DeploymentUnitProcessor} registers required CDI portable extension that adds support * for MP Fault Tolerance interceptor bindings. Moreover, it specifies which metrics provider to use according to * metrics integrations available at runtime (MP Metrics, Micrometer, or no metrics). * * @author Radoslav Husar */ public class MicroProfileFaultToleranceDeploymentProcessor implements DeploymentUnitProcessor { @Override public void deploy(DeploymentPhaseContext phaseContext) { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (!MicroProfileFaultToleranceMarker.isMarked(deploymentUnit)) { return; } // Weld Extension CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT); WeldCapability weldCapability; try { weldCapability = support.getCapabilityRuntimeAPI(Capabilities.WELD_CAPABILITY_NAME, WeldCapability.class); } catch (CapabilityServiceSupport.NoSuchCapabilityException e) { throw new IllegalStateException(); } // Configure which metrics provider to use Set<String> registeredSubsystems = deploymentUnit.getAttachment(Attachments.REGISTERED_SUBSYSTEMS); MetricsIntegration metricsIntegration = registeredSubsystems.contains("micrometer") ? MetricsIntegration.MICROMETER : MetricsIntegration.NOOP; ROOT_LOGGER.metricsProvider(metricsIntegration.name()); weldCapability.registerExtensionInstance(new FaultToleranceExtension(metricsIntegration), deploymentUnit); } }
3,361
43.826667
150
java
null
wildfly-main/microprofile/fault-tolerance-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/faulttolerance/deployment/MicroProfileFaultToleranceDependenciesProcessor.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.microprofile.faulttolerance.deployment; import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME; import java.util.Optional; 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; /** * Conditionally adds "org.eclipse.microprofile.fault-tolerance.api" dependency if this deployment is part of Weld deployment. * * @author Radoslav Husar */ public class MicroProfileFaultToleranceDependenciesProcessor implements DeploymentUnitProcessor { @Override public void deploy(DeploymentPhaseContext phaseContext) { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT); Optional<WeldCapability> weldCapability = support.getOptionalCapabilityRuntimeAPI(WELD_CAPABILITY_NAME, WeldCapability.class); if (weldCapability.isPresent() && weldCapability.get().isPartOfWeldDeployment(deploymentUnit) && MicroProfileFaultToleranceMarker.hasMicroProfileFaultToleranceAnnotations(deploymentUnit)) { MicroProfileFaultToleranceMarker.mark(deploymentUnit); ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); ModuleLoader moduleLoader = Module.getBootModuleLoader(); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, "org.eclipse.microprofile.fault-tolerance.api", false, false, false, false)); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, "org.wildfly.microprofile.fault-tolerance-smallrye.deployment", false, false, true, false)); } } @Override public void undeploy(DeploymentUnit deploymentUnit) { MicroProfileFaultToleranceMarker.clearMark(deploymentUnit); } }
3,358
48.397059
197
java
null
wildfly-main/microprofile/fault-tolerance-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/faulttolerance/deployment/MicroProfileFaultToleranceAnnotation.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.microprofile.faulttolerance.deployment; import org.jboss.jandex.DotName; /** * Class that stores the {@link DotName}s of MP FT annotations. * * @author Radoslav Husar */ public enum MicroProfileFaultToleranceAnnotation { /** * @see org.eclipse.microprofile.faulttolerance.Retry */ RETRY("Retry"), /** * @see org.eclipse.microprofile.faulttolerance.Timeout */ TIMEOUT("Timeout"), /** * @see org.eclipse.microprofile.faulttolerance.Fallback */ FALLBACK("Fallback"), /** * @see org.eclipse.microprofile.faulttolerance.CircuitBreaker */ CIRCUIT_BREAKER("CircuitBreaker"), /** * @see org.eclipse.microprofile.faulttolerance.Bulkhead */ BULKHEAD("Bulkhead"), /** * @see org.eclipse.microprofile.faulttolerance.Asynchronous */ ASYNCHRONOUS("Asynchronous"), ; private final DotName dotName; MicroProfileFaultToleranceAnnotation(String simpleName) { this.dotName = DotName.createComponentized(FaultToleranceDotName.ORG_ECLIPSE_MICROPROFILE_FAULTTOLERANCE, simpleName); } private interface FaultToleranceDotName { DotName ORG_ECLIPSE_MICROPROFILE_FAULTTOLERANCE = DotName.createComponentized(DotName.createComponentized(DotName.createComponentized(DotName.createComponentized(null, "org"), "eclipse"), "microprofile"), "faulttolerance"); } public DotName getDotName() { return dotName; } }
2,510
32.48
231
java
null
wildfly-main/microprofile/fault-tolerance-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/faulttolerance/deployment/MicroProfileFaultToleranceMarker.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.microprofile.faulttolerance.deployment; import org.jboss.as.server.deployment.AttachmentKey; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.annotation.CompositeIndex; import org.wildfly.extension.microprofile.faulttolerance.MicroProfileFaultToleranceLogger; /** * Utility class which marks MP FT deployments. * * @author Radoslav Husar */ public class MicroProfileFaultToleranceMarker { private static final AttachmentKey<Boolean> ATTACHMENT_KEY = AttachmentKey.create(Boolean.class); static void mark(DeploymentUnit deployment) { deployment.putAttachment(ATTACHMENT_KEY, true); } /** * @return whether the deployment was marked as MP FT deployment */ public static boolean isMarked(DeploymentUnit deploymentUnit) { Boolean b = deploymentUnit.getAttachment(ATTACHMENT_KEY); return (b != null) && b; } static void clearMark(DeploymentUnit deployment) { deployment.removeAttachment(ATTACHMENT_KEY); } public static boolean hasMicroProfileFaultToleranceAnnotations(DeploymentUnit deploymentUnit) { CompositeIndex index = deploymentUnit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX); for (MicroProfileFaultToleranceAnnotation ftAnnotation : MicroProfileFaultToleranceAnnotation.values()) { if (!index.getAnnotations(ftAnnotation.getDotName()).isEmpty()) { MicroProfileFaultToleranceLogger.ROOT_LOGGER.debugf("Deployment '%s' is a MicroProfile Fault Tolerance deployment – @%s annotation found.", deploymentUnit.getName(), ftAnnotation.getDotName()); return true; } } MicroProfileFaultToleranceLogger.ROOT_LOGGER.debugf("No MicroProfile Fault Tolerance annotations found in deployment '%s'.", deploymentUnit.getName()); return false; } private MicroProfileFaultToleranceMarker() { // Utility class. } }
3,064
40.418919
209
java
null
wildfly-main/microprofile/fault-tolerance-smallrye/deployment/src/main/java/org/wildfly/microprofile/faulttolerance/deployment/FaultToleranceContainerExecutorFactory.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.microprofile.faulttolerance.deployment; import java.util.OptionalInt; import java.util.concurrent.ThreadFactory; import javax.naming.InitialContext; import jakarta.enterprise.concurrent.ManagedThreadFactory; import jakarta.enterprise.inject.Alternative; import jakarta.inject.Inject; import io.smallrye.faulttolerance.DefaultAsyncExecutorProvider; import org.eclipse.microprofile.config.inject.ConfigProperty; /** * Subclass of {@link DefaultAsyncExecutorProvider} that provides a {@link ThreadFactory} as * configured in the server. * * @author Radoslav Husar * @author Jason Lee */ @Alternative public class FaultToleranceContainerExecutorFactory extends DefaultAsyncExecutorProvider { @Inject public FaultToleranceContainerExecutorFactory( @ConfigProperty(name = "io.smallrye.faulttolerance.mainThreadPoolSize") OptionalInt mainThreadPoolSize, @ConfigProperty(name = "io.smallrye.faulttolerance.mainThreadPoolQueueSize") OptionalInt mainThreadPoolQueueSize, @ConfigProperty(name = "io.smallrye.faulttolerance.globalThreadPoolSize") OptionalInt globalThreadPoolSize ) { super(mainThreadPoolSize, mainThreadPoolQueueSize, globalThreadPoolSize); } @Override protected ThreadFactory threadFactory() { try { InitialContext initialContext = new InitialContext(); return (ManagedThreadFactory) initialContext.lookup("java:jboss/ee/concurrency/factory/default"); } catch (Exception e) { throw new RuntimeException(e); } } }
2,608
38.530303
125
java
null
wildfly-main/microprofile/config-smallrye/src/test/java/org/wildfly/extension/microprofile/config/smallrye/MPConfigSubsystemParsingTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.config.smallrye; import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME; import static org.junit.Assert.assertTrue; import static org.wildfly.extension.microprofile.config.smallrye.MicroProfileConfigExtension.CONFIG_SOURCE_PATH; import static org.wildfly.extension.microprofile.config.smallrye.MicroProfileConfigExtension.SUBSYSTEM_PATH; import static org.wildfly.extension.microprofile.config.smallrye.MicroProfileConfigExtension.VERSION_1_0_0; import static org.wildfly.extension.microprofile.config.smallrye.MicroProfileConfigExtension.VERSION_1_1_0; import java.io.IOException; import java.util.List; import java.util.Properties; 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.AdditionalInitialization; import org.jboss.as.subsystem.test.KernelServices; import org.jboss.as.subsystem.test.KernelServicesBuilder; import org.jboss.dmr.ModelNode; import org.junit.Test; public class MPConfigSubsystemParsingTestCase extends AbstractSubsystemBaseTest { public MPConfigSubsystemParsingTestCase() { super(MicroProfileConfigExtension.SUBSYSTEM_NAME, new MicroProfileConfigExtension()); } @Override protected String getSubsystemXml() throws IOException { return readResource("subsystem.xml"); } @Override protected String getSubsystemXsdPath() { return "schema/wildfly-microprofile-config-smallrye_2_0.xsd"; } protected Properties getResolvedProperties() { return System.getProperties(); } @Test public void testRejectingTransformersEAP_XP4() throws Exception { testRejectingTransformers(ModelTestControllerVersion.EAP_XP_4, VERSION_1_1_0); } private static String getMicroProfileConfigSmallryeGAV(ModelTestControllerVersion version) { if (version.isEap()) { return "org.jboss.eap:wildfly-microprofile-config-smallrye:" + version.getMavenGavVersion(); } return "org.wildfly:wildfly-microprofile-config-smallrye:" + version.getMavenGavVersion(); } @Override protected AdditionalInitialization createAdditionalInitialization() { return AdditionalInitialization.withCapabilities( WELD_CAPABILITY_NAME); } private void testRejectingTransformers(ModelTestControllerVersion controllerVersion, ModelVersion microprofileConfigVersion) throws Exception { //Boot up empty controllers with the resources needed for the ops coming from the xml to work KernelServicesBuilder builder = createKernelServicesBuilder(createAdditionalInitialization()); builder.createLegacyKernelServicesBuilder(createAdditionalInitialization(), controllerVersion, microprofileConfigVersion) .addMavenResourceURL(getMicroProfileConfigSmallryeGAV(controllerVersion)) .skipReverseControllerCheck() .dontPersistXml(); KernelServices mainServices = builder.build(); assertTrue(mainServices.isSuccessfulBoot()); assertTrue(mainServices.getLegacyServices(microprofileConfigVersion).isSuccessfulBoot()); List<ModelNode> ops = builder.parseXmlResource("subsystem_reject_transformers.xml"); PathAddress subsystemAddress = PathAddress.pathAddress(SUBSYSTEM_PATH); FailedOperationTransformationConfig config = new FailedOperationTransformationConfig(); if (microprofileConfigVersion.compareTo(VERSION_1_0_0) >= 0) { config.addFailedAttribute(subsystemAddress.append(CONFIG_SOURCE_PATH.getKey(), "my-config-source-with-ordinal-expression"), new FailedOperationTransformationConfig.NewAttributesConfig( ConfigSourceDefinition.ORDINAL)); } if (microprofileConfigVersion.compareTo(VERSION_1_1_0) >= 0) { config.addFailedAttribute(subsystemAddress.append(CONFIG_SOURCE_PATH.getKey(), "my-config-source-with-root"), new FailedOperationTransformationConfig.AttributesPathAddressConfig() { @Override protected boolean isAttributeWritable(String attributeName) { return true; } @Override protected boolean checkValue(String attrName, ModelNode attribute, boolean isGeneratedWriteAttribute) { if (attribute.hasDefined(ConfigSourceDefinition.ROOT.getName())) { return attribute.get(ConfigSourceDefinition.ROOT.getName()).asString().equals("false"); } return false; } @Override protected ModelNode correctValue(ModelNode toResolve, boolean isGeneratedWriteAttribute) { toResolve.remove(ConfigSourceDefinition.ROOT.getName()); return toResolve; } }); } ModelTestUtils.checkFailedTransformedBootOperations(mainServices, microprofileConfigVersion, ops, config); } }
6,325
45.514706
193
java
null
wildfly-main/microprofile/config-smallrye/src/test/java/org/wildfly/extension/microprofile/config/smallrye/MPConfigSubsystem_1_0_ParsingTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.config.smallrye; import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME; import java.io.IOException; import java.util.Properties; import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest; import org.jboss.as.subsystem.test.AdditionalInitialization; public class MPConfigSubsystem_1_0_ParsingTestCase extends AbstractSubsystemBaseTest { public MPConfigSubsystem_1_0_ParsingTestCase() { super(MicroProfileConfigExtension.SUBSYSTEM_NAME, new MicroProfileConfigExtension()); } @Override protected String getSubsystemXml() throws IOException { return readResource("subsystem_1_0.xml"); } @Override protected String getSubsystemXsdPath() throws IOException { return "schema/wildfly-microprofile-config-smallrye_1_0.xsd"; } protected Properties getResolvedProperties() { return System.getProperties(); } @Override protected AdditionalInitialization createAdditionalInitialization() { return AdditionalInitialization.withCapabilities( WELD_CAPABILITY_NAME); } @Override protected void compareXml(String configId, String original, String marshalled) throws Exception { super.compareXml(configId, original, marshalled, true); } }
2,342
34.5
101
java
null
wildfly-main/microprofile/config-smallrye/src/main/java/org/wildfly/extension/microprofile/config/smallrye/DirConfigSourceRegistrationService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.config.smallrye; import java.io.File; import java.util.function.Supplier; import io.smallrye.config.source.file.FileSystemConfigSource; import org.eclipse.microprofile.config.spi.ConfigSource; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.services.path.AbsolutePathService; import org.jboss.as.controller.services.path.PathManager; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StopContext; import org.wildfly.extension.microprofile.config.smallrye._private.MicroProfileConfigLogger; /** * Service to register a ConfigSource reading its configuration from a directory (where files are property keys and * their content is the property values). * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ class DirConfigSourceRegistrationService implements Service { private final String name; private final String path; /** * Can be null */ private final String relativeTo; private final int ordinal; private final Supplier<PathManager> pathManager; private final Registry<ConfigSource> sources; DirConfigSourceRegistrationService(String name, String path, String relativeTo, int ordinal, Supplier<PathManager> pathManager, Registry<ConfigSource> sources) { this.name = name; this.path = path; this.relativeTo = relativeTo; this.ordinal = ordinal; this.pathManager = pathManager; this.sources = sources; } static void install(OperationContext context, String name, String path, String relativeTo, int ordinal, Registry registry) { ServiceBuilder<?> builder = context.getServiceTarget() .addService(ServiceNames.CONFIG_SOURCE.append(name)); Supplier<PathManager> pathManager = builder.requires(context.getCapabilityServiceName("org.wildfly.management.path-manager", PathManager.class)); builder.setInstance(new DirConfigSourceRegistrationService(name, path, relativeTo, ordinal, pathManager, registry)) .install(); } @Override public void start(StartContext startContext) { String relativeToPath = AbsolutePathService.isAbsoluteUnixOrWindowsPath(path) ? null : relativeTo; String dirPath = pathManager.get().resolveRelativePathEntry(path, relativeToPath); File dir = new File(dirPath); MicroProfileConfigLogger.ROOT_LOGGER.loadConfigSourceFromDir(dir.getAbsolutePath()); this.sources.register(this.name, new FileSystemConfigSource(dir, ordinal)); } @Override public void stop(StopContext context) { this.sources.unregister(this.name); } }
3,809
41.333333
165
java
null
wildfly-main/microprofile/config-smallrye/src/main/java/org/wildfly/extension/microprofile/config/smallrye/PropertiesConfigSourceRegistrationService.java
package org.wildfly.extension.microprofile.config.smallrye; import io.smallrye.config.PropertiesConfigSource; import org.eclipse.microprofile.config.spi.ConfigSource; import org.jboss.as.controller.OperationContext; import org.jboss.msc.Service; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StopContext; public class PropertiesConfigSourceRegistrationService implements Service { private final String name; private final PropertiesConfigSource configSource; private final Registry<ConfigSource> sources; PropertiesConfigSourceRegistrationService(String name, PropertiesConfigSource configSource, Registry<ConfigSource> sources) { this.name = name; this.configSource = configSource; this.sources = sources; } static void install(OperationContext context, String name, PropertiesConfigSource configSource, Registry registry) { context.getServiceTarget() .addService(ServiceNames.CONFIG_SOURCE.append(name)) .setInstance(new PropertiesConfigSourceRegistrationService(name, configSource, registry)) .install(); } @Override public void start(StartContext startContext) { this.sources.register(this.name, configSource); } @Override public void stop(StopContext context) { this.sources.unregister(this.name); } }
1,388
34.615385
129
java
null
wildfly-main/microprofile/config-smallrye/src/main/java/org/wildfly/extension/microprofile/config/smallrye/IterableRegistry.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.microprofile.config.smallrye; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentSkipListMap; /** * A registry whose items can be iterated over. * @author Paul Ferraro */ public class IterableRegistry<T> implements Iterable<T>, Registry<T> { // Use a sorted map since we need a deterministic sort order. The order things are added to the SmallRyeConfigBuilder // has influence on the final sorting order, and we have tests checking this order is deterministic. private final Map<String, T> objects = new ConcurrentSkipListMap<>(); @Override public void register(String name, T object) { this.objects.put(name, object); } @Override public void unregister(String name) { this.objects.remove(name); } @Override public Iterator<T> iterator() { return this.objects.values().iterator(); } }
1,956
35.240741
121
java
null
wildfly-main/microprofile/config-smallrye/src/main/java/org/wildfly/extension/microprofile/config/smallrye/MicroProfileConfigExtension.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.config.smallrye; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import org.eclipse.microprofile.config.spi.ConfigSource; import org.eclipse.microprofile.config.spi.ConfigSourceProvider; 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.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.persistence.SubsystemMarshallingContext; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.staxmapper.XMLElementWriter; /** * @author <a href="[email protected]">Kabir Khan</a> */ public class MicroProfileConfigExtension implements Extension { /** * The name of our subsystem within the model. */ public static final String SUBSYSTEM_NAME = "microprofile-config-smallrye"; protected static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME); protected static final PathElement CONFIG_SOURCE_PATH = PathElement.pathElement("config-source"); protected static final PathElement CONFIG_SOURCE_PROVIDER_PATH = PathElement.pathElement("config-source-provider"); private static final String RESOURCE_NAME = MicroProfileConfigExtension.class.getPackage().getName() + ".LocalDescriptions"; protected static final ModelVersion VERSION_1_0_0 = ModelVersion.create(1, 0, 0); protected static final ModelVersion VERSION_1_1_0 = ModelVersion.create(1, 1, 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 MicroProfileConfigSubsystemParser_1_0 PARSER_1_0 = new MicroProfileConfigSubsystemParser_1_0(); private static final MicroProfileConfigSubsystemParser_2_0 PARSER_2_0 = new MicroProfileConfigSubsystemParser_2_0(); private static final XMLElementWriter<SubsystemMarshallingContext> CURRENT_WRITER = PARSER_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, MicroProfileConfigExtension.class.getClassLoader(), true, useUnprefixedChildTypes); } @Override public void initialize(ExtensionContext context) { final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION); subsystem.registerXMLElementWriter(CURRENT_WRITER); IterableRegistry<ConfigSourceProvider> providers = new IterableRegistry<>(); IterableRegistry<ConfigSource> sources = new IterableRegistry<>(); final ManagementResourceRegistration registration = subsystem.registerSubsystemModel(new MicroProfileSubsystemDefinition(providers, sources)); registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE); registration.registerSubModel(new ConfigSourceDefinition(providers, sources)); registration.registerSubModel(new ConfigSourceProviderDefinition(providers)); } @Override public void initializeParsers(ExtensionParsingContext context) { context.setSubsystemXmlMapping(SUBSYSTEM_NAME, MicroProfileConfigSubsystemParser_1_0.NAMESPACE, PARSER_1_0); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, MicroProfileConfigSubsystemParser_2_0.NAMESPACE, PARSER_2_0); } }
5,343
49.895238
172
java
null
wildfly-main/microprofile/config-smallrye/src/main/java/org/wildfly/extension/microprofile/config/smallrye/Registry.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.microprofile.config.smallrye; /** * Encapsulates a generic registry of objects. * @author Paul Ferraro * @param <T> The target object type of this registry */ public interface Registry<T> { /** * Registers the specified object with this registry * @param name the object name * @param object the object to register */ void register(String name, T object); /** * Unregisters the specified object from this registry * @param name the object name */ void unregister(String name); }
1,590
35.159091
70
java
null
wildfly-main/microprofile/config-smallrye/src/main/java/org/wildfly/extension/microprofile/config/smallrye/MicroProfileSubsystemDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.config.smallrye; import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME; import java.util.Collection; import java.util.Collections; import org.eclipse.microprofile.config.spi.ConfigSource; import org.eclipse.microprofile.config.spi.ConfigSourceProvider; 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; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> */ class MicroProfileSubsystemDefinition extends PersistentResourceDefinition { static final String CONFIG_CAPABILITY_NAME = "org.wildfly.microprofile.config"; static final RuntimeCapability<Void> CONFIG_CAPABILITY = RuntimeCapability.Builder.of(CONFIG_CAPABILITY_NAME) .addRequirements(WELD_CAPABILITY_NAME) .build(); protected MicroProfileSubsystemDefinition(Iterable<ConfigSourceProvider> providers, Iterable<ConfigSource> sources) { super(new SimpleResourceDefinition.Parameters(MicroProfileConfigExtension.SUBSYSTEM_PATH, MicroProfileConfigExtension.getResourceDescriptionResolver(MicroProfileConfigExtension.SUBSYSTEM_NAME)) .setAddHandler(new MicroProfileConfigSubsystemAdd(providers, sources)) .setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE) .setCapabilities(CONFIG_CAPABILITY) ); } @Override public Collection<AttributeDefinition> getAttributes() { return Collections.emptySet(); } @Override public void registerOperations(ManagementResourceRegistration resourceRegistration) { super.registerOperations(resourceRegistration); //you can register aditional operations here } @Override public void registerAttributes(ManagementResourceRegistration resourceRegistration) { //you can register attributes here } }
3,204
42.310811
201
java
null
wildfly-main/microprofile/config-smallrye/src/main/java/org/wildfly/extension/microprofile/config/smallrye/ServiceNames.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.config.smallrye; import org.jboss.msc.service.ServiceName; /** * Service Names for MicroProfile Config objects. * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ public interface ServiceNames { ServiceName MICROPROFILE_CONFIG = ServiceName.JBOSS.append("eclipse", "microprofile", "config"); ServiceName CONFIG_SOURCE = MICROPROFILE_CONFIG.append("config-source"); ServiceName CONFIG_SOURCE_PROVIDER = MICROPROFILE_CONFIG.append("config-source-provider"); ServiceName CONFIG_SOURCE_ROOT = MICROPROFILE_CONFIG.append("config-source-root"); }
1,666
38.690476
100
java
null
wildfly-main/microprofile/config-smallrye/src/main/java/org/wildfly/extension/microprofile/config/smallrye/ConfigSourceProviderDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.config.smallrye; import static org.jboss.as.controller.SimpleAttributeDefinitionBuilder.create; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MODULE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; import static org.wildfly.extension.microprofile.config.smallrye._private.MicroProfileConfigLogger.ROOT_LOGGER; import java.util.Arrays; import java.util.Collection; import org.eclipse.microprofile.config.spi.ConfigSourceProvider; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.AttributeMarshaller; import org.jboss.as.controller.ObjectTypeAttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.ReloadRequiredRemoveStepHandler; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.modules.Module; import org.jboss.modules.ModuleIdentifier; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ class ConfigSourceProviderDefinition extends PersistentResourceDefinition { static ObjectTypeAttributeDefinition CLASS = ObjectTypeAttributeDefinition.Builder.of("class", create(NAME, ModelType.STRING, false) .setAllowExpression(false) .build(), create(MODULE, ModelType.STRING, false) .setAllowExpression(false) .build()) .setRequired(false) .setAttributeMarshaller(AttributeMarshaller.ATTRIBUTE_OBJECT) .setRestartAllServices() .build(); static AttributeDefinition[] ATTRIBUTES = { CLASS }; protected ConfigSourceProviderDefinition(Registry<ConfigSourceProvider> providers) { super(new SimpleResourceDefinition.Parameters(MicroProfileConfigExtension.CONFIG_SOURCE_PROVIDER_PATH, MicroProfileConfigExtension.getResourceDescriptionResolver(MicroProfileConfigExtension.CONFIG_SOURCE_PROVIDER_PATH.getKey())) .setAddHandler(new ConfigSourceProviderDefinitionAddHandler(providers)) .setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE)); } @Override public Collection<AttributeDefinition> getAttributes() { return Arrays.asList(ATTRIBUTES); } private static Class unwrapClass(ModelNode classModel) throws OperationFailedException { String className = classModel.get(NAME).asString(); String moduleName = classModel.get(MODULE).asString(); try { ModuleIdentifier moduleID = ModuleIdentifier.fromString(moduleName); Module module = Module.getCallerModuleLoader().loadModule(moduleID); Class<?> clazz = module.getClassLoader().loadClass(className); return clazz; } catch (Exception e) { throw ROOT_LOGGER.unableToLoadClassFromModule(className, moduleName); } } private static class ConfigSourceProviderDefinitionAddHandler extends AbstractAddStepHandler { private final Registry<ConfigSourceProvider> providers; private ConfigSourceProviderDefinitionAddHandler(Registry<ConfigSourceProvider> providers) { super(ATTRIBUTES); this.providers = providers; } @Override protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { super.performRuntime(context, operation, model); ModelNode classModel = CLASS.resolveModelAttribute(context, model); if (classModel.isDefined()) { Class configSourceProviderClass = unwrapClass(classModel); try { ConfigSourceProviderRegistrationService.install(context, context.getCurrentAddressValue(), ConfigSourceProvider.class.cast(configSourceProviderClass.getDeclaredConstructor().newInstance()), providers); } catch (Exception e) { throw new OperationFailedException(e); } } } } }
5,457
45.254237
141
java
null
wildfly-main/microprofile/config-smallrye/src/main/java/org/wildfly/extension/microprofile/config/smallrye/ConfigSourceDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.config.smallrye; import static org.jboss.as.controller.SimpleAttributeDefinitionBuilder.create; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FILESYSTEM_PATH; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MODULE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; import static org.wildfly.extension.microprofile.config.smallrye._private.MicroProfileConfigLogger.ROOT_LOGGER; import java.util.Arrays; import java.util.Collection; import io.smallrye.config.PropertiesConfigSource; import org.eclipse.microprofile.config.spi.ConfigSource; import org.eclipse.microprofile.config.spi.ConfigSourceProvider; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.AttributeMarshaller; import org.jboss.as.controller.AttributeMarshallers; import org.jboss.as.controller.AttributeParsers; import org.jboss.as.controller.ObjectTypeAttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.PropertiesAttributeDefinition; import org.jboss.as.controller.ReloadRequiredRemoveStepHandler; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.modules.Module; import org.jboss.modules.ModuleIdentifier; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ class ConfigSourceDefinition extends PersistentResourceDefinition { static AttributeDefinition ORDINAL = SimpleAttributeDefinitionBuilder.create("ordinal", ModelType.INT) .setDefaultValue(new ModelNode(100)) .setAllowExpression(true) .setRequired(false) .setRestartAllServices() .build(); static AttributeDefinition PROPERTIES = new PropertiesAttributeDefinition.Builder("properties", true) .setAttributeParser(new AttributeParsers.PropertiesParser(false)) .setAttributeMarshaller(new AttributeMarshallers.PropertiesAttributeMarshaller(null, false)) .setAlternatives("class", "dir") .setRequired(false) .setRestartAllServices() .build(); static ObjectTypeAttributeDefinition CLASS = ObjectTypeAttributeDefinition.Builder.of("class", create(NAME, ModelType.STRING, false) .setAllowExpression(false) .build(), create(MODULE, ModelType.STRING, false) .setAllowExpression(false) .build()) .setAlternatives("properties", "dir") .setRequired(false) .setAttributeMarshaller(AttributeMarshaller.ATTRIBUTE_OBJECT) .setRestartAllServices() .build(); static AttributeDefinition PATH = create(ModelDescriptionConstants.PATH, ModelType.STRING, false) .setAllowExpression(true) .addArbitraryDescriptor(FILESYSTEM_PATH, ModelNode.TRUE) .build(); static AttributeDefinition RELATIVE_TO = create(ModelDescriptionConstants.RELATIVE_TO, ModelType.STRING, true) .setAllowExpression(false) .build(); static AttributeDefinition ROOT = create("root", ModelType.STRING, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); // For the 1.0 parser, in 2.0 we introduce the ROOT nested attribute static ObjectTypeAttributeDefinition DIR_1_0 = ObjectTypeAttributeDefinition.Builder.of("dir", PATH, RELATIVE_TO) .setAlternatives("properties", "class") .setRequired(false) .setAttributeMarshaller(AttributeMarshaller.ATTRIBUTE_OBJECT) .setRestartAllServices() .setCapabilityReference("org.wildfly.management.path-manager") .build(); static ObjectTypeAttributeDefinition DIR = ObjectTypeAttributeDefinition.Builder.of("dir", PATH, RELATIVE_TO, ROOT) .setAlternatives("properties", "class") .setRequired(false) .setAttributeMarshaller(AttributeMarshaller.ATTRIBUTE_OBJECT) .setRestartAllServices() .setCapabilityReference("org.wildfly.management.path-manager") .build(); static AttributeDefinition[] ATTRIBUTES = {ORDINAL, PROPERTIES, CLASS, DIR}; protected ConfigSourceDefinition(Registry<ConfigSourceProvider> providers, Registry<ConfigSource> sources) { super(new SimpleResourceDefinition.Parameters(MicroProfileConfigExtension.CONFIG_SOURCE_PATH, MicroProfileConfigExtension.getResourceDescriptionResolver(MicroProfileConfigExtension.CONFIG_SOURCE_PATH.getKey())) .setAddHandler(new ConfigSourceDefinitionAddHandler(providers, sources)) .setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE)); } @Override public Collection<AttributeDefinition> getAttributes() { return Arrays.asList(ATTRIBUTES); } private static Class unwrapClass(ModelNode classModel) throws OperationFailedException { String className = classModel.get(NAME).asString(); String moduleName = classModel.get(MODULE).asString(); try { ModuleIdentifier moduleID = ModuleIdentifier.fromString(moduleName); Module module = Module.getCallerModuleLoader().loadModule(moduleID); Class<?> clazz = module.getClassLoader().loadClass(className); return clazz; } catch (Exception e) { throw ROOT_LOGGER.unableToLoadClassFromModule(className, moduleName); } } private static class ConfigSourceDefinitionAddHandler extends AbstractAddStepHandler { private Registry<ConfigSourceProvider> providers; private final Registry<ConfigSource> sources; ConfigSourceDefinitionAddHandler(Registry<ConfigSourceProvider> providers, Registry<ConfigSource> sources) { super(ATTRIBUTES); this.providers = providers; this.sources = sources; } @Override protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { super.performRuntime(context, operation, model); String name = context.getCurrentAddressValue(); int ordinal = ORDINAL.resolveModelAttribute(context, model).asInt(); ModelNode classModel = CLASS.resolveModelAttribute(context, model); ModelNode dirModel = DIR.resolveModelAttribute(context, model); if (classModel.isDefined()) { try { ClassConfigSourceRegistrationService.install(context, name, ConfigSource.class.cast(unwrapClass(classModel).getDeclaredConstructor().newInstance()), sources); } catch (Exception e) { throw new OperationFailedException(e); } } else if (dirModel.isDefined()) { String path = PATH.resolveModelAttribute(context, dirModel).asString(); String relativeTo = RELATIVE_TO.resolveModelAttribute(context, dirModel).asStringOrNull(); boolean root = ROOT.resolveModelAttribute(context, dirModel).asBoolean(); if (root) { ConfigSourceRootRegistrationService.install(context, name, path, relativeTo, ordinal, providers); } else { DirConfigSourceRegistrationService.install(context, name, path, relativeTo, ordinal, sources); } } else { PropertiesConfigSourceRegistrationService.install(context, name, new PropertiesConfigSource( PropertiesAttributeDefinition.unwrapModel(context, PROPERTIES.resolveModelAttribute(context, model)), name, ordinal), sources); } } } }
9,527
47.612245
135
java
null
wildfly-main/microprofile/config-smallrye/src/main/java/org/wildfly/extension/microprofile/config/smallrye/ClassConfigSourceRegistrationService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.config.smallrye; import org.eclipse.microprofile.config.spi.ConfigSource; import org.jboss.as.controller.OperationContext; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StopContext; import org.wildfly.extension.microprofile.config.smallrye._private.MicroProfileConfigLogger; /** * Service to register a ConfigSource reading its configuration from a directory (where files are property keys and * their content is the property values). * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ class ClassConfigSourceRegistrationService implements Service { private final String name; private final ConfigSource configSource; private final Registry<ConfigSource> sources; ClassConfigSourceRegistrationService(String name, ConfigSource configSource, Registry<ConfigSource> sources) { this.name = name; this.configSource = configSource; this.sources = sources; } static void install(OperationContext context, String name, ConfigSource configSource, Registry<ConfigSource> registry) { ServiceBuilder<?> builder = context.getServiceTarget() .addService(ServiceNames.CONFIG_SOURCE.append(name)); builder.setInstance(new ClassConfigSourceRegistrationService(name, configSource, registry)) .install(); } @Override public void start(StartContext startContext) { MicroProfileConfigLogger.ROOT_LOGGER.loadConfigSourceFromClass(configSource.getClass()); this.sources.register(this.name, configSource); } @Override public void stop(StopContext context) { this.sources.unregister(this.name); } }
2,836
39.528571
124
java
null
wildfly-main/microprofile/config-smallrye/src/main/java/org/wildfly/extension/microprofile/config/smallrye/MicroProfileConfigSubsystemParser_2_0.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.config.smallrye; import static org.jboss.as.controller.PersistentResourceXMLDescription.builder; import org.jboss.as.controller.PersistentResourceXMLDescription; import org.jboss.as.controller.PersistentResourceXMLParser; class MicroProfileConfigSubsystemParser_2_0 extends PersistentResourceXMLParser { /** * The name space used for the {@code subsystem} element */ public static final String NAMESPACE = "urn:wildfly:microprofile-config-smallrye:2.0"; private static final PersistentResourceXMLDescription xmlDescription; static { xmlDescription = builder(MicroProfileConfigExtension.SUBSYSTEM_PATH, NAMESPACE) .addChild(builder(MicroProfileConfigExtension.CONFIG_SOURCE_PATH) .addAttributes( ConfigSourceDefinition.ORDINAL, ConfigSourceDefinition.PROPERTIES, ConfigSourceDefinition.CLASS, ConfigSourceDefinition.DIR)) .addChild(builder(MicroProfileConfigExtension.CONFIG_SOURCE_PROVIDER_PATH) .addAttributes( ConfigSourceProviderDefinition.CLASS)) .build(); } @Override public PersistentResourceXMLDescription getParserDescription() { return xmlDescription; } }
2,452
42.035088
90
java
null
wildfly-main/microprofile/config-smallrye/src/main/java/org/wildfly/extension/microprofile/config/smallrye/MicroProfileConfigSubsystemAdd.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.config.smallrye; import org.eclipse.microprofile.config.spi.ConfigProviderResolver; import org.eclipse.microprofile.config.spi.ConfigSource; import org.eclipse.microprofile.config.spi.ConfigSourceProvider; import org.jboss.as.controller.AbstractBoottimeAddStepHandler; import org.jboss.as.controller.OperationContext; import org.jboss.as.server.AbstractDeploymentChainStep; import org.jboss.as.server.DeploymentProcessorTarget; import org.jboss.as.server.deployment.Phase; import org.jboss.dmr.ModelNode; import org.wildfly.extension.microprofile.config.smallrye._private.MicroProfileConfigLogger; import org.wildfly.extension.microprofile.config.smallrye.deployment.DependencyProcessor; import org.wildfly.extension.microprofile.config.smallrye.deployment.SubsystemDeploymentProcessor; import io.smallrye.config.SmallRyeConfigBuilder; import io.smallrye.config.SmallRyeConfigProviderResolver; /** * Handler responsible for adding the subsystem resource to the model * * @author <a href="[email protected]">Kabir Khan</a> */ class MicroProfileConfigSubsystemAdd extends AbstractBoottimeAddStepHandler { final Iterable<ConfigSourceProvider> providers; final Iterable<ConfigSource> sources; MicroProfileConfigSubsystemAdd(Iterable<ConfigSourceProvider> providers, Iterable<ConfigSource> sources) { this.providers = providers; this.sources = sources; // Override smallrye-config's ConfigProviderResolver so that // the builder loads config sources from the microprofile-config-smallrye subsystem by default ConfigProviderResolver.setInstance(new SmallRyeConfigProviderResolver() { @Override public SmallRyeConfigBuilder getBuilder() { // The builder will take into account the config-sources available when the Config object is created. // any config-sources added or modified subsequently will not be taken into account. SmallRyeConfigBuilder builder = new SmallRyeConfigBuilder() { @Override public SmallRyeConfigBuilder forClassLoader(ClassLoader classLoader) { SmallRyeConfigBuilder builder = super.forClassLoader(classLoader); for (ConfigSourceProvider provider : providers) { for (ConfigSource source : provider.getConfigSources(classLoader)) { builder.withSources(source); } } for (ConfigSource source : sources) { builder.withSources(source); } return builder; } }; builder.addDefaultInterceptors(); return builder; } }); } /** * {@inheritDoc} */ @Override public void performBoottime(OperationContext context, ModelNode operation, ModelNode model) { MicroProfileConfigLogger.ROOT_LOGGER.activatingSubsystem(); context.addStep(new AbstractDeploymentChainStep() { @Override public void execute(DeploymentProcessorTarget processorTarget) { processorTarget.addDeploymentProcessor(MicroProfileConfigExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_MICROPROFILE_CONFIG, new DependencyProcessor()); processorTarget.addDeploymentProcessor(MicroProfileConfigExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_MICROPROFILE_CONFIG, new SubsystemDeploymentProcessor()); } }, OperationContext.Stage.RUNTIME); } }
4,753
45.607843
193
java
null
wildfly-main/microprofile/config-smallrye/src/main/java/org/wildfly/extension/microprofile/config/smallrye/MicroProfileConfigSubsystemParser_1_0.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.config.smallrye; 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) 2017 Red Hat inc. */ class MicroProfileConfigSubsystemParser_1_0 extends PersistentResourceXMLParser { /** * The name space used for the {@code subsystem} element */ public static final String NAMESPACE = "urn:wildfly:microprofile-config-smallrye:1.0"; private static final PersistentResourceXMLDescription xmlDescription; static { xmlDescription = builder(MicroProfileConfigExtension.SUBSYSTEM_PATH, NAMESPACE) .addChild(builder(MicroProfileConfigExtension.CONFIG_SOURCE_PATH) .addAttributes( ConfigSourceDefinition.ORDINAL, ConfigSourceDefinition.PROPERTIES, ConfigSourceDefinition.CLASS, ConfigSourceDefinition.DIR_1_0)) .addChild(builder(MicroProfileConfigExtension.CONFIG_SOURCE_PROVIDER_PATH) .addAttributes( ConfigSourceProviderDefinition.CLASS)) .build(); } @Override public PersistentResourceXMLDescription getParserDescription() { return xmlDescription; } }
2,543
41.4
90
java
null
wildfly-main/microprofile/config-smallrye/src/main/java/org/wildfly/extension/microprofile/config/smallrye/ConfigSourceProviderRegistrationService.java
package org.wildfly.extension.microprofile.config.smallrye; import org.eclipse.microprofile.config.spi.ConfigSourceProvider; import org.jboss.as.controller.OperationContext; import org.jboss.msc.Service; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; public class ConfigSourceProviderRegistrationService implements Service { private final String name; private ConfigSourceProvider configSourceProvider; private final Registry<ConfigSourceProvider> sources; ConfigSourceProviderRegistrationService(String name, ConfigSourceProvider configSourceProvider, Registry<ConfigSourceProvider> sources) { this.name = name; this.configSourceProvider = configSourceProvider; this.sources = sources; } static void install(OperationContext context, String name, ConfigSourceProvider configSourceProvider, Registry<ConfigSourceProvider> registry) { context.getServiceTarget() .addService(ServiceNames.CONFIG_SOURCE_PROVIDER.append(name)) .setInstance(new ConfigSourceProviderRegistrationService(name, configSourceProvider, registry)) .install(); } @Override public void start(StartContext startContext) throws StartException { sources.register(name, configSourceProvider); } @Override public void stop(StopContext stopContext) { sources.unregister(name); } }
1,481
38
148
java
null
wildfly-main/microprofile/config-smallrye/src/main/java/org/wildfly/extension/microprofile/config/smallrye/MicroProfileConfigTransformers.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.microprofile.config.smallrye; import java.util.HashMap; import java.util.Map; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.transform.ExtensionTransformerRegistration; import org.jboss.as.controller.transform.SubsystemTransformerRegistration; import org.jboss.as.controller.transform.TransformationContext; import org.jboss.as.controller.transform.description.AttributeConverter; import org.jboss.as.controller.transform.description.ChainedTransformationDescriptionBuilder; 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.jboss.dmr.ModelNode; import org.kohsuke.MetaInfServices; @MetaInfServices public class MicroProfileConfigTransformers implements ExtensionTransformerRegistration { @Override public String getSubsystemName() { return MicroProfileConfigExtension.SUBSYSTEM_NAME; } @Override public void registerTransformers(SubsystemTransformerRegistration registration) { ChainedTransformationDescriptionBuilder builder = TransformationDescriptionBuilder.Factory.createChainedSubystemInstance(registration.getCurrentSubsystemVersion()); registerTransformers_WildFly_26(builder.createBuilder(MicroProfileConfigExtension.VERSION_2_0_0, MicroProfileConfigExtension.VERSION_1_1_0)); builder.buildAndRegister(registration, new ModelVersion[] { MicroProfileConfigExtension.VERSION_1_1_0}); } private void registerTransformers_WildFly_26(ResourceTransformationDescriptionBuilder builder) { Map<String, RejectAttributeChecker> checkers = new HashMap<>(); checkers.put(ConfigSourceDefinition.ROOT.getName(), new RejectAttributeChecker.SimpleAcceptAttributeChecker(ModelNode.FALSE) { @Override protected boolean rejectAttribute(PathAddress address, String attributeName, ModelNode attributeValue, TransformationContext context) { if (!attributeValue.hasDefined(ConfigSourceDefinition.ROOT.getName())) { return false; } return super.rejectAttribute(address, attributeName, attributeValue, context); } }); builder.addChildResource(MicroProfileConfigExtension.CONFIG_SOURCE_PATH).getAttributeBuilder() .addRejectCheck(new RejectAttributeChecker.ObjectFieldsRejectAttributeChecker(checkers), ConfigSourceDefinition.DIR) .setValueConverter(new AttributeConverter.DefaultAttributeConverter() { @Override protected void convertAttribute(PathAddress address, String attributeName, ModelNode attributeValue, TransformationContext context) { if (attributeValue.hasDefined(ConfigSourceDefinition.ROOT.getName())) { attributeValue.remove(ConfigSourceDefinition.ROOT.getName()); } } }, ConfigSourceDefinition.DIR); } }
4,242
51.382716
172
java
null
wildfly-main/microprofile/config-smallrye/src/main/java/org/wildfly/extension/microprofile/config/smallrye/ConfigSourceRootRegistrationService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.config.smallrye; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; import java.util.function.Supplier; import org.eclipse.microprofile.config.spi.ConfigSource; import org.eclipse.microprofile.config.spi.ConfigSourceProvider; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.services.path.AbsolutePathService; import org.jboss.as.controller.services.path.PathManager; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StopContext; import org.wildfly.extension.microprofile.config.smallrye._private.MicroProfileConfigLogger; import io.smallrye.config.source.file.FileSystemConfigSource; /** * Service to register a ConfigSourceProvider for a root directory, creating a FileSystemConfigSource for each directory * under the given location. * * @author Kabir Khan */ class ConfigSourceRootRegistrationService implements Service { private final String name; private final String path; /** * Can be null */ private final String relativeTo; private final int ordinal; private final Supplier<PathManager> pathManager; private final Registry<ConfigSourceProvider> providerRegistry; private ConfigSourceRootRegistrationService(String name, String path, String relativeTo, int ordinal, Supplier<PathManager> pathManager, Registry<ConfigSourceProvider> sources) { this.name = name; this.path = path; this.relativeTo = relativeTo; this.ordinal = ordinal; this.pathManager = pathManager; this.providerRegistry = sources; } static void install(OperationContext context, String name, String path, String relativeTo, int ordinal, Registry<ConfigSourceProvider> registry) { ServiceBuilder<?> builder = context.getServiceTarget() .addService(ServiceNames.CONFIG_SOURCE_ROOT.append(name)); Supplier<PathManager> pathManager = builder.requires(context.getCapabilityServiceName("org.wildfly.management.path-manager", PathManager.class)); builder.setInstance(new ConfigSourceRootRegistrationService(name, path, relativeTo, ordinal, pathManager, registry)) .install(); } @Override public void start(StartContext startContext) { String relativeToPath = AbsolutePathService.isAbsoluteUnixOrWindowsPath(path) ? null : relativeTo; String dirPath = pathManager.get().resolveRelativePathEntry(path, relativeToPath); File dir = new File(dirPath); MicroProfileConfigLogger.ROOT_LOGGER.loadConfigSourceRootFromDir(dir.getAbsolutePath()); this.providerRegistry.register(this.name, new RootDirectoryConfigSourceProvider(name, dir, ordinal)); } @Override public void stop(StopContext context) { this.providerRegistry.unregister(this.name); } private static class RootDirectoryConfigSourceProvider implements ConfigSourceProvider { private final String name; private final File rootDirectory; private int ordinal; public RootDirectoryConfigSourceProvider(String name, File rootDirectory, int ordinal) { this.name = name; this.rootDirectory = rootDirectory; this.ordinal = ordinal; } @Override public Iterable<ConfigSource> getConfigSources(ClassLoader forClassLoader) { TreeMap<String, ConfigSource> map = new TreeMap<>(); File[] files = rootDirectory.listFiles(); List<String> configSourceDirs = new ArrayList<>(); if (files != null) { // If the directory exist, this will be an empty list for (File file : rootDirectory.listFiles()) { if (file.isDirectory()) { map.put(file.getName(), new FileSystemConfigSource(file, ordinal)); configSourceDirs.add(file.getAbsolutePath()); } } } MicroProfileConfigLogger.ROOT_LOGGER.logDirectoriesUnderConfigSourceRoot(name, configSourceDirs); return map.values(); } } }
5,292
41.344
182
java
null
wildfly-main/microprofile/config-smallrye/src/main/java/org/wildfly/extension/microprofile/config/smallrye/_private/MicroProfileConfigLogger.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.config.smallrye._private; import static org.jboss.logging.Logger.Level.DEBUG; import static org.jboss.logging.Logger.Level.INFO; import java.util.List; import org.jboss.as.controller.OperationFailedException; 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; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ @MessageLogger(projectCode = "WFLYCONF", length = 4) public interface MicroProfileConfigLogger extends BasicLogger { /** * The root logger with a category of the package name. */ MicroProfileConfigLogger ROOT_LOGGER = Logger.getMessageLogger(MicroProfileConfigLogger.class,"org.wildfly.extension.microprofile.config.smallrye"); /** * Logs an informational message indicating the naming subsystem is being activated. */ @LogMessage(level = INFO) @Message(id = 1, value = "Activating MicroProfile Config Subsystem") void activatingSubsystem(); @Message(id = 2, value = "Unable to load class %s from module %s") OperationFailedException unableToLoadClassFromModule(String className, String moduleName); @LogMessage(level = DEBUG) @Message(id = 3, value = "Use directory for MicroProfile Config Source: %s") void loadConfigSourceFromDir(String path); @LogMessage(level = DEBUG) @Message(id = 4, value = "Use class for MicroProfile Config Source: %s") void loadConfigSourceFromClass(Class clazz); // 5 and 6 will come from https://github.com/wildfly/wildfly/pull/15030 // 7 and 8 are used downstream /* @Message(id = 7, value = "") OperationFailedException seeDownstream(); @Message(id = 8, value = "") String seeDownstream(); */ @LogMessage(level = DEBUG) @Message(id = 9, value = "Use directory for MicroProfile Config Source Root: %s") void loadConfigSourceRootFromDir(String path); @LogMessage(level = INFO) @Message(id = 10, value = "The MicroProfile Config Source root directory '%s' contains the following directories which will be used as MicroProfile Config Sources: %s") void logDirectoriesUnderConfigSourceRoot(String name, List<String> directories); }
3,386
38.847059
172
java
null
wildfly-main/microprofile/config-smallrye/src/main/java/org/wildfly/extension/microprofile/config/smallrye/deployment/DependencyProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.config.smallrye.deployment; 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.modules.Module; import org.jboss.modules.ModuleLoader; /** * Add dependencies required by deployment unit to access the Config API (programmatically or using Jakarta Contexts and Dependency Injection). */ public class DependencyProcessor implements DeploymentUnitProcessor { @Override public void deploy(DeploymentPhaseContext phaseContext) { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); addDependencies(deploymentUnit); } private void addDependencies(DeploymentUnit deploymentUnit) { final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); final ModuleLoader moduleLoader = Module.getBootModuleLoader(); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, "org.eclipse.microprofile.config.api", false, false, true, false)); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, "io.smallrye.config", false, false, true, false)); } }
2,503
44.527273
150
java
null
wildfly-main/microprofile/config-smallrye/src/main/java/org/wildfly/extension/microprofile/config/smallrye/deployment/SubsystemDeploymentProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.config.smallrye.deployment; import org.eclipse.microprofile.config.Config; import org.eclipse.microprofile.config.spi.ConfigProviderResolver; import org.jboss.as.server.deployment.AttachmentKey; 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.modules.Module; /** */ public class SubsystemDeploymentProcessor implements DeploymentUnitProcessor { public static final AttachmentKey<Config> CONFIG = AttachmentKey.create(Config.class); public SubsystemDeploymentProcessor() { } @Override public void deploy(DeploymentPhaseContext phaseContext) { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); Module module = deploymentUnit.getAttachment(Attachments.MODULE); Config config = ConfigProviderResolver.instance().getConfig(module.getClassLoader()); deploymentUnit.putAttachment(CONFIG, config); } @Override public void undeploy(DeploymentUnit context) { Config config = context.removeAttachment(CONFIG); ConfigProviderResolver.instance().releaseConfig(config); } }
2,335
38.59322
93
java
null
wildfly-main/microprofile/reactive-messaging-smallrye/kafka/src/main/java/org/wildfly/microprofile/reactive/messaging/config/kafka/ssl/context/ElytronSSLContextRegistry.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.microprofile.reactive.messaging.config.kafka.ssl.context; import static org.wildfly.microprofile.reactive.messaging.config.kafka.ssl.context._private.MicroProfileReactiveMessagingKafkaLogger.LOGGER; import javax.net.ssl.SSLContext; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceRegistry; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ public class ElytronSSLContextRegistry { private static final ElytronSSLContextRegistry INSTANCE = new ElytronSSLContextRegistry(); private static final ServiceName BASE_CLIENT_SSL_CONTEXT_NAME = ServiceName.of("org", "wildfly", "security", "ssl-context"); private volatile ServiceRegistry serviceRegistry; private ElytronSSLContextRegistry() { } public static void setServiceRegistry(ServiceRegistry serviceRegistry) { INSTANCE.serviceRegistry = serviceRegistry; } static boolean isSSLContextInstalled(String name) { return INSTANCE.getSSLContextController(name) != null; } static SSLContext getInstalledSSLContext(String name) { ServiceController<SSLContext> controller = INSTANCE.getSSLContextController(name); if (controller == null) { throw LOGGER.noElytronClientSSLContext(name); } return controller.getValue(); } private ServiceController<SSLContext> getSSLContextController(String name) { return (ServiceController<SSLContext>)INSTANCE.serviceRegistry.getService(getSSLContextName(name)); } static ServiceName getSSLContextName(String name) { return BASE_CLIENT_SSL_CONTEXT_NAME.append(name); } }
2,738
37.577465
140
java
null
wildfly-main/microprofile/reactive-messaging-smallrye/kafka/src/main/java/org/wildfly/microprofile/reactive/messaging/config/kafka/ssl/context/ReactiveMessagingSslConfigProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.microprofile.reactive.messaging.config.kafka.ssl.context; import static org.wildfly.microprofile.reactive.messaging.common.ReactiveMessagingAttachments.IS_REACTIVE_MESSAGING_DEPLOYMENT; import static org.wildfly.microprofile.reactive.messaging.config.kafka.ssl.context._private.MicroProfileReactiveMessagingKafkaLogger.LOGGER; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.eclipse.microprofile.config.Config; import org.eclipse.microprofile.config.spi.ConfigProviderResolver; import org.jboss.as.server.deployment.AttachmentKey; 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.modules.Module; import org.jboss.msc.service.ServiceName; import org.wildfly.microprofile.reactive.messaging.config.ReactiveMessagingConfigSource; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ class ReactiveMessagingSslConfigProcessor implements DeploymentUnitProcessor { private static final String RM_KAFKA_GLOBAL_PROPERTY_PREFIX = "mp.messaging.connector.smallrye-kafka."; private static final String RM_INCOMING_PROPERTY_PREFIX = "mp.messaging.outgoing."; private static final String RM_OUTGOING_PROPERTY_PREFIX = "mp.messaging.incoming."; static final String SSL_CONTEXT_PROPERTY_SUFFIX = "wildfly.elytron.ssl.context"; private static final String SSL_ENGINE_FACTORY_CLASS = "ssl.engine.factory.class"; private static final AttachmentKey<Object> DEPLOYMENT_ATTACHMENT_KEY = AttachmentKey.create(Object.class); @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (!isReactiveMessagingDeployment(deploymentUnit)) { return; } Module module = deploymentUnit.getAttachment(Attachments.MODULE); Config config = ConfigProviderResolver.instance().getConfig(module.getClassLoader()); Map<String, String> addedProperties = new HashMap<>(); Set<ServiceName> mscDependencies = new HashSet<>(); for (String propertyName : config.getPropertyNames()) { if (propertyName.endsWith(SSL_CONTEXT_PROPERTY_SUFFIX)) { String propertyValue = config.getValue(propertyName, String.class); String prefix = null; if (propertyName.equals(RM_KAFKA_GLOBAL_PROPERTY_PREFIX + SSL_CONTEXT_PROPERTY_SUFFIX)) { prefix = RM_KAFKA_GLOBAL_PROPERTY_PREFIX; } else if (propertyName.startsWith(RM_INCOMING_PROPERTY_PREFIX) || propertyName.startsWith(RM_OUTGOING_PROPERTY_PREFIX)) { prefix = propertyName.substring(0, propertyName.indexOf(SSL_CONTEXT_PROPERTY_SUFFIX)); } if (prefix != null) { LOGGER.foundPropertyUsingElytronClientSSLContext(propertyName, propertyValue); if (!ElytronSSLContextRegistry.isSSLContextInstalled(propertyValue)) { throw LOGGER.noElytronClientSSLContext(propertyValue); } mscDependencies.add(ElytronSSLContextRegistry.getSSLContextName(propertyValue)); addedProperties.put(prefix + SSL_ENGINE_FACTORY_CLASS, WildFlyKafkaSSLEngineFactory.class.getName()); } } } if (addedProperties.size() > 0) { ReactiveMessagingConfigSource.addProperties(config, addedProperties); for (ServiceName svcName : mscDependencies) { phaseContext.addDeploymentDependency(svcName, DEPLOYMENT_ATTACHMENT_KEY); } } } private boolean isReactiveMessagingDeployment(DeploymentUnit deploymentUnit) { if (deploymentUnit.hasAttachment(IS_REACTIVE_MESSAGING_DEPLOYMENT)) { Boolean isRm = deploymentUnit.getAttachment(IS_REACTIVE_MESSAGING_DEPLOYMENT); return isRm; } return false; } }
5,330
48.361111
140
java
null
wildfly-main/microprofile/reactive-messaging-smallrye/kafka/src/main/java/org/wildfly/microprofile/reactive/messaging/config/kafka/ssl/context/WildFlyKafkaSSLEngineFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.microprofile.reactive.messaging.config.kafka.ssl.context; import static org.wildfly.microprofile.reactive.messaging.config.kafka.ssl.context.ReactiveMessagingSslConfigProcessor.SSL_CONTEXT_PROPERTY_SUFFIX; import static org.wildfly.microprofile.reactive.messaging.config.kafka.ssl.context._private.MicroProfileReactiveMessagingKafkaLogger.LOGGER; import java.io.IOException; import java.security.KeyStore; import java.util.Collections; import java.util.Map; import java.util.Set; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLParameters; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ public class WildFlyKafkaSSLEngineFactory implements org.apache.kafka.common.security.auth.SslEngineFactory { private volatile SSLContext sslContext; @Override public void configure(Map<String, ?> configs) { SSLContext context = ElytronSSLContextRegistry.getInstalledSSLContext((String) configs.get(SSL_CONTEXT_PROPERTY_SUFFIX)); if (context == null) { throw LOGGER.noElytronClientSSLContext((String) configs.get(SSL_CONTEXT_PROPERTY_SUFFIX)); } sslContext = context; } @Override public SSLEngine createClientSslEngine(String peerHost, int peerPort, String endpointIdentification) { // Code copied and adjusted from Kafka SSLEngine sslEngine = sslContext.createSSLEngine(peerHost, peerPort); sslEngine.setUseClientMode(true); SSLParameters sslParams = sslEngine.getSSLParameters(); // SSLParameters#setEndpointIdentificationAlgorithm enables endpoint validation // only in client mode. Hence, validation is enabled only for clients. // Hard code this to https for now // This is the default value for SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG // which is documented as setting it to an empty string if we don't want host name verification. // There is a 'Host name verification' subsection under https://kafka.apache.org/documentation/#security_ssl // which explains it in more detail sslParams.setEndpointIdentificationAlgorithm("https"); sslEngine.setSSLParameters(sslParams); return sslEngine; } @Override public SSLEngine createServerSslEngine(String peerHost, int peerPort) { // We are only dealing with clients throw new UnsupportedOperationException(); } @Override public boolean shouldBeRebuilt(Map<String, Object> nextConfigs) { return false; } @Override public Set<String> reconfigurableConfigs() { return Collections.emptySet(); } @Override public KeyStore keystore() { // We are only dealing with clients // This only comes into play during reconfiguration. Returning null is ok return null; } @Override public KeyStore truststore() { // This only comes into play during reconfiguration. Returning null is ok return null; } @Override public void close() throws IOException { this.sslContext = null; } }
4,177
37.685185
147
java
null
wildfly-main/microprofile/reactive-messaging-smallrye/kafka/src/main/java/org/wildfly/microprofile/reactive/messaging/config/kafka/ssl/context/KafkaDynamicDeploymentProcessorAdder.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.microprofile.reactive.messaging.config.kafka.ssl.context; import org.jboss.as.server.DeploymentProcessorTarget; import org.jboss.as.server.deployment.Phase; import org.wildfly.microprofile.reactive.messaging.common.DynamicDeploymentProcessorAdder; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ public class KafkaDynamicDeploymentProcessorAdder implements DynamicDeploymentProcessorAdder { @Override public void addDeploymentProcessor(DeploymentProcessorTarget target, String subsystemName) { final int POST_MODULE_MICROPROFILE_REACTIVE_MESSAGING = 0x3828; target.addDeploymentProcessor(subsystemName, Phase.POST_MODULE, POST_MODULE_MICROPROFILE_REACTIVE_MESSAGING, new ReactiveMessagingSslConfigProcessor()); } }
1,863
41.363636
96
java
null
wildfly-main/microprofile/reactive-messaging-smallrye/kafka/src/main/java/org/wildfly/microprofile/reactive/messaging/config/kafka/ssl/context/_private/MicroProfileReactiveMessagingKafkaLogger.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.microprofile.reactive.messaging.config.kafka.ssl.context._private; import static org.jboss.logging.Logger.Level.INFO; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * Log messages for WildFly microprofile-reactive-messaging-smallrye Extension. * * @author <a href="[email protected]">Kabir Khan</a> */ @MessageLogger(projectCode = "WFLYRXMKAF", length = 4) public interface MicroProfileReactiveMessagingKafkaLogger extends BasicLogger { MicroProfileReactiveMessagingKafkaLogger LOGGER = Logger.getMessageLogger(MicroProfileReactiveMessagingKafkaLogger.class, "org.wildfly.extension.microprofile.reactive.messaging"); /** * Logs an informational message indicating the subsystem is being activated. */ @LogMessage(level = INFO) @Message(id = 1, value = "Found property %s, will use the Elytron client-ssl-context: %s") void foundPropertyUsingElytronClientSSLContext(String prop, String ctx); @Message(id = 2, value = "Could not find an Elytron client-ssl-context called: %s") IllegalStateException noElytronClientSSLContext(String ctx); }
2,305
41.703704
183
java
null
wildfly-main/microprofile/reactive-messaging-smallrye/extension/src/test/java/org/wildfly/extension/microprofile/reactive/messaging/MicroprofileReactiveMessagingSubsystemTestCase.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.microprofile.reactive.messaging; import static org.wildfly.extension.microprofile.reactive.messaging.MicroProfileReactiveMessagingExtension.CONFIG_CAPABILITY_NAME; import static org.wildfly.extension.microprofile.reactive.messaging.MicroProfileReactiveMessagingExtension.REACTIVE_STREAMS_OPERATORS_CAPABILITY_NAME; import static org.wildfly.extension.microprofile.reactive.messaging.MicroProfileReactiveMessagingExtension.WELD_CAPABILITY_NAME; import java.util.EnumSet; import org.jboss.as.subsystem.test.AbstractSubsystemSchemaTest; import org.jboss.as.subsystem.test.AdditionalInitialization; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @RunWith(Parameterized.class) public class MicroprofileReactiveMessagingSubsystemTestCase extends AbstractSubsystemSchemaTest<MicroProfileReactiveMessagingSubsystemSchema> { @Parameters public static Iterable<MicroProfileReactiveMessagingSubsystemSchema> parameters() { return EnumSet.allOf(MicroProfileReactiveMessagingSubsystemSchema.class); } public MicroprofileReactiveMessagingSubsystemTestCase(MicroProfileReactiveMessagingSubsystemSchema schema) { super(MicroProfileReactiveMessagingExtension.SUBSYSTEM_NAME, new MicroProfileReactiveMessagingExtension(), schema, MicroProfileReactiveMessagingSubsystemSchema.CURRENT); } @Override protected AdditionalInitialization createAdditionalInitialization() { return AdditionalInitialization.withCapabilities(CONFIG_CAPABILITY_NAME, REACTIVE_STREAMS_OPERATORS_CAPABILITY_NAME, WELD_CAPABILITY_NAME); } }
2,758
48.267857
177
java
null
wildfly-main/microprofile/reactive-messaging-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/reactive/messaging/MicroProfileReactiveMessagingExtension.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.microprofile.reactive.messaging; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import java.util.EnumSet; import java.util.List; import io.netty.util.internal.logging.InternalLoggerFactory; import io.netty.util.internal.logging.JdkLoggerFactory; 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.modules.Module; import org.jboss.modules.ModuleClassLoader; import org.jboss.modules.ModuleLoadException; import org.jboss.modules.ModuleLoader; import org.jboss.staxmapper.XMLElementReader; import org.wildfly.security.manager.WildFlySecurityManager; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ public class MicroProfileReactiveMessagingExtension implements Extension { /** * The name of our subsystem within the model. */ public static final String SUBSYSTEM_NAME = "microprofile-reactive-messaging-smallrye"; static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME); static final ParentResourceDescriptionResolver SUBSYSTEM_RESOLVER = new SubsystemResourceDescriptionResolver(SUBSYSTEM_NAME, MicroProfileReactiveMessagingExtension.class); static final String WELD_CAPABILITY_NAME = "org.wildfly.weld"; static final String REACTIVE_STREAMS_OPERATORS_CAPABILITY_NAME = "org.wildfly.microprofile.reactive-streams-operators"; static final String CONFIG_CAPABILITY_NAME = "org.wildfly.microprofile.config"; 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 = MicroProfileReactiveMessagingSubsystemSchema.CURRENT.getXMLDescription(); @Override public void initialize(ExtensionContext extensionContext) { // Initialize the Netty logger factory or we get horrible stack traces ClassLoader cl = WildFlySecurityManager.getClassLoaderPrivileged(this.getClass()); if (cl instanceof ModuleClassLoader) { ModuleLoader loader = ((ModuleClassLoader) cl).getModule().getModuleLoader(); try { Module module = loader.loadModule("io.netty"); InternalLoggerFactory.setDefaultFactory(JdkLoggerFactory.INSTANCE); } catch (ModuleLoadException e) { // The netty module is not there so don't do anything } } final SubsystemRegistration sr = extensionContext.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION); sr.registerXMLElementWriter(new PersistentResourceXMLDescriptionWriter(this.currentDescription)); final ManagementResourceRegistration root = sr.registerSubsystemModel(new MicroProfileReactiveMessagingSubsystemDefinition()); root.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE, false); } @Override public void initializeParsers(ExtensionParsingContext extensionParsingContext) { for (MicroProfileReactiveMessagingSubsystemSchema schema : EnumSet.allOf(MicroProfileReactiveMessagingSubsystemSchema.class)) { XMLElementReader<List<ModelNode>> reader = (schema == MicroProfileReactiveMessagingSubsystemSchema.CURRENT) ? new PersistentResourceXMLDescriptionReader(this.currentDescription) : schema; extensionParsingContext.setSubsystemXmlMapping(SUBSYSTEM_NAME, schema.getNamespace().getUri(), reader); } } }
5,395
49.90566
199
java
null
wildfly-main/microprofile/reactive-messaging-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/reactive/messaging/MicroProfileReactiveMessagingSubsystemDefinition.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.microprofile.reactive.messaging; import static org.jboss.as.controller.OperationContext.Stage.RUNTIME; import static org.jboss.as.server.deployment.Phase.DEPENDENCIES; import static org.jboss.as.server.deployment.Phase.DEPENDENCIES_MICROPROFILE_REACTIVE_MESSAGING; import static org.wildfly.extension.microprofile.reactive.messaging.MicroProfileReactiveMessagingExtension.REACTIVE_STREAMS_OPERATORS_CAPABILITY_NAME; import static org.wildfly.extension.microprofile.reactive.messaging.MicroProfileReactiveMessagingExtension.SUBSYSTEM_NAME; import static org.wildfly.extension.microprofile.reactive.messaging.MicroProfileReactiveMessagingExtension.SUBSYSTEM_PATH; import static org.wildfly.extension.microprofile.reactive.messaging.MicroProfileReactiveMessagingExtension.WELD_CAPABILITY_NAME; import java.util.Collection; import java.util.Collections; import java.util.ServiceLoader; 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.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; import org.jboss.as.server.AbstractDeploymentChainStep; import org.jboss.as.server.DeploymentProcessorTarget; import org.jboss.dmr.ModelNode; import org.jboss.modules.Module; import org.jboss.modules.ModuleClassLoader; import org.jboss.modules.ModuleLoadException; import org.jboss.modules.ModuleLoader; import org.wildfly.extension.microprofile.reactive.messaging._private.MicroProfileReactiveMessagingLogger; import org.wildfly.extension.microprofile.reactive.messaging.deployment.ReactiveMessagingDependencyProcessor; import org.wildfly.microprofile.reactive.messaging.common.DynamicDeploymentProcessorAdder; import org.wildfly.microprofile.reactive.messaging.config.kafka.ssl.context.ElytronSSLContextRegistry; import org.wildfly.security.manager.WildFlySecurityManager; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ public class MicroProfileReactiveMessagingSubsystemDefinition extends PersistentResourceDefinition { private static final String REACTIVE_MESSAGING_CAPABILITY_NAME = "org.wildfly.microprofile.reactive-messaging"; private static final RuntimeCapability<Void> REACTIVE_STREAMS_OPERATORS_CAPABILITY = RuntimeCapability.Builder .of(REACTIVE_MESSAGING_CAPABILITY_NAME) .addRequirements(WELD_CAPABILITY_NAME) .addRequirements(REACTIVE_STREAMS_OPERATORS_CAPABILITY_NAME) .build(); public MicroProfileReactiveMessagingSubsystemDefinition() { super( new SimpleResourceDefinition.Parameters( SUBSYSTEM_PATH, MicroProfileReactiveMessagingExtension.SUBSYSTEM_RESOLVER) .setAddHandler(new AddHandler()) .setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE) .setCapabilities(REACTIVE_STREAMS_OPERATORS_CAPABILITY) ); } @Override public Collection<AttributeDefinition> getAttributes() { return Collections.emptyList(); } @Override public void registerAdditionalRuntimePackages(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerAdditionalRuntimePackages( RuntimePackageDependency.required("io.reactivex.rxjava2.rxjava"), RuntimePackageDependency.required("io.smallrye.reactive.messaging"), RuntimePackageDependency.required("io.smallrye.reactive.messaging.connector"), RuntimePackageDependency.required("io.vertx.client"), RuntimePackageDependency.required("org.apache.commons.lang3"), RuntimePackageDependency.required("org.eclipse.microprofile.reactive-messaging.api"), RuntimePackageDependency.required("org.wildfly.reactive.messaging.config"), RuntimePackageDependency.required("org.slf4j")); } static class AddHandler extends AbstractBoottimeAddStepHandler { @Override protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { super.performBoottime(context, operation, model); installKafkaElytronSSLContextRegistryServiceIfPresent(context); context.addStep(new AbstractDeploymentChainStep() { @Override public void execute(DeploymentProcessorTarget processorTarget) { processorTarget.addDeploymentProcessor(SUBSYSTEM_NAME, DEPENDENCIES, DEPENDENCIES_MICROPROFILE_REACTIVE_MESSAGING, new ReactiveMessagingDependencyProcessor()); MicroProfileReactiveMessagingLogger.LOGGER.debug("Looking for DynamicDeploymentProcessorAdder implementations"); Module module = ((ModuleClassLoader)WildFlySecurityManager.getClassLoaderPrivileged(this.getClass())).getModule(); ServiceLoader<DynamicDeploymentProcessorAdder> sl = module.loadService(DynamicDeploymentProcessorAdder.class); for (DynamicDeploymentProcessorAdder adder : sl) { MicroProfileReactiveMessagingLogger.LOGGER.debugf("Invoking DynamicDeploymentProcessorAdder implementation: %s", adder); adder.addDeploymentProcessor(processorTarget, SUBSYSTEM_NAME); } } }, RUNTIME); MicroProfileReactiveMessagingLogger.LOGGER.activatingSubsystem(); } private void installKafkaElytronSSLContextRegistryServiceIfPresent(OperationContext context) { ClassLoader cl = WildFlySecurityManager.getClassLoaderPrivileged(this.getClass()); if (cl instanceof ModuleClassLoader) { ModuleLoader loader = ((ModuleClassLoader)cl).getModule().getModuleLoader(); try { loader.loadModule("org.wildfly.reactive.messaging.kafka"); ElytronSSLContextRegistry.setServiceRegistry(context.getServiceRegistry(false)); } catch (ModuleLoadException e) { // Ignore, it means the module is not available so we don't install the service } } } } }
7,755
51.761905
150
java
null
wildfly-main/microprofile/reactive-messaging-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/reactive/messaging/MicroProfileReactiveMessagingSubsystemSchema.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.reactive.messaging; import static org.jboss.as.controller.PersistentResourceXMLDescription.builder; import org.jboss.as.controller.PersistentResourceXMLDescription; import org.jboss.as.controller.PersistentSubsystemSchema; import org.jboss.as.controller.SubsystemSchema; import org.jboss.as.controller.xml.VersionedNamespace; import org.jboss.staxmapper.IntVersion; /** * Enumerates the supported namespaces of the MicroProfile reactive messaging subsystem. * @author Paul Ferraro */ public enum MicroProfileReactiveMessagingSubsystemSchema implements PersistentSubsystemSchema<MicroProfileReactiveMessagingSubsystemSchema> { VERSION_1_0(1), ; static final MicroProfileReactiveMessagingSubsystemSchema CURRENT = VERSION_1_0; private final VersionedNamespace<IntVersion, MicroProfileReactiveMessagingSubsystemSchema> namespace; MicroProfileReactiveMessagingSubsystemSchema(int major) { this.namespace = SubsystemSchema.createSubsystemURN(MicroProfileReactiveMessagingExtension.SUBSYSTEM_NAME, new IntVersion(major)); } @Override public VersionedNamespace<IntVersion, MicroProfileReactiveMessagingSubsystemSchema> getNamespace() { return this.namespace; } @Override public PersistentResourceXMLDescription getXMLDescription() { return builder(MicroProfileReactiveMessagingExtension.SUBSYSTEM_PATH, this.namespace).build(); } }
2,475
40.966102
141
java
null
wildfly-main/microprofile/reactive-messaging-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/reactive/messaging/_private/MicroProfileReactiveMessagingLogger.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.microprofile.reactive.messaging._private; import static org.jboss.logging.Logger.Level.INFO; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.jandex.DotName; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * Log messages for WildFly microprofile-reactive-messaging-smallrye Extension. * * @author <a href="[email protected]">Kabir Khan</a> */ @MessageLogger(projectCode = "WFLYRXMESS", length = 4) public interface MicroProfileReactiveMessagingLogger extends BasicLogger { MicroProfileReactiveMessagingLogger LOGGER = Logger.getMessageLogger(MicroProfileReactiveMessagingLogger.class, "org.wildfly.extension.microprofile.reactive.messaging"); /** * Logs an informational message indicating the subsystem is being activated. */ @LogMessage(level = INFO) @Message(id = 1, value = "Activating MicroProfile Reactive Messaging Subsystem") void activatingSubsystem(); @Message(id = 2, value = "Deployment %s requires use of the '%s' capability but it is not currently registered") DeploymentUnitProcessingException deploymentRequiresCapability(String deploymentName, String capabilityName); @LogMessage(level = INFO) @Message(id = 3, value = "Intermediate module %s is not present. Skipping recursively adding modules from it") void intermediateModuleNotPresent(String intermediateModuleName); @Message(id = 4, value = "Use of -D%s=true is not allowed in this setup") DeploymentUnitProcessingException experimentalPropertyNotAllowed(String experimentalProperty); @Message(id = 5, value = "Use of @%s is not allowed in this setup") DeploymentUnitProcessingException experimentalAnnotationNotAllowed(DotName dotName); }
2,960
43.863636
173
java
null
wildfly-main/microprofile/reactive-messaging-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/reactive/messaging/deployment/ReactiveMessagingDependencyProcessor.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.microprofile.reactive.messaging.deployment; import static org.wildfly.microprofile.reactive.messaging.common.ReactiveMessagingAttachments.IS_REACTIVE_MESSAGING_DEPLOYMENT; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collections; 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.deployment.module.ModuleDependency; import org.jboss.as.server.deployment.module.ModuleSpecification; import org.jboss.jandex.DotName; import org.jboss.modules.DependencySpec; import org.jboss.modules.Module; import org.jboss.modules.ModuleDependencySpec; import org.jboss.modules.ModuleLoadException; import org.jboss.modules.ModuleLoader; import org.wildfly.extension.microprofile.reactive.messaging._private.MicroProfileReactiveMessagingLogger; import org.wildfly.security.manager.WildFlySecurityManager; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ public class ReactiveMessagingDependencyProcessor implements DeploymentUnitProcessor { // TODO Set to false for EAP https://issues.redhat.com/browse/JBEAP-20660 private final boolean allowExperimental = true; private static final String EXPERIMENTAL_PROPERTY = "jboss.as.reactive.messaging.experimental"; private static final List<DotName> REACTIVE_MESSAGING_ANNOTATIONS; private static final List<DotName> BANNED_REACTIVE_MESSAGING_ANNOTATIONS; static { List<DotName> annotations = new ArrayList<>(); String rmPackage = "org.eclipse.microprofile.reactive.messaging."; annotations.add(DotName.createSimple(rmPackage + "Acknowledgment")); annotations.add(DotName.createSimple(rmPackage + "Channel")); annotations.add(DotName.createSimple(rmPackage + "Incoming")); annotations.add(DotName.createSimple(rmPackage + "Outgoing")); annotations.add(DotName.createSimple(rmPackage + "OnOverflow")); REACTIVE_MESSAGING_ANNOTATIONS = Collections.unmodifiableList(annotations); String spiPackage = "org.eclipse.microprofile.reactive.messaging.spi."; annotations.add(DotName.createSimple(spiPackage + "Connector")); annotations.add(DotName.createSimple(spiPackage + "ConnectorAttribute")); annotations.add(DotName.createSimple(spiPackage + "ConnectorAttributes")); List<DotName> banned = new ArrayList<>(); String smallryePackage = "io.smallrye.reactive.messaging.annotations."; banned.add(DotName.createSimple(smallryePackage + "Blocking")); banned.add(DotName.createSimple(smallryePackage + "Broadcast")); banned.add(DotName.createSimple(smallryePackage + "Channel")); banned.add(DotName.createSimple(smallryePackage + "ConnectorAttribute")); banned.add(DotName.createSimple(smallryePackage + "ConnectorAttributes")); banned.add(DotName.createSimple(smallryePackage + "Incomings")); banned.add(DotName.createSimple(smallryePackage + "Merge")); banned.add(DotName.createSimple(smallryePackage + "OnOverflow")); BANNED_REACTIVE_MESSAGING_ANNOTATIONS = Collections.unmodifiableList(banned); } @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (isReactiveMessagingDeployment(deploymentUnit)) { addModuleDependencies(deploymentUnit); deploymentUnit.putAttachment(IS_REACTIVE_MESSAGING_DEPLOYMENT, true); } } 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.reactive-messaging.api", false, false, true, false)); moduleSpecification.addSystemDependency( cdiDependency( new ModuleDependency(moduleLoader, "io.smallrye.reactive.messaging", false, false, true, false))); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, "io.smallrye.config", false, false, true, false)); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, "org.eclipse.microprofile.config.api", false, false, true, false)); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, "io.reactivex.rxjava2.rxjava", false, false, true, false)); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, "io.smallrye.reactive.mutiny.reactive-streams-operators", false, false, true, false)); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, "org.wildfly.reactive.messaging.config", false, false, true, false)); // These are optional über modules that export all the independent connectors/clients. However, it seems // to confuse the ExternalBeanArchiveProcessor which provides the modules to scan for beans, so we // load them and list them all individually instead addDependenciesForIntermediateModule(moduleSpecification, moduleLoader, "io.smallrye.reactive.messaging.connector"); // Provisioned along with the connectors above moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, "io.vertx.client", true, false, true, false)); } private void addDependenciesForIntermediateModule(ModuleSpecification moduleSpecification, ModuleLoader moduleLoader, String intermediateModuleName) { try { Module module = moduleLoader.loadModule(intermediateModuleName); for (DependencySpec dep : module.getDependencies()) { if (dep instanceof ModuleDependencySpec) { ModuleDependencySpec mds = (ModuleDependencySpec) dep; ModuleDependency md = cdiDependency( new ModuleDependency(moduleLoader, mds.getName(), mds.isOptional(), false, true, false)); moduleSpecification.addSystemDependency(md); } } } catch (ModuleLoadException e) { // The module was not provisioned MicroProfileReactiveMessagingLogger.LOGGER.intermediateModuleNotPresent(intermediateModuleName); } } private boolean isReactiveMessagingDeployment(DeploymentUnit deploymentUnit) throws DeploymentUnitProcessingException { final boolean allowExperimentalAnnotations = allowExperimentalAnnotations(); CompositeIndex index = deploymentUnit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX); // Check the experimental annotations first for (DotName dotName : BANNED_REACTIVE_MESSAGING_ANNOTATIONS) { if (!index.getAnnotations(dotName).isEmpty()) { if (allowExperimentalAnnotations) { MicroProfileReactiveMessagingLogger.LOGGER.debugf("Deployment '%s' is a MicroProfile Reactive Messaging deployment – @%s annotation found.", deploymentUnit.getName(), dotName); return true; } else { throw MicroProfileReactiveMessagingLogger.LOGGER.experimentalAnnotationNotAllowed(dotName); } } } for (DotName dotName : REACTIVE_MESSAGING_ANNOTATIONS) { if (!index.getAnnotations(dotName).isEmpty()) { MicroProfileReactiveMessagingLogger.LOGGER.debugf("Deployment '%s' is a MicroProfile Reactive Messaging deployment – @%s annotation found.", deploymentUnit.getName(), dotName); return true; } } MicroProfileReactiveMessagingLogger.LOGGER.debugf("Deployment '%s' is not a MicroProfile Reactive Messaging deployment.", deploymentUnit.getName()); return false; } private ModuleDependency cdiDependency(ModuleDependency moduleDependency) { // This is needed following https://issues.redhat.com/browse/WFLY-13641 / https://github.com/wildfly/wildfly/pull/13406 moduleDependency.addImportFilter(s -> s.equals("META-INF"), true); return moduleDependency; } private boolean allowExperimentalAnnotations() throws DeploymentUnitProcessingException { final boolean experimental; if (WildFlySecurityManager.isChecking()) { experimental = WildFlySecurityManager.doChecked((PrivilegedAction<Boolean>) () -> Boolean.getBoolean(EXPERIMENTAL_PROPERTY)); } else { experimental = Boolean.getBoolean(EXPERIMENTAL_PROPERTY); } if (experimental && !allowExperimental) { throw MicroProfileReactiveMessagingLogger.LOGGER.experimentalPropertyNotAllowed(EXPERIMENTAL_PROPERTY); } return experimental; } }
10,344
54.026596
196
java
null
wildfly-main/microprofile/reactive-messaging-smallrye/config/src/main/java/org/wildfly/microprofile/reactive/messaging/config/ReactiveMessagingConfigSource.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.microprofile.reactive.messaging.config; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.eclipse.microprofile.config.Config; import org.eclipse.microprofile.config.spi.ConfigSource; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ public class ReactiveMessagingConfigSource implements ConfigSource { private static final String NAME = ReactiveMessagingConfigSource.class.getName(); private static final Map<String, String> PROPERTIES; static { Map<String, String> map = new HashMap<>(); map.put("mp.messaging.connector.smallrye-kafka.tracing-enabled", "false"); map.put("smallrye-messaging-strict-binding", "true"); PROPERTIES = Collections.unmodifiableMap(map); } private final Map<String, String> properties; public ReactiveMessagingConfigSource() { properties = new ConcurrentHashMap<>(); properties.putAll(PROPERTIES); } @Override public Map<String, String> getProperties() { return properties; } @Override public String getValue(String propertyName) { return properties.get(propertyName); } @Override public String getName() { return NAME; } @Override public int getOrdinal() { // Make the ordinal high so it cannot be overridden return Integer.MAX_VALUE; } @Override public Set<String> getPropertyNames() { return properties.keySet(); } /** * Adds properties to the {@code ReactiveMessagingConfigSource} instance in the deployment's overall * {@code Config} * * @param config the deployment's {@code Config} * @param properties the properties we want to add */ public static void addProperties(Config config, Map<String, String> properties) { for (ConfigSource source : config.getConfigSources()) { if (source.getName().equals(NAME) && source instanceof ReactiveMessagingConfigSource) { // We have found the instance of this class in the Config, and add our properties here ((ReactiveMessagingConfigSource)source).properties.putAll(properties); } } } }
3,346
33.153061
104
java
null
wildfly-main/microprofile/reactive-messaging-smallrye/common/src/main/java/org/wildfly/microprofile/reactive/messaging/common/ReactiveMessagingAttachments.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.microprofile.reactive.messaging.common; import org.jboss.as.server.deployment.AttachmentKey; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ public class ReactiveMessagingAttachments { public static AttachmentKey<Boolean> IS_REACTIVE_MESSAGING_DEPLOYMENT = AttachmentKey.create(Boolean.class); }
1,370
40.545455
112
java
null
wildfly-main/microprofile/reactive-messaging-smallrye/common/src/main/java/org/wildfly/microprofile/reactive/messaging/common/DynamicDeploymentProcessorAdder.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.microprofile.reactive.messaging.common; import org.jboss.as.server.DeploymentProcessorTarget; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ public interface DynamicDeploymentProcessorAdder { void addDeploymentProcessor(DeploymentProcessorTarget target, String subsystemName); }
1,354
40.060606
88
java
null
wildfly-main/microprofile/reactive-streams-operators-smallrye/extension/src/test/java/org/wildfly/extension/microprofile/reactive/streams/operators/MicroprofileReactiveStreamsOperatorsSubsystemTestCase.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.microprofile.reactive.streams.operators; import static org.wildfly.extension.microprofile.reactive.streams.operators.MicroProfileReactiveStreamsOperatorsExtension.WELD_CAPABILITY_NAME; import java.util.EnumSet; import org.jboss.as.subsystem.test.AbstractSubsystemSchemaTest; import org.jboss.as.subsystem.test.AdditionalInitialization; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @RunWith(Parameterized.class) public class MicroprofileReactiveStreamsOperatorsSubsystemTestCase extends AbstractSubsystemSchemaTest<MicroProfileReactiveStreamsOperatorsSubsystemSchema> { @Parameters public static Iterable<MicroProfileReactiveStreamsOperatorsSubsystemSchema> parameters() { return EnumSet.allOf(MicroProfileReactiveStreamsOperatorsSubsystemSchema.class); } public MicroprofileReactiveStreamsOperatorsSubsystemTestCase(MicroProfileReactiveStreamsOperatorsSubsystemSchema schema) { super(MicroProfileReactiveStreamsOperatorsExtension.SUBSYSTEM_NAME, new MicroProfileReactiveStreamsOperatorsExtension(), schema, MicroProfileReactiveStreamsOperatorsSubsystemSchema.CURRENT); } @Override protected AdditionalInitialization createAdditionalInitialization() { return AdditionalInitialization.withCapabilities(WELD_CAPABILITY_NAME); } }
2,494
45.203704
198
java
null
wildfly-main/microprofile/reactive-streams-operators-smallrye/extension/src/test/java/org/wildfly/extension/microprofile/reactive/streams/operators/ReactiveOperatorsSanityTest.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.microprofile.reactive.streams.operators; import java.util.List; import java.util.concurrent.CompletionStage; import java.util.stream.Collectors; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; import org.junit.Assert; import org.junit.Test; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ public class ReactiveOperatorsSanityTest { @Test public void testReactiveApi() throws Exception { CompletionStage<List<String>> cs = ReactiveStreams.of("this", "is", "only", "a", "test") .map(String::toUpperCase) // Transform the words .filter(s -> s.length() > 3) // Filter items .collect(Collectors.toList()) .run(); List<String> result = cs.toCompletableFuture().get(); Assert.assertEquals(3, result.size()); Assert.assertEquals("THIS", result.get(0)); Assert.assertEquals("ONLY", result.get(1)); Assert.assertEquals("TEST", result.get(2)); } }
2,072
38.113208
96
java
null
wildfly-main/microprofile/reactive-streams-operators-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/reactive/streams/operators/MicroProfileReactiveStreamsOperatorsSubsystemSchema.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.reactive.streams.operators; import static org.jboss.as.controller.PersistentResourceXMLDescription.builder; import org.jboss.as.controller.PersistentResourceXMLDescription; import org.jboss.as.controller.PersistentSubsystemSchema; import org.jboss.as.controller.SubsystemSchema; import org.jboss.as.controller.xml.VersionedNamespace; import org.jboss.staxmapper.IntVersion; /** * Enumerates the supported namespaces of the MicroProfile reactive streams operators subsystem. * @author Paul Ferraro */ public enum MicroProfileReactiveStreamsOperatorsSubsystemSchema implements PersistentSubsystemSchema<MicroProfileReactiveStreamsOperatorsSubsystemSchema> { VERSION_1_0(1), ; static final MicroProfileReactiveStreamsOperatorsSubsystemSchema CURRENT = VERSION_1_0; private final VersionedNamespace<IntVersion, MicroProfileReactiveStreamsOperatorsSubsystemSchema> namespace; MicroProfileReactiveStreamsOperatorsSubsystemSchema(int major) { this.namespace = SubsystemSchema.createSubsystemURN(MicroProfileReactiveStreamsOperatorsExtension.SUBSYSTEM_NAME, new IntVersion(major)); } @Override public VersionedNamespace<IntVersion, MicroProfileReactiveStreamsOperatorsSubsystemSchema> getNamespace() { return this.namespace; } @Override public PersistentResourceXMLDescription getXMLDescription() { return builder(MicroProfileReactiveStreamsOperatorsExtension.SUBSYSTEM_PATH, this.namespace).build(); } }
2,547
42.186441
155
java
null
wildfly-main/microprofile/reactive-streams-operators-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/reactive/streams/operators/MicroProfileReactiveStreamsOperatorsExtension.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.microprofile.reactive.streams.operators; 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; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ public class MicroProfileReactiveStreamsOperatorsExtension implements Extension { /** * The name of our subsystem within the model. */ public static final String SUBSYSTEM_NAME = "microprofile-reactive-streams-operators-smallrye"; protected static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME); static final String WELD_CAPABILITY_NAME = "org.wildfly.weld"; static final ParentResourceDescriptionResolver SUBSYSTEM_RESOLVER = new SubsystemResourceDescriptionResolver(SUBSYSTEM_NAME, MicroProfileReactiveStreamsOperatorsExtension.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 = MicroProfileReactiveStreamsOperatorsSubsystemSchema.CURRENT.getXMLDescription(); @Override public void initialize(ExtensionContext extensionContext) { final SubsystemRegistration sr = extensionContext.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION); sr.registerXMLElementWriter(new PersistentResourceXMLDescriptionWriter(this.currentDescription)); final ManagementResourceRegistration root = sr.registerSubsystemModel(new MicroProfileReactiveStreamsOperatorsSubsystemDefinition()); root.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE, false); } @Override public void initializeParsers(ExtensionParsingContext context) { for (MicroProfileReactiveStreamsOperatorsSubsystemSchema schema : EnumSet.allOf(MicroProfileReactiveStreamsOperatorsSubsystemSchema.class)) { XMLElementReader<List<ModelNode>> reader = (schema == MicroProfileReactiveStreamsOperatorsSubsystemSchema.CURRENT) ? new PersistentResourceXMLDescriptionReader(this.currentDescription) : schema; context.setSubsystemXmlMapping(SUBSYSTEM_NAME, schema.getNamespace().getUri(), reader); } } }
4,276
50.53012
206
java
null
wildfly-main/microprofile/reactive-streams-operators-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/reactive/streams/operators/MicroProfileReactiveStreamsOperatorsSubsystemDefinition.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.microprofile.reactive.streams.operators; import static org.jboss.as.controller.OperationContext.Stage.RUNTIME; import static org.jboss.as.server.deployment.Phase.DEPENDENCIES; import static org.jboss.as.server.deployment.Phase.DEPENDENCIES_MICROPROFILE_REACTIVE_STREAMS_OPERATORS; import java.util.Collection; import java.util.Collections; 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.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; import org.jboss.as.server.AbstractDeploymentChainStep; import org.jboss.as.server.DeploymentProcessorTarget; import org.jboss.dmr.ModelNode; import org.wildfly.extension.microprofile.reactive.streams.operators._private.MicroProfileReactiveStreamsOperatorsLogger; import org.wildfly.extension.microprofile.reactive.streams.operators.deployment.ReactiveStreamsOperatorsDependencyProcessor; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ public class MicroProfileReactiveStreamsOperatorsSubsystemDefinition extends PersistentResourceDefinition { private static final String REACTIVE_STREAMS_OPERATORS_CAPABILITY_NAME = "org.wildfly.microprofile.reactive-streams-operators"; private static final RuntimeCapability<Void> REACTIVE_STREAMS_OPERATORS_CAPABILITY = RuntimeCapability.Builder .of(REACTIVE_STREAMS_OPERATORS_CAPABILITY_NAME) .addRequirements(MicroProfileReactiveStreamsOperatorsExtension.WELD_CAPABILITY_NAME) .build(); public MicroProfileReactiveStreamsOperatorsSubsystemDefinition() { super( new SimpleResourceDefinition.Parameters( MicroProfileReactiveStreamsOperatorsExtension.SUBSYSTEM_PATH, MicroProfileReactiveStreamsOperatorsExtension.SUBSYSTEM_RESOLVER) .setAddHandler(new AddHandler()) .setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE) .setCapabilities(REACTIVE_STREAMS_OPERATORS_CAPABILITY) ); } @Override public void registerAdditionalRuntimePackages(ManagementResourceRegistration resourceRegistration) { // Set up the dependencies needed by the deployments resourceRegistration.registerAdditionalRuntimePackages( RuntimePackageDependency.required("io.smallrye.reactive.mutiny.reactive-streams-operators"), RuntimePackageDependency.required("org.wildfly.reactive.mutiny.reactive-streams-operators.cdi-provider"), RuntimePackageDependency.required("org.wildfly.security.manager") ); } @Override public Collection<AttributeDefinition> getAttributes() { return Collections.emptyList(); } static class AddHandler extends AbstractBoottimeAddStepHandler { @Override protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { super.performBoottime(context, operation, model); context.addStep(new AbstractDeploymentChainStep() { @Override public void execute(DeploymentProcessorTarget processorTarget) { processorTarget.addDeploymentProcessor(MicroProfileReactiveStreamsOperatorsExtension.SUBSYSTEM_NAME, DEPENDENCIES, DEPENDENCIES_MICROPROFILE_REACTIVE_STREAMS_OPERATORS, new ReactiveStreamsOperatorsDependencyProcessor()); } }, RUNTIME); MicroProfileReactiveStreamsOperatorsLogger.LOGGER.activatingSubsystem(); } } }
5,084
48.368932
240
java
null
wildfly-main/microprofile/reactive-streams-operators-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/reactive/streams/operators/_private/MicroProfileReactiveStreamsOperatorsLogger.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.microprofile.reactive.streams.operators._private; import static org.jboss.logging.Logger.Level.INFO; 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; /** * Log messages for WildFly microprofile-reactive-messaging-smallrye Extension. * * @author <a href="[email protected]">Kabir Khan</a> */ @MessageLogger(projectCode = "WFLYRXSTOPS", length = 4) public interface MicroProfileReactiveStreamsOperatorsLogger extends BasicLogger { MicroProfileReactiveStreamsOperatorsLogger LOGGER = Logger.getMessageLogger(MicroProfileReactiveStreamsOperatorsLogger.class, "org.wildfly.extension.microprofile.reactive.streams.operators"); /** * Logs an informational message indicating the subsystem is being activated. */ @LogMessage(level = INFO) @Message(id = 1, value = "Activating MicroProfile Reactive Streams Operators Subsystem") void activatingSubsystem(); @Message(id = 2, value = "Deployment %s requires use of the '%s' capability but it is not currently registered") DeploymentUnitProcessingException deploymentRequiresCapability(String deploymentName, String capabilityName); }
2,417
42.963636
195
java
null
wildfly-main/microprofile/reactive-streams-operators-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/reactive/streams/operators/deployment/ReactiveStreamsOperatorsDependencyProcessor.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.microprofile.reactive.streams.operators.deployment; 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.modules.Module; import org.jboss.modules.ModuleLoader; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ public class ReactiveStreamsOperatorsDependencyProcessor implements DeploymentUnitProcessor { @Override public void deploy(DeploymentPhaseContext phaseContext) { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); addModuleDependencies(deploymentUnit); } 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.reactive-streams-operators.core", false, false, true, false)); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, "org.eclipse.microprofile.reactive-streams-operators.api", false, false, true, false)); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, "org.reactivestreams", false, false, true, false)); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, "io.smallrye.reactive.mutiny.reactive-streams-operators", false, false, true, false)); ModuleDependency moduleDependency = cdiDependency(new ModuleDependency(moduleLoader, "org.wildfly.reactive.mutiny.reactive-streams-operators.cdi-provider", false, false, true, false)); moduleSpecification.addSystemDependency(moduleDependency); // Converters moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, "io.smallrye.reactive.converters.api", true, false, false, false)); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, "io.smallrye.reactive.converters.rxjava2", true, false, true, false)); } private ModuleDependency cdiDependency(ModuleDependency moduleDependency) { // This is needed following https://issues.redhat.com/browse/WFLY-13641 / https://github.com/wildfly/wildfly/pull/13406 moduleDependency.addImportFilter(s -> s.equals("META-INF"), true); return moduleDependency; } }
3,748
50.356164
192
java
null
wildfly-main/microprofile/reactive-streams-operators-smallrye/cdi-provider/src/main/java/org/wildfly/extension/microprofile/reactive/streams/operators/cdi/ReactiveEngineProvider.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.microprofile.reactive.streams.operators.cdi; import static org.wildfly.extension.microprofile.reactive.streams.operators.cdi._private.CdiProviderLogger.LOGGER; import java.util.Iterator; import java.util.ServiceLoader; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.context.Dependent; import jakarta.enterprise.inject.Produces; import org.eclipse.microprofile.reactive.streams.operators.spi.ReactiveStreamsEngine; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @Dependent public class ReactiveEngineProvider { /** * @return the reactive stream engine. It uses {@link ServiceLoader#load(Class)} to find an implementation from the * Classpath. * @throws IllegalStateException if no implementations are found. */ @Produces @ApplicationScoped public ReactiveStreamsEngine getEngine() { Iterator<ReactiveStreamsEngine> iterator = ServiceLoader.load(ReactiveStreamsEngine.class).iterator(); if (iterator.hasNext()) { return iterator.next(); } throw LOGGER.noImplementationFound(ReactiveStreamsEngine.class.getName()); } }
2,225
38.052632
119
java
null
wildfly-main/microprofile/reactive-streams-operators-smallrye/cdi-provider/src/main/java/org/wildfly/extension/microprofile/reactive/streams/operators/cdi/_private/CdiProviderLogger.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.microprofile.reactive.streams.operators.cdi._private; 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-health-smallrye Extension. * * @author <a href="[email protected]">Kabir Khan</a> */ @MessageLogger(projectCode = "WFLYRXSTOPSCDI", length = 4) public interface CdiProviderLogger extends BasicLogger { CdiProviderLogger LOGGER = Logger.getMessageLogger(CdiProviderLogger.class, "org.wildfly.extension.microprofile.reactive.streams.operators.cdi"); @Message(id = 1, value = "No implementation of the %s found in the classpath") IllegalStateException noImplementationFound(String className); }
1,832
40.659091
149
java
null
wildfly-main/microprofile/openapi-smallrye/src/test/java/org/wildfly/extension/microprofile/openapi/MicroProfileOpenAPISubsystemTestCase.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.microprofile.openapi; import java.util.EnumSet; import org.jboss.as.subsystem.test.AbstractSubsystemSchemaTest; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * Unit test for MicroProfile OpenAPI subsystem. * @author Paul Ferraro */ @RunWith(value = Parameterized.class) public class MicroProfileOpenAPISubsystemTestCase extends AbstractSubsystemSchemaTest<MicroProfileOpenAPISubsystemSchema> { @Parameters public static Iterable<MicroProfileOpenAPISubsystemSchema> parameters() { return EnumSet.allOf(MicroProfileOpenAPISubsystemSchema.class); } public MicroProfileOpenAPISubsystemTestCase(MicroProfileOpenAPISubsystemSchema schema) { super(MicroProfileOpenAPIExtension.SUBSYSTEM_NAME, new MicroProfileOpenAPIExtension(), schema, MicroProfileOpenAPISubsystemSchema.CURRENT); } }
1,957
41.565217
147
java
null
wildfly-main/microprofile/openapi-smallrye/src/main/java/org/wildfly/extension/microprofile/openapi/MicroProfileOpenAPISubsystemModel.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.microprofile.openapi; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.SubsystemModel; /** * Enumeration of MicroProfile OpenAPI subsystem model versions. * @author Paul Ferraro */ public enum MicroProfileOpenAPISubsystemModel implements SubsystemModel { VERSION_1_0_0(1, 0, 0), // WildFly 19 ; static final MicroProfileOpenAPISubsystemModel CURRENT = VERSION_1_0_0; private final ModelVersion version; MicroProfileOpenAPISubsystemModel(int major, int minor, int micro) { this.version = ModelVersion.create(major, minor, micro); } @Override public ModelVersion getVersion() { return this.version; } }
1,742
35.3125
75
java
null
wildfly-main/microprofile/openapi-smallrye/src/main/java/org/wildfly/extension/microprofile/openapi/MicroProfileOpenAPISubsystemDefinition.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.microprofile.openapi; import org.jboss.as.clustering.controller.DeploymentChainContributingResourceRegistrar; import org.jboss.as.clustering.controller.ResourceDescriptor; import org.jboss.as.clustering.controller.SubsystemRegistration; import org.jboss.as.clustering.controller.SubsystemResourceDefinition; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler; import org.jboss.as.controller.registry.ManagementResourceRegistration; /** * Root resource definition for MicroProfile Open API subsystem * @author Michael Edgar */ public class MicroProfileOpenAPISubsystemDefinition extends SubsystemResourceDefinition { static final PathElement PATH = PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, MicroProfileOpenAPIExtension.SUBSYSTEM_NAME); enum Capability implements org.jboss.as.clustering.controller.Capability { MICROPROFILE_OPENAPI("org.wildfly.microprofile.openapi"), ; private final RuntimeCapability<Void> definition; Capability(String name) { this.definition = RuntimeCapability.Builder.of(name) .addRequirements("org.wildfly.microprofile.config") .build(); } @Override public RuntimeCapability<?> getDefinition() { return this.definition; } } MicroProfileOpenAPISubsystemDefinition() { super(PATH, MicroProfileOpenAPIExtension.SUBSYSTEM_RESOLVER); } @Override public void register(SubsystemRegistration parent) { ManagementResourceRegistration registration = parent.registerSubsystemModel(this); registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE); ResourceDescriptor descriptor = new ResourceDescriptor(this.getResourceDescriptionResolver()) .addCapabilities(Capability.class) ; MicroProfileOpenAPIServiceHandler handler = new MicroProfileOpenAPIServiceHandler(); new DeploymentChainContributingResourceRegistrar(descriptor, handler, handler).register(registration); } }
3,379
44.066667
142
java
null
wildfly-main/microprofile/openapi-smallrye/src/main/java/org/wildfly/extension/microprofile/openapi/MicroProfileOpenAPISubsystemSchema.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.microprofile.openapi; 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; /** * Enumeration of MicroProfile OpenAPI subsystem schema versions. * @author Paul Ferraro */ public enum MicroProfileOpenAPISubsystemSchema implements PersistentSubsystemSchema<MicroProfileOpenAPISubsystemSchema> { VERSION_1_0(1, 0), // WildFly 19 ; static final MicroProfileOpenAPISubsystemSchema CURRENT = VERSION_1_0; private final VersionedNamespace<IntVersion, MicroProfileOpenAPISubsystemSchema> namespace; MicroProfileOpenAPISubsystemSchema(int major, int minor) { this.namespace = SubsystemSchema.createSubsystemURN(MicroProfileOpenAPIExtension.SUBSYSTEM_NAME, new IntVersion(major, minor)); } @Override public VersionedNamespace<IntVersion, MicroProfileOpenAPISubsystemSchema> getNamespace() { return this.namespace; } @Override public PersistentResourceXMLDescription getXMLDescription() { return builder(MicroProfileOpenAPISubsystemDefinition.PATH, this.namespace).build(); } }
2,396
39.627119
135
java
null
wildfly-main/microprofile/openapi-smallrye/src/main/java/org/wildfly/extension/microprofile/openapi/MicroProfileOpenAPIExtension.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.microprofile.openapi; import org.jboss.as.clustering.controller.PersistentSubsystemExtension; import org.jboss.as.controller.Extension; import org.jboss.as.controller.descriptions.ParentResourceDescriptionResolver; import org.jboss.as.controller.descriptions.SubsystemResourceDescriptionResolver; import org.kohsuke.MetaInfServices; /** * Extension that provides the MicroProfile OpenAPI subsystem. * @author Michael Edgar * @author Paul Ferraro */ @MetaInfServices(Extension.class) public class MicroProfileOpenAPIExtension extends PersistentSubsystemExtension<MicroProfileOpenAPISubsystemSchema> { static final String SUBSYSTEM_NAME = "microprofile-openapi-smallrye"; static final ParentResourceDescriptionResolver SUBSYSTEM_RESOLVER = new SubsystemResourceDescriptionResolver(SUBSYSTEM_NAME, MicroProfileOpenAPIExtension.class); public MicroProfileOpenAPIExtension() { super(SUBSYSTEM_NAME, MicroProfileOpenAPISubsystemModel.CURRENT, MicroProfileOpenAPISubsystemDefinition::new, MicroProfileOpenAPISubsystemSchema.CURRENT); } }
2,116
46.044444
165
java
null
wildfly-main/microprofile/openapi-smallrye/src/main/java/org/wildfly/extension/microprofile/openapi/MicroProfileOpenAPIServiceHandler.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.microprofile.openapi; import java.util.function.Consumer; import org.jboss.as.clustering.controller.ResourceServiceHandler; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.server.DeploymentProcessorTarget; import org.jboss.as.server.deployment.Phase; import org.jboss.dmr.ModelNode; import org.wildfly.extension.microprofile.openapi.deployment.OpenAPIDependencyProcessor; import org.wildfly.extension.microprofile.openapi.deployment.OpenAPIDocumentProcessor; import org.wildfly.extension.microprofile.openapi.logging.MicroProfileOpenAPILogger; /** * @author Paul Ferraro */ public class MicroProfileOpenAPIServiceHandler implements ResourceServiceHandler, Consumer<DeploymentProcessorTarget> { @Override public void installServices(OperationContext context, ModelNode model) throws OperationFailedException { MicroProfileOpenAPILogger.LOGGER.activatingSubsystem(); } @Override public void removeServices(OperationContext context, ModelNode model) throws OperationFailedException { } @Override public void accept(DeploymentProcessorTarget target) { target.addDeploymentProcessor(MicroProfileOpenAPIExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_MICROPROFILE_OPENAPI, new OpenAPIDependencyProcessor()); target.addDeploymentProcessor(MicroProfileOpenAPIExtension.SUBSYSTEM_NAME, Phase.INSTALL, Phase.POST_MODULE_MICROPROFILE_OPENAPI, new OpenAPIDocumentProcessor()); } }
2,586
44.385965
178
java
null
wildfly-main/microprofile/openapi-smallrye/src/main/java/org/wildfly/extension/microprofile/openapi/logging/MicroProfileOpenAPILogger.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.microprofile.openapi.logging; import static org.jboss.logging.Logger.Level.INFO; import static org.jboss.logging.Logger.Level.WARN; import java.io.IOException; import java.util.Set; 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 microprofile-openapi-smallrye subsystem. * * @author Michael Edgar */ @MessageLogger(projectCode = "WFLYMPOAI", length = 4) public interface MicroProfileOpenAPILogger extends BasicLogger { MicroProfileOpenAPILogger LOGGER = Logger.getMessageLogger(MicroProfileOpenAPILogger.class, "org.wildfly.extension.microprofile.openapi.smallrye"); @LogMessage(level = INFO) @Message(id = 1, value = "Activating MicroProfile OpenAPI Subsystem") void activatingSubsystem(); @Message(id = 2, value = "Failed to load OpenAPI '%s' from deployment '%s'") IllegalArgumentException failedToLoadStaticFile(@Cause IOException e, String fileName, String deploymentName); @LogMessage(level = WARN) @Message(id = 3, value = "MicroProfile OpenAPI endpoint already registered for host '%s'. Skipping OpenAPI documentation of '%s'.") void endpointAlreadyRegistered(String hostName, String deployment); @LogMessage(level = INFO) @Message(id = 4, value = "Registered MicroProfile OpenAPI endpoint '%s' for host '%s'") void endpointRegistered(String path, String hostName); @LogMessage(level = INFO) @Message(id = 5, value = "Unregistered MicroProfile OpenAPI endpoint '%s' for host '%s'") void endpointUnregistered(String path, String hostName); @LogMessage(level = WARN) @Message(id = 6, value = "\u00A75.1 of MicroProfile OpenAPI specification requires that the endpoint be accessible via %2$s, but no such listeners exists for server '%1$s'.") void requiredListenersNotFound(String serverName, Set<String> requisiteSchemes); @LogMessage(level = WARN) @Message(id = 7, value = "\u00A75.1 of MicroProfile OpenAPI specification requires documentation to be available at '%3$s', but '%1$s' is configured to use '%2$s'") void nonStandardEndpoint(String deploymentName, String deploymentEndpoint, String standardEndpoint); @LogMessage(level = INFO) @Message(id = 8, value = "MicroProfile OpenAPI documentation disabled for '%s'") void disabled(String deploymentName); }
3,579
45.493506
178
java
null
wildfly-main/microprofile/openapi-smallrye/src/main/java/org/wildfly/extension/microprofile/openapi/deployment/OpenAPIDependencyProcessor.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.microprofile.openapi.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.as.server.deployment.module.ModuleDependency; import org.jboss.as.server.deployment.module.ModuleSpecification; import org.jboss.modules.Module; import org.jboss.modules.ModuleLoader; /** * Adds MicroProfile OpenAPI dependencies to deployment. * * @author Michael Edgar * @author Paul Ferraro */ public class OpenAPIDependencyProcessor implements DeploymentUnitProcessor { @Override public void deploy(DeploymentPhaseContext context) { DeploymentUnit unit = context.getDeploymentUnit(); if (DeploymentTypeMarker.isType(DeploymentType.WAR, unit)) { ModuleSpecification specification = unit.getAttachment(Attachments.MODULE_SPECIFICATION); ModuleLoader loader = Module.getBootModuleLoader(); specification.addSystemDependency(new ModuleDependency(loader, "org.eclipse.microprofile.openapi.api", false, false, false, false)); } } }
2,348
41.709091
144
java
null
wildfly-main/microprofile/openapi-smallrye/src/main/java/org/wildfly/extension/microprofile/openapi/deployment/OpenAPIDocumentBuilder.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.microprofile.openapi.deployment; import org.eclipse.microprofile.openapi.OASFilter; import org.eclipse.microprofile.openapi.models.OpenAPI; import io.smallrye.openapi.api.OpenApiConfig; import io.smallrye.openapi.api.OpenApiDocument; /** * Builder facade to workaround singleton nature of {@link OpenApiDocument}. * @author Michael Edgar */ public class OpenAPIDocumentBuilder { private OpenApiConfig config; private OpenAPI annotationsModel; private OpenAPI readerModel; private OpenAPI staticFileModel; private OASFilter filter; private String archiveName; public OpenAPIDocumentBuilder config(OpenApiConfig config) { this.config = config; return this; } public OpenAPIDocumentBuilder archiveName(String archiveName) { this.archiveName = archiveName; return this; } public OpenAPIDocumentBuilder staticFileModel(OpenAPI staticFileModel) { this.staticFileModel = staticFileModel; return this; } public OpenAPIDocumentBuilder annotationsModel(OpenAPI annotationsModel) { this.annotationsModel = annotationsModel; return this; } public OpenAPIDocumentBuilder readerModel(OpenAPI readerModel) { this.readerModel = readerModel; return this; } public OpenAPIDocumentBuilder filter(OASFilter filter) { this.filter = filter; return this; } public OpenAPI build() { OpenAPI result = null; OpenApiDocument instance = OpenApiDocument.INSTANCE; synchronized (instance) { instance.reset(); instance.config(this.config); instance.modelFromReader(this.readerModel); instance.modelFromStaticFile(this.staticFileModel); instance.modelFromAnnotations(this.annotationsModel); instance.filter(this.filter); instance.archiveName(this.archiveName); instance.initialize(); result = instance.get(); // Release statically referenced intermediate objects instance.reset(); } return result; } }
3,189
32.229167
78
java
null
wildfly-main/microprofile/openapi-smallrye/src/main/java/org/wildfly/extension/microprofile/openapi/deployment/OpenAPIDocumentProcessor.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.microprofile.openapi.deployment; import java.util.Arrays; import java.util.EnumMap; import java.util.EnumSet; import java.util.List; import java.util.Map; import org.eclipse.microprofile.config.Config; import org.eclipse.microprofile.config.ConfigProvider; 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.dmr.ModelNode; import org.jboss.msc.service.DuplicateServiceException; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.jboss.vfs.VirtualFile; import org.wildfly.extension.microprofile.openapi.logging.MicroProfileOpenAPILogger; import org.wildfly.extension.undertow.DeploymentDefinition; import org.wildfly.extension.undertow.UndertowExtension; import io.smallrye.openapi.api.OpenApiConfig; import io.smallrye.openapi.api.OpenApiConfigImpl; import io.smallrye.openapi.runtime.io.Format; /** * Processes the Open API model for a deployment. * @author Michael Edgar * @author Paul Ferraro */ public class OpenAPIDocumentProcessor implements DeploymentUnitProcessor { private static final String ENABLED = "mp.openapi.extensions.enabled"; @Override public void deploy(DeploymentPhaseContext context) throws DeploymentUnitProcessingException { DeploymentUnit unit = context.getDeploymentUnit(); if (DeploymentTypeMarker.isType(DeploymentType.WAR, unit)) { DeploymentConfiguration configuration = new DeploymentOpenAPIConfiguration(unit); OpenApiConfig config = configuration.getOpenApiConfig(); if (!configuration.getProperty(ENABLED, Boolean.TRUE).booleanValue()) { MicroProfileOpenAPILogger.LOGGER.disabled(unit.getName()); return; } // The MicroProfile OpenAPI specification expects the container to register an OpenAPI endpoint if any of the following conditions are met: // * An OASModelReader was configured // * An OASFilter was configured // * A static OpenAPI file is present // * Application contains Jakarta RESTful Web Services if ((config.modelReader() != null) || (config.filter() != null) || (configuration.getStaticFile() != null) || isRestful(unit)) { ServiceTarget target = context.getServiceTarget(); OpenAPIModelServiceConfigurator configurator = new OpenAPIModelServiceConfigurator(unit, configuration); ServiceName modelServiceName = configurator.getServiceName(); try { // Only one deployment can register the same OpenAPI endpoint with a given host // Let the first one to register win if (context.getServiceRegistry().getService(modelServiceName) != null) { throw new DuplicateServiceException(modelServiceName.getCanonicalName()); } configurator.build(target).install(); new OpenAPIHttpHandlerServiceConfigurator(configurator).build(target).install(); } catch (DuplicateServiceException e) { MicroProfileOpenAPILogger.LOGGER.endpointAlreadyRegistered(configuration.getHostName(), unit.getName()); } } } } private static boolean isRestful(DeploymentUnit unit) { CompositeIndex index = unit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX); for (JaxrsAnnotations annotation : EnumSet.allOf(JaxrsAnnotations.class)) { if (!index.getAnnotations(annotation.getDotName()).isEmpty()) { return true; } } return false; } private static class DeploymentOpenAPIConfiguration implements DeploymentConfiguration { private static final Map<Format, List<String>> STATIC_FILES = new EnumMap<>(Format.class); static { // Order resource names by search order STATIC_FILES.put(Format.YAML, Arrays.asList( "/META-INF/openapi.yaml", "/WEB-INF/classes/META-INF/openapi.yaml", "/META-INF/openapi.yml", "/WEB-INF/classes/META-INF/openapi.yml")); STATIC_FILES.put(Format.JSON, Arrays.asList( "/META-INF/openapi.json", "/WEB-INF/classes/META-INF/openapi.json")); } private static Map.Entry<VirtualFile, Format> findStaticFile(VirtualFile root) { // Format search order for (Format format : EnumSet.of(Format.YAML, Format.JSON)) { for (String resource : STATIC_FILES.get(format)) { VirtualFile file = root.getChild(resource); if (file.exists()) { return Map.entry(file, format); } } } return null; } private final Config config; private final OpenApiConfig openApiConfig; private final Map.Entry<VirtualFile, Format> staticFile; private final String serverName; private final String hostName; DeploymentOpenAPIConfiguration(DeploymentUnit unit) { this.config = ConfigProvider.getConfig(unit.getAttachment(Attachments.MODULE).getClassLoader()); this.openApiConfig = OpenApiConfigImpl.fromConfig(this.config); this.staticFile = findStaticFile(unit.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot()); // Fetch server/host as determined by Undertow DUP ModelNode model = unit.getAttachment(Attachments.DEPLOYMENT_RESOURCE_SUPPORT).getDeploymentSubsystemModel(UndertowExtension.SUBSYSTEM_NAME); this.serverName = model.get(DeploymentDefinition.SERVER.getName()).asString(); this.hostName = model.get(DeploymentDefinition.VIRTUAL_HOST.getName()).asString(); } @SuppressWarnings("unchecked") @Override public <T> T getProperty(String name, T defaultValue) { return this.config.getOptionalValue(name, (Class<T>) defaultValue.getClass()).orElse(defaultValue); } @Override public OpenApiConfig getOpenApiConfig() { return this.openApiConfig; } @Override public Map.Entry<VirtualFile, Format> getStaticFile() { return this.staticFile; } @Override public String getServerName() { return this.serverName; } @Override public String getHostName() { return this.hostName; } } }
8,124
42.918919
152
java
null
wildfly-main/microprofile/openapi-smallrye/src/main/java/org/wildfly/extension/microprofile/openapi/deployment/DeploymentConfiguration.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.openapi.deployment; import java.util.Map; import org.jboss.vfs.VirtualFile; import io.smallrye.openapi.api.OpenApiConfig; import io.smallrye.openapi.runtime.io.Format; /** * The configuration of an OpenAPI deployment. * @author Paul Ferraro */ public interface DeploymentConfiguration { /** * Returns the config property with the specified name, or the provided default value, if unspecified. * @return the config property with the specified name, or the provided default value, if unspecified. */ <T> T getProperty(String name, T defaultValue); /** * Returns the OpenAPI configuration for this deployment. * @return the OpenAPI configuration for this deployment. */ OpenApiConfig getOpenApiConfig(); /** * Returns a tuple containing the static file and its format, or null, if the deployment does not define a static file. * @return a tuple containing the static file and its format, or null, if the deployment does not define a static file. */ Map.Entry<VirtualFile, Format> getStaticFile(); /** * Returns the name of the Undertow server to which this application is deployed. * @return the name of an Undertow server */ String getServerName(); /** * Returns the name of the Undertow host to which this application is deployed. * @return the name of an Undertow server */ String getHostName(); }
2,492
35.661765
123
java
null
wildfly-main/microprofile/openapi-smallrye/src/main/java/org/wildfly/extension/microprofile/openapi/deployment/OpenAPIHttpHandler.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.microprofile.openapi.deployment; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import jakarta.ws.rs.core.MediaType; import org.eclipse.microprofile.openapi.models.OpenAPI; import org.jboss.resteasy.util.AcceptParser; import io.smallrye.openapi.runtime.io.Format; import io.smallrye.openapi.runtime.io.OpenApiSerializer; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.util.HeaderMap; import io.undertow.util.Headers; import io.undertow.util.HttpString; import io.undertow.util.Methods; import io.undertow.util.StatusCodes; /** * {@link HttpHandler} for the Open API endpoint. * @author Michael Edgar * @author Paul Ferraro */ public class OpenAPIHttpHandler implements HttpHandler { private static final String ALLOW_METHODS = String.join(",", Methods.GET_STRING, Methods.HEAD_STRING, Methods.OPTIONS_STRING); private static final String DEFAULT_ALLOW_HEADERS = String.join(",", Headers.CONTENT_TYPE_STRING, Headers.AUTHORIZATION_STRING); private static final long DEFAULT_MAX_AGE = ChronoUnit.DAYS.getDuration().getSeconds(); private static final Map<MediaType, Format> ACCEPTED_TYPES = new LinkedHashMap<>(); private static final Map<String, Format> FORMATS = new HashMap<>(); private static final String FORMAT = "format"; static { for (Format format : EnumSet.allOf(Format.class)) { ACCEPTED_TYPES.put(MediaType.valueOf(format.getMimeType()), format); FORMATS.put(format.name(), format); } } private final OpenAPI model; public OpenAPIHttpHandler(OpenAPI model) { this.model = model; } @Override public void handleRequest(HttpServerExchange exchange) throws IOException { HttpString requestMethod = exchange.getRequestMethod(); HeaderMap responseHeaders = exchange.getResponseHeaders(); // Add CORS response headers responseHeaders.put(new HttpString("Access-Control-Allow-Origin"), "*"); responseHeaders.put(new HttpString("Access-Control-Allow-Credentials"), "true"); responseHeaders.put(new HttpString("Access-Control-Allow-Methods"), ALLOW_METHODS); responseHeaders.put(new HttpString("Access-Control-Allow-Headers"), DEFAULT_ALLOW_HEADERS); responseHeaders.put(new HttpString("Access-Control-Max-Age"), DEFAULT_MAX_AGE); if (requestMethod.equals(Methods.GET) || requestMethod.equals(Methods.HEAD)) { // Determine preferred media type List<MediaType> preferredTypes = Collections.emptyList(); List<MediaType> types = parseAcceptedTypes(exchange); for (MediaType type : types) { List<MediaType> compatibleTypes = new ArrayList<>(ACCEPTED_TYPES.size()); for (MediaType acceptedType : ACCEPTED_TYPES.keySet()) { if (type.isCompatible(acceptedType)) { compatibleTypes.add(acceptedType); } } if (!compatibleTypes.isEmpty()) { preferredTypes = compatibleTypes; break; } } // Determine preferred charset Charset charset = parseCharset(exchange); if (preferredTypes.isEmpty() || (charset == null)) { exchange.setStatusCode(StatusCodes.NOT_ACCEPTABLE); return; } // Use format preferred by Accept header if unambiguous, otherwise determine format from query parameter Format format = (preferredTypes.size() == 1) ? ACCEPTED_TYPES.get(preferredTypes.get(0)) : parseFormatParameter(exchange); byte[] result = OpenApiSerializer.serialize(this.model, format).getBytes(charset); responseHeaders.put(Headers.CONTENT_TYPE, format.getMimeType()); responseHeaders.put(Headers.CONTENT_LENGTH, result.length); if (requestMethod.equals(Methods.GET)) { exchange.getResponseSender().send(ByteBuffer.wrap(result)); } } else if (requestMethod.equals(Methods.OPTIONS)) { responseHeaders.put(Headers.ALLOW, ALLOW_METHODS); } else { exchange.setStatusCode(StatusCodes.METHOD_NOT_ALLOWED); } } private static final Comparator<MediaType> MEDIA_TYPE_SORTER = new Comparator<>() { @Override public int compare(MediaType type1, MediaType type2) { float quality1 = Float.parseFloat(type1.getParameters().getOrDefault("q", "1")); float quality2 = Float.parseFloat(type2.getParameters().getOrDefault("q", "1")); return Float.compare(quality1, quality2); } }; private static List<MediaType> parseAcceptedTypes(HttpServerExchange exchange) { String headerValue = exchange.getRequestHeaders().getFirst(Headers.ACCEPT); if (headerValue == null) return Collections.singletonList(MediaType.WILDCARD_TYPE); List<String> values = AcceptParser.parseAcceptHeader(headerValue); List<MediaType> types = new ArrayList<>(values.size()); for (String value : values) { types.add(MediaType.valueOf(value)); } // Sort media types by quality Collections.sort(types, MEDIA_TYPE_SORTER); return types; } private static Charset parseCharset(HttpServerExchange exchange) { String headerValue = exchange.getRequestHeaders().getFirst(Headers.ACCEPT_CHARSET); if (headerValue == null) return StandardCharsets.UTF_8; List<String> values = AcceptParser.parseAcceptHeader(headerValue); Charset defaultCharset = null; for (String value : values) { if (value.equals(MediaType.MEDIA_TYPE_WILDCARD)) { defaultCharset = StandardCharsets.UTF_8; } if (Charset.isSupported(value)) { return Charset.forName(value); } } return defaultCharset; } private static Format parseFormatParameter(HttpServerExchange exchange) { Deque<String> formatValues = exchange.getQueryParameters().get(FORMAT); String formatValue = (formatValues != null) ? formatValues.peek() : null; Format format = (formatValue != null) ? FORMATS.get(formatValue) : null; // Default format is YAML return (format != null) ? format : Format.YAML; } }
7,851
41.215054
134
java
null
wildfly-main/microprofile/openapi-smallrye/src/main/java/org/wildfly/extension/microprofile/openapi/deployment/OpenAPIServiceNameProvider.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.microprofile.openapi.deployment; import org.jboss.msc.service.ServiceName; import org.wildfly.clustering.service.ServiceNameProvider; /** * @author Paul Ferraro */ public interface OpenAPIServiceNameProvider extends ServiceNameProvider { default String getPath() { return this.getServiceName().getSimpleName(); } default ServiceName getHostServiceName() { return this.getServiceName().getParent(); } }
1,494
35.463415
73
java
null
wildfly-main/microprofile/openapi-smallrye/src/main/java/org/wildfly/extension/microprofile/openapi/deployment/OpenAPIModelServiceConfigurator.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.microprofile.openapi.deployment; import static org.wildfly.extension.microprofile.openapi.logging.MicroProfileOpenAPILogger.LOGGER; import java.io.IOException; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import io.smallrye.openapi.api.OpenApiConfig; import io.smallrye.openapi.runtime.OpenApiProcessor; import io.smallrye.openapi.runtime.OpenApiStaticFile; import io.smallrye.openapi.runtime.io.Format; import io.smallrye.openapi.runtime.scanner.FilteredIndexView; import io.smallrye.openapi.runtime.scanner.spi.AnnotationScanner; import io.smallrye.openapi.spi.OASFactoryResolverImpl; import io.undertow.servlet.api.DeploymentInfo; import org.eclipse.microprofile.openapi.OASFactory; import org.eclipse.microprofile.openapi.models.OpenAPI; import org.eclipse.microprofile.openapi.models.info.Info; import org.eclipse.microprofile.openapi.models.servers.Server; import org.eclipse.microprofile.openapi.spi.OASFactoryResolver; import org.jboss.as.network.ClientMapping; import org.jboss.as.network.SocketBinding; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.web.common.WarMetaData; import org.jboss.jandex.CompositeIndex; import org.jboss.jandex.Index; import org.jboss.jandex.IndexView; import org.jboss.metadata.javaee.spec.DescriptionGroupMetaData; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.jboss.modules.Module; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.jboss.vfs.VirtualFile; import org.wildfly.clustering.service.CompositeDependency; import org.wildfly.clustering.service.FunctionalService; import org.wildfly.clustering.service.ServiceConfigurator; import org.wildfly.clustering.service.ServiceSupplierDependency; import org.wildfly.clustering.service.SimpleServiceNameProvider; import org.wildfly.clustering.service.SupplierDependency; import org.wildfly.extension.microprofile.openapi.logging.MicroProfileOpenAPILogger; import org.wildfly.extension.undertow.Capabilities; import org.wildfly.extension.undertow.Host; import org.wildfly.extension.undertow.UndertowListener; import org.wildfly.extension.undertow.UndertowService; import org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService; /** * Configures a service that provides an OpenAPI model for a deployment. * @author Paul Ferraro */ public class OpenAPIModelServiceConfigurator extends SimpleServiceNameProvider implements OpenAPIServiceNameProvider, ServiceConfigurator, Supplier<OpenAPI> { private static final String PATH = "mp.openapi.extensions.path"; private static final String DEFAULT_PATH = "/openapi"; private static final String RELATIVE_SERVER_URLS = "mp.openapi.extensions.servers.relative"; private static final String DEFAULT_TITLE = "Generated API"; private static final Set<String> REQUISITE_LISTENERS = Collections.singleton("http"); static { // Set the static OASFactoryResolver eagerly avoiding the need perform TCCL service loading later OASFactoryResolver.setInstance(new OASFactoryResolverImpl()); } private final DeploymentConfiguration configuration; private final String deploymentName; private final VirtualFile root; private final CompositeIndex index; private final Module module; private final JBossWebMetaData metaData; private final SupplierDependency<Host> host; private final SupplierDependency<DeploymentInfo> info; public OpenAPIModelServiceConfigurator(DeploymentUnit unit, DeploymentConfiguration configuration) { super(unit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT).getCapabilityServiceName(Capabilities.CAPABILITY_HOST, configuration.getServerName(), configuration.getHostName()).append(configuration.getProperty(PATH, DEFAULT_PATH))); this.deploymentName = unit.getName(); this.root = unit.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot(); // Convert org.jboss.as.server.deployment.annotation.CompositeIndex to org.jboss.jandex.CompositeIndex Collection<Index> indexes = new ArrayList<>(unit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX).getIndexes()); if (unit.getParent() != null) { // load all composite indexes of the parent deployment unit indexes.addAll(unit.getParent().getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX).getIndexes()); // load all composite indexes of the parent's accessible sub deployments unit.getParent() .getAttachment(Attachments.ACCESSIBLE_SUB_DEPLOYMENTS) .forEach(subdeployment -> indexes.addAll( subdeployment.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX).getIndexes())); } this.index = CompositeIndex.create(indexes.stream().map(IndexView.class::cast).collect(Collectors.toList())); this.module = unit.getAttachment(Attachments.MODULE); this.metaData = unit.getAttachment(WarMetaData.ATTACHMENT_KEY).getMergedJBossWebMetaData(); this.configuration = configuration; this.host = new ServiceSupplierDependency<>(this.getHostServiceName()); this.info = new ServiceSupplierDependency<>(UndertowService.deploymentServiceName(unit.getServiceName()).append(UndertowDeploymentInfoService.SERVICE_NAME)); if (!this.getPath().equals(DEFAULT_PATH)) { MicroProfileOpenAPILogger.LOGGER.nonStandardEndpoint(unit.getName(), this.getPath(), DEFAULT_PATH); } } @Override public ServiceBuilder<?> build(ServiceTarget target) { ServiceName name = this.getServiceName(); ServiceBuilder<?> builder = target.addService(name); Consumer<OpenAPI> model = new CompositeDependency(this.host, this.info).register(builder).provides(name); Service service = new FunctionalService<>(model, Function.identity(), this); return builder.setInstance(service); } @Override public OpenAPI get() { OpenApiConfig config = this.configuration.getOpenApiConfig(); IndexView indexView = new FilteredIndexView(this.index, config); OpenAPIDocumentBuilder builder = new OpenAPIDocumentBuilder(); builder.config(config); Map.Entry<VirtualFile, Format> entry = this.configuration.getStaticFile(); if (entry != null) { VirtualFile file = entry.getKey(); Format format = entry.getValue(); try (OpenApiStaticFile staticFile = new OpenApiStaticFile(file.openStream(), format)) { builder.staticFileModel(OpenApiProcessor.modelFromStaticFile(config, staticFile)); } catch (IOException e) { throw MicroProfileOpenAPILogger.LOGGER.failedToLoadStaticFile(e, file.getPathNameRelativeTo(this.root), this.deploymentName); } } // Workaround for https://github.com/smallrye/smallrye-open-api/issues/1508 ClassLoader scannerClassLoader = new CompositeClassLoader(List.of(AnnotationScanner.class.getClassLoader(), this.module.getClassLoader())); builder.annotationsModel(OpenApiProcessor.modelFromAnnotations(config, scannerClassLoader, indexView)); builder.readerModel(OpenApiProcessor.modelFromReader(config, this.module.getClassLoader())); builder.filter(OpenApiProcessor.getFilter(config, this.module.getClassLoader())); OpenAPI model = builder.build(); // Generate default title and description based on web metadata DescriptionGroupMetaData descriptionMetaData = this.metaData.getDescriptionGroup(); String displayName = (descriptionMetaData != null) ? descriptionMetaData.getDisplayName() : null; String title = (displayName != null) ? displayName : this.deploymentName; String description = (descriptionMetaData != null) ? descriptionMetaData.getDescription() : null; Info info = model.getInfo(); // Override SmallRye's default title if (info.getTitle().equals(DEFAULT_TITLE)) { info.setTitle(title); } if (info.getDescription() == null) { info.setDescription(description); } Host host = this.host.get(); List<UndertowListener> listeners = host.getServer().getListeners(); if (model.getServers() == null) { // Generate Server entries if none exist String contextPath = this.info.get().getContextPath(); if (this.configuration.getProperty(RELATIVE_SERVER_URLS, Boolean.TRUE).booleanValue()) { model.setServers(Collections.singletonList(OASFactory.createServer().url(contextPath))); } else { int aliases = host.getAllAliases().size(); int size = 0; for (UndertowListener listener : listeners) { size += aliases + listener.getSocketBinding().getClientMappings().size(); } List<Server> servers = new ArrayList<>(size); for (UndertowListener listener : listeners) { SocketBinding binding = listener.getSocketBinding(); Set<String> virtualHosts = new TreeSet<>(host.getAllAliases()); // The name of the host is not a real virtual host (e.g. default-host) virtualHosts.remove(host.getName()); InetAddress address = binding.getAddress(); // Omit wildcard addresses if (!address.isAnyLocalAddress()) { virtualHosts.add(address.getCanonicalHostName()); } for (String virtualHost : virtualHosts) { Server server = createServer(listener.getProtocol(), virtualHost, binding.getPort(), contextPath); if (server != null) { servers.add(server); } } for (ClientMapping mapping : binding.getClientMappings()) { Server server = createServer(listener.getProtocol(), mapping.getDestinationAddress(), mapping.getDestinationPort(), contextPath); if (server != null) { servers.add(server); } } } model.setServers(servers); } } if (listeners.stream().map(UndertowListener::getProtocol).noneMatch(REQUISITE_LISTENERS::contains)) { LOGGER.requiredListenersNotFound(host.getServer().getName(), REQUISITE_LISTENERS); } return model; } private static Server createServer(String protocol, String host, int port, String path) { try { URL url = new URL(protocol, host, port, path); if (port == url.getDefaultPort()) { url = new URL(protocol, host, path); } return OASFactory.createServer().url(url.toString()); } catch (MalformedURLException e) { // Skip listeners with no known URLStreamHandler (e.g. AJP) return null; } } private static class CompositeClassLoader extends ClassLoader { private final List<ClassLoader> loaders; CompositeClassLoader(List<ClassLoader> loaders) { this.loaders = loaders; } @Override public Enumeration<URL> getResources(String name) throws IOException { List<URL> result = new LinkedList<>(); for (ClassLoader loader : this.loaders) { result.addAll(Collections.list(loader.getResources(name))); } return Collections.enumeration(result); } @Override protected URL findResource(String name) { for (ClassLoader loader : this.loaders) { URL url = loader.getResource(name); if (url != null) { return url; } } return super.findResource(name); } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { for (ClassLoader loader : this.loaders) { try { return loader.loadClass(name); } catch (ClassNotFoundException e) { // try again } } return super.findClass(name); } } }
14,052
46.637288
243
java
null
wildfly-main/microprofile/openapi-smallrye/src/main/java/org/wildfly/extension/microprofile/openapi/deployment/OpenAPIHttpHandlerServiceConfigurator.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.microprofile.openapi.deployment; import static org.wildfly.extension.microprofile.openapi.logging.MicroProfileOpenAPILogger.LOGGER; import org.eclipse.microprofile.openapi.models.OpenAPI; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StopContext; import org.wildfly.clustering.service.CompositeDependency; import org.wildfly.clustering.service.ServiceConfigurator; import org.wildfly.clustering.service.ServiceSupplierDependency; import org.wildfly.clustering.service.SimpleServiceNameProvider; import org.wildfly.clustering.service.SupplierDependency; import org.wildfly.extension.undertow.Host; /** * Service that registers the OpenAPI HttpHandler. * @author Paul Ferraro * @author Michael Edgar */ public class OpenAPIHttpHandlerServiceConfigurator extends SimpleServiceNameProvider implements ServiceConfigurator, Service { private final SupplierDependency<OpenAPI> model; private final SupplierDependency<Host> host; private final String path; public OpenAPIHttpHandlerServiceConfigurator(OpenAPIServiceNameProvider provider) { super(provider.getServiceName().append("handler")); this.model = new ServiceSupplierDependency<>(provider.getServiceName()); this.host = new ServiceSupplierDependency<>(provider.getHostServiceName()); this.path = provider.getPath(); } @Override public ServiceBuilder<?> build(ServiceTarget target) { ServiceName name = this.getServiceName(); ServiceBuilder<?> builder = target.addService(name); new CompositeDependency(this.model, this.host).register(builder); return builder.setInstance(this); } @Override public void start(StartContext context) { Host host = this.host.get(); host.registerHandler(this.path, new OpenAPIHttpHandler(this.model.get())); LOGGER.endpointRegistered(this.path, host.getName()); } @Override public void stop(StopContext context) { Host host = this.host.get(); host.unregisterHandler(this.path); LOGGER.endpointUnregistered(this.path, host.getName()); } }
3,339
39.240964
126
java
null
wildfly-main/microprofile/telemetry-smallrye/extension/src/test/java/org/wildfly/extension/microprofile/telemetry/MicroProfileTelemetrySubsystemTestCase.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.microprofile.telemetry; import java.util.EnumSet; import org.jboss.as.subsystem.test.AbstractSubsystemSchemaTest; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * Unit test for MicroProfile Telemetry subsystem. * @author Jason Lee */ @RunWith(value = Parameterized.class) public class MicroProfileTelemetrySubsystemTestCase extends AbstractSubsystemSchemaTest<MicroProfileTelemetrySubsystemSchema> { @Parameters public static Iterable<MicroProfileTelemetrySubsystemSchema> parameters() { return EnumSet.allOf(MicroProfileTelemetrySubsystemSchema.class); } public MicroProfileTelemetrySubsystemTestCase(MicroProfileTelemetrySubsystemSchema schema) { super(MicroProfileTelemetryExtension.SUBSYSTEM_NAME, new MicroProfileTelemetryExtension(), schema, MicroProfileTelemetrySubsystemSchema.CURRENT); } @Override protected String getSubsystemXmlPathPattern() { return "%s_%d_%d.xml"; } }
2,081
39.038462
153
java
null
wildfly-main/microprofile/telemetry-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/telemetry/MicroProfileTelemetrySubsystemDefinition.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 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.telemetry; import static org.jboss.as.weld.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.capability.RuntimeCapability; public class MicroProfileTelemetrySubsystemDefinition extends PersistentResourceDefinition { static final String MICROPROFILE_TELEMETRY_MODULE = "org.wildfly.extension.microprofile.telemetry"; static final String MICROPROFILE_TELEMETRY_API_MODULE = "org.wildfly.extension.microprofile.telemetry-api"; static final String OPENTELEMETRY_CAPABILITY_NAME = "org.wildfly.extension.opentelemetry"; public static final String[] EXPORTED_MODULES = { "io.opentelemetry.api", "io.opentelemetry.context", "io.opentelemetry.exporter", "io.opentelemetry.sdk", "io.smallrye.config", "io.smallrye.opentelemetry", "org.eclipse.microprofile.config.api", MICROPROFILE_TELEMETRY_API_MODULE }; static final RuntimeCapability<Void> MICROPROFILE_TELEMETRY_CAPABILITY = RuntimeCapability.Builder.of(MICROPROFILE_TELEMETRY_MODULE) .addRequirements(WELD_CAPABILITY_NAME, OPENTELEMETRY_CAPABILITY_NAME) .build(); protected MicroProfileTelemetrySubsystemDefinition() { super(new Parameters(MicroProfileTelemetryExtension.SUBSYSTEM_PATH, MicroProfileTelemetryExtension.SUBSYSTEM_RESOLVER) .setAddHandler(new MicroProfileTelemetrySubsystemAdd()) .setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE) .setCapabilities(MICROPROFILE_TELEMETRY_CAPABILITY) ); } @Override public Collection<AttributeDefinition> getAttributes() { return Collections.EMPTY_LIST; } }
2,736
41.107692
126
java
null
wildfly-main/microprofile/telemetry-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/telemetry/MicroProfileTelemetryExtensionLogger.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 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.telemetry; import static org.jboss.logging.Logger.Level.INFO; 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; @MessageLogger(projectCode = "WFLYMPTEL", length = 4) interface MicroProfileTelemetryExtensionLogger extends BasicLogger { MicroProfileTelemetryExtensionLogger MPTEL_LOGGER = Logger.getMessageLogger(MicroProfileTelemetryExtensionLogger.class, MicroProfileTelemetryExtensionLogger.class.getPackage().getName()); @LogMessage(level = INFO) @Message(id = 1, value = "Activating MicroProfile Telemetry Subsystem") void activatingSubsystem(); @Message(id = 2, value = "Deployment %s requires use of the '%s' capability but it is not currently registered") DeploymentUnitProcessingException deploymentRequiresCapability(String deploymentName, String capabilityName); }
1,811
40.181818
123
java
null
wildfly-main/microprofile/telemetry-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/telemetry/MicroProfileTelemetrySubsystemSchema.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 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.telemetry; import static org.jboss.as.controller.PersistentResourceXMLDescription.builder; import org.jboss.as.controller.PersistentResourceXMLDescription; import org.jboss.as.controller.PersistentSubsystemSchema; import org.jboss.as.controller.SubsystemSchema; import org.jboss.as.controller.xml.VersionedNamespace; import org.jboss.staxmapper.IntVersion; enum MicroProfileTelemetrySubsystemSchema implements PersistentSubsystemSchema<MicroProfileTelemetrySubsystemSchema> { VERSION_1_0(1, 0), // WildFly 28 ; public static final MicroProfileTelemetrySubsystemSchema CURRENT = VERSION_1_0; private final VersionedNamespace<IntVersion, MicroProfileTelemetrySubsystemSchema> namespace; MicroProfileTelemetrySubsystemSchema(int major, int minor) { this.namespace = SubsystemSchema.createSubsystemURN(MicroProfileTelemetryExtension.SUBSYSTEM_NAME, new IntVersion(major, minor)); } @Override public VersionedNamespace<IntVersion, MicroProfileTelemetrySubsystemSchema> getNamespace() { return this.namespace; } @Override public PersistentResourceXMLDescription getXMLDescription() { return builder(MicroProfileTelemetryExtension.SUBSYSTEM_PATH, this.namespace).build(); } }
2,004
36.830189
137
java
null
wildfly-main/microprofile/telemetry-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/telemetry/MicroProfileTelemetryExtension.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 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.telemetry; 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; public class MicroProfileTelemetryExtension implements Extension { /** * The name of our subsystem within the model. */ public static final String SUBSYSTEM_NAME = "microprofile-telemetry"; static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME); static final ParentResourceDescriptionResolver SUBSYSTEM_RESOLVER = new SubsystemResourceDescriptionResolver(SUBSYSTEM_NAME, MicroProfileTelemetryExtension.class); private 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 = MicroProfileTelemetrySubsystemSchema.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 MicroProfileTelemetrySubsystemDefinition()); registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE); } @Override public void initializeParsers(ExtensionParsingContext context) { for (MicroProfileTelemetrySubsystemSchema schema : EnumSet.allOf(MicroProfileTelemetrySubsystemSchema.class)) { XMLElementReader<List<ModelNode>> reader = (schema == MicroProfileTelemetrySubsystemSchema.CURRENT) ? new PersistentResourceXMLDescriptionReader(this.currentDescription) : schema; context.setSubsystemXmlMapping(SUBSYSTEM_NAME, schema.getNamespace().getUri(), reader); } } }
3,705
47.763158
191
java
null
wildfly-main/microprofile/telemetry-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/telemetry/MicroProfileTelemetryDependencyProcessor.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 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.telemetry; import static org.wildfly.extension.microprofile.telemetry.MicroProfileTelemetrySubsystemDefinition.EXPORTED_MODULES; 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.modules.Module; import org.jboss.modules.ModuleLoader; class MicroProfileTelemetryDependencyProcessor implements DeploymentUnitProcessor { public MicroProfileTelemetryDependencyProcessor() { } @Override public void deploy(DeploymentPhaseContext phaseContext) { addDependencies(phaseContext.getDeploymentUnit()); } private void addDependencies(DeploymentUnit deploymentUnit) { final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); final ModuleLoader moduleLoader = Module.getBootModuleLoader(); for (String module : EXPORTED_MODULES) { moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, module, false, true, true, false)); } } }
2,076
38.188679
119
java
null
wildfly-main/microprofile/telemetry-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/telemetry/MicroProfileTelemetrySubsystemAdd.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 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.telemetry; import static org.wildfly.extension.microprofile.telemetry.MicroProfileTelemetryExtensionLogger.MPTEL_LOGGER; import org.jboss.as.controller.AbstractBoottimeAddStepHandler; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.server.AbstractDeploymentChainStep; import org.jboss.as.server.DeploymentProcessorTarget; import org.jboss.as.server.deployment.Phase; import org.jboss.dmr.ModelNode; public class MicroProfileTelemetrySubsystemAdd extends AbstractBoottimeAddStepHandler { MicroProfileTelemetrySubsystemAdd() { super(); } /** * {@inheritDoc} */ @Override protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { MPTEL_LOGGER.activatingSubsystem(); super.performBoottime(context, operation, model); context.addStep(new AbstractDeploymentChainStep() { @Override public void execute(DeploymentProcessorTarget processorTarget) { processorTarget.addDeploymentProcessor( MicroProfileTelemetryExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_MICROPROFILE_TELEMETRY, new MicroProfileTelemetryDependencyProcessor() ); processorTarget.addDeploymentProcessor( MicroProfileTelemetryExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_MICROPROFILE_TELEMETRY, new MicroProfileTelemetryDeploymentProcessor()); } }, OperationContext.Stage.RUNTIME); } }
2,538
38.671875
132
java
null
wildfly-main/microprofile/telemetry-smallrye/extension/src/main/java/org/wildfly/extension/microprofile/telemetry/MicroProfileTelemetryDeploymentProcessor.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 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.telemetry; import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME; import static org.wildfly.extension.microprofile.telemetry.MicroProfileTelemetryExtensionLogger.MPTEL_LOGGER; import java.util.HashMap; import java.util.Map; import java.util.function.Supplier; import io.smallrye.opentelemetry.api.OpenTelemetryConfig; 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.weld.WeldCapability; import org.wildfly.extension.microprofile.telemetry.api.MicroProfileTelemetryCdiExtension; public class MicroProfileTelemetryDeploymentProcessor implements DeploymentUnitProcessor { @Override public void deploy(DeploymentPhaseContext deploymentPhaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = deploymentPhaseContext.getDeploymentUnit(); if (DeploymentTypeMarker.isType(DeploymentType.EAR, deploymentUnit)) { return; } try { final CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT); final WeldCapability weldCapability = support.getCapabilityRuntimeAPI(WELD_CAPABILITY_NAME, WeldCapability.class); if (weldCapability != null && !weldCapability.isPartOfWeldDeployment(deploymentUnit)) { MPTEL_LOGGER.debug("The deployment does not have Jakarta Contexts and Dependency Injection enabled. " + "Skipping MicroProfile Telemetry integration."); } else { final OpenTelemetryConfig serverConfig = (OpenTelemetryConfig) support.getCapabilityRuntimeAPI("org.wildfly.extension.opentelemetry.config", Supplier.class).get(); Map<String, String> properties = new HashMap<>(serverConfig.properties()); properties.put("otel.service.name", getServiceName(deploymentUnit)); weldCapability.registerExtensionInstance(new MicroProfileTelemetryCdiExtension(properties), deploymentUnit); } } catch (CapabilityServiceSupport.NoSuchCapabilityException e) { throw MPTEL_LOGGER.deploymentRequiresCapability(deploymentPhaseContext.getDeploymentUnit().getName(), WELD_CAPABILITY_NAME); } } @Override public void undeploy(DeploymentUnit context) { } private String getServiceName(DeploymentUnit deploymentUnit) { String serviceName = deploymentUnit.getServiceName().getSimpleName(); if (null != deploymentUnit.getParent()) { serviceName = deploymentUnit.getParent().getServiceName().getSimpleName() + "!" + serviceName; } return serviceName; } }
3,934
46.409639
126
java
null
wildfly-main/microprofile/telemetry-smallrye/cdi-provider/src/main/java/org/wildfly/extension/microprofile/telemetry/api/MicroProfileTelemetryCdiExtension.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 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.telemetry.api; import java.util.HashMap; import java.util.Map; import io.smallrye.opentelemetry.api.OpenTelemetryConfig; import jakarta.enterprise.event.Observes; import jakarta.enterprise.inject.Default; import jakarta.enterprise.inject.spi.AfterBeanDiscovery; import jakarta.enterprise.inject.spi.BeanManager; import jakarta.enterprise.inject.spi.Extension; import jakarta.inject.Singleton; import org.eclipse.microprofile.config.Config; public class MicroProfileTelemetryCdiExtension implements Extension { private final Map<String, String> serverConfig; public MicroProfileTelemetryCdiExtension(Map<String, String> serverConfig) { this.serverConfig = serverConfig; } public void registerOpenTelemetryConfigBean(@Observes AfterBeanDiscovery abd, BeanManager beanManager) { abd.addBean() .scope(Singleton.class) .addQualifier(Default.Literal.INSTANCE) .types(OpenTelemetryConfig.class) .createWith(c -> { Config appConfig = beanManager.createInstance().select(Config.class).get(); Map<String, String> properties = new HashMap<>(serverConfig); // MicroProfile Telemetry is disabled by default properties.put("otel.sdk.disabled", "true"); properties.put("otel.experimental.sdk.enabled", "false"); for (String propertyName : appConfig.getPropertyNames()) { if (propertyName.startsWith("otel.") || propertyName.startsWith("OTEL_")) { appConfig.getOptionalValue(propertyName, String.class).ifPresent( value -> properties.put(propertyName, value)); } } return (OpenTelemetryConfig) () -> properties; } ); } }
2,772
43.015873
108
java
null
wildfly-main/microprofile/health-smallrye/src/test/java/org/wildfly/extension/microprofile/health/Subsystem_3_0_ParsingTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.health; import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest; import org.jboss.as.subsystem.test.AdditionalInitialization; import java.io.IOException; import java.util.Properties; import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME; import static org.wildfly.extension.microprofile.health.MicroProfileHealthSubsystemDefinition.HEALTH_HTTP_CONTEXT_CAPABILITY; import static org.wildfly.extension.microprofile.health.MicroProfileHealthSubsystemDefinition.HEALTH_SERVER_PROBE_CAPABILITY; /** * @author <a href="http://xstefank.io/">Martin Stefanko</a> (c) 2021 Red Hat inc. */ public class Subsystem_3_0_ParsingTestCase extends AbstractSubsystemBaseTest { public Subsystem_3_0_ParsingTestCase() { super(MicroProfileHealthExtension.SUBSYSTEM_NAME, new MicroProfileHealthExtension()); } @Override protected String getSubsystemXml() throws IOException { return readResource("subsystem_3_0.xml"); } @Override protected String getSubsystemXsdPath() { return "schema/wildfly-microprofile-health-smallrye_3_0.xsd"; } protected Properties getResolvedProperties() { return System.getProperties(); } @Override protected AdditionalInitialization createAdditionalInitialization() { return AdditionalInitialization.withCapabilities( WELD_CAPABILITY_NAME, "org.wildfly.management.executor", "org.wildfly.management.http.extensible", HEALTH_HTTP_CONTEXT_CAPABILITY, HEALTH_SERVER_PROBE_CAPABILITY); } }
2,657
38.088235
125
java
null
wildfly-main/microprofile/health-smallrye/src/test/java/org/wildfly/extension/microprofile/health/Subsystem_2_0_ParsingTestCase.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.microprofile.health; import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME; import static org.wildfly.extension.microprofile.health.MicroProfileHealthSubsystemDefinition.HEALTH_HTTP_CONTEXT_CAPABILITY; import static org.wildfly.extension.microprofile.health.MicroProfileHealthSubsystemDefinition.HEALTH_SERVER_PROBE_CAPABILITY; 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) 2019 Red Hat inc. */ public class Subsystem_2_0_ParsingTestCase extends AbstractSubsystemBaseTest { public Subsystem_2_0_ParsingTestCase() { super(MicroProfileHealthExtension.SUBSYSTEM_NAME, new MicroProfileHealthExtension()); } @Override protected KernelServices standardSubsystemTest(String configId, boolean compareXml) throws Exception { return super.standardSubsystemTest(configId, false); } @Override protected String getSubsystemXml() throws IOException { return readResource("subsystem_2_0.xml"); } @Override protected String getSubsystemXsdPath() { return "schema/wildfly-microprofile-health-smallrye_2_0.xsd"; } protected Properties getResolvedProperties() { return System.getProperties(); } @Override protected AdditionalInitialization createAdditionalInitialization() { return AdditionalInitialization.withCapabilities( WELD_CAPABILITY_NAME, "org.wildfly.management.executor", "org.wildfly.management.http.extensible", HEALTH_HTTP_CONTEXT_CAPABILITY, HEALTH_SERVER_PROBE_CAPABILITY); } }
2,893
38.108108
125
java
null
wildfly-main/microprofile/health-smallrye/src/test/java/org/wildfly/extension/microprofile/health/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.health; import java.io.IOException; import java.util.Properties; import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest; 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(MicroProfileHealthExtension.SUBSYSTEM_NAME, new MicroProfileHealthExtension()); } @Override protected KernelServices standardSubsystemTest(String configId, boolean compareXml) throws Exception { return super.standardSubsystemTest(configId, false); } @Override protected String getSubsystemXml() throws IOException { return readResource("subsystem_1_0.xml"); } @Override protected String getSubsystemXsdPath() throws IOException { return "schema/wildfly-microprofile-health-smallrye_1_0.xsd"; } protected Properties getResolvedProperties() { return System.getProperties(); } }
2,136
34.032787
106
java
null
wildfly-main/microprofile/health-smallrye/src/main/java/org/wildfly/extension/microprofile/health/MicroProfileHealthReporter.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.microprofile.health; import java.util.Collections; import java.util.HashMap; import java.util.Map; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonArrayBuilder; import jakarta.json.JsonObject; import jakarta.json.JsonObjectBuilder; import io.smallrye.health.SmallRyeHealth; import org.eclipse.microprofile.health.HealthCheck; import org.eclipse.microprofile.health.HealthCheckResponse; import org.eclipse.microprofile.health.HealthCheckResponseBuilder; import org.wildfly.extension.microprofile.health._private.MicroProfileHealthLogger; public class MicroProfileHealthReporter { public static final String DOWN = "DOWN"; public static final String UP = "UP"; private final boolean defaultServerProceduresDisabled; private final String defaultReadinessEmptyResponse; private final String defaultStartupEmptyResponse; private Map<HealthCheck, ClassLoader> healthChecks = new HashMap<>(); private Map<HealthCheck, ClassLoader> livenessChecks = new HashMap<>(); private Map<HealthCheck, ClassLoader> readinessChecks = new HashMap<>(); private Map<HealthCheck, ClassLoader> startupChecks = new HashMap<>(); private Map<HealthCheck, ClassLoader> serverReadinessChecks = new HashMap<>(); private final HealthCheck emptyDeploymentLivenessCheck; private final HealthCheck emptyDeploymentReadinessCheck; private final HealthCheck emptyDeploymentStartupCheck; private boolean userChecksProcessed = false; private static class EmptyDeploymentCheckStatus implements HealthCheck { private final String name; private final String status; EmptyDeploymentCheckStatus(String name, String status) { this.name = name; this.status = status; } @Override public HealthCheckResponse call() { return HealthCheckResponse.named(name) .status(status.equals("UP")) .build(); } } public MicroProfileHealthReporter(String emptyLivenessChecksStatus, String emptyReadinessChecksStatus, String emptyStartupChecksStatus, boolean defaultServerProceduresDisabled, String defaultReadinessEmptyResponse, String defaultStartupEmptyResponse) { this.emptyDeploymentLivenessCheck = new EmptyDeploymentCheckStatus("empty-liveness-checks", emptyLivenessChecksStatus); this.emptyDeploymentReadinessCheck = new EmptyDeploymentCheckStatus("empty-readiness-checks", emptyReadinessChecksStatus); this.emptyDeploymentStartupCheck = new EmptyDeploymentCheckStatus("empty-startup-checks", emptyStartupChecksStatus); this.defaultServerProceduresDisabled = defaultServerProceduresDisabled; this.defaultReadinessEmptyResponse = defaultReadinessEmptyResponse; this.defaultStartupEmptyResponse = defaultStartupEmptyResponse; } public SmallRyeHealth getHealth() { HashMap<HealthCheck, ClassLoader> deploymentChecks = new HashMap<>(); deploymentChecks.putAll(healthChecks); deploymentChecks.putAll(livenessChecks); deploymentChecks.putAll(readinessChecks); deploymentChecks.putAll(startupChecks); HashMap<HealthCheck, ClassLoader> serverChecks= new HashMap<>(); serverChecks.putAll(serverReadinessChecks); if (deploymentChecks.size() == 0 && !defaultServerProceduresDisabled) { serverChecks.put(emptyDeploymentLivenessCheck, Thread.currentThread().getContextClassLoader()); serverChecks.put(emptyDeploymentReadinessCheck, Thread.currentThread().getContextClassLoader()); serverChecks.put(emptyDeploymentStartupCheck, Thread.currentThread().getContextClassLoader()); } return getHealth(serverChecks, deploymentChecks); } public SmallRyeHealth getLiveness() { final Map<HealthCheck, ClassLoader> serverChecks; if (livenessChecks.size() == 0 && !defaultServerProceduresDisabled) { serverChecks = Collections.singletonMap(emptyDeploymentLivenessCheck, Thread.currentThread().getContextClassLoader()); } else { serverChecks = Collections.emptyMap(); } return getHealth(serverChecks, livenessChecks); } public SmallRyeHealth getReadiness() { final Map<HealthCheck, ClassLoader> serverChecks = new HashMap<>(); serverChecks.putAll(serverReadinessChecks); if (readinessChecks.size() == 0) { if (defaultServerProceduresDisabled) { return getHealth(serverChecks, readinessChecks, userChecksProcessed ? HealthCheckResponse.Status.UP : HealthCheckResponse.Status.valueOf(defaultReadinessEmptyResponse)); } else { serverChecks.put(emptyDeploymentReadinessCheck, Thread.currentThread().getContextClassLoader()); return getHealth(serverChecks, readinessChecks); } } return getHealth(serverChecks, readinessChecks); } public SmallRyeHealth getStartup() { Map<HealthCheck, ClassLoader> serverChecks = Collections.emptyMap(); if (startupChecks.size() == 0) { if (defaultServerProceduresDisabled) { return getHealth(serverChecks, startupChecks, userChecksProcessed ? HealthCheckResponse.Status.UP : HealthCheckResponse.Status.valueOf(defaultStartupEmptyResponse)); } else { serverChecks = Collections.singletonMap(emptyDeploymentStartupCheck, Thread.currentThread().getContextClassLoader()); return getHealth(serverChecks, startupChecks); } } return getHealth(serverChecks, startupChecks); } private SmallRyeHealth getHealth(Map<HealthCheck, ClassLoader> serverChecks, Map<HealthCheck, ClassLoader> deploymentChecks) { return getHealth(serverChecks, deploymentChecks, HealthCheckResponse.Status.UP); } private SmallRyeHealth getHealth(Map<HealthCheck, ClassLoader> serverChecks, Map<HealthCheck, ClassLoader> deploymentChecks, HealthCheckResponse.Status defaultStatus) { JsonArrayBuilder results = Json.createArrayBuilder(); HealthCheckResponse.Status status = defaultStatus; status = processChecks(serverChecks, results, status); status = processChecks(deploymentChecks, results, status); JsonObjectBuilder builder = Json.createObjectBuilder(); JsonArray checkResults = results.build(); builder.add("status", status.toString()); builder.add("checks", checkResults); JsonObject build = builder.build(); if (status.equals(HealthCheckResponse.Status.DOWN)) { MicroProfileHealthLogger.LOGGER.healthDownStatus(build.toString()); } return new SmallRyeHealth(build); } private HealthCheckResponse.Status processChecks(Map<HealthCheck, ClassLoader> checks, JsonArrayBuilder results, HealthCheckResponse.Status status) { if (checks != null) { for (Map.Entry<HealthCheck, ClassLoader> entry : checks.entrySet()) { // use the classloader of the deployment's module instead of the TCCL (which is the server's ModuleClassLoader // to ensure that any resources that checks the TCCL (such as MP Config) will use the correct one // when the health checks are called. final ClassLoader oldTCCL = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(entry.getValue()); status = fillCheck(entry.getKey(), results, status); } finally { Thread.currentThread().setContextClassLoader(oldTCCL); } } } return status; } private HealthCheckResponse.Status fillCheck(HealthCheck check, JsonArrayBuilder results, HealthCheckResponse.Status globalOutcome) { JsonObject each = jsonObject(check); results.add(each); if (globalOutcome == HealthCheckResponse.Status.UP) { String status = each.getString("status"); if (status.equals(DOWN)) { return HealthCheckResponse.Status.DOWN; } } return globalOutcome; } private JsonObject jsonObject(HealthCheck check) { try { return jsonObject(check.call()); } catch (RuntimeException e) { // Log Stacktrace to server log so an error is not just in Health Check response MicroProfileHealthLogger.LOGGER.error("Error processing Health Checks", e); HealthCheckResponseBuilder response = HealthCheckResponse.named(check.getClass().getName()).down(); return jsonObject(response.build()); } } private JsonObject jsonObject(HealthCheckResponse response) { JsonObjectBuilder builder = Json.createObjectBuilder(); builder.add("name", response.getName()); builder.add("status", response.getStatus().toString()); response.getData().ifPresent(d -> { JsonObjectBuilder data = Json.createObjectBuilder(); for (Map.Entry<String, Object> entry : d.entrySet()) { Object value = entry.getValue(); if (value instanceof String) { data.add(entry.getKey(), (String) value); } else if (value instanceof Long) { data.add(entry.getKey(), (Long) value); } else if (value instanceof Boolean) { data.add(entry.getKey(), (Boolean) value); } } builder.add("data", data.build()); }); return builder.build(); } public void addHealthCheck(HealthCheck check, ClassLoader moduleClassLoader) { if (check != null) { healthChecks.put(check, moduleClassLoader); } } public void removeHealthCheck(HealthCheck check) { healthChecks.remove(check); } public void addReadinessCheck(HealthCheck check, ClassLoader moduleClassLoader) { if (check != null) { readinessChecks.put(check, moduleClassLoader); } } public void addServerReadinessCheck(HealthCheck check, ClassLoader moduleClassLoader) { if (check != null) { serverReadinessChecks.put(check, moduleClassLoader); } } public void removeReadinessCheck(HealthCheck check) { readinessChecks.remove(check); } public void addLivenessCheck(HealthCheck check, ClassLoader moduleClassLoader) { if (check != null) { livenessChecks.put(check, moduleClassLoader); } } public void removeLivenessCheck(HealthCheck check) { livenessChecks.remove(check); } public void addStartupCheck(HealthCheck check, ClassLoader moduleClassLoader) { if (check != null) { startupChecks.put(check, moduleClassLoader); } } public void removeStartupCheck(HealthCheck check) { startupChecks.remove(check); } public void setUserChecksProcessed(boolean userChecksProcessed) { this.userChecksProcessed = userChecksProcessed; } }
12,447
41.340136
153
java
null
wildfly-main/microprofile/health-smallrye/src/main/java/org/wildfly/extension/microprofile/health/MicroProfileHealthSubsystemDefinition.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.health; import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME; import java.util.Arrays; import java.util.Collection; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.ServiceRemoveStepHandler; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.as.controller.operations.validation.StringAllowedValuesValidator; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.msc.service.ServiceName; import org.wildfly.extension.health.HealthSubsystemDefinition; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc. */ public class MicroProfileHealthSubsystemDefinition extends PersistentResourceDefinition { private static final String[] ALLOWED_STATUS = {"UP", "DOWN"}; static final String MICROPROFILE_HEALTH_REPORTER_CAPABILITY = "org.wildfly.extension.microprofile.health.reporter"; static final String HEALTH_HTTP_CONTEXT_CAPABILITY = "org.wildfly.extension.health.http-context"; static final String HEALTH_SERVER_PROBE_CAPABILITY = "org.wildfly.extension.health.server-probes"; static final RuntimeCapability<Void> HEALTH_REPORTER_RUNTIME_CAPABILITY = RuntimeCapability.Builder.of(MICROPROFILE_HEALTH_REPORTER_CAPABILITY, MicroProfileHealthReporter.class) .addRequirements(WELD_CAPABILITY_NAME, HEALTH_SERVER_PROBE_CAPABILITY) .build(); public static final ServiceName HEALTH_REPORTER_SERVICE = ServiceName.parse(MICROPROFILE_HEALTH_REPORTER_CAPABILITY); static final RuntimeCapability<Void> MICROPROFILE_HEALTH_HTTP_CONTEXT_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.extension.microprofile.health.http-context", MicroProfileHealthContextService.class) .addRequirements(HEALTH_HTTP_CONTEXT_CAPABILITY) .build(); static final ServiceName HTTP_CONTEXT_SERVICE = MICROPROFILE_HEALTH_HTTP_CONTEXT_CAPABILITY.getCapabilityServiceName(); static final RuntimeCapability<Void> MICROPROFILE_HEALTH_HTTP_SECURITY_CAPABILITY = RuntimeCapability.Builder.of(HealthSubsystemDefinition.HEALTH_HTTP_SECURITY_CAPABILITY, Boolean.class) .build(); static final AttributeDefinition SECURITY_ENABLED = SimpleAttributeDefinitionBuilder.create("security-enabled", ModelType.BOOLEAN) .setDefaultValue(ModelNode.TRUE) .setRequired(false) .setRestartAllServices() .setAllowExpression(true) .build(); static final AttributeDefinition EMPTY_LIVENESS_CHECKS_STATUS = SimpleAttributeDefinitionBuilder.create("empty-liveness-checks-status", ModelType.STRING) .setDefaultValue(new ModelNode("UP")) .setRequired(false) .setRestartAllServices() .setAllowExpression(true) .setValidator(new StringAllowedValuesValidator(ALLOWED_STATUS)) .build(); static final AttributeDefinition EMPTY_READINESS_CHECKS_STATUS = SimpleAttributeDefinitionBuilder.create("empty-readiness-checks-status", ModelType.STRING) .setDefaultValue(new ModelNode("UP")) .setRequired(false) .setRestartAllServices() .setAllowExpression(true) .setValidator(new StringAllowedValuesValidator(ALLOWED_STATUS)) .build(); static final AttributeDefinition EMPTY_STARTUP_CHECKS_STATUS = SimpleAttributeDefinitionBuilder.create("empty-startup-checks-status", ModelType.STRING) .setDefaultValue(new ModelNode("UP")) .setRequired(false) .setRestartAllServices() .setAllowExpression(true) .setValidator(new StringAllowedValuesValidator(ALLOWED_STATUS)) .build(); static final AttributeDefinition[] ATTRIBUTES = { SECURITY_ENABLED, EMPTY_LIVENESS_CHECKS_STATUS, EMPTY_READINESS_CHECKS_STATUS, EMPTY_STARTUP_CHECKS_STATUS}; private boolean registerRuntimeOperations; protected MicroProfileHealthSubsystemDefinition(boolean registerRuntimeOperations) { super(new Parameters(MicroProfileHealthExtension.SUBSYSTEM_PATH, MicroProfileHealthExtension.SUBSYSTEM_RESOLVER) .setAddHandler(MicroProfileHealthSubsystemAdd.INSTANCE) .setRemoveHandler(new ServiceRemoveStepHandler(MicroProfileHealthSubsystemAdd.INSTANCE)) .setCapabilities(HEALTH_REPORTER_RUNTIME_CAPABILITY, MICROPROFILE_HEALTH_HTTP_CONTEXT_CAPABILITY, MICROPROFILE_HEALTH_HTTP_SECURITY_CAPABILITY)); this.registerRuntimeOperations = registerRuntimeOperations; } @Override public Collection<AttributeDefinition> getAttributes() { return Arrays.asList(ATTRIBUTES); } @Override public void registerOperations(ManagementResourceRegistration resourceRegistration) { super.registerOperations(resourceRegistration); if (registerRuntimeOperations) { CheckOperations.register(resourceRegistration); } } }
6,276
48.425197
213
java
null
wildfly-main/microprofile/health-smallrye/src/main/java/org/wildfly/extension/microprofile/health/MicroProfileHealthExtension.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.health; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; 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.RunningMode; 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; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc. */ public class MicroProfileHealthExtension implements Extension { static final String EXTENSION_NAME = "org.wildfly.extension.microprofile.health.smallrye"; /** * The name of our subsystem within the model. */ public static final String SUBSYSTEM_NAME = "microprofile-health-smallrye"; protected static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME); static final ParentResourceDescriptionResolver SUBSYSTEM_RESOLVER = new SubsystemResourceDescriptionResolver(SUBSYSTEM_NAME, MicroProfileHealthExtension.class); 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); protected static final ModelVersion VERSION_3_0_0 = ModelVersion.create(3, 0, 0); private static final ModelVersion CURRENT_MODEL_VERSION = VERSION_3_0_0; private static final MicroProfileHealthParser_3_0 CURRENT_PARSER = new MicroProfileHealthParser_3_0(); @Override public void initialize(ExtensionContext context) { final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION); subsystem.registerXMLElementWriter(CURRENT_PARSER); final ManagementResourceRegistration registration = subsystem.registerSubsystemModel(new MicroProfileHealthSubsystemDefinition(context.isRuntimeOnlyRegistrationValid() && context.getRunningMode() == RunningMode.NORMAL)); registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE); } @Override public void initializeParsers(ExtensionParsingContext context) { context.setSubsystemXmlMapping(SUBSYSTEM_NAME, MicroProfileHealthParser_1_0.NAMESPACE, MicroProfileHealthParser_1_0::new); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, MicroProfileHealthParser_2_0.NAMESPACE, MicroProfileHealthParser_2_0::new); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, MicroProfileHealthParser_3_0.NAMESPACE, CURRENT_PARSER); } }
4,017
50.512821
229
java
null
wildfly-main/microprofile/health-smallrye/src/main/java/org/wildfly/extension/microprofile/health/CheckOperations.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.health; import java.util.function.Function; import io.smallrye.health.SmallRyeHealth; import org.jboss.as.controller.AbstractRuntimeOnlyHandler; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationDefinition; import org.jboss.as.controller.SimpleOperationDefinitionBuilder; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.msc.service.ServiceName; /** * Management operation that returns the DMR representation of the MicroProfile Health Check JSON payload. * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc. */ public class CheckOperations extends AbstractRuntimeOnlyHandler { private static final OperationDefinition CHECK_DEFINITION = new SimpleOperationDefinitionBuilder("check", MicroProfileHealthExtension.SUBSYSTEM_RESOLVER) .setRuntimeOnly() .setReplyType(ModelType.OBJECT) .setReplyValueType(ModelType.OBJECT) .setRuntimeOnly() .build(); private static final OperationDefinition CHECK_LIVE_DEFINITION = new SimpleOperationDefinitionBuilder("check-live", MicroProfileHealthExtension.SUBSYSTEM_RESOLVER) .setRuntimeOnly() .setReplyType(ModelType.OBJECT) .setReplyValueType(ModelType.OBJECT) .setRuntimeOnly() .build(); private static final OperationDefinition CHECK_READY_DEFINITION = new SimpleOperationDefinitionBuilder("check-ready", MicroProfileHealthExtension.SUBSYSTEM_RESOLVER) .setRuntimeOnly() .setReplyType(ModelType.OBJECT) .setReplyValueType(ModelType.OBJECT) .setRuntimeOnly() .build(); private static final OperationDefinition CHECK_STARTED_DEFINITION = new SimpleOperationDefinitionBuilder("check-started", MicroProfileHealthExtension.SUBSYSTEM_RESOLVER) .setRuntimeOnly() .setReplyType(ModelType.OBJECT) .setReplyValueType(ModelType.OBJECT) .setRuntimeOnly() .build(); private final Function<MicroProfileHealthReporter, SmallRyeHealth> healthOperation; public CheckOperations(Function<MicroProfileHealthReporter, SmallRyeHealth> healthOperation) { this.healthOperation = healthOperation; } static void register(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerOperationHandler(CHECK_DEFINITION, new CheckOperations((MicroProfileHealthReporter h) -> h.getHealth())); resourceRegistration.registerOperationHandler(CHECK_LIVE_DEFINITION, new CheckOperations((MicroProfileHealthReporter h) -> h.getLiveness())); resourceRegistration.registerOperationHandler(CHECK_READY_DEFINITION, new CheckOperations((MicroProfileHealthReporter h) -> h.getReadiness())); resourceRegistration.registerOperationHandler(CHECK_STARTED_DEFINITION, new CheckOperations((MicroProfileHealthReporter h) -> h.getStartup())); } @Override protected void executeRuntimeStep(OperationContext context, ModelNode operation) { ServiceName serviceName = context.getCapabilityServiceName(MicroProfileHealthSubsystemDefinition.MICROPROFILE_HEALTH_REPORTER_CAPABILITY, MicroProfileHealthReporter.class); MicroProfileHealthReporter reporter = (MicroProfileHealthReporter) context.getServiceRegistry(false).getService(serviceName).getValue(); SmallRyeHealth health = healthOperation.apply(reporter); ModelNode result = ModelNode.fromJSONString(health.getPayload().toString()); context.getResult().set(result); } }
4,729
49.860215
180
java
null
wildfly-main/microprofile/health-smallrye/src/main/java/org/wildfly/extension/microprofile/health/MicroProfileHealthSubsystemAdd.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.health; import static org.jboss.as.controller.OperationContext.Stage.RUNTIME; import static org.jboss.as.server.deployment.Phase.DEPENDENCIES; import static org.jboss.as.server.deployment.Phase.DEPENDENCIES_MICROPROFILE_HEALTH; import static org.jboss.as.server.deployment.Phase.POST_MODULE; import static org.jboss.as.server.deployment.Phase.POST_MODULE_MICROPROFILE_HEALTH; import org.jboss.as.controller.AbstractBoottimeAddStepHandler; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.server.AbstractDeploymentChainStep; import org.jboss.as.server.DeploymentProcessorTarget; import org.jboss.dmr.ModelNode; import org.wildfly.extension.microprofile.health._private.MicroProfileHealthLogger; import org.wildfly.extension.microprofile.health.deployment.DependencyProcessor; import org.wildfly.extension.microprofile.health.deployment.DeploymentProcessor; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc. */ class MicroProfileHealthSubsystemAdd extends AbstractBoottimeAddStepHandler { static MicroProfileHealthSubsystemAdd INSTANCE = new MicroProfileHealthSubsystemAdd(); private MicroProfileHealthSubsystemAdd() { super(MicroProfileHealthSubsystemDefinition.ATTRIBUTES); } @Override protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { super.performBoottime(context, operation, model); context.addStep(new AbstractDeploymentChainStep() { public void execute(DeploymentProcessorTarget processorTarget) { processorTarget.addDeploymentProcessor(MicroProfileHealthExtension.SUBSYSTEM_NAME, DEPENDENCIES, DEPENDENCIES_MICROPROFILE_HEALTH, new DependencyProcessor()); processorTarget.addDeploymentProcessor(MicroProfileHealthExtension.SUBSYSTEM_NAME, POST_MODULE, POST_MODULE_MICROPROFILE_HEALTH, new DeploymentProcessor()); } }, RUNTIME); final boolean securityEnabled = MicroProfileHealthSubsystemDefinition.SECURITY_ENABLED.resolveModelAttribute(context, model).asBoolean(); final String emptyLivenessChecksStatus = MicroProfileHealthSubsystemDefinition.EMPTY_LIVENESS_CHECKS_STATUS.resolveModelAttribute(context, model).asString(); final String emptyReadinessChecksStatus = MicroProfileHealthSubsystemDefinition.EMPTY_READINESS_CHECKS_STATUS.resolveModelAttribute(context, model).asString(); final String emptyStartupChecksStatus = MicroProfileHealthSubsystemDefinition.EMPTY_STARTUP_CHECKS_STATUS.resolveModelAttribute(context, model).asString(); HealthHTTPSecurityService.install(context, securityEnabled); MicroProfileHealthReporterService.install(context, emptyLivenessChecksStatus, emptyReadinessChecksStatus, emptyStartupChecksStatus); MicroProfileHealthContextService.install(context); MicroProfileHealthLogger.LOGGER.activatingSubsystem(); } }
4,093
53.586667
174
java
null
wildfly-main/microprofile/health-smallrye/src/main/java/org/wildfly/extension/microprofile/health/MicroProfileHealthParser_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.wildfly.extension.microprofile.health; import static org.jboss.as.controller.PersistentResourceXMLDescription.builder; import static org.wildfly.extension.microprofile.health.MicroProfileHealthSubsystemDefinition.EMPTY_LIVENESS_CHECKS_STATUS; import static org.wildfly.extension.microprofile.health.MicroProfileHealthSubsystemDefinition.EMPTY_READINESS_CHECKS_STATUS; import static org.wildfly.extension.microprofile.health.MicroProfileHealthSubsystemDefinition.SECURITY_ENABLED; import org.jboss.as.controller.PersistentResourceXMLDescription; import org.jboss.as.controller.PersistentResourceXMLParser; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2019 Red Hat inc. */ public class MicroProfileHealthParser_2_0 extends PersistentResourceXMLParser { /** * The name space used for the {@code subsystem} element */ public static final String NAMESPACE = "urn:wildfly:microprofile-health-smallrye:2.0"; private static final PersistentResourceXMLDescription xmlDescription; static { xmlDescription = builder(MicroProfileHealthExtension.SUBSYSTEM_PATH, NAMESPACE) .addAttributes(SECURITY_ENABLED, EMPTY_LIVENESS_CHECKS_STATUS, EMPTY_READINESS_CHECKS_STATUS) .build(); } @Override public PersistentResourceXMLDescription getParserDescription() { return xmlDescription; } }
2,469
42.333333
124
java
null
wildfly-main/microprofile/health-smallrye/src/main/java/org/wildfly/extension/microprofile/health/HealthHTTPSecurityService.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.health; import static org.wildfly.extension.health.HealthSubsystemDefinition.HEALTH_HTTP_SECURITY_CAPABILITY; import java.util.function.Consumer; import org.jboss.as.controller.OperationContext; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StopContext; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc. */ public class HealthHTTPSecurityService implements Service { private final boolean securityEnabled; private final Consumer<Boolean> consumer; static void install(OperationContext context, boolean securityEnabled) { ServiceBuilder<?> serviceBuilder = context.getServiceTarget().addService(ServiceName.parse(HEALTH_HTTP_SECURITY_CAPABILITY)); Consumer<Boolean> consumer = serviceBuilder.provides(ServiceName.parse(HEALTH_HTTP_SECURITY_CAPABILITY)); serviceBuilder.setInstance(new HealthHTTPSecurityService(consumer, securityEnabled)).install(); } public HealthHTTPSecurityService(Consumer<Boolean> consumer, boolean securityEnabled) { this.consumer = consumer; this.securityEnabled = securityEnabled; } @Override public void start(StartContext context) { consumer.accept(securityEnabled); } @Override public void stop(StopContext context) { consumer.accept(null); } }
2,533
35.724638
133
java
null
wildfly-main/microprofile/health-smallrye/src/main/java/org/wildfly/extension/microprofile/health/MicroProfileHealthReporterService.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.health; import static org.wildfly.extension.microprofile.health.MicroProfileHealthSubsystemDefinition.HEALTH_SERVER_PROBE_CAPABILITY; import static org.wildfly.extension.microprofile.health.MicroProfileHealthSubsystemDefinition.MICROPROFILE_HEALTH_REPORTER_CAPABILITY; import java.util.function.Supplier; import io.smallrye.health.ResponseProvider; import io.smallrye.health.SmallRyeHealthReporter; import org.eclipse.microprofile.config.ConfigProvider; import org.eclipse.microprofile.health.HealthCheck; import org.eclipse.microprofile.health.HealthCheckResponse; import org.eclipse.microprofile.health.HealthCheckResponseBuilder; import org.jboss.as.controller.CapabilityServiceBuilder; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.dmr.Property; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StopContext; import org.wildfly.extension.health.ServerProbe; import org.wildfly.extension.health.ServerProbesService; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc. * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class MicroProfileHealthReporterService implements Service<MicroProfileHealthReporter> { private static MicroProfileHealthReporter healthReporter; private Supplier<ServerProbesService> serverProbesService; private String emptyLivenessChecksStatus; private String emptyReadinessChecksStatus; private String emptyStartupChecksStatus; static void install(OperationContext context, String emptyLivenessChecksStatus, String emptyReadinessChecksStatus, String emptyStartupChecksStatus) { CapabilityServiceBuilder<?> serviceBuilder = context.getCapabilityServiceTarget() .addCapability(RuntimeCapability.Builder.of(MICROPROFILE_HEALTH_REPORTER_CAPABILITY, SmallRyeHealthReporter.class).build()); Supplier<ServerProbesService> serverProbesService = serviceBuilder.requires(ServiceName.parse(HEALTH_SERVER_PROBE_CAPABILITY)); serviceBuilder.setInstance(new MicroProfileHealthReporterService(serverProbesService, emptyLivenessChecksStatus, emptyReadinessChecksStatus, emptyStartupChecksStatus)) .install(); } private MicroProfileHealthReporterService(Supplier<ServerProbesService> serverProbesService, String emptyLivenessChecksStatus, String emptyReadinessChecksStatus, String emptyStartupChecksStatus) { this.serverProbesService = serverProbesService; this.emptyLivenessChecksStatus = emptyLivenessChecksStatus; this.emptyReadinessChecksStatus = emptyReadinessChecksStatus; this.emptyStartupChecksStatus = emptyStartupChecksStatus; } @Override public void start(StartContext context) { // MicroProfile Health supports the mp.health.disable-default-procedures to let users disable any vendor procedures final boolean defaultServerProceduresDisabled = ConfigProvider.getConfig().getOptionalValue("mp.health.disable-default-procedures", Boolean.class).orElse(false); // MicroProfile Health supports the mp.health.default.readiness.empty.response to let users specify default empty readiness responses final String defaultReadinessEmptyResponse = ConfigProvider.getConfig().getOptionalValue("mp.health.default.readiness.empty.response", String.class).orElse("DOWN"); // MicroProfile Health supports the mp.health.default.startup.empty.response to let users specify default empty startup responses final String defaultStartupEmptyResponse = ConfigProvider.getConfig().getOptionalValue("mp.health.default.startup.empty.response", String.class).orElse("DOWN"); healthReporter = new MicroProfileHealthReporter(emptyLivenessChecksStatus, emptyReadinessChecksStatus, emptyStartupChecksStatus, defaultServerProceduresDisabled, defaultReadinessEmptyResponse, defaultStartupEmptyResponse); if (!defaultServerProceduresDisabled) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); for (ServerProbe serverProbe : serverProbesService.get().getServerProbes()) { healthReporter.addServerReadinessCheck(wrap(serverProbe), tccl); } } HealthCheckResponse.setResponseProvider(new ResponseProvider()); } @Override public void stop(StopContext context) { healthReporter = null; HealthCheckResponse.setResponseProvider(null); } @Override public MicroProfileHealthReporter getValue() { return healthReporter; } static HealthCheck wrap(ServerProbe delegate) { return new HealthCheck() { @Override public HealthCheckResponse call() { ServerProbe.Outcome outcome = delegate.getOutcome(); HealthCheckResponseBuilder check = HealthCheckResponse.named(delegate.getName()) .status(outcome.isSuccess()); if (outcome.getData().isDefined()) { for (Property property : outcome.getData().asPropertyList()) { check.withData(property.getName(), property.getValue().asString()); } } return check.build(); } }; } }
6,554
49.423077
172
java
null
wildfly-main/microprofile/health-smallrye/src/main/java/org/wildfly/extension/microprofile/health/MicroProfileHealthContextService.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.health; import static org.wildfly.extension.microprofile.health.MicroProfileHealthSubsystemDefinition.HTTP_CONTEXT_SERVICE; import java.util.function.Supplier; import io.smallrye.health.SmallRyeHealth; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.util.Headers; import org.jboss.as.controller.OperationContext; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StopContext; import org.wildfly.extension.health.HealthContextService; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc. */ public class MicroProfileHealthContextService implements Service { private final Supplier<MicroProfileHealthReporter> healthReporter; private Supplier<HealthContextService> healthContextService; static void install(OperationContext context) { ServiceBuilder<?> serviceBuilder = context.getServiceTarget().addService(HTTP_CONTEXT_SERVICE); Supplier<HealthContextService> healthContextService = serviceBuilder.requires(context.getCapabilityServiceName(MicroProfileHealthSubsystemDefinition.HEALTH_HTTP_CONTEXT_CAPABILITY, HealthContextService.class)); Supplier<MicroProfileHealthReporter> healthReporter = serviceBuilder.requires(context.getCapabilityServiceName(MicroProfileHealthSubsystemDefinition.MICROPROFILE_HEALTH_REPORTER_CAPABILITY, MicroProfileHealthReporter.class)); serviceBuilder.setInstance(new MicroProfileHealthContextService(healthContextService, healthReporter)) .install(); } private MicroProfileHealthContextService(Supplier<HealthContextService> healthContextService, Supplier<MicroProfileHealthReporter> healthReporter) { this.healthContextService = healthContextService; this.healthReporter = healthReporter; } @Override public void start(StartContext context) { healthContextService.get().setOverrideableHealthHandler(new HealthCheckHandler(healthReporter.get())); } @Override public void stop(StopContext context) { healthContextService.get().setOverrideableHealthHandler(null); } private class HealthCheckHandler implements HttpHandler { private final MicroProfileHealthReporter healthReporter; public static final String HEALTH = "/health" ; public static final String HEALTH_LIVE = HEALTH + "/live"; public static final String HEALTH_READY = HEALTH + "/ready"; public static final String HEALTH_STARTED = HEALTH + "/started"; public HealthCheckHandler(MicroProfileHealthReporter healthReporter) { this.healthReporter = healthReporter; } @Override public void handleRequest(HttpServerExchange exchange) { final SmallRyeHealth health; if (HEALTH.equals(exchange.getRequestPath())) { health = healthReporter.getHealth(); } else if (HEALTH_LIVE.equals(exchange.getRequestPath())) { health = healthReporter.getLiveness(); } else if (HEALTH_READY.equals(exchange.getRequestPath())) { health = healthReporter.getReadiness(); } else if (HEALTH_STARTED.equals(exchange.getRequestPath())) { health = healthReporter.getStartup(); } else { exchange.setStatusCode(404); return; } exchange.setStatusCode(health.isDown() ? 503 : 200) .getResponseHeaders().add(Headers.CONTENT_TYPE, "application/json"); exchange.getResponseSender().send(health.getPayload().toString()); } } }
4,800
42.252252
233
java
null
wildfly-main/microprofile/health-smallrye/src/main/java/org/wildfly/extension/microprofile/health/MicroProfileHealthParser_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.health; 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 MicroProfileHealthParser_1_0 extends PersistentResourceXMLParser { /** * The name space used for the {@code subsystem} element */ public static final String NAMESPACE = "urn:wildfly:microprofile-health-smallrye:1.0"; private static final PersistentResourceXMLDescription xmlDescription; static { xmlDescription = builder(MicroProfileHealthExtension.SUBSYSTEM_PATH, NAMESPACE) .addAttribute(MicroProfileHealthSubsystemDefinition.SECURITY_ENABLED) .build(); } @Override public PersistentResourceXMLDescription getParserDescription() { return xmlDescription; } }
2,036
38.173077
90
java
null
wildfly-main/microprofile/health-smallrye/src/main/java/org/wildfly/extension/microprofile/health/MicroProfileHealthParser_3_0.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.health; import org.jboss.as.controller.PersistentResourceXMLDescription; import org.jboss.as.controller.PersistentResourceXMLParser; import static org.jboss.as.controller.PersistentResourceXMLDescription.builder; import static org.wildfly.extension.microprofile.health.MicroProfileHealthSubsystemDefinition.EMPTY_LIVENESS_CHECKS_STATUS; import static org.wildfly.extension.microprofile.health.MicroProfileHealthSubsystemDefinition.EMPTY_READINESS_CHECKS_STATUS; import static org.wildfly.extension.microprofile.health.MicroProfileHealthSubsystemDefinition.EMPTY_STARTUP_CHECKS_STATUS; import static org.wildfly.extension.microprofile.health.MicroProfileHealthSubsystemDefinition.SECURITY_ENABLED; /** * @author <a href="http://xstefank.io/">Martin Stefanko</a> (c) 2021 Red Hat inc. */ public class MicroProfileHealthParser_3_0 extends PersistentResourceXMLParser { /** * The name space used for the {@code subsystem} element */ public static final String NAMESPACE = "urn:wildfly:microprofile-health-smallrye:3.0"; private static final PersistentResourceXMLDescription xmlDescription; static { xmlDescription = builder(MicroProfileHealthExtension.SUBSYSTEM_PATH, NAMESPACE) .addAttributes(SECURITY_ENABLED, EMPTY_LIVENESS_CHECKS_STATUS, EMPTY_READINESS_CHECKS_STATUS, EMPTY_STARTUP_CHECKS_STATUS) .build(); } @Override public PersistentResourceXMLDescription getParserDescription() { return xmlDescription; } }
2,649
43.915254
124
java
null
wildfly-main/microprofile/health-smallrye/src/main/java/org/wildfly/extension/microprofile/health/_private/MicroProfileHealthLogger.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.health._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; /** * Log messages for WildFly microprofile-health-smallrye Extension. * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc. */ @MessageLogger(projectCode = "WFLYMPHEALTH", length = 4) public interface MicroProfileHealthLogger extends BasicLogger { /** * A logger with the category {@code org.wildfly.extension.batch}. */ MicroProfileHealthLogger LOGGER = Logger.getMessageLogger(MicroProfileHealthLogger.class, "org.wildfly.extension.microprofile.health.smallrye"); /** * Logs an informational message indicating the naming subsystem is being activated. */ @LogMessage(level = INFO) @Message(id = 1, value = "Activating MicroProfile Health Subsystem") void activatingSubsystem(); @Message(id = 2, value = "Deployment %s requires use of the '%s' capability but it is not currently registered") DeploymentUnitProcessingException deploymentRequiresCapability(String deploymentName, String capabilityName); @LogMessage(level = WARN) @Message(id = 3, value = "Reporting health down status: %s") void healthDownStatus(String cause); // 4, 5 and 6 are taken downstream /* @Message(id = 4, value = "") OperationFailedException seeDownstream(); @Message(id = 5, value = "") String seeDownstream(); @Message(id = 6, value = "") OperationFailedException seeDownstream(); */ }
2,882
38.493151
148
java
null
wildfly-main/microprofile/health-smallrye/src/main/java/org/wildfly/extension/microprofile/health/deployment/DeploymentProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.health.deployment; import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME; 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.weld.WeldCapability; import org.jboss.modules.Module; import org.wildfly.extension.microprofile.health.MicroProfileHealthReporter; import org.wildfly.extension.microprofile.health.MicroProfileHealthSubsystemDefinition; import org.wildfly.extension.microprofile.health._private.MicroProfileHealthLogger; /** */ public class DeploymentProcessor implements DeploymentUnitProcessor { @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); Module module = deploymentUnit.getAttachment(Attachments.MODULE); final CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT); final WeldCapability weldCapability; try { weldCapability = support.getCapabilityRuntimeAPI(WELD_CAPABILITY_NAME, WeldCapability.class); } catch (CapabilityServiceSupport.NoSuchCapabilityException e) { //We should not be here since the subsystem depends on weld capability. Just in case ... throw MicroProfileHealthLogger.LOGGER.deploymentRequiresCapability( deploymentUnit.getName(), WELD_CAPABILITY_NAME); } if (weldCapability.isPartOfWeldDeployment(deploymentUnit)) { final MicroProfileHealthReporter healthReporter = (MicroProfileHealthReporter) phaseContext.getServiceRegistry().getService(MicroProfileHealthSubsystemDefinition.HEALTH_REPORTER_SERVICE).getValue(); weldCapability.registerExtensionInstance(new CDIExtension(healthReporter, module), deploymentUnit); } } }
3,244
48.166667
210
java
null
wildfly-main/microprofile/health-smallrye/src/main/java/org/wildfly/extension/microprofile/health/deployment/CDIExtension.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.health.deployment; import java.util.ArrayList; import java.util.List; import java.util.function.BiConsumer; import java.util.function.Consumer; import jakarta.enterprise.event.Observes; import jakarta.enterprise.inject.Instance; import jakarta.enterprise.inject.spi.AfterDeploymentValidation; import jakarta.enterprise.inject.spi.BeanManager; import jakarta.enterprise.inject.spi.BeforeShutdown; import jakarta.enterprise.inject.spi.Extension; import jakarta.enterprise.inject.spi.ProcessAnnotatedType; import jakarta.enterprise.util.AnnotationLiteral; import io.smallrye.health.SmallRyeHealthReporter; import org.eclipse.microprofile.config.Config; import org.eclipse.microprofile.config.ConfigProvider; import org.eclipse.microprofile.health.HealthCheck; import org.eclipse.microprofile.health.HealthCheckResponse; import org.eclipse.microprofile.health.Liveness; import org.eclipse.microprofile.health.Readiness; import org.eclipse.microprofile.health.Startup; import org.jboss.modules.Module; import org.wildfly.extension.microprofile.health.MicroProfileHealthReporter; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ public class CDIExtension implements Extension { private final String MP_HEALTH_DISABLE_DEFAULT_PROCEDURES = "mp.health.disable-default-procedures"; private final MicroProfileHealthReporter reporter; private final Module module; // Use a single Jakarta Contexts and Dependency Injection instance to select and destroy all HealthCheck probes instances private Instance<Object> instance; private final List<HealthCheck> livenessChecks = new ArrayList<>(); private final List<HealthCheck> readinessChecks = new ArrayList<>(); private final List<HealthCheck> startupChecks = new ArrayList<>(); private HealthCheck defaultReadinessCheck; private HealthCheck defaultStartupCheck; public CDIExtension(MicroProfileHealthReporter healthReporter, Module module) { this.reporter = healthReporter; this.module = module; } /** * Get Jakarta Contexts and Dependency Injection <em>instances</em> of HealthCheck and * add them to the {@link MicroProfileHealthReporter}. */ private void afterDeploymentValidation(@Observes final AfterDeploymentValidation avd, BeanManager bm) { instance = bm.createInstance(); addHealthChecks(Liveness.Literal.INSTANCE, reporter::addLivenessCheck, livenessChecks); addHealthChecks(Readiness.Literal.INSTANCE, reporter::addReadinessCheck, readinessChecks); addHealthChecks(Startup.Literal.INSTANCE, reporter::addStartupCheck, startupChecks); reporter.setUserChecksProcessed(true); if (readinessChecks.isEmpty()) { Config config = ConfigProvider.getConfig(module.getClassLoader()); boolean disableDefaultprocedure = config.getOptionalValue(MP_HEALTH_DISABLE_DEFAULT_PROCEDURES, Boolean.class).orElse(false); if (!disableDefaultprocedure) { // no readiness probe are present in the deployment. register a readiness check so that the deployment is considered ready defaultReadinessCheck = new DefaultReadinessHealthCheck(module.getName()); reporter.addReadinessCheck(defaultReadinessCheck, module.getClassLoader()); } } if (startupChecks.isEmpty()) { Config config = ConfigProvider.getConfig(module.getClassLoader()); boolean disableDefaultprocedure = config.getOptionalValue(MP_HEALTH_DISABLE_DEFAULT_PROCEDURES, Boolean.class).orElse(false); if (!disableDefaultprocedure) { // no startup probes are present in the deployment. register a startup check so that the deployment is considered started defaultStartupCheck = new DefaultStartupHealthCheck(module.getName()); reporter.addStartupCheck(defaultStartupCheck, module.getClassLoader()); } } } private void addHealthChecks(AnnotationLiteral qualifier, BiConsumer<HealthCheck, ClassLoader> healthFunction, List<HealthCheck> healthChecks) { for (HealthCheck healthCheck : instance.select(HealthCheck.class, qualifier)) { healthFunction.accept(healthCheck, module.getClassLoader()); healthChecks.add(healthCheck); } } /** * Called when the deployment is undeployed. * <p> * Remove all the instances of {@link HealthCheck} from the {@link MicroProfileHealthReporter}. */ public void beforeShutdown(@Observes final BeforeShutdown bs) { removeHealthCheck(livenessChecks, reporter::removeLivenessCheck); removeHealthCheck(readinessChecks, reporter::removeReadinessCheck); removeHealthCheck(startupChecks, reporter::removeStartupCheck); if (defaultReadinessCheck != null) { reporter.removeReadinessCheck(defaultReadinessCheck); defaultReadinessCheck = null; } if (defaultStartupCheck != null) { reporter.removeStartupCheck(defaultStartupCheck); defaultStartupCheck = null; } instance = null; } private void removeHealthCheck(List<HealthCheck> healthChecks, Consumer<HealthCheck> healthFunction) { for (HealthCheck healthCheck : healthChecks) { healthFunction.accept(healthCheck); instance.destroy(healthCheck); } healthChecks.clear(); } public void vetoSmallryeHealthReporter(@Observes ProcessAnnotatedType<SmallRyeHealthReporter> pat) { pat.veto(); } private static final class DefaultReadinessHealthCheck implements HealthCheck { private final String deploymentName; DefaultReadinessHealthCheck(String deploymentName) { this.deploymentName = deploymentName; } @Override public HealthCheckResponse call() { return HealthCheckResponse.named("ready-" + deploymentName) .up() .build(); } } private static final class DefaultStartupHealthCheck implements HealthCheck { private final String deploymentName; DefaultStartupHealthCheck(String deploymentName) { this.deploymentName = deploymentName; } @Override public HealthCheckResponse call() { return HealthCheckResponse.named("started-" + deploymentName) .up() .build(); } } }
7,656
40.84153
138
java
null
wildfly-main/microprofile/health-smallrye/src/main/java/org/wildfly/extension/microprofile/health/deployment/DependencyProcessor.java
package org.wildfly.extension.microprofile.health.deployment; 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.modules.Module; import org.jboss.modules.ModuleLoader; /** * Add dependencies required by deployment unit to access the Config API (programmatically or using CDI). */ public class DependencyProcessor implements DeploymentUnitProcessor { @Override public void deploy(DeploymentPhaseContext phaseContext) { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); addModuleDependencies(deploymentUnit); } private static 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.health.api", false, false, false, false)); } }
1,318
40.21875
151
java
null
wildfly-main/xts/src/test/java/org/jboss/as/xts/XTSSubsystemTestCase.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.xts; import java.io.IOException; import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest; /** * @author <a href="[email protected]">Kabir Khan</a> */ public class XTSSubsystemTestCase extends AbstractSubsystemBaseTest { public XTSSubsystemTestCase() { super(XTSExtension.SUBSYSTEM_NAME, new XTSExtension()); } @Override protected String getSubsystemXml() throws IOException { return readResource(String.format("subsystem-%s.xml", XTSExtension.CURRENT_MODEL_VERSION)); } @Override protected String getSubsystemXsdPath() { return "schema/jboss-as-xts_3_0.xsd"; } }
1,667
35.26087
99
java
null
wildfly-main/xts/src/main/java/org/jboss/as/xts/XTSSubsystemParser.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.xts; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.xts.XTSSubsystemDefinition.DEFAULT_CONTEXT_PROPAGATION; import static org.jboss.as.xts.XTSSubsystemDefinition.ASYNC_REGISTRATION; import static org.jboss.as.xts.XTSSubsystemDefinition.ENVIRONMENT_URL; import static org.jboss.as.xts.XTSSubsystemDefinition.HOST_NAME; import java.util.ArrayList; 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.operations.common.Util; import org.jboss.as.controller.parsing.ParseUtils; 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]">Andrew Dinn</a> * @author <a href="mailto:[email protected]">Tomaz Cerar</a> */ class XTSSubsystemParser implements XMLStreamConstants, XMLElementReader<List<ModelNode>>, XMLElementWriter<SubsystemMarshallingContext> { /** * {@inheritDoc} */ @Override public void readElement(XMLExtendedStreamReader reader, List<ModelNode> list) throws XMLStreamException { // no attributes if (reader.getAttributeCount() > 0) { throw ParseUtils.unexpectedAttribute(reader, 0); } final ModelNode subsystem = Util.getEmptyOperation(ADD, PathAddress.pathAddress(XTSExtension.SUBSYSTEM_PATH) .toModelNode()); list.add(subsystem); final EnumSet<Element> encountered = EnumSet.noneOf(Element.class); final List<Element> expected = getExpectedElements(reader); while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { final Element element = Element.forName(reader.getLocalName()); if (!expected.contains(element) || !encountered.add(element)) { throw ParseUtils.unexpectedElement(reader); } switch (element) { case HOST: { parseHostElement(reader, subsystem); break; } case XTS_ENVIRONMENT: { parseXTSEnvironmentElement(reader,subsystem); break; } case DEFAULT_CONTEXT_PROPAGATION: { parseDefaultContextPropagationElement(reader, subsystem); break; } case ASYNC_REGISTRATION: { parseAsyncRegistrationElement(reader, subsystem); break; } default: { throw ParseUtils.unexpectedElement(reader); } } } } /** * {@inheritDoc} XMLExtendedStreamReader reader */ @Override public void writeContent(XMLExtendedStreamWriter writer, SubsystemMarshallingContext context) throws XMLStreamException { context.startSubsystemElement(Namespace.CURRENT.getUriString(), false); ModelNode node = context.getModelNode(); if (node.hasDefined(HOST_NAME.getName())) { writer.writeStartElement(Element.HOST.getLocalName()); HOST_NAME.marshallAsAttribute(node, writer); writer.writeEndElement(); } if (node.hasDefined(ENVIRONMENT_URL.getName())) { writer.writeStartElement(Element.XTS_ENVIRONMENT.getLocalName()); ENVIRONMENT_URL.marshallAsAttribute(node, writer); writer.writeEndElement(); } if (node.hasDefined(DEFAULT_CONTEXT_PROPAGATION.getName())) { writer.writeStartElement(Element.DEFAULT_CONTEXT_PROPAGATION.getLocalName()); DEFAULT_CONTEXT_PROPAGATION.marshallAsAttribute(node, writer); writer.writeEndElement(); } if (node.hasDefined(ASYNC_REGISTRATION.getName())) { writer.writeStartElement(Element.ASYNC_REGISTRATION.getLocalName()); ASYNC_REGISTRATION.marshallAsAttribute(node, writer); writer.writeEndElement(); } writer.writeEndElement(); } private void parseHostElement(XMLExtendedStreamReader reader, ModelNode subsystem) throws XMLStreamException { final EnumSet<Attribute> required = EnumSet.of(Attribute.NAME); processAttributes(reader, (index, attribute) -> { required.remove(attribute); final String value = reader.getAttributeValue(index); switch (attribute) { case NAME: HOST_NAME.parseAndSetParameter(value, subsystem, reader); break; default: throw ParseUtils.unexpectedAttribute(reader, index); } }); // Handle elements ParseUtils.requireNoContent(reader); if (!required.isEmpty()) { throw ParseUtils.missingRequired(reader, required); } } /** * Handle the xts-environment element * * * @param reader * @param subsystem * @return ModelNode for the core-environment * @throws javax.xml.stream.XMLStreamException * */ private void parseXTSEnvironmentElement(XMLExtendedStreamReader reader, ModelNode subsystem) throws XMLStreamException { processAttributes(reader, (index, attribute) -> { final String value = reader.getAttributeValue(index); switch (attribute) { case URL: ENVIRONMENT_URL.parseAndSetParameter(value, subsystem, reader); break; default: throw ParseUtils.unexpectedAttribute(reader, index); } }); // Handle elements ParseUtils.requireNoContent(reader); } /** * Handle the enable-client-handler element. * * @param reader * @param subsystem * @throws XMLStreamException */ private void parseDefaultContextPropagationElement(XMLExtendedStreamReader reader, ModelNode subsystem) throws XMLStreamException { processAttributes(reader, (index, attribute) -> { final String value = reader.getAttributeValue(index); switch (attribute) { case ENABLED: if (value == null || (!value.toLowerCase().equals("true") && !value.toLowerCase().equals("false"))) { throw ParseUtils.invalidAttributeValue(reader, index); } DEFAULT_CONTEXT_PROPAGATION.parseAndSetParameter(value, subsystem, reader); break; default: throw ParseUtils.unexpectedAttribute(reader, index); } }); // Handle elements ParseUtils.requireNoContent(reader); } /** * Handle the async-registration element. */ private void parseAsyncRegistrationElement(XMLExtendedStreamReader reader, ModelNode subsystem) throws XMLStreamException { processAttributes(reader, (index, attribute) -> { final String value = reader.getAttributeValue(index); switch (attribute) { case ENABLED: ASYNC_REGISTRATION.parseAndSetParameter(value, subsystem, reader); break; default: throw ParseUtils.unexpectedAttribute(reader, index); } }); // Handle elements ParseUtils.requireNoContent(reader); } private List<Element> getExpectedElements(final XMLExtendedStreamReader reader) { final Namespace namespace = Namespace.forUri(reader.getNamespaceURI()); final List<Element> elements = new ArrayList<>(); if (Namespace.XTS_1_0.equals(namespace)) { elements.add(Element.XTS_ENVIRONMENT); } else if (Namespace.XTS_2_0.equals(namespace)) { elements.add(Element.XTS_ENVIRONMENT); elements.add(Element.HOST); elements.add(Element.DEFAULT_CONTEXT_PROPAGATION); } else if (Namespace.XTS_3_0.equals(namespace)) { elements.add(Element.XTS_ENVIRONMENT); elements.add(Element.HOST); elements.add(Element.DEFAULT_CONTEXT_PROPAGATION); elements.add(Element.ASYNC_REGISTRATION); } return elements; } /** * Functional interface to provide similar functionality as {@link BiConsumer} * but with cought exception {@link XMLStreamException} declared. */ @FunctionalInterface private interface AttributeProcessor<T, R> { void process(T t, R r) throws XMLStreamException; } /** * Iterating over all attributes got from the reader parameter. * * @param reader reading the parameters from * @param attributeProcessorCallback callback being processed for each attribute * @throws XMLStreamException troubles parsing xml */ private void processAttributes(final XMLExtendedStreamReader reader, AttributeProcessor<Integer, Attribute> attributeProcessorCallback) throws XMLStreamException { final int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { ParseUtils.requireNoNamespaceAttribute(reader, i); // final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); attributeProcessorCallback.process(i, attribute); } } }
10,835
38.547445
167
java