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/ee/src/main/java/org/jboss/as/ee/component/ResourceInjectionConfiguration.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component; /** * A configuration for resource injection. * * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ public final class ResourceInjectionConfiguration { private final InjectionTarget target; private final InjectionSource source; private final boolean optional; /** * Construct a new instance. * * @param target the resource injection target * @param source the resource injection source * @param optional if the injection is optional or not */ public ResourceInjectionConfiguration(final InjectionTarget target, final InjectionSource source, boolean optional) { this.target = target; this.source = source; this.optional = optional; } /** * Construct a new instance. * * @param target the resource injection target * @param source the resource injection source */ public ResourceInjectionConfiguration(final InjectionTarget target, final InjectionSource source) { this(target, source, false); } /** * Get the resource injection for this configuration. * * @return the resource injection */ public InjectionTarget getTarget() { return target; } /** * Get the injection source for this configuration. * * @return the injection source */ public InjectionSource getSource() { return source; } /** * * @return True if the injection is optional */ public boolean isOptional() { return optional; } }
2,618
30.178571
121
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/AbstractDeploymentDescriptorBindingsProcessor.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jboss.as.ee.logging.EeLogger; import org.jboss.as.ee.component.Attachments; import org.jboss.as.ee.component.BindingConfiguration; import org.jboss.as.ee.component.ComponentDescription; import org.jboss.as.ee.component.DeploymentDescriptorEnvironment; import org.jboss.as.ee.component.EEApplicationClasses; import org.jboss.as.ee.component.EEModuleDescription; import org.jboss.as.ee.component.FieldInjectionTarget; import org.jboss.as.ee.component.InjectionSource; import org.jboss.as.ee.component.InjectionTarget; import org.jboss.as.ee.component.InterceptorEnvironment; import org.jboss.as.ee.component.MethodInjectionTarget; import org.jboss.as.ee.component.ResourceInjectionConfiguration; import org.jboss.as.ee.component.ResourceInjectionTarget; 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.reflect.DeploymentReflectionIndex; import org.jboss.metadata.javaee.spec.ResourceInjectionMetaData; import org.jboss.metadata.javaee.spec.ResourceInjectionTargetMetaData; import org.jboss.modules.Module; import static org.jboss.as.ee.utils.InjectionUtils.getInjectionTarget; /** * Class that provides common functionality required by processors that process environment information from deployment descriptors. * * @author Stuart Douglas * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public abstract class AbstractDeploymentDescriptorBindingsProcessor implements DeploymentUnitProcessor { private static final Map<Class<?>, Class<?>> BOXED_TYPES; static { Map<Class<?>, Class<?>> types = new HashMap<Class<?>, Class<?>>(); types.put(int.class, Integer.class); types.put(byte.class, Byte.class); types.put(short.class, Short.class); types.put(long.class, Long.class); types.put(char.class, Character.class); types.put(float.class, Float.class); types.put(double.class, Double.class); types.put(boolean.class, Boolean.class); BOXED_TYPES = Collections.unmodifiableMap(types); } @Override public final void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final DeploymentDescriptorEnvironment environment = deploymentUnit.getAttachment(Attachments.MODULE_DEPLOYMENT_DESCRIPTOR_ENVIRONMENT); final EEApplicationClasses applicationClasses = deploymentUnit.getAttachment(Attachments.EE_APPLICATION_CLASSES_DESCRIPTION); final Module module = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.MODULE); final DeploymentReflectionIndex deploymentReflectionIndex = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.REFLECTION_INDEX); final EEModuleDescription description = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION); if (module == null || description == null) { return; } if (environment != null) { final List<BindingConfiguration> bindings = processDescriptorEntries(deploymentUnit, environment, description, null, module.getClassLoader(), deploymentReflectionIndex, applicationClasses); description.getBindingConfigurations().addAll(bindings); } for (final ComponentDescription componentDescription : description.getComponentDescriptions()) { if (componentDescription.getDeploymentDescriptorEnvironment() != null) { final List<BindingConfiguration> bindings = processDescriptorEntries(deploymentUnit, componentDescription.getDeploymentDescriptorEnvironment(), componentDescription, componentDescription, module.getClassLoader(), deploymentReflectionIndex, applicationClasses); componentDescription.getBindingConfigurations().addAll(bindings); } } for(final InterceptorEnvironment interceptorEnv : description.getInterceptorEnvironment().values()) { final List<BindingConfiguration> bindings = processDescriptorEntries(deploymentUnit, interceptorEnv.getDeploymentDescriptorEnvironment(), interceptorEnv, null, module.getClassLoader(), deploymentReflectionIndex, applicationClasses); interceptorEnv.getBindingConfigurations().addAll(bindings); } } protected abstract List<BindingConfiguration> processDescriptorEntries(DeploymentUnit deploymentUnit, DeploymentDescriptorEnvironment environment, ResourceInjectionTarget resourceInjectionTarget, final ComponentDescription componentDescription, ClassLoader classLoader, DeploymentReflectionIndex deploymentReflectionIndex, final EEApplicationClasses applicationClasses) throws DeploymentUnitProcessingException; /** * Processes the injection targets of a resource binding * * * @param injectionSource The injection source for the injection target * @param classLoader The module class loader * @param deploymentReflectionIndex The deployment reflection index * @param entry The resource with injection targets * @param classType The expected type of the injection point, may be null if this is to be inferred from the injection target * @return The actual class type of the injection point * @throws DeploymentUnitProcessingException * If the injection points could not be resolved */ protected Class<?> processInjectionTargets(final ResourceInjectionTarget resourceInjectionTarget, InjectionSource injectionSource, ClassLoader classLoader, DeploymentReflectionIndex deploymentReflectionIndex, ResourceInjectionMetaData entry, Class<?> classType) throws DeploymentUnitProcessingException { if (entry.getInjectionTargets() != null) { for (ResourceInjectionTargetMetaData injectionTarget : entry.getInjectionTargets()) { final String injectionTargetClassName = injectionTarget.getInjectionTargetClass(); final String injectionTargetName = injectionTarget.getInjectionTargetName(); final AccessibleObject fieldOrMethod = getInjectionTarget(injectionTargetClassName, injectionTargetName, classLoader, deploymentReflectionIndex); final Class<?> injectionTargetType = fieldOrMethod instanceof Field ? ((Field) fieldOrMethod).getType() : ((Method) fieldOrMethod).getParameterTypes()[0]; final String memberName = fieldOrMethod instanceof Field ? ((Field) fieldOrMethod).getName() : ((Method) fieldOrMethod).getName(); if (classType != null) { if (!injectionTargetType.isAssignableFrom(classType)) { boolean ok = false; if (classType.isPrimitive()) { if (BOXED_TYPES.get(classType).equals(injectionTargetType)) { ok = true; } } else if (injectionTargetType.isPrimitive() && BOXED_TYPES.get(injectionTargetType).equals(classType)) { ok = true; } if (!ok) { throw EeLogger.ROOT_LOGGER.invalidInjectionTarget(injectionTarget.getInjectionTargetName(), injectionTarget.getInjectionTargetClass(), classType); } classType = injectionTargetType; } } else { classType = injectionTargetType; } final InjectionTarget injectionTargetDescription = fieldOrMethod instanceof Field ? new FieldInjectionTarget(injectionTargetClassName, memberName, classType.getName()) : new MethodInjectionTarget(injectionTargetClassName, memberName, classType.getName()); final ResourceInjectionConfiguration injectionConfiguration = new ResourceInjectionConfiguration(injectionTargetDescription, injectionSource); resourceInjectionTarget.addResourceInjection(injectionConfiguration); } } return classType; } }
9,704
57.818182
415
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/ResourceInjectionAnnotationParsingProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import org.jboss.as.ee.logging.EeLogger; import org.jboss.as.ee.component.Attachments; import org.jboss.as.ee.component.BindingConfiguration; import org.jboss.as.ee.component.EEApplicationClasses; import org.jboss.as.ee.component.EEModuleClassDescription; import org.jboss.as.ee.component.EEModuleDescription; import org.jboss.as.ee.component.FieldInjectionTarget; import org.jboss.as.ee.component.InjectionSource; import org.jboss.as.ee.component.InjectionTarget; import org.jboss.as.ee.component.LookupInjectionSource; import org.jboss.as.ee.component.MethodInjectionTarget; import org.jboss.as.ee.component.ResourceInjectionConfiguration; import org.jboss.as.ee.structure.EJBAnnotationPropertyReplacement; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.annotation.CompositeIndex; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.AnnotationTarget; import org.jboss.jandex.AnnotationValue; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; import org.jboss.jandex.FieldInfo; import org.jboss.jandex.MethodInfo; import org.jboss.metadata.property.PropertyReplacer; import org.jboss.modules.Module; import jakarta.annotation.Resource; import jakarta.annotation.Resources; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; /** * Deployment processor responsible for analyzing each attached {@link org.jboss.as.ee.component.ComponentDescription} instance to configure * required resource injection configurations. * * @author John Bailey * @author <a href="mailto:[email protected]">David M. Lloyd</a> * @author <a href="mailto:[email protected]">Richard Opalka</a> * @author Eduardo Martins */ public class ResourceInjectionAnnotationParsingProcessor implements DeploymentUnitProcessor { private static final DotName RESOURCE_ANNOTATION_NAME = DotName.createSimple(Resource.class.getName()); private static final DotName RESOURCES_ANNOTATION_NAME = DotName.createSimple(Resources.class.getName()); private static final String JAVAX_NAMING_CONTEXT = "javax.naming.Context"; public static final Map<String, String> FIXED_LOCATIONS; public static final Set<String> SIMPLE_ENTRIES; static { final Map<String, String> locations = new HashMap<String, String>(); locations.put("jakarta.transaction.UserTransaction", "java:jboss/UserTransaction"); locations.put("jakarta.transaction.TransactionSynchronizationRegistry", "java:jboss/TransactionSynchronizationRegistry"); //we have to be careful with java:comp lookups here //as they will not work in entries in application.xml, as there is no comp context available //so we can only use it for resources that are not valid to be entries in application.xml locations.put("jakarta.enterprise.inject.spi.BeanManager", "java:comp/BeanManager"); locations.put("jakarta.ejb.TimerService", "java:comp/TimerService"); locations.put("org.omg.CORBA.ORB", "java:comp/ORB"); FIXED_LOCATIONS = Collections.unmodifiableMap(locations); final Set<String> simpleEntries = new HashSet<String>(); simpleEntries.add("boolean"); simpleEntries.add("char"); simpleEntries.add("byte"); simpleEntries.add("short"); simpleEntries.add("int"); simpleEntries.add("long"); simpleEntries.add("double"); simpleEntries.add("float"); simpleEntries.add("java.lang.Boolean"); simpleEntries.add("java.lang.Character"); simpleEntries.add("java.lang.Byte"); simpleEntries.add("java.lang.Short"); simpleEntries.add("java.lang.Integer"); simpleEntries.add("java.lang.Long"); simpleEntries.add("java.lang.Double"); simpleEntries.add("java.lang.Float"); simpleEntries.add("java.lang.String"); simpleEntries.add("java.lang.Class"); SIMPLE_ENTRIES = Collections.unmodifiableSet(simpleEntries); } public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION); final CompositeIndex index = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.COMPOSITE_ANNOTATION_INDEX); final EEApplicationClasses applicationClasses = deploymentUnit.getAttachment(Attachments.EE_APPLICATION_CLASSES_DESCRIPTION); final Module module = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.MODULE); final PropertyReplacer replacer = EJBAnnotationPropertyReplacement.propertyReplacer(deploymentUnit); if (module == null) { return; } final List<AnnotationInstance> resourceAnnotations = index.getAnnotations(RESOURCE_ANNOTATION_NAME); for (AnnotationInstance annotation : resourceAnnotations) { final AnnotationTarget annotationTarget = annotation.target(); final AnnotationValue nameValue = annotation.value("name"); final String name = (nameValue != null) ? replacer.replaceProperties(nameValue.asString()) : null; final AnnotationValue typeValue = annotation.value("type"); final String type = typeValue != null ? typeValue.asClass().name().toString() : null; if (annotationTarget instanceof FieldInfo) { final FieldInfo fieldInfo = (FieldInfo) annotationTarget; final ClassInfo classInfo = fieldInfo.declaringClass(); EEModuleClassDescription classDescription = eeModuleDescription.addOrGetLocalClassDescription(classInfo.name().toString()); processFieldResource(phaseContext, fieldInfo, name, type, classDescription, annotation, eeModuleDescription, module, applicationClasses, replacer); } else if (annotationTarget instanceof MethodInfo) { final MethodInfo methodInfo = (MethodInfo) annotationTarget; ClassInfo classInfo = methodInfo.declaringClass(); EEModuleClassDescription classDescription = eeModuleDescription.addOrGetLocalClassDescription(classInfo.name().toString()); processMethodResource(phaseContext, methodInfo, name, type, classDescription, annotation, eeModuleDescription, module, applicationClasses, replacer); } else if (annotationTarget instanceof ClassInfo) { final ClassInfo classInfo = (ClassInfo) annotationTarget; EEModuleClassDescription classDescription = eeModuleDescription.addOrGetLocalClassDescription(classInfo.name().toString()); processClassResource(phaseContext, name, type, classDescription, annotation, eeModuleDescription, module, applicationClasses, replacer); } } final List<AnnotationInstance> resourcesAnnotations = index.getAnnotations(RESOURCES_ANNOTATION_NAME); for (AnnotationInstance outerAnnotation : resourcesAnnotations) { final AnnotationTarget annotationTarget = outerAnnotation.target(); if (annotationTarget instanceof ClassInfo) { final ClassInfo classInfo = (ClassInfo) annotationTarget; final AnnotationInstance[] values = outerAnnotation.value("value").asNestedArray(); for (AnnotationInstance annotation : values) { final AnnotationValue nameValue = annotation.value("name"); final String name = (nameValue != null) ? replacer.replaceProperties(nameValue.asString()) : null; final AnnotationValue typeValue = annotation.value("type"); final String type = (typeValue != null) ? typeValue.asClass().name().toString() : null; EEModuleClassDescription classDescription = eeModuleDescription.addOrGetLocalClassDescription(classInfo.name().toString()); processClassResource(phaseContext, name, type, classDescription, annotation, eeModuleDescription, module, applicationClasses, replacer); } } } } protected void processFieldResource(final DeploymentPhaseContext phaseContext, final FieldInfo fieldInfo, final String name, final String type, final EEModuleClassDescription classDescription, final AnnotationInstance annotation, final EEModuleDescription eeModuleDescription, final Module module, final EEApplicationClasses applicationClasses, final PropertyReplacer replacer) throws DeploymentUnitProcessingException { final String fieldName = fieldInfo.name(); final String injectionType = isEmpty(type) || type.equals(Object.class.getName()) ? fieldInfo.type().name().toString() : type; final String localContextName = isEmpty(name) ? fieldInfo.declaringClass().name().toString() + "/" + fieldName : name; final InjectionTarget targetDescription = new FieldInjectionTarget(fieldInfo.declaringClass().name().toString(), fieldName, fieldInfo.type().name().toString()); process(phaseContext, classDescription, annotation, injectionType, localContextName, targetDescription, eeModuleDescription, module, applicationClasses, replacer); } protected void processMethodResource(final DeploymentPhaseContext phaseContext, final MethodInfo methodInfo, final String name, final String type, final EEModuleClassDescription classDescription, final AnnotationInstance annotation, final EEModuleDescription eeModuleDescription, final Module module, final EEApplicationClasses applicationClasses, final PropertyReplacer replacer) throws DeploymentUnitProcessingException { final String methodName = methodInfo.name(); if (!methodName.startsWith("set") || methodInfo.args().length != 1) { throw EeLogger.ROOT_LOGGER.setterMethodOnly("@Resource", methodInfo); } final String contextNameSuffix = methodName.substring(3, 4).toLowerCase(Locale.ENGLISH) + methodName.substring(4); final String localContextName = isEmpty(name) ? methodInfo.declaringClass().name().toString() + "/" + contextNameSuffix : name; final String injectionType = isEmpty(type) || type.equals(Object.class.getName()) ? methodInfo.args()[0].name().toString() : type; final InjectionTarget targetDescription = new MethodInjectionTarget(methodInfo.declaringClass().name().toString(), methodName, methodInfo.args()[0].name().toString()); process(phaseContext, classDescription, annotation, injectionType, localContextName, targetDescription, eeModuleDescription, module, applicationClasses, replacer); } protected void processClassResource(final DeploymentPhaseContext phaseContext, final String name, final String type, final EEModuleClassDescription classDescription, final AnnotationInstance annotation, final EEModuleDescription eeModuleDescription, final Module module, final EEApplicationClasses applicationClasses, final PropertyReplacer replacer) throws DeploymentUnitProcessingException { if (isEmpty(name)) { throw EeLogger.ROOT_LOGGER.annotationAttributeMissing("@Resource", "name"); } final String realType; if (isEmpty(type)) { realType = Object.class.getName(); } else { realType = type; } process(phaseContext, classDescription, annotation, realType, name, null, eeModuleDescription, module, applicationClasses, replacer); } protected void process(final DeploymentPhaseContext phaseContext, final EEModuleClassDescription classDescription, final AnnotationInstance annotation, final String injectionType, final String localContextName, final InjectionTarget targetDescription, final EEModuleDescription eeModuleDescription, final Module module, final EEApplicationClasses applicationClasses, final PropertyReplacer replacer) throws DeploymentUnitProcessingException { final EEResourceReferenceProcessorRegistry registry = phaseContext.getDeploymentUnit().getAttachment(Attachments.RESOURCE_REFERENCE_PROCESSOR_REGISTRY); final AnnotationValue lookupAnnotation = annotation.value("lookup"); String lookup = (lookupAnnotation == null) ? null : replacer.replaceProperties(lookupAnnotation.asString()); // if "lookup" hasn't been specified then fallback on "mappedName" which we treat the same as "lookup" if (isEmpty(lookup)) { final AnnotationValue mappedNameAnnotationValue = annotation.value("mappedName"); lookup = (mappedNameAnnotationValue == null) ? null : replacer.replaceProperties(mappedNameAnnotationValue.asString()); } if (isEmpty(lookup) && FIXED_LOCATIONS.containsKey(injectionType)) { lookup = FIXED_LOCATIONS.get(injectionType); } InjectionSource valueSource = null; final boolean isEnvEntryType = this.isEnvEntryType(injectionType, module); if (!isEmpty(lookup)) { valueSource = new LookupInjectionSource(lookup, JAVAX_NAMING_CONTEXT.equals(injectionType)); } else if (isEnvEntryType) { // if it's an env-entry type then we do *not* create a BindingConfiguration to bind to the ENC // since the binding (value) for env-entry is always driven from a deployment descriptor. // The deployment descriptor processing and subsequent binding in the ENC is taken care off by a // different Deployment unit processor. If the value isn't specified in the deployment descriptor, // then there will be no binding the ENC and that's what is expected by the Jakarta EE spec. Furthermore, // if the @Resource is an env-entry binding then the injection target will be optional since in the absence of // an env-entry-value, there won't be a binding and effectively no injection. This again is as expected by spec. } else { //otherwise we just try and handle it //if we don't have a value source we will try and inject from a lookup //and the user has to configure the value in a deployment descriptor final EEResourceReferenceProcessor resourceReferenceProcessor = registry.getResourceReferenceProcessor(injectionType); if (resourceReferenceProcessor != null) { valueSource = resourceReferenceProcessor.getResourceReferenceBindingSource(); } } // EE.5.2.4 // Each injection of an object corresponds to a JNDI lookup. Whether a new // instance of the requested object is injected, or whether a shared instance is // injected, is determined by the rules described above. // Because of performance we allow any type of InjectionSource. if (valueSource == null) { // the ResourceInjectionConfiguration is created by LazyResourceInjection if (targetDescription != null) { final LookupInjectionSource optionalInjection = new LookupInjectionSource(localContextName, true); final ResourceInjectionConfiguration injectionConfiguration = new ResourceInjectionConfiguration(targetDescription, optionalInjection, true); classDescription.addResourceInjection(injectionConfiguration); } } else { // our injection comes from the local lookup, no matter what. final InjectionSource injectionSource = new LookupInjectionSource(localContextName); final ResourceInjectionConfiguration injectionConfiguration = targetDescription != null ? new ResourceInjectionConfiguration(targetDescription, injectionSource) : null; final BindingConfiguration bindingConfiguration = new BindingConfiguration(localContextName, valueSource); classDescription.getBindingConfigurations().add(bindingConfiguration); if (injectionConfiguration != null) { classDescription.addResourceInjection(injectionConfiguration); } } } private boolean isEmpty(final String string) { return string == null || string.isEmpty(); } private boolean isEnvEntryType(final String type, final Module module) { if (SIMPLE_ENTRIES.contains(type)) { return true; } try { return module.getClassLoader().loadClass(type).isEnum(); } catch (ClassNotFoundException e) { return false; } } }
17,934
62.599291
446
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/EEModuleNameProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import org.jboss.as.ee.component.EEModuleDescription; 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 java.util.HashSet; import java.util.List; import java.util.Set; /** * Class that is responsible for resolving name conflicts. * * //TODO: this must be able to deal with the case of module names being changed via deployment descriptor * * @author Stuart Douglas */ public final class EEModuleNameProcessor implements DeploymentUnitProcessor { public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final List<DeploymentUnit> subDeployments = deploymentUnit.getAttachmentList(Attachments.SUB_DEPLOYMENTS); final Set<String> moduleNames = new HashSet<String>(); final Set<String> moduleConflicts = new HashSet<String>(); //look for modules with the same name // for(DeploymentUnit deployment : subDeployments) { final EEModuleDescription module = deployment.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION); if(module != null) { if(moduleNames.contains(module.getModuleName())) { moduleConflicts.add(module.getModuleName()); } moduleNames.add(module.getModuleName()); } } for(DeploymentUnit deployment : subDeployments) { final EEModuleDescription module = deployment.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION); if (module != null && moduleConflicts.contains(module.getModuleName())) { module.setModuleName(deployment.getName()); } } } }
3,123
43
133
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/AroundInvokeAnnotationParsingProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import java.util.List; import jakarta.interceptor.AroundInvoke; import jakarta.interceptor.InvocationContext; import org.jboss.as.ee.logging.EeLogger; import org.jboss.as.ee.component.Attachments; import org.jboss.as.ee.component.EEModuleClassDescription; import org.jboss.as.ee.component.EEModuleDescription; import org.jboss.as.ee.component.interceptors.InterceptorClassDescription; 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.invocation.proxy.MethodIdentifier; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.AnnotationTarget; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; import org.jboss.jandex.MethodInfo; import org.jboss.jandex.Type; /** * Deployment processor responsible for finding @AroundInvoke annotated methods in classes within a deployment. * * @author John Bailey * @author Stuart Douglas */ public class AroundInvokeAnnotationParsingProcessor implements DeploymentUnitProcessor { private static final DotName AROUND_INVOKE_ANNOTATION_NAME = DotName.createSimple(AroundInvoke.class.getName()); @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION); final CompositeIndex index = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.COMPOSITE_ANNOTATION_INDEX); final List<AnnotationInstance> aroundInvokes = index.getAnnotations(AROUND_INVOKE_ANNOTATION_NAME); for (AnnotationInstance annotation : aroundInvokes) { processAroundInvoke(eeModuleDescription, annotation.target()); } } private void processAroundInvoke(final EEModuleDescription eeModuleDescription, final AnnotationTarget target) throws DeploymentUnitProcessingException { if (!(target instanceof MethodInfo)) { throw EeLogger.ROOT_LOGGER.methodOnlyAnnotation(AROUND_INVOKE_ANNOTATION_NAME); } final MethodInfo methodInfo = MethodInfo.class.cast(target); final ClassInfo classInfo = methodInfo.declaringClass(); final EEModuleClassDescription classDescription = eeModuleDescription.addOrGetLocalClassDescription(classInfo.name().toString()); final List<AnnotationInstance> classAroundInvokes = classInfo.annotationsMap().get(AROUND_INVOKE_ANNOTATION_NAME); if(classAroundInvokes.size() > 1) { throw EeLogger.ROOT_LOGGER.aroundInvokeAnnotationUsedTooManyTimes(classInfo.name(), classAroundInvokes.size()); } validateArgumentType(classInfo, methodInfo); InterceptorClassDescription.Builder builder = InterceptorClassDescription.builder(classDescription.getInterceptorClassDescription()); builder.setAroundInvoke(MethodIdentifier.getIdentifier(Object.class, methodInfo.name(), InvocationContext.class)); classDescription.setInterceptorClassDescription(builder.build()); } private void validateArgumentType(final ClassInfo classInfo, final MethodInfo methodInfo) { final Type[] args = methodInfo.args(); switch (args.length) { case 0: throw new IllegalArgumentException(EeLogger.ROOT_LOGGER.invalidSignature(methodInfo.name(), AROUND_INVOKE_ANNOTATION_NAME, classInfo.name(), "Object methodName(InvocationContext ctx)")); case 1: if (!InvocationContext.class.getName().equals(args[0].name().toString())) { throw new IllegalArgumentException(EeLogger.ROOT_LOGGER.invalidSignature(methodInfo.name(), AROUND_INVOKE_ANNOTATION_NAME, classInfo.name(), "Object methodName(InvocationContext ctx)")); } break; default: throw new IllegalArgumentException(EeLogger.ROOT_LOGGER.invalidNumberOfArguments(methodInfo.name(), AROUND_INVOKE_ANNOTATION_NAME, classInfo.name())); } if (!methodInfo.returnType().name().toString().equals(Object.class.getName())) { throw EeLogger.ROOT_LOGGER.invalidReturnType(Object.class.getName(), methodInfo.name(), AROUND_INVOKE_ANNOTATION_NAME, classInfo.name()); } } }
5,636
52.685714
206
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/AbstractPlatformBindingProcessor.java
/* * JBoss, Home of Professional Open Source * Copyright 2019, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import org.jboss.as.ee.component.Attachments; import org.jboss.as.ee.component.BindingConfiguration; import org.jboss.as.ee.component.ComponentDescription; import org.jboss.as.ee.component.ComponentNamingMode; import org.jboss.as.ee.component.EEModuleDescription; import org.jboss.as.ee.component.LookupInjectionSource; import org.jboss.as.ee.structure.DeploymentType; import org.jboss.as.ee.structure.DeploymentTypeMarker; 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; /** * Foundation for processors which binds EE platform common resources, to all EE module and comp naming contexts. * * @author emmartins */ public abstract class AbstractPlatformBindingProcessor implements DeploymentUnitProcessor { private static final String JAVA_COMP = "java:comp/"; private static final String JAVA_MODULE = "java:module/"; @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (DeploymentTypeMarker.isType(DeploymentType.EAR, deploymentUnit)) { return; } final EEModuleDescription moduleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION); if(moduleDescription == null) { return; } addBindings(deploymentUnit, moduleDescription); } /** * Concrete implementations should use this method to add bindings to the module description, through {@link #addBinding(String, String, DeploymentUnit, EEModuleDescription)} * @param deploymentUnit * @param moduleDescription */ protected abstract void addBindings(DeploymentUnit deploymentUnit, EEModuleDescription moduleDescription); /** * * @param source * @param target target jndi name, relative to namespace root, e.g. for java:comp/DefaultDataSource the target param value should be DefaultDataSource * @param moduleDescription */ protected void addBinding(String source, String target, DeploymentUnit deploymentUnit, EEModuleDescription moduleDescription) { final LookupInjectionSource injectionSource = new LookupInjectionSource(source); final String moduleTarget = JAVA_MODULE+target; moduleDescription.getBindingConfigurations().add(new BindingConfiguration(moduleTarget, injectionSource)); if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) { final String compTarget = JAVA_COMP+target; for(ComponentDescription componentDescription : moduleDescription.getComponentDescriptions()) { if(componentDescription.getNamingMode() == ComponentNamingMode.CREATE) { componentDescription.getBindingConfigurations().add(new BindingConfiguration(compTarget, injectionSource)); } } } } }
4,159
46.816092
178
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/EEResourceReferenceProcessorRegistry.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.jboss.as.ee.logging.EeLogger; /** * User: jpai */ public class EEResourceReferenceProcessorRegistry { private final Map<String, EEResourceReferenceProcessor> resourceReferenceProcessors = new ConcurrentHashMap<String, EEResourceReferenceProcessor>(); public void registerResourceReferenceProcessor(final EEResourceReferenceProcessor resourceReferenceProcessor) { if (resourceReferenceProcessor == null) { throw EeLogger.ROOT_LOGGER.nullResourceReference(); } final String resourceReferenceType = resourceReferenceProcessor.getResourceReferenceType(); if (resourceReferenceType == null || resourceReferenceType.trim().isEmpty()) { throw EeLogger.ROOT_LOGGER.nullOrEmptyResourceReferenceType(); } resourceReferenceProcessors.put(resourceReferenceType, resourceReferenceProcessor); } public EEResourceReferenceProcessor getResourceReferenceProcessor(final String resourceReferenceType) { return resourceReferenceProcessors.get(resourceReferenceType); } }
2,210
40.716981
152
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/MessageDestinationResolutionProcessor.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import java.util.List; import org.jboss.as.ee.component.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; /** * Processor that resolves all message destinations. This cannot be done when they are first discovered, as * they may resolve to destinations in other deployments. * * @author Stuart Douglas */ public class MessageDestinationResolutionProcessor implements DeploymentUnitProcessor { @Override public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final List<MessageDestinationInjectionSource> injections = phaseContext.getDeploymentUnit().getAttachmentList(Attachments.MESSAGE_DESTINATIONS); for (final MessageDestinationInjectionSource injection : injections) { injection.resolve(phaseContext); } } }
2,041
42.446809
152
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/EEModuleConfigurationProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.jboss.as.ee.logging.EeLogger; import org.jboss.as.ee.component.Attachments; import org.jboss.as.ee.component.ComponentConfiguration; import org.jboss.as.ee.component.ComponentConfigurator; import org.jboss.as.ee.component.ComponentDescription; import org.jboss.as.ee.component.EEModuleConfiguration; import org.jboss.as.ee.component.EEModuleDescription; import org.jboss.as.ee.utils.ClassLoadingUtils; 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.reflect.DeploymentReflectionIndex; import org.jboss.modules.Module; import org.jboss.msc.service.ServiceName; import org.wildfly.security.manager.WildFlySecurityManager; import static org.jboss.as.ee.logging.EeLogger.ROOT_LOGGER; /** * Deployment processor responsible for creating a {@link org.jboss.as.ee.component.EEModuleConfiguration} from a {@link org.jboss.as.ee.component.EEModuleDescription} and * populating it with component and class configurations * * @author John Bailey */ public class EEModuleConfigurationProcessor implements DeploymentUnitProcessor { public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final EEModuleDescription moduleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION); final Module module = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.MODULE); final DeploymentReflectionIndex reflectionIndex = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.REFLECTION_INDEX); if (module == null || moduleDescription == null) { return; } final Set<ServiceName> failed = new HashSet<ServiceName>(); final EEModuleConfiguration moduleConfiguration = new EEModuleConfiguration(moduleDescription); deploymentUnit.putAttachment(Attachments.EE_MODULE_CONFIGURATION, moduleConfiguration); final ClassLoader oldCl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); try { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(module.getClassLoader()); final Iterator<ComponentDescription> iterator = moduleDescription.getComponentDescriptions().iterator(); while (iterator.hasNext()) { final ComponentDescription componentDescription = iterator.next(); ROOT_LOGGER.debugf("Configuring component class: %s named %s", componentDescription.getComponentClassName(), componentDescription.getComponentName()); final ComponentConfiguration componentConfiguration; try { componentConfiguration = componentDescription.createConfiguration(reflectionIndex.getClassIndex(ClassLoadingUtils.loadClass(componentDescription.getComponentClassName(), module)), module.getClassLoader(), module.getModuleLoader()); for (final ComponentConfigurator componentConfigurator : componentDescription.getConfigurators()) { componentConfigurator.configure(phaseContext, componentDescription, componentConfiguration); } moduleConfiguration.addComponentConfiguration(componentConfiguration); } catch (Throwable e) { if (componentDescription.isOptional()) { // https://issues.jboss.org/browse/WFLY-924 Just log a WARN summary of which component failed and then log the cause at DEBUG level ROOT_LOGGER.componentInstallationFailure(componentDescription.getComponentName()); ROOT_LOGGER.debugf(e, "Not installing optional component %s due to an exception", componentDescription.getComponentName()); // keep track of failed optional components failed.add(componentDescription.getStartServiceName()); failed.add(componentDescription.getCreateServiceName()); failed.add(componentDescription.getServiceName()); iterator.remove(); } else { throw EeLogger.ROOT_LOGGER.cannotConfigureComponent(e, componentDescription.getComponentName()); } } } deploymentUnit.putAttachment(Attachments.FAILED_COMPONENTS, Collections.synchronizedSet(failed)); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldCl); } } }
6,009
55.168224
251
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/EEDefaultPermissionsProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import java.io.File; import java.io.FilePermission; import java.io.IOException; import java.security.Permission; import java.security.Permissions; import java.util.Enumeration; import java.util.List; import org.wildfly.naming.java.permission.JndiPermission; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.module.ModuleSpecification; import org.jboss.as.server.deployment.module.ResourceRoot; import org.jboss.modules.security.ImmediatePermissionFactory; import org.jboss.modules.security.PermissionFactory; /** * A processor which sets up the default Jakarta EE permission set. * * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ public final class EEDefaultPermissionsProcessor implements DeploymentUnitProcessor { private static final Permissions DEFAULT_PERMISSIONS; static { final Permissions permissions = new Permissions(); final int actionBits = JndiPermission.ACTION_LOOKUP | JndiPermission.ACTION_LIST | JndiPermission.ACTION_LIST_BINDINGS; permissions.add(new JndiPermission("java:comp", actionBits)); permissions.add(new JndiPermission("java:comp/-", actionBits)); permissions.add(new JndiPermission("java:module", actionBits)); permissions.add(new JndiPermission("java:module/-", actionBits)); permissions.add(new JndiPermission("java:app", actionBits)); permissions.add(new JndiPermission("java:app/-", actionBits)); permissions.add(new JndiPermission("java:global", JndiPermission.ACTION_LOOKUP)); permissions.add(new JndiPermission("java:global/-", JndiPermission.ACTION_LOOKUP)); permissions.add(new JndiPermission("java:jboss", JndiPermission.ACTION_LOOKUP)); permissions.add(new JndiPermission("java:jboss/-", JndiPermission.ACTION_LOOKUP)); permissions.add(new JndiPermission("java:/-", JndiPermission.ACTION_LOOKUP)); DEFAULT_PERMISSIONS = permissions; } public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final ModuleSpecification attachment = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); if (attachment == null) { return; } final List<PermissionFactory> permissions = attachment.getPermissionFactories(); final Enumeration<Permission> e = DEFAULT_PERMISSIONS.elements(); while (e.hasMoreElements()) { permissions.add(new ImmediatePermissionFactory(e.nextElement())); } //make sure they can read the contents of the deployment ResourceRoot root = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT); try { File file = root.getRoot().getPhysicalFile(); if(file != null && file.isDirectory()) { FilePermission permission = new FilePermission(file.getAbsolutePath() + File.separatorChar + "-", "read"); permissions.add(new ImmediatePermissionFactory(permission)); } } catch (IOException ex) { throw new DeploymentUnitProcessingException(ex); } } }
4,547
46.873684
127
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/EEDistinctNameProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import org.jboss.as.ee.component.EEModuleDescription; 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; /** * Examines a deployment unit and its top level parent to check for any distinct-name that's configured in the * deployment descriptor(s) of the deployment units. If a top level deployment unit has a distinct-name configured * then it will be applied to all sub-deployments in that unit (unless the sub-deployment has overridden the distinct-name) * * @author Stuart Douglas * @author Jaikiran Pai */ public final class EEDistinctNameProcessor implements DeploymentUnitProcessor { @Override public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final EEModuleDescription module = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION); if (module == null) { return; } // see if the deployment unit has an explicit distinct-name final String distinctName = deploymentUnit.getAttachment(org.jboss.as.ee.structure.Attachments.DISTINCT_NAME); if (distinctName != null) { module.setDistinctName(distinctName); return; } // check the parent DU for any explicit distinct-name if (deploymentUnit.getParent() != null) { final DeploymentUnit parentDU = deploymentUnit.getParent(); final String distinctNameInParentDeployment = parentDU.getAttachment(org.jboss.as.ee.structure.Attachments.DISTINCT_NAME); if (distinctNameInParentDeployment != null) { module.setDistinctName(distinctNameInParentDeployment); } return; } } }
3,070
46.246154
134
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/StartupCountdown.java
package org.jboss.as.ee.component.deployers; import java.util.LinkedList; import java.util.Queue; /** * Countdown tracker with capabilities similar to SE CountDownLatch, but allowing threads * to mark and unmark themselves as privileged. Privileged threads, when entering await method, * will immediately proceed without checking latch's state. This reentrant behaviour allows to work around situations * where there is a possibility of a deadlock. * @author Fedor Gavrilov */ public final class StartupCountdown { private static final ThreadLocal<Frame> frames = new ThreadLocal<>(); private volatile int count; private final Queue<Runnable> callbacks = new LinkedList<Runnable>(); public StartupCountdown(int count) { this.count = count; } public void countDown() { synchronized (this) { if (-- count == 0) { try { while (!callbacks.isEmpty()) callbacks.poll().run(); } finally { notifyAll(); } } } } public void countUp(final int count) { synchronized (this) { this.count += count; } } public void await() throws InterruptedException { if (isPrivileged()) return; if (count != 0) { synchronized (this) { while (count != 0) wait(); } } } /** * Executes a lightweight action when the countdown reaches 0. * If StartupCountdown is not at zero when the method is called, passed callback will be executed by the last thread to call countDown. * If StartupCountdown is at zero already, passed callback will be executed immediately by the caller thread. * @param callback to execute. Should not be null. */ public void addCallback(final Runnable callback) { synchronized (this) { if (count != 0) callbacks.add(callback); else callback.run(); } } public boolean isPrivileged() { final Frame frame = frames.get(); return frame != null && frame.contains(this); } public Frame enter() { final Frame frame = frames.get(); frames.set(new Frame(frame, this)); return frame; } public static Frame current() { return frames.get(); } public static void restore(Frame frame) { frames.set(frame); } public static final class Frame { private final Frame prev; private final StartupCountdown countdown; Frame(final Frame prev, final StartupCountdown countdown) { this.prev = prev; this.countdown = countdown; } boolean contains(StartupCountdown countdown) { return countdown == this.countdown || prev != null && prev.contains(countdown); } } }
2,614
26.239583
137
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/EarMessageDestinationProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import org.jboss.as.ee.component.EEModuleDescription; import org.jboss.as.ee.structure.Attachments; import org.jboss.as.ee.structure.DeploymentType; import org.jboss.as.ee.structure.DeploymentTypeMarker; 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.metadata.ear.spec.EarMetaData; import org.jboss.metadata.javaee.spec.MessageDestinationMetaData; /** * @author Stuart Douglas */ public class EarMessageDestinationProcessor implements DeploymentUnitProcessor { @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (DeploymentTypeMarker.isType(DeploymentType.EAR, deploymentUnit)) { final EarMetaData metadata = deploymentUnit.getAttachment(Attachments.EAR_METADATA); final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION); if (metadata != null && metadata.getEarEnvironmentRefsGroup() != null && metadata.getEarEnvironmentRefsGroup().getMessageDestinations() != null) { for (final MessageDestinationMetaData destination : metadata.getEarEnvironmentRefsGroup() .getMessageDestinations()) { // TODO: should these be two separate metadata attributes? if (destination.getJndiName() != null) { eeModuleDescription.addMessageDestination(destination.getName(), destination.getJndiName()); } else if (destination.getLookupName() != null) { eeModuleDescription.addMessageDestination(destination.getName(), destination.getLookupName()); } } } } } }
3,157
49.126984
150
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/EEResourceReferenceProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import org.jboss.as.ee.component.InjectionSource; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; /** * User: jpai */ public interface EEResourceReferenceProcessor { String getResourceReferenceType(); InjectionSource getResourceReferenceBindingSource() throws DeploymentUnitProcessingException; }
1,405
37
97
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/DescriptorEnvironmentLifecycleMethodProcessor.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import org.jboss.as.ee.component.Attachments; import org.jboss.as.ee.component.DeploymentDescriptorEnvironment; import org.jboss.as.ee.component.EEModuleDescription; import org.jboss.as.ee.component.interceptors.InterceptorClassDescription; 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.invocation.proxy.MethodIdentifier; import org.jboss.metadata.javaee.spec.LifecycleCallbackMetaData; import org.jboss.metadata.javaee.spec.LifecycleCallbacksMetaData; import org.jboss.metadata.javaee.spec.RemoteEnvironment; /** * Deployment descriptor that resolves interceptor methods defined in ejb-jar.xml that could not be resolved at * DD parse time. * * @author Stuart Douglas */ public class DescriptorEnvironmentLifecycleMethodProcessor implements DeploymentUnitProcessor { @Override public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION); final DeploymentDescriptorEnvironment environment = deploymentUnit.getAttachment(Attachments.MODULE_DEPLOYMENT_DESCRIPTOR_ENVIRONMENT); if (environment != null) { handleMethods(environment, eeModuleDescription, null); } } public static void handleMethods(DeploymentDescriptorEnvironment env, EEModuleDescription eeModuleDescription, String defaultClassName) throws DeploymentUnitProcessingException { final RemoteEnvironment environment = env.getEnvironment(); // post-construct(s) of the interceptor configured (if any) in the deployment descriptor LifecycleCallbacksMetaData postConstructs = environment.getPostConstructs(); if (postConstructs != null) { for (LifecycleCallbackMetaData postConstruct : postConstructs) { String className = postConstruct.getClassName(); if (className == null || className.isEmpty()) { if (defaultClassName == null) { continue; } else { className = defaultClassName; } } final InterceptorClassDescription.Builder builder = InterceptorClassDescription.builder(); String methodName = postConstruct.getMethodName(); MethodIdentifier methodIdentifier = MethodIdentifier.getIdentifier(void.class, methodName); builder.setPostConstruct(methodIdentifier); eeModuleDescription.addInterceptorMethodOverride(className, builder.build()); } } // pre-destroy(s) of the interceptor configured (if any) in the deployment descriptor LifecycleCallbacksMetaData preDestroys = environment.getPreDestroys(); if (preDestroys != null) { for (LifecycleCallbackMetaData preDestroy : preDestroys) { String className = preDestroy.getClassName(); if (className == null || className.isEmpty()) { if (defaultClassName == null) { continue; } else { className = defaultClassName; } } final InterceptorClassDescription.Builder builder = InterceptorClassDescription.builder(); String methodName = preDestroy.getMethodName(); MethodIdentifier methodIdentifier = MethodIdentifier.getIdentifier(void.class, methodName); builder.setPreDestroy(methodIdentifier); eeModuleDescription.addInterceptorMethodOverride(className, builder.build()); } } } }
5,101
48.533981
182
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/ResourceReferenceProcessor.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import org.jboss.as.ee.logging.EeLogger; import org.jboss.as.ee.component.Attachments; import org.jboss.as.ee.component.BindingConfiguration; import org.jboss.as.ee.component.ComponentDescription; import org.jboss.as.ee.component.DeploymentDescriptorEnvironment; import org.jboss.as.ee.component.EEApplicationClasses; import org.jboss.as.ee.component.EnvEntryInjectionSource; import org.jboss.as.ee.component.FixedInjectionSource; import org.jboss.as.ee.component.InjectionSource; import org.jboss.as.ee.component.LookupInjectionSource; import org.jboss.as.ee.component.ResourceInjectionTarget; import org.jboss.as.naming.ImmediateManagedReference; import org.jboss.as.naming.ManagedReference; import org.jboss.as.naming.ManagedReferenceFactory; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex; import org.jboss.metadata.javaee.spec.EnvironmentEntriesMetaData; import org.jboss.metadata.javaee.spec.EnvironmentEntryMetaData; import org.jboss.metadata.javaee.spec.MessageDestinationReferenceMetaData; import org.jboss.metadata.javaee.spec.MessageDestinationReferencesMetaData; import org.jboss.metadata.javaee.spec.ResourceEnvironmentReferenceMetaData; import org.jboss.metadata.javaee.spec.ResourceEnvironmentReferencesMetaData; import org.jboss.metadata.javaee.spec.ResourceReferenceMetaData; import org.jboss.metadata.javaee.spec.ResourceReferencesMetaData; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.List; import static org.jboss.as.ee.logging.EeLogger.ROOT_LOGGER; /** * Deployment processor that sets up env-entry, resource-ref and resource-env-ref bindings * * @author Stuart Douglas * @author Eduardo Martins */ public class ResourceReferenceProcessor extends AbstractDeploymentDescriptorBindingsProcessor { private static final String JAVAX_NAMING_CONTEXT = "javax.naming.Context"; @Override protected List<BindingConfiguration> processDescriptorEntries(DeploymentUnit deploymentUnit, DeploymentDescriptorEnvironment environment, ResourceInjectionTarget resourceInjectionTarget, final ComponentDescription componentDescription, ClassLoader classLoader, DeploymentReflectionIndex deploymentReflectionIndex, final EEApplicationClasses applicationClasses) throws DeploymentUnitProcessingException { List<BindingConfiguration> bindings = new ArrayList<BindingConfiguration>(); bindings.addAll(getEnvironmentEntries(environment, classLoader, deploymentReflectionIndex, resourceInjectionTarget)); bindings.addAll(getResourceEnvRefEntries(deploymentUnit, environment, classLoader, deploymentReflectionIndex, resourceInjectionTarget)); bindings.addAll(getResourceRefEntries(deploymentUnit, environment, classLoader, deploymentReflectionIndex, resourceInjectionTarget)); bindings.addAll(getMessageDestinationRefs(environment, classLoader, deploymentReflectionIndex, resourceInjectionTarget, deploymentUnit)); return bindings; } private List<BindingConfiguration> getResourceEnvRefEntries(final DeploymentUnit deploymentUnit, final DeploymentDescriptorEnvironment environment, ClassLoader classLoader, DeploymentReflectionIndex deploymentReflectionIndex, ResourceInjectionTarget resourceInjectionTarget) throws DeploymentUnitProcessingException { List<BindingConfiguration> bindings = new ArrayList<BindingConfiguration>(); final ResourceEnvironmentReferencesMetaData resourceEnvRefs = environment.getEnvironment().getResourceEnvironmentReferences(); final EEResourceReferenceProcessorRegistry registry = deploymentUnit.getAttachment(Attachments.RESOURCE_REFERENCE_PROCESSOR_REGISTRY); if (resourceEnvRefs == null) { return bindings; } for (ResourceEnvironmentReferenceMetaData resourceEnvRef : resourceEnvRefs) { if(resourceEnvRef.isDependencyIgnored()) { continue; } final String name; if (resourceEnvRef.getName().startsWith("java:")) { name = resourceEnvRef.getName(); } else { name = environment.getDefaultContext() + resourceEnvRef.getName(); } Class<?> classType = null; if (resourceEnvRef.getType() != null) { try { classType = classLoader.loadClass(resourceEnvRef.getType()); } catch (ClassNotFoundException e) { throw EeLogger.ROOT_LOGGER.cannotLoad(e, resourceEnvRef.getType()); } } // our injection (source) comes from the local (ENC) lookup, no matter what. InjectionSource injectionSource = new LookupInjectionSource(name); classType = processInjectionTargets(resourceInjectionTarget, injectionSource, classLoader, deploymentReflectionIndex, resourceEnvRef, classType); if (!isEmpty(resourceEnvRef.getLookupName())) { injectionSource = new LookupInjectionSource(resourceEnvRef.getLookupName(), classType != null && JAVAX_NAMING_CONTEXT.equals(classType.getName())); } else { if (classType == null) { throw EeLogger.ROOT_LOGGER.cannotDetermineType(name); } //check if it is a well known type final String lookup = ResourceInjectionAnnotationParsingProcessor.FIXED_LOCATIONS.get(classType.getName()); if (lookup != null) { injectionSource = new LookupInjectionSource(lookup); } else { final EEResourceReferenceProcessor resourceReferenceProcessor = registry.getResourceReferenceProcessor(classType.getName()); if (resourceReferenceProcessor != null) { injectionSource = resourceReferenceProcessor.getResourceReferenceBindingSource(); } else { //TODO: how are we going to handle these? Previously they would have been handled by jboss-*.xml if (resourceEnvRef.getResourceEnvRefName().startsWith("java:")) { ROOT_LOGGER.cannotResolve("resource-env-ref", name); continue; } else { injectionSource = new LookupInjectionSource("java:jboss/resources/" + resourceEnvRef.getResourceEnvRefName()); } } } } bindings.add(new BindingConfiguration(name, injectionSource)); } return bindings; } private List<BindingConfiguration> getResourceRefEntries(final DeploymentUnit deploymentUnit, DeploymentDescriptorEnvironment environment, ClassLoader classLoader, DeploymentReflectionIndex deploymentReflectionIndex, ResourceInjectionTarget resourceInjectionTarget) throws DeploymentUnitProcessingException { List<BindingConfiguration> bindings = new ArrayList<BindingConfiguration>(); final EEResourceReferenceProcessorRegistry registry = deploymentUnit.getAttachment(Attachments.RESOURCE_REFERENCE_PROCESSOR_REGISTRY); final ResourceReferencesMetaData resourceRefs = environment.getEnvironment().getResourceReferences(); if (resourceRefs == null) { return bindings; } for (final ResourceReferenceMetaData resourceRef : resourceRefs) { if(resourceRef.isDependencyIgnored()) { continue; } final String name; if (resourceRef.getName().startsWith("java:")) { name = resourceRef.getName(); } else { name = environment.getDefaultContext() + resourceRef.getName(); } Class<?> classType = null; if (resourceRef.getType() != null) { try { classType = classLoader.loadClass(resourceRef.getType()); } catch (ClassNotFoundException e) { throw EeLogger.ROOT_LOGGER.cannotLoad(e, resourceRef.getType()); } } // our injection (source) comes from the local (ENC) lookup, no matter what. InjectionSource injectionSource = new LookupInjectionSource(name); classType = processInjectionTargets(resourceInjectionTarget, injectionSource, classLoader, deploymentReflectionIndex, resourceRef, classType); if (!isEmpty(resourceRef.getLookupName())) { injectionSource = new LookupInjectionSource(resourceRef.getLookupName(), classType != null && JAVAX_NAMING_CONTEXT.equals(classType.getName())); } else if (!isEmpty(resourceRef.getResUrl())) { final String url = resourceRef.getResUrl(); if (classType != null && classType.equals(URI.class)) { try { //we need a newURI every time injectionSource = new FixedInjectionSource(new ManagedReferenceFactory() { @Override public ManagedReference getReference() { try { return new ImmediateManagedReference(new URI(url)); } catch (URISyntaxException e) { throw new RuntimeException(e); } } }, new URI(url)); } catch (URISyntaxException e) { throw EeLogger.ROOT_LOGGER.cannotParseResourceRefUri(e, resourceRef.getResUrl()); } } else { try { injectionSource = new FixedInjectionSource(new ManagedReferenceFactory() { @Override public ManagedReference getReference() { try { return new ImmediateManagedReference(new URL(url)); } catch (MalformedURLException e) { throw new RuntimeException(e); } } }, new URL(url)); } catch (MalformedURLException e) { throw EeLogger.ROOT_LOGGER.cannotParseResourceRefUri(e, resourceRef.getResUrl()); } } } else { if (classType == null) { throw EeLogger.ROOT_LOGGER.cannotDetermineType(name); } //check if it is a well known type final String lookup = ResourceInjectionAnnotationParsingProcessor.FIXED_LOCATIONS.get(classType.getName()); if (lookup != null) { injectionSource = new LookupInjectionSource(lookup); } else { final EEResourceReferenceProcessor resourceReferenceProcessor = registry.getResourceReferenceProcessor(classType.getName()); if (resourceReferenceProcessor != null) { injectionSource = resourceReferenceProcessor.getResourceReferenceBindingSource(); } else if (!resourceRef.getResourceRefName().startsWith("java:")) { injectionSource = new LookupInjectionSource("java:jboss/resources/" + resourceRef.getResourceRefName()); } else { //if we cannot resolve it just log ROOT_LOGGER.cannotResolve("resource-env-ref", name); continue; } } } bindings.add(new BindingConfiguration(name, injectionSource)); } return bindings; } private List<BindingConfiguration> getEnvironmentEntries(final DeploymentDescriptorEnvironment environment, final ClassLoader classLoader, DeploymentReflectionIndex deploymentReflectionIndex, ResourceInjectionTarget resourceInjectionTarget) throws DeploymentUnitProcessingException { final List<BindingConfiguration> bindings = new ArrayList<BindingConfiguration>(); final EnvironmentEntriesMetaData envEntries = environment.getEnvironment().getEnvironmentEntries(); if (envEntries == null) { return bindings; } for (final EnvironmentEntryMetaData envEntry : envEntries) { if(envEntry.isDependencyIgnored()) { continue; } final String name; if (envEntry.getName().startsWith("java:")) { name = envEntry.getName(); } else { name = environment.getDefaultContext() + envEntry.getEnvEntryName(); } Class<?> classType = null; if (envEntry.getType() != null) { try { classType = this.loadClass(envEntry.getType(), classLoader); } catch (ClassNotFoundException e) { throw EeLogger.ROOT_LOGGER.cannotLoad(e, envEntry.getType()); } } final String value = envEntry.getValue(); final String lookup = envEntry.getLookupName(); if (!isEmpty(value) && !isEmpty(lookup)) { throw EeLogger.ROOT_LOGGER.cannotSpecifyBoth("<env-entry-value>", "<lookup-name>"); } else if (isEmpty(lookup) && isEmpty(value)) { //if no value is provided then it is not an error //this reference should simply be ignored // (Java ee platform spec 6.0 fr pg 80) continue; } // our injection (source) comes from the local (ENC) lookup, no matter what. LookupInjectionSource injectionSource = new LookupInjectionSource(name); classType = processInjectionTargets(resourceInjectionTarget, injectionSource, classLoader, deploymentReflectionIndex, envEntry, classType); if (classType == null) { throw EeLogger.ROOT_LOGGER.cannotDetermineType("<env-entry>", name, "<env-entry-type>"); } final String type = classType.getName(); final BindingConfiguration bindingConfiguration; if (!isEmpty(lookup)) { bindingConfiguration = new BindingConfiguration(name, new LookupInjectionSource(lookup)); } else if (type.equals(String.class.getName())) { bindingConfiguration = new BindingConfiguration(name, new EnvEntryInjectionSource(value)); } else if (type.equals(Integer.class.getName()) || type.equals("int")) { bindingConfiguration = new BindingConfiguration(name, new EnvEntryInjectionSource(Integer.valueOf(value))); } else if (type.equals(Short.class.getName()) || type.equals("short")) { bindingConfiguration = new BindingConfiguration(name, new EnvEntryInjectionSource(Short.valueOf(value))); } else if (type.equals(Long.class.getName()) || type.equals("long")) { bindingConfiguration = new BindingConfiguration(name, new EnvEntryInjectionSource(Long.valueOf(value))); } else if (type.equals(Byte.class.getName()) || type.equals("byte")) { bindingConfiguration = new BindingConfiguration(name, new EnvEntryInjectionSource(Byte.valueOf(value))); } else if (type.equals(Double.class.getName()) || type.equals("double")) { bindingConfiguration = new BindingConfiguration(name, new EnvEntryInjectionSource(Double.valueOf(value))); } else if (type.equals(Float.class.getName()) || type.equals("float")) { bindingConfiguration = new BindingConfiguration(name, new EnvEntryInjectionSource(Float.valueOf(value))); } else if (type.equals(Boolean.class.getName()) || type.equals("boolean")) { bindingConfiguration = new BindingConfiguration(name, new EnvEntryInjectionSource(Boolean.valueOf(value))); } else if (type.equals(Character.class.getName()) || type.equals("char")) { if (value.length() != 1) { throw EeLogger.ROOT_LOGGER.invalidCharacterLength("env-entry", value); } bindingConfiguration = new BindingConfiguration(name, new EnvEntryInjectionSource(value.charAt(0))); } else if (type.equals(Class.class.getName())) { try { bindingConfiguration = new BindingConfiguration(name, new EnvEntryInjectionSource(classLoader.loadClass(value))); } catch (ClassNotFoundException e) { throw EeLogger.ROOT_LOGGER.cannotLoad(value); } } else if (classType.isEnum() || (classType.getEnclosingClass() != null && classType.getEnclosingClass().isEnum())) { bindingConfiguration = new BindingConfiguration(name, new EnvEntryInjectionSource(Enum.valueOf((Class) classType, value))); } else { throw EeLogger.ROOT_LOGGER.unknownElementType("env-entry", type); } bindings.add(bindingConfiguration); } return bindings; } /** * TODO: should this be part of the messaging subsystem */ private List<BindingConfiguration> getMessageDestinationRefs(final DeploymentDescriptorEnvironment environment, final ClassLoader classLoader, final DeploymentReflectionIndex deploymentReflectionIndex, final ResourceInjectionTarget resourceInjectionTarget, final DeploymentUnit deploymentUnit) throws DeploymentUnitProcessingException { final List<BindingConfiguration> bindings = new ArrayList<BindingConfiguration>(); final MessageDestinationReferencesMetaData messageDestinationReferences = environment.getEnvironment().getMessageDestinationReferences(); if (messageDestinationReferences == null) { return bindings; } for (final MessageDestinationReferenceMetaData messageRef : messageDestinationReferences) { if(messageRef.isDependencyIgnored()) { continue; } final String name; if (messageRef.getName().startsWith("java:")) { name = messageRef.getName(); } else { name = environment.getDefaultContext() + messageRef.getName(); } Class<?> classType = null; if (messageRef.getType() != null) { try { classType = classLoader.loadClass(messageRef.getType()); } catch (ClassNotFoundException e) { throw EeLogger.ROOT_LOGGER.cannotLoad(e, messageRef.getType()); } } // our injection (source) comes from the local (ENC) lookup, no matter what. final LookupInjectionSource injectionSource = new LookupInjectionSource(name); classType = processInjectionTargets(resourceInjectionTarget, injectionSource, classLoader, deploymentReflectionIndex, messageRef, classType); final BindingConfiguration bindingConfiguration; if (!isEmpty(messageRef.getLookupName())) { bindingConfiguration = new BindingConfiguration(name, new LookupInjectionSource(messageRef.getLookupName())); bindings.add(bindingConfiguration); } else if (!isEmpty(messageRef.getMappedName())) { bindingConfiguration = new BindingConfiguration(name, new LookupInjectionSource(messageRef.getMappedName())); bindings.add(bindingConfiguration); } else if (!isEmpty(messageRef.getLink())) { final MessageDestinationInjectionSource messageDestinationInjectionSource = new MessageDestinationInjectionSource(messageRef.getLink(), name); bindingConfiguration = new BindingConfiguration(name, messageDestinationInjectionSource); deploymentUnit.addToAttachmentList(Attachments.MESSAGE_DESTINATIONS, messageDestinationInjectionSource); bindings.add(bindingConfiguration); } else { ROOT_LOGGER.cannotResolve("message-destination-ref", name); } } return bindings; } private boolean isEmpty(final String string) { return string == null || string.isEmpty(); } private Class<?> loadClass(String className, ClassLoader cl) throws ClassNotFoundException { if (className == null || className.trim().isEmpty()) { throw EeLogger.ROOT_LOGGER.cannotBeNullOrEmpty("Classname", className); } if (className.equals(void.class.getName())) { return void.class; } if (className.equals(byte.class.getName())) { return byte.class; } if (className.equals(short.class.getName())) { return short.class; } if (className.equals(int.class.getName())) { return int.class; } if (className.equals(long.class.getName())) { return long.class; } if (className.equals(char.class.getName())) { return char.class; } if (className.equals(boolean.class.getName())) { return boolean.class; } if (className.equals(float.class.getName())) { return float.class; } if (className.equals(double.class.getName())) { return double.class; } // Now that we know its not a primitive, lets just allow // the passed classloader to handle the request. return Class.forName(className, false, cl); } }
23,021
56.268657
407
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/ApplicationClassesAggregationProcessor.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import java.util.ArrayList; import java.util.List; import org.jboss.as.ee.component.Attachments; import org.jboss.as.ee.component.EEApplicationClasses; import org.jboss.as.ee.component.EEModuleDescription; 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; /** * Processor that aggregates all module descriptions visible to the deployment in an EEApplicationClasses structure. * * @author Stuart Douglas */ public class ApplicationClassesAggregationProcessor implements DeploymentUnitProcessor { @Override public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final List<EEModuleDescription> descriptions = new ArrayList<EEModuleDescription>(); for (final DeploymentUnit visibleDeployment : deploymentUnit.getAttachmentList(org.jboss.as.server.deployment.Attachments.ACCESSIBLE_SUB_DEPLOYMENTS)) { final EEModuleDescription description = visibleDeployment.getAttachment(Attachments.EE_MODULE_DESCRIPTION); if (description != null) { descriptions.add(description); } } final EEApplicationClasses classes = new EEApplicationClasses(descriptions); deploymentUnit.putAttachment(Attachments.EE_APPLICATION_CLASSES_DESCRIPTION, classes); } }
2,641
46.178571
160
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/AbstractComponentConfigProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import org.jboss.as.ee.component.Attachments; import org.jboss.as.ee.component.ComponentDescription; import org.jboss.as.ee.component.EEModuleDescription; import org.jboss.as.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 java.util.Collection; /** * Abstract deployment unit processors used to process {@link org.jboss.as.ee.component.ComponentDescription} instances. * * @author John Bailey */ public abstract class AbstractComponentConfigProcessor implements DeploymentUnitProcessor { /** * {@inheritDoc} * */ public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION); final Collection<ComponentDescription> componentConfigurations = eeModuleDescription.getComponentDescriptions(); if (componentConfigurations == null || componentConfigurations.isEmpty()) { return; } for (ComponentDescription componentConfiguration : componentConfigurations) { final CompositeIndex index = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.COMPOSITE_ANNOTATION_INDEX); if (index != null) { processComponentConfig(deploymentUnit, phaseContext, index, componentConfiguration); } } } /** * Process the component configuration instance. * * @param deploymentUnit The deployment unit * @param phaseContext The phase context * @param index The annotation index * @param componentDescription The component configuration * @throws DeploymentUnitProcessingException if any problems occur */ protected abstract void processComponentConfig(final DeploymentUnit deploymentUnit, final DeploymentPhaseContext phaseContext, final CompositeIndex index, final ComponentDescription componentDescription) throws DeploymentUnitProcessingException; }
3,425
45.931507
249
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/ComponentInstallProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import static org.jboss.as.ee.component.Attachments.COMPONENT_REGISTRY; import static org.jboss.as.ee.component.Attachments.EE_MODULE_CONFIGURATION; import static org.jboss.as.ee.logging.EeLogger.ROOT_LOGGER; import static org.jboss.as.server.deployment.Attachments.MODULE; import java.util.HashSet; import java.util.List; import java.util.Set; import org.jboss.as.ee.component.Attachments; import org.jboss.as.ee.component.BasicComponent; import org.jboss.as.ee.component.BasicComponentCreateService; import org.jboss.as.ee.component.BindingConfiguration; import org.jboss.as.ee.component.ClassDescriptionTraversal; import org.jboss.as.ee.component.Component; import org.jboss.as.ee.component.ComponentConfiguration; import org.jboss.as.ee.component.ComponentNamingMode; import org.jboss.as.ee.component.ComponentRegistry; import org.jboss.as.ee.component.ComponentStartService; import org.jboss.as.ee.component.ComponentView; import org.jboss.as.ee.component.DependencyConfigurator; import org.jboss.as.ee.component.EEApplicationClasses; import org.jboss.as.ee.component.EEModuleClassDescription; import org.jboss.as.ee.component.EEModuleConfiguration; import org.jboss.as.ee.component.InjectionSource; import org.jboss.as.ee.component.InterceptorDescription; import org.jboss.as.ee.component.ViewConfiguration; import org.jboss.as.ee.component.ViewService; import org.jboss.as.ee.logging.EeLogger; import org.jboss.as.ee.metadata.MetadataCompleteMarker; import org.jboss.as.naming.ManagedReferenceFactory; import org.jboss.as.naming.ServiceBasedNamingStore; import org.jboss.as.naming.deployment.ContextNames; import org.jboss.as.naming.deployment.JndiNamingDependencyProcessor; import org.jboss.as.naming.service.BinderService; import org.jboss.as.naming.service.NamingStoreService; import org.jboss.as.server.CurrentServiceContainer; import org.jboss.as.server.Services; 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.CircularDependencyException; import org.jboss.msc.service.DuplicateServiceException; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; /** * @author <a href="mailto:[email protected]">David M. Lloyd</a> * @author Eduardo Martins */ public final class ComponentInstallProcessor implements DeploymentUnitProcessor { private static final ServiceName JNDI_BINDINGS_SERVICE = ServiceName.of("JndiBindingsService"); private static final List<String> SPEC_COMPONENTS = List.of( "BeanManager", "DefaultContextService", "DefaultDataSource", "DefaultJMSConnectionFactory", "DefaultManagedExecutorService", "DefaultManagedScheduledExecutorService", "DefaultManagedThreadFactory", "EJBContext", "HandleDelegate", "InAppClientContainer", "InstanceName", "ModuleName", "ORB", "TimerService", "TransactionSynchronizationRegistry", "Validator", "ValidatorFactory" ); public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final Module module = deploymentUnit.getAttachment(MODULE); final EEModuleConfiguration moduleConfiguration = deploymentUnit.getAttachment(EE_MODULE_CONFIGURATION); if (module == null || moduleConfiguration == null) { return; } ComponentRegistry componentRegistry = deploymentUnit.getAttachment(COMPONENT_REGISTRY); final List<ServiceName> dependencies = deploymentUnit.getAttachmentList(org.jboss.as.server.deployment.Attachments.JNDI_DEPENDENCIES); final ServiceName bindingDependencyService = JndiNamingDependencyProcessor.serviceName(deploymentUnit.getServiceName()); // Iterate through each component, installing it into the container for (final ComponentConfiguration configuration : moduleConfiguration.getComponentConfigurations()) { try { ROOT_LOGGER.tracef("Installing component %s", configuration.getComponentClass().getName()); deployComponent(phaseContext, configuration, dependencies, bindingDependencyService); componentRegistry.addComponent(configuration); //we need to make sure that the web deployment has a dependency on all components it the app, so web components are started //when the web subsystem is starting //we only add a dependency on components in the same sub deployment, otherwise we get circular dependencies when initialize-in-order is used deploymentUnit.addToAttachmentList(org.jboss.as.server.deployment.Attachments.WEB_DEPENDENCIES, configuration.getComponentDescription().getStartServiceName()); } catch (Exception e) { throw EeLogger.ROOT_LOGGER.failedToInstallComponent(e, configuration.getComponentName()); } } } @SuppressWarnings({ "unchecked", "rawtypes" }) protected void deployComponent(final DeploymentPhaseContext phaseContext, final ComponentConfiguration configuration, final List<ServiceName> jndiDependencies, final ServiceName bindingDependencyService) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final ServiceTarget serviceTarget = phaseContext.getServiceTarget(); final String applicationName = configuration.getApplicationName(); final String moduleName = configuration.getModuleName(); final String componentName = configuration.getComponentName(); final EEApplicationClasses applicationClasses = deploymentUnit.getAttachment(Attachments.EE_APPLICATION_CLASSES_DESCRIPTION); final Module module = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.MODULE); //create additional injectors final ServiceName createServiceName = configuration.getComponentDescription().getCreateServiceName(); final ServiceName startServiceName = configuration.getComponentDescription().getStartServiceName(); final BasicComponentCreateService createService = configuration.getComponentCreateServiceFactory().constructService(configuration); final ServiceBuilder<Component> createBuilder = serviceTarget.addService(createServiceName, createService); final ComponentStartService startService = new ComponentStartService(); final ServiceBuilder<Component> startBuilder = serviceTarget.addService(startServiceName, startService); deploymentUnit.addToAttachmentList(org.jboss.as.server.deployment.Attachments.DEPLOYMENT_COMPLETE_SERVICES, startServiceName); //WFLY-1402 we don't add the bindings to the jndi dependencies list directly, instead //the bindings depend on the this artificial service ServiceName jndiDepServiceName = configuration.getComponentDescription().getServiceName().append(JNDI_BINDINGS_SERVICE); final ServiceBuilder<Void> jndiDepServiceBuilder = serviceTarget.addService(jndiDepServiceName, Service.NULL); jndiDependencies.add(jndiDepServiceName); // Add all service dependencies for (DependencyConfigurator configurator : configuration.getCreateDependencies()) { configurator.configureDependency(createBuilder, createService); } for (DependencyConfigurator configurator : configuration.getStartDependencies()) { configurator.configureDependency(startBuilder, startService); } // START depends on CREATE startBuilder.addDependency(createServiceName, BasicComponent.class, startService.getComponentInjector()); Services.addServerExecutorDependency(startBuilder, startService.getExecutorInjector()); //don't start components until all bindings are up startBuilder.requires(bindingDependencyService); final ServiceName contextServiceName; //set up the naming context if necessary if (configuration.getComponentDescription().getNamingMode() == ComponentNamingMode.CREATE) { final NamingStoreService contextService = new NamingStoreService(true); serviceTarget.addService(configuration.getComponentDescription().getContextServiceName(), contextService).install(); } final InjectionSource.ResolutionContext resolutionContext = new InjectionSource.ResolutionContext( configuration.getComponentDescription().getNamingMode() == ComponentNamingMode.USE_MODULE, configuration.getComponentName(), configuration.getModuleName(), configuration.getApplicationName() ); // Iterate through each view, creating the services for each for (ViewConfiguration viewConfiguration : configuration.getViews()) { final ServiceName serviceName = viewConfiguration.getViewServiceName(); final ViewService viewService = new ViewService(viewConfiguration); final ServiceBuilder<ComponentView> componentViewServiceBuilder = serviceTarget.addService(serviceName, viewService); componentViewServiceBuilder .addDependency(createServiceName, Component.class, viewService.getComponentInjector()); for(final DependencyConfigurator<ViewService> depConfig : viewConfiguration.getDependencies()) { depConfig.configureDependency(componentViewServiceBuilder, viewService); } componentViewServiceBuilder.install(); startBuilder.requires(serviceName); // The bindings for the view for (BindingConfiguration bindingConfiguration : viewConfiguration.getBindingConfigurations()) { final String bindingName = bindingConfiguration.getName(); final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(applicationName, moduleName, componentName, bindingName); final BinderService service = new BinderService(bindInfo.getBindName(), bindingConfiguration.getSource()); //these bindings should never be merged, if a view binding is duplicated it is an error jndiDepServiceBuilder.requires(bindInfo.getBinderServiceName()); ServiceBuilder<ManagedReferenceFactory> serviceBuilder = serviceTarget.addService(bindInfo.getBinderServiceName(), service); bindingConfiguration.getSource().getResourceValue(resolutionContext, serviceBuilder, phaseContext, service.getManagedObjectInjector()); serviceBuilder.addDependency(bindInfo.getParentContextServiceName(), ServiceBasedNamingStore.class, service.getNamingStoreInjector()); try { serviceBuilder.install(); } catch (DuplicateServiceException e) { handleDuplicateService(configuration, bindInfo.getAbsoluteJndiName()); throw e; } } } if (configuration.getComponentDescription().getNamingMode() == ComponentNamingMode.CREATE) { // The bindings for the component final Set<ServiceName> bound = new HashSet<ServiceName>(); processBindings(phaseContext, configuration, serviceTarget, resolutionContext, configuration.getComponentDescription().getBindingConfigurations(), jndiDepServiceBuilder, bound); //class level bindings should be ignored if the deployment is metadata complete if (!MetadataCompleteMarker.isMetadataComplete(phaseContext.getDeploymentUnit())) { // The bindings for the component class new ClassDescriptionTraversal(configuration.getComponentClass(), applicationClasses) { @Override protected void handle(final Class<?> clazz, final EEModuleClassDescription classDescription) throws DeploymentUnitProcessingException { if (classDescription != null) { processBindings(phaseContext, configuration, serviceTarget, resolutionContext, classDescription.getBindingConfigurations(), jndiDepServiceBuilder, bound); } } }.run(); for (InterceptorDescription interceptor : configuration.getComponentDescription().getAllInterceptors()) { final Class<?> interceptorClass; try { interceptorClass = module.getClassLoader().loadClass(interceptor.getInterceptorClassName()); } catch (ClassNotFoundException e) { throw EeLogger.ROOT_LOGGER.cannotLoadInterceptor(e, interceptor.getInterceptorClassName(), configuration.getComponentClass()); } if (interceptorClass != null) { new ClassDescriptionTraversal(interceptorClass, applicationClasses) { @Override protected void handle(final Class<?> clazz, final EEModuleClassDescription classDescription) throws DeploymentUnitProcessingException { if (classDescription != null) { processBindings(phaseContext, configuration, serviceTarget, resolutionContext, classDescription.getBindingConfigurations(), jndiDepServiceBuilder, bound); } } }.run(); } } } } createBuilder.install(); startBuilder.install(); jndiDepServiceBuilder.install(); } @SuppressWarnings("unchecked") private void processBindings(DeploymentPhaseContext phaseContext, ComponentConfiguration configuration, ServiceTarget serviceTarget, InjectionSource.ResolutionContext resolutionContext, List<BindingConfiguration> bindings, final ServiceBuilder<?> jndiDepServiceBuilder, final Set<ServiceName> bound) throws DeploymentUnitProcessingException { //we only handle java:comp bindings for components that have their own namespace here, the rest are processed by ModuleJndiBindingProcessor for (BindingConfiguration bindingConfiguration : bindings) { if (bindingConfiguration.getName().startsWith("java:comp") || !bindingConfiguration.getName().startsWith("java:")) { final String bindingName = bindingConfiguration.getName().startsWith("java:comp") ? bindingConfiguration.getName() : "java:comp/env/" + bindingConfiguration.getName(); final ContextNames.BindInfo bindInfo = ContextNames.bindInfoForEnvEntry(configuration.getApplicationName(), configuration.getModuleName(), configuration.getComponentName(), configuration.getComponentDescription().getNamingMode() == ComponentNamingMode.CREATE, bindingName); if (bound.contains(bindInfo.getBinderServiceName())) { continue; } bound.add(bindInfo.getBinderServiceName()); try { final BinderService service = new BinderService(bindInfo.getBindName(), bindingConfiguration.getSource()); jndiDepServiceBuilder.requires(bindInfo.getBinderServiceName()); ServiceBuilder<ManagedReferenceFactory> serviceBuilder = serviceTarget.addService(bindInfo.getBinderServiceName(), service); bindingConfiguration.getSource().getResourceValue(resolutionContext, serviceBuilder, phaseContext, service.getManagedObjectInjector()); serviceBuilder.addDependency(bindInfo.getParentContextServiceName(), ServiceBasedNamingStore.class, service.getNamingStoreInjector()); serviceBuilder.install(); } catch (DuplicateServiceException e) { ServiceController<ManagedReferenceFactory> registered = (ServiceController<ManagedReferenceFactory>) CurrentServiceContainer.getServiceContainer().getService(bindInfo.getBinderServiceName()); if (registered == null) throw e; BinderService service = (BinderService) registered.getService(); if (!service.getSource().equals(bindingConfiguration.getSource())) throw EeLogger.ROOT_LOGGER.conflictingBinding(bindingName, bindingConfiguration.getSource()); } catch (CircularDependencyException e) { throw EeLogger.ROOT_LOGGER.circularDependency(bindingName); } } } } private void handleDuplicateService(ComponentConfiguration configuration, String bindingName) { String name = configuration.getComponentName(); if (SPEC_COMPONENTS.contains(name)) { Class conflict = configuration.getComponentClass(); ROOT_LOGGER.duplicateJndiBindingFound(name, bindingName, conflict); } } }
18,578
58.16879
346
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/ResourceReferenceRegistrySetupProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import org.jboss.as.ee.component.Attachments; import org.jboss.as.ee.component.EEModuleDescription; import org.jboss.as.ee.concurrent.deployers.injection.ContextServiceResourceReferenceProcessor; import org.jboss.as.ee.concurrent.deployers.injection.ManagedExecutorServiceResourceReferenceProcessor; import org.jboss.as.ee.concurrent.deployers.injection.ManagedScheduledExecutorServiceResourceReferenceProcessor; import org.jboss.as.ee.concurrent.deployers.injection.ManagedThreadFactoryResourceReferenceProcessor; 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; /** * DUP that adds the {@Link EEResourceReferenceProcessorRegistry} to the deployment, and adds the bean validation resolvers. * * @author Stuart Douglas */ public class ResourceReferenceRegistrySetupProcessor implements DeploymentUnitProcessor { @Override public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if(deploymentUnit.getParent() == null) { final EEResourceReferenceProcessorRegistry registry = new EEResourceReferenceProcessorRegistry(); final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION); if (eeModuleDescription != null) { if (eeModuleDescription.getDefaultResourceJndiNames().getContextService() != null) { registry.registerResourceReferenceProcessor(ContextServiceResourceReferenceProcessor.INSTANCE); } if (eeModuleDescription.getDefaultResourceJndiNames().getManagedExecutorService() != null) { registry.registerResourceReferenceProcessor(ManagedExecutorServiceResourceReferenceProcessor.INSTANCE); } if (eeModuleDescription.getDefaultResourceJndiNames().getManagedScheduledExecutorService() != null) { registry.registerResourceReferenceProcessor(ManagedScheduledExecutorServiceResourceReferenceProcessor.INSTANCE); } if (eeModuleDescription.getDefaultResourceJndiNames().getManagedThreadFactory() != null) { registry.registerResourceReferenceProcessor(ManagedThreadFactoryResourceReferenceProcessor.INSTANCE); } } deploymentUnit.putAttachment(Attachments.RESOURCE_REFERENCE_PROCESSOR_REGISTRY, registry); } else{ deploymentUnit.putAttachment(Attachments.RESOURCE_REFERENCE_PROCESSOR_REGISTRY, deploymentUnit.getParent().getAttachment(Attachments.RESOURCE_REFERENCE_PROCESSOR_REGISTRY)); } } }
3,965
55.657143
185
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/BooleanAnnotationInformationFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import java.lang.annotation.Annotation; import org.jboss.as.ee.metadata.ClassAnnotationInformationFactory; import org.jboss.jandex.AnnotationInstance; import org.jboss.metadata.property.PropertyReplacer; /** * An annotation information factory that simply returns true if the annotation is present * * @author Stuart Douglas */ public class BooleanAnnotationInformationFactory<T extends Annotation> extends ClassAnnotationInformationFactory<T, Boolean> { public BooleanAnnotationInformationFactory(final Class<T> annotationType) { super(annotationType, null); } @Override protected Boolean fromAnnotation(final AnnotationInstance annotationInstance, final PropertyReplacer propertyReplacer) { return true; } }
1,824
37.829787
126
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/ModuleJndiBindingProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import org.jboss.as.ee.logging.EeLogger; import org.jboss.as.ee.component.Attachments; import org.jboss.as.ee.component.BindingConfiguration; import org.jboss.as.ee.component.ClassDescriptionTraversal; import org.jboss.as.ee.component.ComponentConfiguration; import org.jboss.as.ee.component.ComponentNamingMode; import org.jboss.as.ee.component.EEApplicationClasses; import org.jboss.as.ee.component.EEModuleClassDescription; import org.jboss.as.ee.component.EEModuleConfiguration; import org.jboss.as.ee.component.EEModuleDescription; import org.jboss.as.ee.component.InjectionSource; import org.jboss.as.ee.component.InterceptorDescription; import org.jboss.as.ee.metadata.MetadataCompleteMarker; import org.jboss.as.ee.naming.ContextInjectionSource; import org.jboss.as.ee.structure.DeploymentType; import org.jboss.as.ee.structure.DeploymentTypeMarker; import org.jboss.as.ee.utils.ClassLoadingUtils; import org.jboss.as.naming.ManagedReferenceFactory; import org.jboss.as.naming.ServiceBasedNamingStore; import org.jboss.as.naming.deployment.ContextNames; import org.jboss.as.naming.service.BinderService; import org.jboss.as.server.CurrentServiceContainer; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.annotation.CompositeIndex; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; import org.jboss.modules.Module; import org.jboss.msc.service.CircularDependencyException; import org.jboss.msc.service.DuplicateServiceException; import org.jboss.msc.service.LifecycleEvent; import org.jboss.msc.service.LifecycleListener; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.wildfly.security.manager.WildFlySecurityManager; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static org.jboss.as.ee.logging.EeLogger.ROOT_LOGGER; /** * Processor that sets up JNDI bindings that are owned by the module. It also handles class level jndi bindings * that belong to components that do not have their own java:comp namespace, and class level bindings declared in * namespaces above java:comp. * <p/> * This processor is also responsible for throwing an exception if any ee component classes have been marked as invalid. * * @author Stuart Douglas * @author Eduardo Martins */ public class ModuleJndiBindingProcessor implements DeploymentUnitProcessor { private final boolean appclient; private final boolean ignoreUnusedResourceBinding = Boolean.valueOf(WildFlySecurityManager.getPropertyPrivileged("jboss.ee.ignore-unused-resource-binding", "false")); public ModuleJndiBindingProcessor(boolean appclient) { this.appclient = appclient; } public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final EEApplicationClasses applicationClasses = deploymentUnit.getAttachment(Attachments.EE_APPLICATION_CLASSES_DESCRIPTION); final EEModuleConfiguration moduleConfiguration = deploymentUnit.getAttachment(Attachments.EE_MODULE_CONFIGURATION); final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION); final Module module = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.MODULE); if (moduleConfiguration == null) { return; } final List<ServiceName> dependencies = deploymentUnit.getAttachmentList(org.jboss.as.server.deployment.Attachments.JNDI_DEPENDENCIES); final Map<ServiceName, BindingConfiguration> deploymentDescriptorBindings = new HashMap<ServiceName, BindingConfiguration>(); final List<BindingConfiguration> bindingConfigurations = eeModuleDescription.getBindingConfigurations(); //we need to make sure that java:module/env and java:comp/env are always available if (!DeploymentTypeMarker.isType(DeploymentType.EAR, deploymentUnit)) { bindingConfigurations.add(new BindingConfiguration("java:module/env", new ContextInjectionSource("env", "java:module/env"))); } if (deploymentUnit.getParent() == null) { bindingConfigurations.add(new BindingConfiguration("java:app/env", new ContextInjectionSource("env", "java:app/env"))); } for (BindingConfiguration binding : bindingConfigurations) { final ContextNames.BindInfo bindInfo = ContextNames.bindInfoForEnvEntry(moduleConfiguration.getApplicationName(), moduleConfiguration.getModuleName(), null, false, binding.getName()); deploymentDescriptorBindings.put(bindInfo.getBinderServiceName(), binding); addJndiBinding(moduleConfiguration, binding, phaseContext, dependencies); } //now we process all component level bindings, for components that do not have their own java:comp namespace. // these are bindings that have been added via a deployment descriptor for (final ComponentConfiguration componentConfiguration : moduleConfiguration.getComponentConfigurations()) { // TODO: Should the view configuration just return a Set instead of a List? Or is there a better way to // handle these duplicates? for (BindingConfiguration binding : componentConfiguration.getComponentDescription().getBindingConfigurations()) { final String bindingName = binding.getName(); final boolean compBinding = bindingName.startsWith("java:comp") || !bindingName.startsWith("java:"); if (componentConfiguration.getComponentDescription().getNamingMode() == ComponentNamingMode.CREATE && compBinding) { //components with there own comp context do their own binding continue; } final ContextNames.BindInfo bindInfo = ContextNames.bindInfoForEnvEntry(moduleConfiguration.getApplicationName(), moduleConfiguration.getModuleName(), null, false, binding.getName()); deploymentDescriptorBindings.put(bindInfo.getBinderServiceName(), binding); addJndiBinding(moduleConfiguration, binding, phaseContext, dependencies); } } //now add all class level bindings final Set<String> handledClasses = new HashSet<String>(); for (final ComponentConfiguration componentConfiguration : moduleConfiguration.getComponentConfigurations()) { final Set<Class<?>> classConfigurations = new HashSet<Class<?>>(); classConfigurations.add(componentConfiguration.getComponentClass()); for (final InterceptorDescription interceptor : componentConfiguration.getComponentDescription().getAllInterceptors()) { try { classConfigurations.add(ClassLoadingUtils.loadClass(interceptor.getInterceptorClassName(), module)); } catch (ClassNotFoundException e) { throw EeLogger.ROOT_LOGGER.cannotLoadInterceptor(e, interceptor.getInterceptorClassName(), componentConfiguration.getComponentClass()); } } processClassConfigurations(phaseContext, applicationClasses, moduleConfiguration, deploymentDescriptorBindings, handledClasses, componentConfiguration.getComponentDescription().getNamingMode(), classConfigurations, componentConfiguration.getComponentName(), dependencies); } //now we need to process resource bindings that are not part of a component //we don't process app client modules, as it just causes problems by installing bindings that //were only intended to be installed when running as an app client boolean appClient = DeploymentTypeMarker.isType(DeploymentType.APPLICATION_CLIENT, deploymentUnit) || this.appclient; if (!ignoreUnusedResourceBinding && !MetadataCompleteMarker.isMetadataComplete(phaseContext.getDeploymentUnit()) && !appClient) { final CompositeIndex index = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.COMPOSITE_ANNOTATION_INDEX); for (EEModuleClassDescription config : eeModuleDescription.getClassDescriptions()) { if (handledClasses.contains(config.getClassName())) { continue; } if(config.isInvalid()) { continue; } final Set<BindingConfiguration> classLevelBindings = new HashSet<>(config.getBindingConfigurations()); // only process concrete classes and their superclasses // (An Index contains info on all classes in a jar, and the CompositeIndex in the 'index' var aggregates // all the Index objects for the jars visible to the deployment unit. So it can be scanned for relationships // between classes and not miss out on any.) if (!classLevelBindings.isEmpty()) { ClassInfo classInfo = index.getClassByName(DotName.createSimple(config.getClassName())); if (!isConcreteClass(classInfo) && !hasConcreteSubclass(index, classInfo)) { continue; } } for (BindingConfiguration binding : classLevelBindings) { final String bindingName = binding.getName(); final boolean compBinding = bindingName.startsWith("java:comp") || !bindingName.startsWith("java:"); if(compBinding && !DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) { //we don't have a comp namespace continue; } final ContextNames.BindInfo bindInfo = ContextNames.bindInfoForEnvEntry(moduleConfiguration.getApplicationName(), moduleConfiguration.getModuleName(), null, false, binding.getName()); if (deploymentDescriptorBindings.containsKey(bindInfo.getBinderServiceName())) { continue; //this has been overridden by a DD binding } ROOT_LOGGER.tracef("Binding %s using service %s", binding.getName(), bindInfo.getBinderServiceName()); addJndiBinding(moduleConfiguration, binding, phaseContext, dependencies); } } } } private void processClassConfigurations(final DeploymentPhaseContext phaseContext, final EEApplicationClasses applicationClasses, final EEModuleConfiguration moduleConfiguration, final Map<ServiceName, BindingConfiguration> deploymentDescriptorBindings, final Set<String> handledClasses, final ComponentNamingMode namingMode, final Set<Class<?>> classes, final String componentName, final List<ServiceName> dependencies) throws DeploymentUnitProcessingException { for (final Class<?> clazz : classes) { new ClassDescriptionTraversal(clazz, applicationClasses) { @Override protected void handle(final Class<?> currentClass, final EEModuleClassDescription classDescription) throws DeploymentUnitProcessingException { if (classDescription == null) { return; } if (classDescription.isInvalid()) { throw EeLogger.ROOT_LOGGER.componentClassHasErrors(classDescription.getClassName(), componentName, classDescription.getInvalidMessage()); } //only process classes once if (handledClasses.contains(classDescription.getClassName())) { return; } handledClasses.add(classDescription.getClassName()); // TODO: Should the view configuration just return a Set instead of a List? Or is there a better way to // handle these duplicates? if (!MetadataCompleteMarker.isMetadataComplete(phaseContext.getDeploymentUnit())) { final Set<BindingConfiguration> classLevelBindings = new HashSet<BindingConfiguration>(classDescription.getBindingConfigurations()); for (BindingConfiguration binding : classLevelBindings) { final String bindingName = binding.getName(); final boolean compBinding = bindingName.startsWith("java:comp") || !bindingName.startsWith("java:"); if (namingMode == ComponentNamingMode.CREATE && compBinding) { //components with their own comp context do their own binding continue; } final ContextNames.BindInfo bindInfo = ContextNames.bindInfoForEnvEntry(moduleConfiguration.getApplicationName(), moduleConfiguration.getModuleName(), null, false, binding.getName()); if (deploymentDescriptorBindings.containsKey(bindInfo.getBinderServiceName())) { continue; //this has been overridden by a DD binding } ROOT_LOGGER.tracef("Binding %s using service %s", binding.getName(), bindInfo.getBinderServiceName()); addJndiBinding(moduleConfiguration, binding, phaseContext, dependencies); } } } }.run(); } } protected void addJndiBinding(final EEModuleConfiguration module, final BindingConfiguration bindingConfiguration, final DeploymentPhaseContext phaseContext, final List<ServiceName> dependencies) throws DeploymentUnitProcessingException { // Gather information about the dependency final String bindingName = bindingConfiguration.getName().startsWith("java:") ? bindingConfiguration.getName() : "java:module/env/" + bindingConfiguration.getName(); InjectionSource.ResolutionContext resolutionContext = new InjectionSource.ResolutionContext( true, module.getModuleName(), module.getModuleName(), module.getApplicationName() ); // Check to see if this entry should actually be bound into JNDI. if (bindingName != null) { final ContextNames.BindInfo bindInfo = ContextNames.bindInfoForEnvEntry(module.getApplicationName(), module.getModuleName(), module.getModuleName(), false, bindingName); dependencies.add(bindInfo.getBinderServiceName()); if (bindingName.startsWith("java:comp") || bindingName.startsWith("java:module") || bindingName.startsWith("java:app")) { //this is a binding that does not need to be shared. try { final BinderService service = new BinderService(bindInfo.getBindName(), bindingConfiguration.getSource()); ServiceBuilder<ManagedReferenceFactory> serviceBuilder = phaseContext.getServiceTarget().addService(bindInfo.getBinderServiceName(), service); bindingConfiguration.getSource().getResourceValue(resolutionContext, serviceBuilder, phaseContext, service.getManagedObjectInjector()); serviceBuilder.addDependency(bindInfo.getParentContextServiceName(), ServiceBasedNamingStore.class, service.getNamingStoreInjector()); serviceBuilder.install(); } catch (DuplicateServiceException e) { ServiceController<ManagedReferenceFactory> registered = (ServiceController<ManagedReferenceFactory>) CurrentServiceContainer.getServiceContainer().getService(bindInfo.getBinderServiceName()); if (registered == null) throw e; BinderService service = (BinderService) registered.getService(); if (service == null || service.getSource() == null) { throw e; } if (!service.getSource().equals(bindingConfiguration.getSource())) throw EeLogger.ROOT_LOGGER.conflictingBinding(bindingName, bindingConfiguration.getSource()); } catch (CircularDependencyException e) { throw EeLogger.ROOT_LOGGER.circularDependency(bindingName); } } else { BinderService service; ServiceController<ManagedReferenceFactory> controller; try { service = new BinderService(bindInfo.getBindName(), bindingConfiguration.getSource(), true); ServiceTarget externalServiceTarget = phaseContext.getDeploymentUnit().getAttachment(org.jboss.as.server.deployment.Attachments.EXTERNAL_SERVICE_TARGET); ServiceBuilder<ManagedReferenceFactory> serviceBuilder = externalServiceTarget.addService(bindInfo.getBinderServiceName(), service); bindingConfiguration.getSource().getResourceValue(resolutionContext, serviceBuilder, phaseContext, service.getManagedObjectInjector()); serviceBuilder.addDependency(bindInfo.getParentContextServiceName(), ServiceBasedNamingStore.class, service.getNamingStoreInjector()); controller = serviceBuilder.install(); } catch (DuplicateServiceException e) { controller = (ServiceController<ManagedReferenceFactory>) CurrentServiceContainer.getServiceContainer().getService(bindInfo.getBinderServiceName()); if (controller == null) throw e; service = (BinderService) controller.getService(); if (!equals(service.getSource(), bindingConfiguration.getSource())) { throw EeLogger.ROOT_LOGGER.conflictingBinding(bindingName, bindingConfiguration.getSource()); } } //as these bindings are not child services //we instead add another service that is a child service that will release the reference count on stop //if the reference count hits zero this service will wait till the binding is down to actually stop //to prevent WFLY-9870 where the undeployment is complete but the binding services are still present try { phaseContext.getServiceTarget().addService(phaseContext.getDeploymentUnit().getServiceName().append("sharedBindingReleaseService").append(bindInfo.getBinderServiceName()), new BinderReleaseService(controller, service)) .install(); service.acquire(); } catch (DuplicateServiceException ignore) { //we ignore this, as it is already managed by this deployment } } } else { throw EeLogger.ROOT_LOGGER.nullBindingName(bindingConfiguration); } } public static boolean equals(Object one, Object two) { return one == two || (one != null && one.equals(two)); } private static boolean isConcreteClass(ClassInfo classInfo) { return !Modifier.isAbstract(classInfo.flags()) && !Modifier.isInterface(classInfo.flags()); } private static boolean hasConcreteSubclass(CompositeIndex index, ClassInfo classInfo) { final Set<ClassInfo> subclasses; if (Modifier.isInterface(classInfo.flags())) { subclasses = index.getAllKnownImplementors(classInfo.name()); } else { subclasses = index.getAllKnownSubclasses(classInfo.name()); } for (ClassInfo subclass: subclasses) { if (isConcreteClass(subclass)) { return true; } } return false; } private static class BinderReleaseService implements Service<BinderReleaseService> { private final ServiceController<ManagedReferenceFactory> sharedBindingController; private final BinderService binderService; private BinderReleaseService(ServiceController<ManagedReferenceFactory> sharedBindingController, BinderService binderService) { this.sharedBindingController = sharedBindingController; this.binderService = binderService; } @Override public void start(StartContext context) throws StartException { } @Override public void stop(StopContext context) { if(binderService.release()) { //we are the last user, it needs to shut down context.asynchronous(); sharedBindingController.addListener(new LifecycleListener() { @Override public void handleEvent(ServiceController<?> controller, LifecycleEvent event) { if(event == LifecycleEvent.REMOVED) { context.complete(); } } }); } } @Override public BinderReleaseService getValue() throws IllegalStateException, IllegalArgumentException { return null; } } }
22,882
58.746736
467
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/InterceptorAnnotationProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import jakarta.interceptor.ExcludeClassInterceptors; import jakarta.interceptor.ExcludeDefaultInterceptors; import jakarta.interceptor.Interceptors; import org.jboss.as.ee.component.Attachments; import org.jboss.as.ee.component.ComponentDescription; import org.jboss.as.ee.component.EEApplicationClasses; import org.jboss.as.ee.component.EEModuleDescription; import org.jboss.as.ee.component.InterceptorDescription; import org.jboss.as.ee.logging.EeLogger; import org.jboss.as.ee.metadata.MetadataCompleteMarker; import org.jboss.as.ee.metadata.MethodAnnotationAggregator; import org.jboss.as.ee.metadata.RuntimeAnnotationInformation; import org.jboss.as.ee.utils.ClassLoadingUtils; 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.reflect.DeploymentReflectionIndex; import org.jboss.invocation.proxy.MethodIdentifier; /** * Processor that takes interceptor information from the class description and applies it to components * * @author Stuart Douglas */ public class InterceptorAnnotationProcessor implements DeploymentUnitProcessor { @Override public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION); final Collection<ComponentDescription> componentConfigurations = eeModuleDescription.getComponentDescriptions(); final DeploymentReflectionIndex deploymentReflectionIndex = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.REFLECTION_INDEX); final EEApplicationClasses applicationClasses = deploymentUnit.getAttachment(Attachments.EE_APPLICATION_CLASSES_DESCRIPTION); if (MetadataCompleteMarker.isMetadataComplete(deploymentUnit)) { return; } if (componentConfigurations == null || componentConfigurations.isEmpty()) { return; } for (final ComponentDescription description : componentConfigurations) { processComponentConfig(applicationClasses, deploymentReflectionIndex, description, deploymentUnit); } } private void processComponentConfig(final EEApplicationClasses applicationClasses, final DeploymentReflectionIndex deploymentReflectionIndex, final ComponentDescription description, DeploymentUnit deploymentUnit) { try { final Class<?> componentClass = ClassLoadingUtils.loadClass(description.getComponentClassName(), deploymentUnit); handleAnnotations(applicationClasses, deploymentReflectionIndex, componentClass, description); } catch (Throwable e) { //just ignore the class for now. //if it is an optional component this is ok, if it is not an optional component //it will fail at configure time anyway EeLogger.ROOT_LOGGER.debugf(e,"Ignoring failure to handle interceptor annotations for %s", description.getComponentClassName()); } } private void handleAnnotations(final EEApplicationClasses applicationClasses, final DeploymentReflectionIndex deploymentReflectionIndex, final Class<?> componentClass, final ComponentDescription description) { final List<Class> heirachy = new ArrayList<Class>(); Class c = componentClass; while (c != Object.class && c != null) { heirachy.add(c); c = c.getSuperclass(); } Collections.reverse(heirachy); final RuntimeAnnotationInformation<Boolean> excludeDefaultInterceptors = MethodAnnotationAggregator.runtimeAnnotationInformation(componentClass, applicationClasses, deploymentReflectionIndex, ExcludeDefaultInterceptors.class); if (excludeDefaultInterceptors.getClassAnnotations().containsKey(componentClass.getName())) { description.setExcludeDefaultInterceptors(true); } for (final Method method : excludeDefaultInterceptors.getMethodAnnotations().keySet()) { description.excludeDefaultInterceptors(MethodIdentifier.getIdentifierForMethod(method)); } final RuntimeAnnotationInformation<Boolean> excludeClassInterceptors = MethodAnnotationAggregator.runtimeAnnotationInformation(componentClass, applicationClasses, deploymentReflectionIndex, ExcludeClassInterceptors.class); for (final Method method : excludeClassInterceptors.getMethodAnnotations().keySet()) { description.excludeClassInterceptors(MethodIdentifier.getIdentifierForMethod(method)); } final RuntimeAnnotationInformation<String[]> interceptors = MethodAnnotationAggregator.runtimeAnnotationInformation(componentClass, applicationClasses, deploymentReflectionIndex, Interceptors.class); //walk the class heirachy in reverse for (final Class<?> clazz : heirachy) { final List<String[]> classInterceptors = interceptors.getClassAnnotations().get(clazz.getName()); if (classInterceptors != null) { for (final String interceptor : classInterceptors.get(0)) { description.addClassInterceptor(new InterceptorDescription(interceptor)); } } } for (final Map.Entry<Method, List<String[]>> entry : interceptors.getMethodAnnotations().entrySet()) { final MethodIdentifier method = MethodIdentifier.getIdentifierForMethod(entry.getKey()); for (final String interceptor : entry.getValue().get(0)) { description.addMethodInterceptor(method, new InterceptorDescription(interceptor)); } } } }
7,146
50.789855
234
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/EECleanUpProcessor.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import org.jboss.as.ee.component.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.el.cache.FactoryFinderCache; import org.jboss.modules.Module; import org.jboss.msc.service.LifecycleEvent; import org.jboss.msc.service.LifecycleListener; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; /** * Cleans up references to EE structures in the deployment unit * * @author Stuart Douglas */ public class EECleanUpProcessor implements DeploymentUnitProcessor { @Override public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); deploymentUnit.removeAttachment(Attachments.EE_APPLICATION_CLASSES_DESCRIPTION); deploymentUnit.removeAttachment(Attachments.EE_APPLICATION_DESCRIPTION); deploymentUnit.removeAttachment(Attachments.EE_MODULE_CONFIGURATION); deploymentUnit.removeAttachment(Attachments.EE_MODULE_DESCRIPTION); deploymentUnit.removeAttachment(Attachments.MODULE_DEPLOYMENT_DESCRIPTOR_ENVIRONMENT); } @Override public void undeploy(final DeploymentUnit context) { final Module module = context.getAttachment(org.jboss.as.server.deployment.Attachments.MODULE); ServiceName deploymentService = context.getServiceName(); ServiceController<?> controller = context.getServiceRegistry().getRequiredService(deploymentService); //WFLY-9666 we do this cleanup at the end of undeploy //if we do it now any code in the undeploy sequence that attempts to use EL can cause it to be re-added controller.addListener(new LifecycleListener() { @Override public void handleEvent(ServiceController<?> serviceController, LifecycleEvent lifecycleEvent) { if(lifecycleEvent == LifecycleEvent.DOWN) { FactoryFinderCache.clearClassLoader(module.getClassLoader()); controller.removeListener(this); } } }); } }
3,383
46.661972
111
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/EEAnnotationProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import java.util.ArrayList; import java.util.Collections; import java.util.List; import jakarta.interceptor.ExcludeClassInterceptors; import jakarta.interceptor.ExcludeDefaultInterceptors; import org.jboss.as.ee.metadata.AbstractEEAnnotationProcessor; import org.jboss.as.ee.metadata.ClassAnnotationInformationFactory; /** * Processes Jakarta Enterprise Beans annotations and attaches them to the {@link org.jboss.as.ee.component.EEModuleClassDescription} * * @author Stuart Douglas */ public class EEAnnotationProcessor extends AbstractEEAnnotationProcessor { final List<ClassAnnotationInformationFactory> factories; public EEAnnotationProcessor() { List<ClassAnnotationInformationFactory> factories = new ArrayList<ClassAnnotationInformationFactory>(); factories.add(new InterceptorsAnnotationInformationFactory()); factories.add(new BooleanAnnotationInformationFactory<ExcludeDefaultInterceptors>(ExcludeDefaultInterceptors.class)); factories.add(new BooleanAnnotationInformationFactory<ExcludeClassInterceptors>(ExcludeClassInterceptors.class)); this.factories = Collections.unmodifiableList(factories); } @Override protected List<ClassAnnotationInformationFactory> annotationInformationFactories() { return factories; } }
2,380
40.051724
133
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/DefaultEarSubDeploymentsIsolationProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; 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.server.deployment.module.ModuleSpecification; /** * {@link DeploymentUnitProcessor} responsible for setting the default ear subdeployments isolation for each .ear * deployment unit. The default is picked up from the EE subsystem and set on the {@link ModuleSpecification} of the deployment unit. * Unless, the specific deployment unit overrides the isolation via jboss-deployment-structure.xml, this * default value will be used to setup isolation of the subdeployments within a .ear. * <p/> * <b>Note: This deployer must run before the {@link org.jboss.as.server.deployment.module.descriptor.DeploymentStructureDescriptorParser}</b> * * @see {@link org.jboss.as.server.deployment.module.descriptor.DeploymentStructureDescriptorParser} * <p/> * User: Jaikiran Pai */ public class DefaultEarSubDeploymentsIsolationProcessor implements DeploymentUnitProcessor { private volatile boolean earSubDeploymentsIsolated; public DefaultEarSubDeploymentsIsolationProcessor() { } @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); // we only process .ear if (!DeploymentTypeMarker.isType(DeploymentType.EAR, deploymentUnit)) { return; } final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); // set the default ear subdeployment isolation value moduleSpecification.setSubDeploymentModulesIsolated(earSubDeploymentsIsolated); } public void setEarSubDeploymentsIsolated(boolean earSubDeploymentsIsolated) { this.earSubDeploymentsIsolated = earSubDeploymentsIsolated; } }
3,267
45.028169
142
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/DefaultBindingsConfigurationProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import org.jboss.as.ee.component.Attachments; import org.jboss.as.ee.component.EEDefaultResourceJndiNames; import org.jboss.as.ee.component.EEModuleDescription; 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; /** * The {@link org.jboss.as.server.deployment.DeploymentUnitProcessor} which adds the EE subsystem default bindings configuration to EE module descriptions. * * @author Eduardo Martins */ public class DefaultBindingsConfigurationProcessor implements DeploymentUnitProcessor { private volatile String contextService; private volatile String dataSource; private volatile String jmsConnectionFactory; private volatile String managedExecutorService; private volatile String managedScheduledExecutorService; private volatile String managedThreadFactory; @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { // store subsystem config in module description final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION); if(eeModuleDescription != null) { // set names only if these are not set yet final EEDefaultResourceJndiNames defaultResourceJndiNames = eeModuleDescription.getDefaultResourceJndiNames(); if(defaultResourceJndiNames.getContextService() == null) { defaultResourceJndiNames.setContextService(contextService); } if(defaultResourceJndiNames.getDataSource() == null) { defaultResourceJndiNames.setDataSource(dataSource); } if(defaultResourceJndiNames.getJmsConnectionFactory() == null) { defaultResourceJndiNames.setJmsConnectionFactory(jmsConnectionFactory); } if(defaultResourceJndiNames.getManagedExecutorService() == null) { defaultResourceJndiNames.setManagedExecutorService(managedExecutorService); } if(defaultResourceJndiNames.getManagedScheduledExecutorService() == null) { defaultResourceJndiNames.setManagedScheduledExecutorService(managedScheduledExecutorService); } if(defaultResourceJndiNames.getManagedThreadFactory() == null) { defaultResourceJndiNames.setManagedThreadFactory(managedThreadFactory); } } } public void setContextService(String contextService) { this.contextService = contextService; } public void setDataSource(String dataSource) { this.dataSource = dataSource; } public void setJmsConnectionFactory(String jmsConnectionFactory) { this.jmsConnectionFactory = jmsConnectionFactory; } public void setManagedExecutorService(String managedExecutorService) { this.managedExecutorService = managedExecutorService; } public void setManagedScheduledExecutorService(String managedScheduledExecutorService) { this.managedScheduledExecutorService = managedScheduledExecutorService; } public void setManagedThreadFactory(String managedThreadFactory) { this.managedThreadFactory = managedThreadFactory; } }
4,545
44.919192
155
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/EarApplicationNameProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import org.jboss.as.ee.component.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.metadata.ear.spec.EarMetaData; /** * The Java EE6 spec and Enterprise Beans 3.1 spec contradict each other on what the "application-name" semantics are. * The Java EE6 spec says that in the absence of a (top level) .ear, the application-name is same as the * (top level) module name. So if a blah.jar is deployed, as per Java EE6 spec, both the module name and * application name are "blah". This is contradictory to the Enterprise Beans 3.1 spec (JNDI naming section) which says * that in the absence of a (top level) .ear, the application-name is null. * <p/> * This deployment processor, sets up the {@link Attachments#EAR_APPLICATION_NAME} attachment with the value * that's semantically equivalent to what the Enterprise Beans 3.1 spec expects. * * @author Jaikiran Pai */ public class EarApplicationNameProcessor implements DeploymentUnitProcessor { @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final String earApplicationName = this.getApplicationName(deploymentUnit); deploymentUnit.putAttachment(Attachments.EAR_APPLICATION_NAME, earApplicationName); } /** * Returns the application name for the passed deployment. If the passed deployment isn't an .ear or doesn't belong * to a .ear, then this method returns null. Else it returns the application-name set in the application.xml of the .ear * or if that's not set, will return the .ear deployment unit name (stripped off the .ear suffix). * * @param deploymentUnit The deployment unit */ private String getApplicationName(DeploymentUnit deploymentUnit) { final DeploymentUnit parentDU = deploymentUnit.getParent(); if (parentDU == null) { final EarMetaData earMetaData = deploymentUnit.getAttachment(org.jboss.as.ee.structure.Attachments.EAR_METADATA); if (earMetaData != null) { final String overriddenAppName = earMetaData.getApplicationName(); if (overriddenAppName == null) { return this.getEarName(deploymentUnit); } return overriddenAppName; } else { return this.getEarName(deploymentUnit); } } // traverse to top level DU return this.getApplicationName(parentDU); } /** * Returns the name (stripped off the .ear suffix) of the passed <code>deploymentUnit</code>. * Returns null if the passed <code>deploymentUnit</code>'s name doesn't end with .ear suffix. * * @param deploymentUnit Deployment unit * @return */ private String getEarName(final DeploymentUnit deploymentUnit) { final String duName = deploymentUnit.getName(); if (duName.endsWith(".ear")) { return duName.substring(0, duName.length() - ".ear".length()); } return null; } }
4,392
46.75
125
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/InterceptorsAnnotationInformationFactory.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import jakarta.interceptor.Interceptors; import org.jboss.as.ee.metadata.ClassAnnotationInformationFactory; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.Type; import org.jboss.metadata.property.PropertyReplacer; /** * @author Stuart Douglas */ public class InterceptorsAnnotationInformationFactory extends ClassAnnotationInformationFactory<Interceptors, String[]> { protected InterceptorsAnnotationInformationFactory() { super(Interceptors.class, null); } @Override protected String[] fromAnnotation(final AnnotationInstance annotationInstance, final PropertyReplacer propertyReplacer) { final Type[] classes = annotationInstance.value().asClassArray(); final String[] ret = new String[classes.length]; for(int i = 0; i < classes.length; ++i) { ret[i] = classes[i].name().toString(); } return ret; } }
1,974
38.5
125
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/MessageDestinationInjectionSource.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import java.util.Set; import org.jboss.as.ee.logging.EeLogger; import org.jboss.as.ee.component.EEApplicationDescription; import org.jboss.as.ee.component.InjectionSource; import org.jboss.as.naming.ManagedReferenceFactory; import org.jboss.as.naming.deployment.ContextNames; 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.module.ResourceRoot; import org.jboss.msc.inject.Injector; import org.jboss.msc.service.ServiceBuilder; import static org.jboss.as.ee.component.Attachments.EE_APPLICATION_DESCRIPTION; /** * Implementation of {@link org.jboss.as.ee.component.InjectionSource} responsible for finding a message destination * * @author Stuart Douglas */ public class MessageDestinationInjectionSource extends InjectionSource { private final String bindingName; private final String messageDestinationName; private volatile String resolvedLookupName; private volatile String error = null; public MessageDestinationInjectionSource(final String messageDestinationName, final String bindingName) { this.messageDestinationName = messageDestinationName; this.bindingName = bindingName; } public void getResourceValue(final ResolutionContext resolutionContext, final ServiceBuilder<?> serviceBuilder, final DeploymentPhaseContext phaseContext, final Injector<ManagedReferenceFactory> injector) throws DeploymentUnitProcessingException { if (error != null) { throw new DeploymentUnitProcessingException(error); } final String applicationName = resolutionContext.getApplicationName(); final String moduleName = resolutionContext.getModuleName(); final String componentName = resolutionContext.getComponentName(); final boolean compUsesModule = resolutionContext.isCompUsesModule(); final String lookupName; if (!this.resolvedLookupName.contains(":")) { if (componentName != null && !compUsesModule) { lookupName = "java:comp/env/" + this.resolvedLookupName; } else if (compUsesModule) { lookupName = "java:module/env/" + this.resolvedLookupName; } else { lookupName = "java:jboss/env" + this.resolvedLookupName; } } else if (this.resolvedLookupName.startsWith("java:comp/") && compUsesModule) { lookupName = "java:module/" + this.resolvedLookupName.substring(10); } else { lookupName = this.resolvedLookupName; } final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(applicationName, moduleName, componentName, lookupName); if (lookupName.startsWith("java:")) { serviceBuilder.addDependency(bindInfo.getBinderServiceName(), ManagedReferenceFactory.class, injector); } } public void resolve(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final EEApplicationDescription applicationDescription = deploymentUnit.getAttachment(EE_APPLICATION_DESCRIPTION); final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT); final Set<String> names = applicationDescription.resolveMessageDestination(messageDestinationName, deploymentRoot.getRoot()); if (names.isEmpty()) { error = EeLogger.ROOT_LOGGER.noMessageDestination(messageDestinationName, bindingName); return; } if (names.size() > 1) { error = EeLogger.ROOT_LOGGER.moreThanOneMessageDestination(messageDestinationName, bindingName, names); return; } resolvedLookupName = names.iterator().next(); } public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof MessageDestinationInjectionSource)) return false; if (error != null) { //we can't do a real equals comparison in this case, so throw the original error throw new RuntimeException(error); } if (resolvedLookupName == null) { throw new RuntimeException("Error equals() cannot be called before resolve()"); } final MessageDestinationInjectionSource other = (MessageDestinationInjectionSource) o; return eq(resolvedLookupName, other.resolvedLookupName); } public int hashCode() { return messageDestinationName.hashCode(); } private static boolean eq(Object a, Object b) { return a == b || (a != null && a.equals(b)); } }
5,906
44.091603
251
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/LifecycleAnnotationParsingProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import static org.jboss.as.ee.logging.EeLogger.ROOT_LOGGER; import java.util.List; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.interceptor.AroundConstruct; import jakarta.interceptor.InvocationContext; import org.jboss.as.ee.logging.EeLogger; import org.jboss.as.ee.component.Attachments; import org.jboss.as.ee.component.EEApplicationClasses; import org.jboss.as.ee.component.EEModuleClassDescription; import org.jboss.as.ee.component.EEModuleDescription; import org.jboss.as.ee.component.interceptors.InterceptorClassDescription; 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.invocation.proxy.MethodIdentifier; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.AnnotationTarget; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; import org.jboss.jandex.MethodInfo; import org.jboss.jandex.Type; /** * Deployment processor responsible for finding @PostConstruct and @PreDestroy annotated methods. * * @author John Bailey * @author Stuart Douglas */ public class LifecycleAnnotationParsingProcessor implements DeploymentUnitProcessor { private static final DotName POST_CONSTRUCT_ANNOTATION = DotName.createSimple(PostConstruct.class.getName()); private static final DotName PRE_DESTROY_ANNOTATION = DotName.createSimple(PreDestroy.class.getName()); private static final DotName AROUND_CONSTRUCT_ANNOTATION = DotName.createSimple(AroundConstruct.class.getName()); private static DotName[] LIFE_CYCLE_ANNOTATIONS = {POST_CONSTRUCT_ANNOTATION, PRE_DESTROY_ANNOTATION, AROUND_CONSTRUCT_ANNOTATION}; public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION); final EEApplicationClasses applicationClasses = deploymentUnit.getAttachment(Attachments.EE_APPLICATION_CLASSES_DESCRIPTION); final CompositeIndex index = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.COMPOSITE_ANNOTATION_INDEX); for (DotName annotationName : LIFE_CYCLE_ANNOTATIONS) { final List<AnnotationInstance> lifecycles = index.getAnnotations(annotationName); for (AnnotationInstance annotation : lifecycles) { processLifeCycle(eeModuleDescription, annotation.target(), annotationName, applicationClasses); } } } private void processLifeCycle(final EEModuleDescription eeModuleDescription, final AnnotationTarget target, final DotName annotationType, final EEApplicationClasses applicationClasses) throws DeploymentUnitProcessingException { if (!(target instanceof MethodInfo)) { throw EeLogger.ROOT_LOGGER.methodOnlyAnnotation(annotationType); } final MethodInfo methodInfo = MethodInfo.class.cast(target); final ClassInfo classInfo = methodInfo.declaringClass(); final EEModuleClassDescription classDescription = eeModuleDescription.addOrGetLocalClassDescription(classInfo.name().toString()); final Type[] args = methodInfo.args(); if (args.length > 1) { ROOT_LOGGER.warn(EeLogger.ROOT_LOGGER.invalidNumberOfArguments(methodInfo.name(), annotationType, classInfo.name())); return; } else if (args.length == 1 && !args[0].name().toString().equals(InvocationContext.class.getName())) { ROOT_LOGGER.warn(EeLogger.ROOT_LOGGER.invalidSignature(methodInfo.name(), annotationType, classInfo.name(), "void methodName(InvocationContext ctx)")); return; } final InterceptorClassDescription.Builder builder = InterceptorClassDescription.builder(classDescription.getInterceptorClassDescription()); if (annotationType == POST_CONSTRUCT_ANNOTATION) { builder.setPostConstruct(getMethodIdentifier(args, methodInfo)); } else if (annotationType == PRE_DESTROY_ANNOTATION) { builder.setPreDestroy(getMethodIdentifier(args, methodInfo)); } else if(annotationType == AROUND_CONSTRUCT_ANNOTATION){ builder.setAroundConstruct(getMethodIdentifier(args, methodInfo)); } classDescription.setInterceptorClassDescription(builder.build()); } private MethodIdentifier getMethodIdentifier(Type[] args, MethodInfo methodInfo){ if (args.length == 0) { return MethodIdentifier.getIdentifier(Void.TYPE, methodInfo.name()); } else { return MethodIdentifier.getIdentifier(methodInfo.returnType().name().toString(), methodInfo.name(), InvocationContext.class.getName()); } } }
6,119
52.217391
231
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/deployers/EEModuleInitialProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.deployers; import java.util.HashMap; import org.jboss.as.ee.component.Attachments; import org.jboss.as.ee.component.EEModuleDescription; 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; /** * @author <a href="mailto:[email protected]">David M. Lloyd</a> * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public final class EEModuleInitialProcessor implements DeploymentUnitProcessor { private final boolean appClient; public EEModuleInitialProcessor(boolean appClient) { this.appClient = appClient; } public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final String deploymentUnitName = deploymentUnit.getName(); final String moduleName; if (deploymentUnitName.endsWith(".war") || deploymentUnitName.endsWith(".jar") || deploymentUnitName.endsWith(".ear") || deploymentUnitName.endsWith(".rar")) { moduleName = deploymentUnitName.substring(0, deploymentUnitName.length() - 4); } else { moduleName = deploymentUnitName; } final String appName; final String earApplicationName = deploymentUnit.getAttachment(Attachments.EAR_APPLICATION_NAME); //the ear application name takes into account the name set in application.xml //if this is non-null this is always the one we want to use if(earApplicationName != null) { appName = earApplicationName; } else { //an appname of null means use the module name appName = null; } deploymentUnit.putAttachment(Attachments.EE_MODULE_DESCRIPTION, new EEModuleDescription(appName, moduleName, earApplicationName, appClient)); deploymentUnit.putAttachment(org.jboss.as.server.deployment.Attachments.COMPONENT_JNDI_DEPENDENCIES, new HashMap<>()); } }
3,207
45.492754
167
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/interceptors/InterceptorClassDescription.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.interceptors; import org.jboss.invocation.proxy.MethodIdentifier; /** * Post class loading description of an interceptor class. * * @author Stuart Douglas */ public class InterceptorClassDescription { public static final InterceptorClassDescription EMPTY_INSTANCE = new Builder().build(); private final MethodIdentifier aroundInvoke; private final MethodIdentifier aroundTimeout; private final MethodIdentifier aroundConstruct; private final MethodIdentifier preDestroy; private final MethodIdentifier postConstruct; private final MethodIdentifier prePassivate; private final MethodIdentifier postActivate; public InterceptorClassDescription(final MethodIdentifier aroundInvoke, final MethodIdentifier aroundTimeout, final MethodIdentifier aroundConstruct, final MethodIdentifier preDestroy, final MethodIdentifier postConstruct, final MethodIdentifier postActivate, final MethodIdentifier prePassivate) { this.aroundInvoke = aroundInvoke; this.aroundTimeout = aroundTimeout; this.aroundConstruct = aroundConstruct; this.preDestroy = preDestroy; this.postConstruct = postConstruct; this.postActivate = postActivate; this.prePassivate = prePassivate; } /** * Merges two descriptors, either of the parameters will be null. * <p/> * this method will never return null; * * @param existing * @param override * @return */ public static InterceptorClassDescription merge(InterceptorClassDescription existing, InterceptorClassDescription override) { if (existing == null && override == null) { return EMPTY_INSTANCE; } if (override == null) { return existing; } if (existing == null) { return override; } final Builder builder = builder(existing); if (override.getAroundInvoke() != null) { builder.setAroundInvoke(override.getAroundInvoke()); } if (override.getAroundTimeout() != null) { builder.setAroundTimeout(override.getAroundTimeout()); } if (override.getAroundConstruct() != null) { builder.setAroundConstruct(override.getAroundConstruct()); } if (override.getPostConstruct() != null) { builder.setPostConstruct(override.getPostConstruct()); } if (override.getPreDestroy() != null) { builder.setPreDestroy(override.getPreDestroy()); } if (override.getPrePassivate() != null) { builder.setPrePassivate(override.getPrePassivate()); } if (override.getPostActivate() != null) { builder.setPostActivate(override.getPostActivate()); } return builder.build(); } /** * Constructs a new empty builder * * @return An empty builder */ public static Builder builder() { return new Builder(); } /** * @param base The existing description, or null for an empty builder * @return A builder based on the existing description */ public static Builder builder(InterceptorClassDescription base) { if (base == null) { return new Builder(); } return new Builder(base); } public static class Builder { private MethodIdentifier aroundInvoke; private MethodIdentifier aroundTimeout; private MethodIdentifier aroundConstruct; private MethodIdentifier preDestroy; private MethodIdentifier postConstruct; private MethodIdentifier prePassivate; private MethodIdentifier postActivate; Builder() { } Builder(InterceptorClassDescription existing) { this.aroundInvoke = existing.aroundInvoke; this.aroundTimeout = existing.aroundTimeout; this.aroundConstruct = existing.aroundConstruct; this.preDestroy = existing.preDestroy; this.postConstruct = existing.postConstruct; this.prePassivate = existing.prePassivate; this.postActivate = existing.postActivate; } public InterceptorClassDescription build() { return new InterceptorClassDescription(aroundInvoke, aroundTimeout, aroundConstruct, preDestroy, postConstruct, postActivate, prePassivate); } public MethodIdentifier getAroundInvoke() { return aroundInvoke; } public void setAroundInvoke(final MethodIdentifier aroundInvoke) { this.aroundInvoke = aroundInvoke; } public MethodIdentifier getAroundTimeout() { return aroundTimeout; } public void setAroundTimeout(final MethodIdentifier aroundTimeout) { this.aroundTimeout = aroundTimeout; } public MethodIdentifier getPostConstruct() { return postConstruct; } public void setPostConstruct(final MethodIdentifier postConstruct) { this.postConstruct = postConstruct; } public MethodIdentifier getPreDestroy() { return preDestroy; } public void setPreDestroy(final MethodIdentifier preDestroy) { this.preDestroy = preDestroy; } public MethodIdentifier getPrePassivate() { return prePassivate; } public void setPrePassivate(final MethodIdentifier prePassivate) { this.prePassivate = prePassivate; } public MethodIdentifier getPostActivate() { return postActivate; } public void setPostActivate(final MethodIdentifier postActivate) { this.postActivate = postActivate; } public MethodIdentifier getAroundConstruct() { return aroundConstruct; } public void setAroundConstruct(final MethodIdentifier aroundConstruct) { this.aroundConstruct = aroundConstruct; } } public MethodIdentifier getAroundInvoke() { return aroundInvoke; } public MethodIdentifier getAroundTimeout() { return aroundTimeout; } public MethodIdentifier getPostConstruct() { return postConstruct; } public MethodIdentifier getPreDestroy() { return preDestroy; } public MethodIdentifier getPrePassivate() { return prePassivate; } public MethodIdentifier getPostActivate() { return postActivate; } public MethodIdentifier getAroundConstruct() { return aroundConstruct; } }
7,651
32.125541
302
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/interceptors/UserInterceptorFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.interceptors; /** * Interceptor factory that handles user interceptors, and switches between timer normal invocations * * @author Stuart Douglas */ import org.jboss.invocation.Interceptor; import org.jboss.invocation.InterceptorContext; import org.jboss.invocation.InterceptorFactory; import org.jboss.invocation.InterceptorFactoryContext; public class UserInterceptorFactory implements InterceptorFactory { private final InterceptorFactory aroundInvoke; private final InterceptorFactory aroundTimeout; public UserInterceptorFactory(final InterceptorFactory aroundInvoke, final InterceptorFactory aroundTimeout) { this.aroundInvoke = aroundInvoke; this.aroundTimeout = aroundTimeout; } @Override public Interceptor create(final InterceptorFactoryContext context) { final Interceptor aroundInvoke = this.aroundInvoke.create(context); final Interceptor aroundTimeout; if(this.aroundTimeout != null) { aroundTimeout = this.aroundTimeout.create(context); } else { aroundTimeout = null; } return new Interceptor() { @Override public Object processInvocation(final InterceptorContext context) throws Exception { final InvocationType marker = context.getPrivateData(InvocationType.class); if (marker == InvocationType.TIMER) { return aroundTimeout.processInvocation(context); } else { return aroundInvoke.processInvocation(context); } } }; } }
2,671
37.171429
114
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/interceptors/OrderedItemContainer.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.interceptors; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import static java.lang.Integer.toHexString; import org.jboss.as.ee.logging.EeLogger; /** * Container for an ordered list of object. Objects are added to the container, and can be sorted and * retrieved via {@link #getSortedItems()}. In order to prevent excessive sorts once the sort has been performed * no new objects can be added. * <p/> * The sort is guaranteed to be stable, so adding multiple objects with the same priority means that they will be * run in the order that they were added. * * @author Stuart Douglas */ public class OrderedItemContainer<T> { private final Map<Integer, T> items = new HashMap<Integer, T>(); private volatile List<T> sortedItems; public void add(final T item, int priority) { if(sortedItems != null) { throw EeLogger.ROOT_LOGGER.cannotAddMoreItems(); } if(item == null) { throw EeLogger.ROOT_LOGGER.nullVar("item"); } final T current = items.get(priority); if (current != null) { throw EeLogger.ROOT_LOGGER.priorityAlreadyExists(item, toHexString(priority), current); } items.put(priority, item); } public List<T> getSortedItems() { if(sortedItems == null) { final SortedMap<Integer, T> sortedMap = new TreeMap<Integer, T>(items); sortedItems = new ArrayList<T>(sortedMap.values()); } return sortedItems; } }
2,652
35.342466
113
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/interceptors/ComponentDispatcherInterceptor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.interceptors; import java.lang.reflect.Method; import org.jboss.as.ee.logging.EeLogger; import org.jboss.as.ee.component.ComponentInstance; import org.jboss.invocation.Interceptor; import org.jboss.invocation.InterceptorContext; /** * @author Stuart Douglas */ public class ComponentDispatcherInterceptor implements Interceptor { private final Method componentMethod; public ComponentDispatcherInterceptor(final Method componentMethod) { this.componentMethod = componentMethod; } public Object processInvocation(final InterceptorContext context) throws Exception { ComponentInstance componentInstance = context.getPrivateData(ComponentInstance.class); if (componentInstance == null) { throw EeLogger.ROOT_LOGGER.noComponentInstance(); } Method oldMethod = context.getMethod(); try { context.setMethod(componentMethod); context.setTarget(componentInstance.getInstance()); return componentInstance.getInterceptor(componentMethod).processInvocation(context); } finally { context.setMethod(oldMethod); context.setTarget(null); } } }
2,249
37.135593
96
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/interceptors/InterceptorOrder.java
/* * JBoss, Home of Professional Open Source * Copyright 2021, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.interceptors; /** * Class that maintains interceptor ordering for various interceptor chains * * @author Stuart Douglas */ public class InterceptorOrder { private InterceptorOrder() { } public static final class Component { public static final int INITIAL_INTERCEPTOR = 0x100; public static final int CONCURRENT_CONTEXT = 0x180; public static final int SYNCHRONIZATION_INTERCEPTOR = 0x500; public static final int REENTRANCY_INTERCEPTOR = 0x501; public static final int BMT_TRANSACTION_INTERCEPTOR = 0x520; public static final int ENTITY_BEAN_REMOVE_INTERCEPTOR = 0x550; public static final int JPA_SFSB_INTERCEPTOR = 0x560; public static final int JPA_SESSION_BEAN_INTERCEPTOR = 0x600; public static final int CMP_RELATIONSHIP_INTERCEPTOR = 0x800; // WS handlers, user and Jakarta Contexts and Dependency Injection Interceptors plus the bean method are considered user execution time public static final int EJB_EXECUTION_TIME_INTERCEPTOR = 0x850; // JSR 109 - Version 1.3 - 6.2.2.4 Security // For Jakarta Enterprise Beans based service implementations, Handlers run after method level authorization has occurred. // JSR 109 - Version 1.3 - 6.2.2.5 Transaction // Handlers run under the transaction context of the component they are associated with. public static final int WS_HANDLERS_INTERCEPTOR = 0x900; public static final int XTS_INTERCEPTOR = 0x901; /** * All user level interceptors are added with the same priority, so they execute * in the order that they are added. */ public static final int INTERCEPTOR_USER_INTERCEPTORS = 0xA00; /** * @Around* methods defined on the component class or its superclasses */ public static final int CDI_INTERCEPTORS = 0xB00; public static final int COMPONENT_USER_INTERCEPTORS = 0xC00; //interceptors defined on the component class, these have to run after Jakarta Contexts and Dependency Injection interceptors public static final int TERMINAL_INTERCEPTOR = 0xD00; private Component() { } } public static final class AroundConstruct { public static final int CONSTRUCTION_START_INTERCEPTOR = 0xA00; public static final int INTERCEPTOR_AROUND_CONSTRUCT = 0xB00; public static final int WELD_AROUND_CONSTRUCT_INTERCEPTORS = 0xC00; public static final int CONSTRUCT_COMPONENT = 0xD00; public static final int TERMINAL_INTERCEPTOR = 0xE00; private AroundConstruct() { } } public static final class ComponentPostConstruct { public static final int STARTUP_COUNTDOWN_INTERCEPTOR = 0x050; public static final int TCCL_INTERCEPTOR = 0x100; public static final int CONCURRENT_CONTEXT = 0x180; public static final int EJB_SESSION_CONTEXT_INTERCEPTOR = 0x200; public static final int WELD_INJECTION_CONTEXT_INTERCEPTOR = 0x300; public static final int JPA_SFSB_PRE_CREATE = 0x400; public static final int TRANSACTION_INTERCEPTOR = 0x500; public static final int JNDI_NAMESPACE_INTERCEPTOR = 0x600; public static final int CREATE_CDI_INTERCEPTORS = 0x0680; public static final int INTERCEPTOR_INSTANTIATION_INTERCEPTORS = 0x700; public static final int INTERCEPTOR_RESOURCE_INJECTION_INTERCEPTORS = 0x800; public static final int INTERCEPTOR_WELD_INJECTION = 0x900; public static final int AROUND_CONSTRUCT_CHAIN = 0xA00; public static final int COMPONENT_RESOURCE_INJECTION_INTERCEPTORS = 0xB00; public static final int EJB_SET_CONTEXT_METHOD_INVOCATION_INTERCEPTOR = 0xC00; public static final int COMPONENT_WELD_INJECTION = 0xD00; public static final int JPA_SFSB_CREATE = 0xE00; public static final int REQUEST_SCOPE_ACTIVATING_INTERCEPTOR = 0xE80; public static final int INTERCEPTOR_USER_INTERCEPTORS = 0xF00; public static final int CDI_INTERCEPTORS = 0x1000; public static final int COMPONENT_USER_INTERCEPTORS = 0x1100; public static final int SFSB_INIT_METHOD = 0x1200; public static final int SETUP_CONTEXT = 0x1300; public static final int TERMINAL_INTERCEPTOR = 0x1400; private ComponentPostConstruct() { } } public static final class ComponentPreDestroy { public static final int TCCL_INTERCEPTOR = 0x100; public static final int CONCURRENT_CONTEXT = 0x180; public static final int EJB_SESSION_CONTEXT_INTERCEPTOR = 0x200; public static final int TRANSACTION_INTERCEPTOR = 0x300; public static final int JNDI_NAMESPACE_INTERCEPTOR = 0x400; public static final int JPA_SFSB_DESTROY = 0x500; public static final int INTERCEPTOR_UNINJECTION_INTERCEPTORS = 0x600; public static final int COMPONENT_UNINJECTION_INTERCEPTORS = 0x700; public static final int INTERCEPTOR_DESTRUCTION_INTERCEPTORS = 0x800; public static final int COMPONENT_DESTRUCTION_INTERCEPTORS = 0x900; public static final int INTERCEPTOR_USER_INTERCEPTORS = 0xA00; public static final int CDI_INTERCEPTORS = 0xB00; public static final int COMPONENT_USER_INTERCEPTORS = 0xC00; public static final int TERMINAL_INTERCEPTOR = 0xD00; private ComponentPreDestroy() { } } public static final class ComponentPassivation { public static final int TCCL_INTERCEPTOR = 0x100; public static final int CONCURRENT_CONTEXT = 0x180; public static final int EJB_SESSION_CONTEXT_INTERCEPTOR = 0x200; public static final int TRANSACTION_INTERCEPTOR = 0x300; public static final int JNDI_NAMESPACE_INTERCEPTOR = 0x400; public static final int INTERCEPTOR_USER_INTERCEPTORS = 0x500; public static final int CDI_INTERCEPTORS = 0x600; public static final int COMPONENT_USER_INTERCEPTORS = 0x700; public static final int TERMINAL_INTERCEPTOR = 0x800; private ComponentPassivation() { } } public static final class View { public static final int CHECKING_INTERCEPTOR = 1; public static final int TCCL_INTERCEPTOR = 0x003; public static final int INVOCATION_TYPE = 0x005; public static final int EJB_IIOP_TRANSACTION = 0x020; public static final int JNDI_NAMESPACE_INTERCEPTOR = 0x050; public static final int REMOTE_EXCEPTION_TRANSFORMER = 0x200; public static final int EJB_EXCEPTION_LOGGING_INTERCEPTOR = 0x210; public static final int GRACEFUL_SHUTDOWN = 0x218; public static final int SHUTDOWN_INTERCEPTOR = 0x220; public static final int INVALID_METHOD_EXCEPTION = 0x230; public static final int STARTUP_AWAIT_INTERCEPTOR = 0x248; public static final int SINGLETON_CONTAINER_MANAGED_CONCURRENCY_INTERCEPTOR = 0x240; // Allows users to specify user application specific "container interceptors" which run before the // other JBoss specific container interceptors like the security interceptor public static final int USER_APP_SPECIFIC_CONTAINER_INTERCEPTORS = 0x249; public static final int SECURITY_CONTEXT = 0x250; public static final int POLICY_CONTEXT = 0x260; public static final int SECURITY_ROLES = 0x270; public static final int EJB_SECURITY_AUTHORIZATION_INTERCEPTOR = 0x300; public static final int RUN_AS_PRINCIPAL = 0x310; public static final int EXTRA_PRINCIPAL_ROLES = 0x320; public static final int RUN_AS_ROLE = 0x330; public static final int SECURITY_IDENTITY_OUTFLOW = 0x340; // after security we take note of the invocation public static final int EJB_WAIT_TIME_INTERCEPTOR = 0x350; public static final int INVOCATION_CONTEXT_INTERCEPTOR = 0x400; // should happen before the CMT/BMT interceptors /** * @deprecated Remove this field once WFLY-7860 is resolved. */ @Deprecated public static final int REMOTE_TRANSACTION_PROPAGATION_INTERCEPTOR = 0x450; public static final int CDI_REQUEST_SCOPE = 0x480; public static final int CMT_TRANSACTION_INTERCEPTOR = 0x500; public static final int EE_SETUP = 0x510; public static final int HOME_METHOD_INTERCEPTOR = 0x600; public static final int ASSOCIATING_INTERCEPTOR = 0x700; public static final int XTS_INTERCEPTOR = 0x701; public static final int SESSION_REMOVE_INTERCEPTOR = 0x900; public static final int COMPONENT_DISPATCHER = 0xA00; private View() { } } public static final class Client { public static final int SECURITY_IDENTITY = 0x001; public static final int TO_STRING = 0x100; public static final int NOT_BUSINESS_METHOD_EXCEPTION = 0x110; public static final int LOCAL_ASYNC_LOG_SAVE = 0x180; public static final int LOCAL_ASYNC_SECURITY_CONTEXT = 0x190; public static final int LOCAL_ASYNC_INVOCATION = 0x200; public static final int LOCAL_ASYNC_LOG_RESTORE = 0x280; public static final int ASSOCIATING_INTERCEPTOR = 0x300; public static final int EJB_EQUALS_HASHCODE = 0x400; public static final int WRITE_REPLACE = 0x500; public static final int CLIENT_DISPATCHER = 0x600; private Client() { } } public static final class ClientPreDestroy { public static final int INSTANCE_DESTROY = 0x100; public static final int TERMINAL_INTERCEPTOR = 0x200; private ClientPreDestroy() { } } public static final class ClientPostConstruct { public static final int INSTANCE_CREATE = 0x100; public static final int TERMINAL_INTERCEPTOR = 0x200; private ClientPostConstruct() { } } }
11,043
44.262295
194
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/interceptors/InvocationType.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.interceptors; /** * Marker enum that can be used to identify special types of invocations * * @author Stuart Douglas */ public enum InvocationType { TIMER("timer"), REMOTE("remote"), ASYNC("async"), MESSAGE_DELIVERY("messageDelivery"), SET_ENTITY_CONTEXT("setEntityContext"), UNSET_ENTITY_CONTEXT("unsetEntityContext"), POST_CONSTRUCT("postConstruct"), PRE_DESTROY("preDestroy"), DEPENDENCY_INJECTION("setSessionContext"), SFSB_INIT_METHOD("stateful session bean init method"), FINDER_METHOD("entity bean finder method"), HOME_METHOD("entity bean home method"), ENTITY_EJB_CREATE("entity bean ejbCreate method"), ENTITY_EJB_ACTIVATE("entity bean ejbActivate method"), ENTITY_EJB_PASSIVATE("entity bean ejbPassivate method"), ENTITY_EJB_EJB_LOAD("entity bean ejbLoad method"), CONCURRENT_CONTEXT("ee concurrent invocation"), ; private final String label; InvocationType(String label) { this.label = label; } public String getLabel() { return label; } }
2,127
33.885246
72
java
null
wildfly-main/ee/src/main/java/org/jboss/as/ee/component/serialization/WriteReplaceInterface.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ee.component.serialization; import java.io.IOException; /** * Interface used to allow the proxy to support serialization. Currently used to work around * a limitation in the ProxyFactory * @author Stuart Douglas */ public interface WriteReplaceInterface { Object writeReplace() throws IOException; }
1,349
36.5
92
java
null
wildfly-main/system-jmx/src/main/java/org/jboss/system/ServiceMBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, 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.system; /** * An interface describing a JBoss service MBean. * * @see Service * @see ServiceMBeanSupport * * @author <a href="mailto:[email protected]">Rickard Oberg</a> * @author <a href="mailto:[email protected]">Andreas Schaefer</a> * @author [email protected] * @version $Revision: 81033 $ */ public interface ServiceMBean extends Service { // Constants ----------------------------------------------------- /** ServiceController notification types corresponding to service lifecycle events */ String CREATE_EVENT = "org.jboss.system.ServiceMBean.create"; String START_EVENT = "org.jboss.system.ServiceMBean.start"; String STOP_EVENT = "org.jboss.system.ServiceMBean.stop"; String DESTROY_EVENT = "org.jboss.system.ServiceMBean.destroy"; String[] states = { "Stopped", "Stopping", "Starting", "Started", "Failed", "Destroyed", "Created", "Unregistered", "Registered" }; /** The Service.stop has completed */ int STOPPED = 0; /** The Service.stop has been invoked */ int STOPPING = 1; /** The Service.start has been invoked */ int STARTING = 2; /** The Service.start has completed */ int STARTED = 3; /** There has been an error during some operation */ int FAILED = 4; /** The Service.destroy has completed */ int DESTROYED = 5; /** The Service.create has completed */ int CREATED = 6; /** The MBean has been created but has not completed MBeanRegistration.postRegister */ int UNREGISTERED = 7; /** The MBean has been created and has completed MBeanRegistration.postRegister */ int REGISTERED = 8; // Public -------------------------------------------------------- String getName(); int getState(); String getStateString(); /** Detyped lifecycle invocation */ void jbossInternalLifecycle(String method) throws Exception; }
2,943
37.233766
103
java
null
wildfly-main/system-jmx/src/main/java/org/jboss/system/ServiceMBeanSupport.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, 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.system; import java.util.concurrent.atomic.AtomicLong; import javax.management.AttributeChangeNotification; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.NotificationBroadcasterSupport; import javax.management.ObjectName; import org.jboss.logging.Logger; import org.jboss.system.logging.ServiceMBeanLogger; /** * An abstract base class JBoss services can subclass to implement a service that conforms to the ServiceMBean interface. * Subclasses must override {@link #getName} method and should override {@link #startService}, and {@link #stopService} as * approriate. * * @see ServiceMBean * * @author <a href="mailto:[email protected]">Rickard Öberg</a> * @author [email protected] * @author <a href="mailto:[email protected]">Andreas Schaefer</a> * @author <a href="mailto:[email protected]">Jason Dillon</a> * @author Eduardo Martins (AS7) */ public class ServiceMBeanSupport extends NotificationBroadcasterSupport implements ServiceMBean, MBeanRegistration { protected Logger log; /** The MBeanServer which we have been register with. */ protected MBeanServer server; /** The object name which we are registered under. */ protected ObjectName serviceName; /** The current state this service is in. */ private int state = UNREGISTERED; /** Sequence number for jmx notifications we send out */ private final AtomicLong sequenceNumber = new AtomicLong(0); // on AS7 MBean lifecycle is CREATED -> STARTED -> REGISTERED -> UNREGISTERED -> STOP -> DESTROY, // on previous AS versions is REGISTERED -> CREATED -> STARTED -> STOP -> DESTROYED -> UNREGISTERED // to maintain compatibility with old ServiceMBeanSupport, we ignore some state changes, but redo // these when proper state change happens // the flags below are used to mark ignored lifecycle methods invocations private boolean createIgnored = false; private boolean startIgnored = false; private boolean stopIgnored = false; private boolean destroyIgnored = false; private boolean unregisterIgnored = false; /** * Construct a <t>ServiceMBeanSupport</tt>. * * <p> * Sets up logging. */ public ServiceMBeanSupport() { // can not call this(Class) because we need to call getClass() this.log = Logger.getLogger(getClass().getName()); log.trace("Constructing"); } /** * Construct a <t>ServiceMBeanSupport</tt>. * * <p> * Sets up logging. * * @param type The class type to determine category name from. */ public ServiceMBeanSupport(final Class<?> type) { this(type.getName()); } /** * Construct a <t>ServiceMBeanSupport</tt>. * * <p> * Sets up logging. * * @param category The logger category name. */ public ServiceMBeanSupport(final String category) { this(Logger.getLogger(category)); } /** * Construct a <t>ServiceMBeanSupport</tt>. * * @param log The logger to use. */ public ServiceMBeanSupport(final Logger log) { this.log = log; log.trace("Constructing"); } /** * Use the short class name as the default for the service name. * * @return a description of the mbean */ public String getName() { final String s = log.getName(); final int i = s.lastIndexOf("."); return i != -1 ? s.substring(i + 1, s.length()) : s; } public ObjectName getServiceName() { return serviceName; } public MBeanServer getServer() { return server; } public int getState() { return state; } public String getStateString() { return states[state]; } public Logger getLog() { return log; } // ///////////////////////////////////////////////////////////////////////// // State Mutators // // ///////////////////////////////////////////////////////////////////////// public void create() throws Exception { jbossInternalCreate(); } public void start() throws Exception { jbossInternalStart(); } public void stop() { try { jbossInternalStop(); } catch (Throwable t) { log.warn(ServiceMBeanLogger.ROOT_LOGGER.errorInStop(jbossInternalDescription()), t); } } public void destroy() { try { jbossInternalDestroy(); } catch (Throwable t) { log.warn(ServiceMBeanLogger.ROOT_LOGGER.errorInDestroy(jbossInternalDescription()), t); } } protected String jbossInternalDescription() { if (serviceName != null) return serviceName.toString(); else return getName(); } public void jbossInternalLifecycle(String method) throws Exception { if (method == null) throw ServiceMBeanLogger.ROOT_LOGGER.nullMethodName(); if (method.equals("create")) jbossInternalCreate(); else if (method.equals("start")) jbossInternalStart(); else if (method.equals("stop")) jbossInternalStop(); else if (method.equals("destroy")) jbossInternalDestroy(); else throw ServiceMBeanLogger.ROOT_LOGGER.unknownLifecycleMethod(method); } protected void jbossInternalCreate() throws Exception { // if (state == CREATED || state == STARTING || state == STARTED // || state == STOPPING || state == STOPPED) if (state != REGISTERED) { createIgnored = true; if (log.isDebugEnabled()) { log.debug("Ignoring create call; current state is " + getStateString()); } return; } createIgnored = false; if (log.isDebugEnabled()) { log.debug("Creating " + jbossInternalDescription()); } try { createService(); state = CREATED; } catch (Exception e) { log.warn(ServiceMBeanLogger.ROOT_LOGGER.initializationFailed(jbossInternalDescription()), e); throw e; } if (log.isDebugEnabled()) { log.debug("Created " + jbossInternalDescription()); } if (startIgnored) { start(); } } protected void jbossInternalStart() throws Exception { if (state != CREATED && state != STOPPED) { startIgnored = true; if (log.isDebugEnabled()) { log.debug("Ignoring start call; current state is " + getStateString()); } return; } startIgnored = false; state = STARTING; sendStateChangeNotification(STOPPED, STARTING, getName() + " starting", null); if (log.isDebugEnabled()) { log.debug("Starting " + jbossInternalDescription()); } try { startService(); } catch (Exception e) { state = FAILED; sendStateChangeNotification(STARTING, FAILED, getName() + " failed", e); log.warn(ServiceMBeanLogger.ROOT_LOGGER.startingFailed(jbossInternalDescription()), e); throw e; } state = STARTED; sendStateChangeNotification(STARTING, STARTED, getName() + " started", null); if (log.isDebugEnabled()) { log.debug("Started " + jbossInternalDescription()); } if (stopIgnored) { stop(); } } protected void jbossInternalStop() { if (state != STARTED) { stopIgnored = true; if (log.isDebugEnabled()) { log.debug("Ignoring stop call; current state is " + getStateString()); } return; } stopIgnored = false; state = STOPPING; sendStateChangeNotification(STARTED, STOPPING, getName() + " stopping", null); if (log.isDebugEnabled()) { log.debug("Stopping " + jbossInternalDescription()); } try { stopService(); } catch (Throwable e) { state = FAILED; sendStateChangeNotification(STOPPING, FAILED, getName() + " failed", e); log.warn(ServiceMBeanLogger.ROOT_LOGGER.stoppingFailed(jbossInternalDescription()), e); return; } state = STOPPED; sendStateChangeNotification(STOPPING, STOPPED, getName() + " stopped", null); if (log.isDebugEnabled()) { log.debug("Stopped " + jbossInternalDescription()); } if (destroyIgnored) { destroy(); } } protected void jbossInternalDestroy() { if (state != STOPPED) { destroyIgnored = true; if (log.isDebugEnabled()) { log.debug("Ignoring destroy call; current state is " + getStateString()); } return; } destroyIgnored = false; if (log.isDebugEnabled()) { log.debug("Destroying " + jbossInternalDescription()); } try { destroyService(); } catch (Throwable t) { log.warn(ServiceMBeanLogger.ROOT_LOGGER.destroyingFailed(jbossInternalDescription()), t); } state = DESTROYED; if (log.isDebugEnabled()) { log.debug("Destroyed " + jbossInternalDescription()); } if (unregisterIgnored) { postDeregister(); } } // ///////////////////////////////////////////////////////////////////////// // JMX Hooks // // ///////////////////////////////////////////////////////////////////////// /** * Callback method of {@link javax.management.MBeanRegistration} before the MBean is registered at the JMX Agent. * * <p> * <b>Attention</b>: Always call this method when you overwrite it in a subclass because it saves the Object Name of the * MBean. * * @param server Reference to the JMX Agent this MBean is registered on * @param name Name specified by the creator of the MBean. Note that you can overwrite it when the given ObjectName is null * otherwise the change is discarded (maybe a bug in JMX-RI). * @return the ObjectName * @throws Exception for any error */ public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { this.server = server; serviceName = getObjectName(server, name); return serviceName; } public void postRegister(Boolean registrationDone) { if (!registrationDone.booleanValue()) { log.debug("Registration is not done -> stop"); stop(); } else { state = REGISTERED; if (createIgnored) { try { create(); } catch (Exception e) { log.error(ServiceMBeanLogger.ROOT_LOGGER.postRegisterInitializationFailed(), e); } } } } public void preDeregister() throws Exception {} public void postDeregister() { if (state != DESTROYED) { unregisterIgnored = true; if (log.isDebugEnabled()) { log.debug("Ignoring postDeregister call; current state is " + getStateString()); } return; } unregisterIgnored = false; server = null; serviceName = null; state = UNREGISTERED; } // ///////////////////////////////////////////////////////////////////////// // Concrete Service Overrides // // ///////////////////////////////////////////////////////////////////////// /** * Sub-classes should override this method if they only need to set their object name during MBean pre-registration. * * @param server the mbeanserver * @param name the suggested name, maybe null * @return the object name * @throws javax.management.MalformedObjectNameException for a bad object name */ protected ObjectName getObjectName(MBeanServer server, ObjectName name) throws MalformedObjectNameException { return name; } /** * Sub-classes should override this method to provide custum 'create' logic. * * <p> * This method is empty, and is provided for convenience when concrete service classes do not need to perform anything * specific for this state change. * * @throws Exception for any error */ protected void createService() throws Exception {} /** * Sub-classes should override this method to provide custum 'start' logic. * * <p> * This method is empty, and is provided for convenience when concrete service classes do not need to perform anything * specific for this state change. * * @throws Exception for any error */ protected void startService() throws Exception {} /** * Sub-classes should override this method to provide custum 'stop' logic. * * <p> * This method is empty, and is provided for convenience when concrete service classes do not need to perform anything * specific for this state change. * * @throws Exception for any error */ protected void stopService() throws Exception {} /** * Sub-classes should override this method to provide custum 'destroy' logic. * * <p> * This method is empty, and is provided for convenience when concrete service classes do not need to perform anything * specific for this state change. * * @throws Exception for any error */ protected void destroyService() throws Exception {} /** * The <code>nextNotificationSequenceNumber</code> method returns the next sequence number for use in notifications. * * @return a <code>long</code> value */ public long nextNotificationSequenceNumber() { return sequenceNumber.incrementAndGet(); } /** * The <code>getNextNotificationSequenceNumber</code> method returns the next sequence number for use in notifications. * * @return a <code>long</code> value */ protected long getNextNotificationSequenceNumber() { return nextNotificationSequenceNumber(); } /** * Helper for sending out state change notifications */ private void sendStateChangeNotification(int oldState, int newState, String msg, Throwable t) { long now = System.currentTimeMillis(); AttributeChangeNotification stateChangeNotification = new AttributeChangeNotification(this, getNextNotificationSequenceNumber(), now, msg, "State", "java.lang.Integer", new Integer(oldState), new Integer(newState)); stateChangeNotification.setUserData(t); sendNotification(stateChangeNotification); } }
16,030
31.985597
127
java
null
wildfly-main/system-jmx/src/main/java/org/jboss/system/Service.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, 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.system; /** * The Service interface. * * @author <a href="mailto:[email protected]">Marc Fleury</a>. * @version $Revision: 81032 $ */ public interface Service { /** * create the service, do expensive operations etc * * @throws Exception for any error */ void create() throws Exception; /** * start the service, create is already called * * @throws Exception for any error */ void start() throws Exception; /** * stop the service */ void stop(); /** * destroy the service, tear down */ void destroy(); }
1,658
29.163636
70
java
null
wildfly-main/system-jmx/src/main/java/org/jboss/system/logging/ServiceMBeanLogger.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.system.logging; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * @author Brian Stansberry (c) 2011 Red Hat Inc. * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @MessageLogger(projectCode = "WFLYSYSJMX", length = 4) public interface ServiceMBeanLogger extends BasicLogger { ServiceMBeanLogger ROOT_LOGGER = Logger.getMessageLogger(ServiceMBeanLogger.class, "org.jboss.system"); @Message(id = 1, value = "Null method name") IllegalArgumentException nullMethodName(); @Message(id = 2, value = "Unknown lifecyle method %s") IllegalArgumentException unknownLifecycleMethod(String methodName); @Message(id = 3, value = "Error in destroy %s") String errorInDestroy(String description); @Message(id = 4, value = "Error in stop %s") String errorInStop(String description); @Message(id = 5, value = "Initialization failed %s") String initializationFailed(String description); @Message(id = 6, value = "Starting failed %s") String startingFailed(String description); @Message(id = 7, value = "Stopping failed %s") String stoppingFailed(String description); @Message(id = 8, value = "Destroying failed %s") String destroyingFailed(String description); @Message(id = 9, value = "Initialization failed during postRegister") String postRegisterInitializationFailed(); }
2,537
37.454545
107
java
null
wildfly-main/legacy/opentracing-extension/src/test/java/org/wildfly/extension/microprofile/opentracing/Subsystem_3_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.opentracing; import java.io.IOException; import java.util.Properties; import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest; import org.jboss.as.subsystem.test.AdditionalInitialization; public class Subsystem_3_0_ParsingTestCase extends AbstractSubsystemBaseTest { public Subsystem_3_0_ParsingTestCase() { super(SubsystemExtension.SUBSYSTEM_NAME, new SubsystemExtension()); } @Override protected String getSubsystemXml() throws IOException { return readResource("subsystem_3_0.xml"); } @Override protected String getSubsystemXsdPath() { return "schema/wildfly-microprofile-opentracing_3_0.xsd"; } @Override protected Properties getResolvedProperties() { return System.getProperties(); } @Override protected AdditionalInitialization createAdditionalInitialization() { return OpentracingAdditionalInitialization.INSTANCE; } }
2,002
34.140351
78
java
null
wildfly-main/legacy/opentracing-extension/src/test/java/org/wildfly/extension/microprofile/opentracing/MigrateOperationTestCase.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.opentracing; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXTENSION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.wildfly.extension.microprofile.opentracing.SubsystemExtension.SUBSYSTEM_NAME; import org.jboss.as.controller.OperationDefinition; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.ProcessType; import org.jboss.as.controller.ReloadRequiredRemoveStepHandler; import org.jboss.as.controller.RunningMode; import org.jboss.as.controller.SimpleOperationDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.capability.registry.RuntimeCapabilityRegistry; import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver; import org.jboss.as.controller.descriptions.common.ControllerResolver; import org.jboss.as.controller.extension.ExtensionRegistry; import org.jboss.as.controller.extension.ExtensionRegistryType; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.Resource; import org.jboss.as.subsystem.test.AbstractSubsystemTest; import org.jboss.as.subsystem.test.AdditionalInitialization; import org.jboss.as.subsystem.test.KernelServices; import org.jboss.dmr.ModelNode; import org.junit.Test; import org.wildfly.extension.opentelemetry.OpenTelemetrySubsystemExtension; /** * Test case for the keycloak migrate op. * * @author <a href="mailto:[email protected]">Farah Juma</a> */ public class MigrateOperationTestCase extends AbstractSubsystemTest { public static final String OPENTELEMETRY_SUBSYSTEM_NAME = "opentelemetry"; public MigrateOperationTestCase() { super(SUBSYSTEM_NAME, new SubsystemExtension()); } @Test public void testMigrateDefaultOpenTracingConfig() throws Exception { // default config is empty String subsystemXml = readResource("opentracing-subsystem-migration-default-config.xml"); NewSubsystemAdditionalInitialization additionalInitialization = new NewSubsystemAdditionalInitialization(); KernelServices services = createKernelServicesBuilder(additionalInitialization).setSubsystemXml(subsystemXml) .build(); ModelNode model = services.readWholeModel(); assertFalse(additionalInitialization.extensionAdded); assertTrue(model.get(SUBSYSTEM, SUBSYSTEM_NAME).isDefined()); assertFalse(model.get(SUBSYSTEM, OPENTELEMETRY_SUBSYSTEM_NAME).isDefined()); ModelNode migrateOp = new ModelNode(); migrateOp.get(OP).set("migrate"); migrateOp.get(OP_ADDR).add(SUBSYSTEM, SUBSYSTEM_NAME); ModelNode response = services.executeOperation(migrateOp); checkOutcome(response); ModelNode warnings = response.get(RESULT, "migration-warnings"); assertEquals(warnings.toString(), 0, warnings.asList().size()); model = services.readWholeModel(); assertFalse(model.get(SUBSYSTEM, SUBSYSTEM_NAME).isDefined()); assertTrue(additionalInitialization.extensionAdded); assertTrue(model.get(SUBSYSTEM, OPENTELEMETRY_SUBSYSTEM_NAME).isDefined()); } private static class NewSubsystemAdditionalInitialization extends AdditionalInitialization { OpenTelemetrySubsystemExtension newSubsystem = new OpenTelemetrySubsystemExtension(); boolean extensionAdded = false; @Override protected void initializeExtraSubystemsAndModel(ExtensionRegistry extensionRegistry, Resource rootResource, ManagementResourceRegistration rootRegistration, RuntimeCapabilityRegistry capabilityRegistry) { final OperationDefinition removeExtension = new SimpleOperationDefinitionBuilder("remove", new StandardResourceDescriptionResolver("test", "test", getClass().getClassLoader())) .build(); PathElement opentracingExtension = PathElement.pathElement(EXTENSION, SubsystemExtension.EXTENSION_NAME); rootRegistration.registerSubModel(new SimpleResourceDefinition(opentracingExtension, ControllerResolver.getResolver(EXTENSION))) .registerOperationHandler(removeExtension, ReloadRequiredRemoveStepHandler.INSTANCE); rootResource.registerChild(opentracingExtension, Resource.Factory.create()); rootRegistration.registerSubModel( new SimpleResourceDefinition(PathElement.pathElement(EXTENSION), ControllerResolver.getResolver(EXTENSION), (context, operation) -> { if (!extensionAdded) { extensionAdded = true; newSubsystem.initialize(extensionRegistry .getExtensionContext("org.wildfly.extension.opentelemtry", rootRegistration, ExtensionRegistryType.SERVER) ); } }, null)); } @Override protected ProcessType getProcessType() { return ProcessType.HOST_CONTROLLER; } @Override protected RunningMode getRunningMode() { return RunningMode.ADMIN_ONLY; } } }
7,022
48.808511
140
java
null
wildfly-main/legacy/opentracing-extension/src/test/java/org/wildfly/extension/microprofile/opentracing/Subsystem_2_0_ParsingTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.opentracing; 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; public class Subsystem_2_0_ParsingTestCase extends AbstractSubsystemBaseTest { public Subsystem_2_0_ParsingTestCase() { super(SubsystemExtension.SUBSYSTEM_NAME, new SubsystemExtension()); } @Override protected String getSubsystemXml() throws IOException { return readResource("subsystem_2_0.xml"); } @Override protected String getSubsystemXsdPath() { return "schema/wildfly-microprofile-opentracing_2_0.xsd"; } @Override protected Properties getResolvedProperties() { return System.getProperties(); } @Override protected KernelServices standardSubsystemTest(String configId, boolean compareXml) throws Exception { return super.standardSubsystemTest(configId, false); } @Override protected AdditionalInitialization createAdditionalInitialization() { return OpentracingAdditionalInitialization.INSTANCE; } }
2,241
35.16129
106
java
null
wildfly-main/legacy/opentracing-extension/src/test/java/org/wildfly/extension/microprofile/opentracing/OpentracingAdditionalInitialization.java
package org.wildfly.extension.microprofile.opentracing; import static org.wildfly.extension.microprofile.opentracing.SubsystemDefinition.MICROPROFILE_CONFIG_CAPABILITY_NAME; import static org.wildfly.extension.microprofile.opentracing.SubsystemDefinition.WELD_CAPABILITY_NAME; import java.util.HashMap; import java.util.Map; import org.jboss.as.controller.ProcessType; import org.jboss.as.controller.capability.registry.RuntimeCapabilityRegistry; import org.jboss.as.controller.extension.ExtensionRegistry; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.Resource; import org.jboss.as.subsystem.test.AdditionalInitialization; class OpentracingAdditionalInitialization extends AdditionalInitialization.ManagementAdditionalInitialization { public static final AdditionalInitialization INSTANCE = new OpentracingAdditionalInitialization(); private static final long serialVersionUID = 1L; @Override protected ProcessType getProcessType() { return ProcessType.HOST_CONTROLLER; } @Override protected void initializeExtraSubystemsAndModel(ExtensionRegistry extensionRegistry, Resource rootResource, ManagementResourceRegistration rootRegistration, RuntimeCapabilityRegistry capabilityRegistry) { super.initializeExtraSubystemsAndModel(extensionRegistry, rootResource, rootRegistration, capabilityRegistry); Map<String, Class> capabilities = new HashMap<>(); capabilities.put(WELD_CAPABILITY_NAME, Void.class); capabilities.put(MICROPROFILE_CONFIG_CAPABILITY_NAME, Void.class); registerServiceCapabilities(capabilityRegistry, capabilities); } }
1,689
47.285714
208
java
null
wildfly-main/legacy/opentracing-extension/src/test/java/org/wildfly/extension/microprofile/opentracing/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.opentracing; 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; public class Subsystem_1_0_ParsingTestCase extends AbstractSubsystemBaseTest { public Subsystem_1_0_ParsingTestCase() { super(SubsystemExtension.SUBSYSTEM_NAME, new SubsystemExtension()); } @Override protected String getSubsystemXml() throws IOException { return readResource("subsystem_1_0.xml"); } @Override protected String getSubsystemXsdPath() throws IOException { return "schema/wildfly-microprofile-opentracing_1_0.xsd"; } @Override protected KernelServices standardSubsystemTest(String configId, boolean compareXml) throws Exception { return super.standardSubsystemTest(configId, false); } @Override protected Properties getResolvedProperties() { return System.getProperties(); } protected AdditionalInitialization createAdditionalInitialization() { return AdditionalInitialization.ADMIN_ONLY_HC; } }
2,240
35.737705
106
java
null
wildfly-main/legacy/opentracing-extension/src/main/java/org/wildfly/extension/microprofile/opentracing/SubsytemParser_2_0.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.opentracing; 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.opentracing.TracerAttributes.PROPAGATION; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.REPORTER_FLUSH_INTERVAL; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.REPORTER_LOG_SPANS; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.REPORTER_MAX_QUEUE_SIZE; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SAMPLER_MANAGER_HOST_PORT; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SAMPLER_PARAM; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SAMPLER_TYPE; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SENDER_BINDING; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SENDER_AUTH_PASSWORD; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SENDER_AUTH_TOKEN; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SENDER_AUTH_USER; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SENDER_ENDPOINT; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.TRACEID_128BIT; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.TRACER_TAGS; import org.jboss.as.controller.PersistentResourceXMLDescription.PersistentResourceXMLBuilder; public class SubsytemParser_2_0 extends PersistentResourceXMLParser { public static final String OPENTRACING_NAMESPACE = "urn:wildfly:microprofile-opentracing-smallrye:2.0"; static final PersistentResourceXMLParser INSTANCE = new SubsytemParser_2_0(); @Override public PersistentResourceXMLDescription getParserDescription() { PersistentResourceXMLBuilder jaegerTracer = builder(JaegerTracerConfigurationDefinition.TRACER_CONFIGURATION_PATH) .addAttributes( PROPAGATION, SAMPLER_TYPE, SAMPLER_PARAM, SAMPLER_MANAGER_HOST_PORT, SENDER_BINDING, SENDER_ENDPOINT, SENDER_AUTH_TOKEN, SENDER_AUTH_USER, SENDER_AUTH_PASSWORD, REPORTER_LOG_SPANS, REPORTER_FLUSH_INTERVAL, REPORTER_MAX_QUEUE_SIZE, TRACER_TAGS, TRACEID_128BIT ); return builder(SubsystemExtension.SUBSYSTEM_PATH, OPENTRACING_NAMESPACE) .addAttributes(SubsystemDefinition.DEFAULT_TRACER) .addChild(jaegerTracer) .build(); } }
3,832
56.208955
122
java
null
wildfly-main/legacy/opentracing-extension/src/main/java/org/wildfly/extension/microprofile/opentracing/SubsytemParser_3_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.opentracing; 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.opentracing.TracerAttributes.PROPAGATION; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.REPORTER_FLUSH_INTERVAL; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.REPORTER_LOG_SPANS; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.REPORTER_MAX_QUEUE_SIZE; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SAMPLER_MANAGER_HOST_PORT; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SAMPLER_PARAM; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SAMPLER_TYPE; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SENDER_BINDING; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SENDER_AUTH_PASSWORD; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SENDER_AUTH_TOKEN; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SENDER_AUTH_USER; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SENDER_ENDPOINT; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.TRACEID_128BIT; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.TRACER_TAGS; import org.jboss.as.controller.PersistentResourceXMLDescription.PersistentResourceXMLBuilder; public class SubsytemParser_3_0 extends PersistentResourceXMLParser { public static final String OPENTRACING_NAMESPACE = "urn:wildfly:microprofile-opentracing-smallrye:3.0"; static final PersistentResourceXMLParser INSTANCE = new SubsytemParser_3_0(); @Override public PersistentResourceXMLDescription getParserDescription() { PersistentResourceXMLBuilder jaegerTracer = builder(JaegerTracerConfigurationDefinition.TRACER_CONFIGURATION_PATH) .addAttributes( PROPAGATION, SAMPLER_TYPE, SAMPLER_PARAM, SAMPLER_MANAGER_HOST_PORT, SENDER_BINDING, SENDER_ENDPOINT, SENDER_AUTH_TOKEN, SENDER_AUTH_USER, SENDER_AUTH_PASSWORD, REPORTER_LOG_SPANS, REPORTER_FLUSH_INTERVAL, REPORTER_MAX_QUEUE_SIZE, TRACER_TAGS, TRACEID_128BIT ); return builder(SubsystemExtension.SUBSYSTEM_PATH, OPENTRACING_NAMESPACE) .addAttributes(SubsystemDefinition.DEFAULT_TRACER) .addChild(jaegerTracer) .build(); } }
3,832
56.208955
122
java
null
wildfly-main/legacy/opentracing-extension/src/main/java/org/wildfly/extension/microprofile/opentracing/OpentracingTransformers.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.opentracing; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.transform.ExtensionTransformerRegistration; import org.jboss.as.controller.transform.SubsystemTransformerRegistration; import org.jboss.as.controller.transform.description.ChainedTransformationDescriptionBuilder; import org.jboss.as.controller.transform.description.DiscardAttributeChecker; import org.jboss.as.controller.transform.description.RejectAttributeChecker; import org.jboss.as.controller.transform.description.ResourceTransformationDescriptionBuilder; import org.jboss.as.controller.transform.description.TransformationDescriptionBuilder; import org.kohsuke.MetaInfServices; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.PROPAGATION; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.REPORTER_FLUSH_INTERVAL; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.REPORTER_LOG_SPANS; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.REPORTER_MAX_QUEUE_SIZE; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SAMPLER_MANAGER_HOST_PORT; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SAMPLER_PARAM; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SAMPLER_TYPE; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SENDER_AUTH_PASSWORD; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SENDER_AUTH_TOKEN; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SENDER_AUTH_USER; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SENDER_BINDING; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SENDER_ENDPOINT; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.TRACEID_128BIT; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.TRACER_TAGS; /** * * @author Emmanuel Hugonnet (c) 2019 Red Hat, Inc. */ @MetaInfServices public class OpentracingTransformers implements ExtensionTransformerRegistration { @Override public String getSubsystemName() { return SubsystemExtension.SUBSYSTEM_NAME; } @Override public void registerTransformers(SubsystemTransformerRegistration registration) { ChainedTransformationDescriptionBuilder builder = TransformationDescriptionBuilder.Factory.createChainedSubystemInstance(registration.getCurrentSubsystemVersion()); registerTransformers_WF_20(builder.createBuilder(SubsystemExtension.VERSION_3_0_0, SubsystemExtension.VERSION_2_0_0)); registerTransformers_WF_19(builder.createBuilder(SubsystemExtension.VERSION_2_0_0, SubsystemExtension.VERSION_1_0_0)); builder.buildAndRegister(registration, new ModelVersion[]{SubsystemExtension.VERSION_3_0_0, SubsystemExtension.VERSION_2_0_0, SubsystemExtension.VERSION_1_0_0}); } private static void registerTransformers_WF_20(ResourceTransformationDescriptionBuilder subsystem) { subsystem.addChildResource(JaegerTracerConfigurationDefinition.TRACER_CONFIGURATION_PATH) .getAttributeBuilder() .addRejectCheck(RejectAttributeChecker.SIMPLE_EXPRESSIONS, PROPAGATION, SAMPLER_TYPE, SAMPLER_PARAM, SAMPLER_MANAGER_HOST_PORT, SENDER_BINDING, SENDER_ENDPOINT, SENDER_AUTH_TOKEN, SENDER_AUTH_USER, SENDER_AUTH_PASSWORD, REPORTER_LOG_SPANS, REPORTER_FLUSH_INTERVAL, REPORTER_MAX_QUEUE_SIZE, TRACER_TAGS, TRACEID_128BIT) .end(); } private static void registerTransformers_WF_19(ResourceTransformationDescriptionBuilder subsystem) { subsystem.rejectChildResource(JaegerTracerConfigurationDefinition.TRACER_CONFIGURATION_PATH); subsystem.getAttributeBuilder() .addRejectCheck(RejectAttributeChecker.DEFINED, SubsystemDefinition.DEFAULT_TRACER) .setDiscard(DiscardAttributeChecker.UNDEFINED, SubsystemDefinition.DEFAULT_TRACER) .end(); } }
5,279
59
172
java
null
wildfly-main/legacy/opentracing-extension/src/main/java/org/wildfly/extension/microprofile/opentracing/SubsystemDefinition.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.opentracing; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.ModelOnlyAddStepHandler; import org.jboss.as.controller.ModelOnlyResourceDefinition; import org.jboss.as.controller.ModelOnlyWriteAttributeHandler; import org.jboss.as.controller.ReloadRequiredRemoveStepHandler; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.dmr.ModelType; public class SubsystemDefinition extends ModelOnlyResourceDefinition { private static final String OPENTRACING_CAPABILITY_NAME = "org.wildfly.microprofile.opentracing"; private static final String TRACER_CAPABILITY_NAME = "org.wildfly.microprofile.opentracing.tracer"; static final String MICROPROFILE_CONFIG_CAPABILITY_NAME = "org.wildfly.microprofile.config"; static final String WELD_CAPABILITY_NAME = "org.wildfly.weld"; public static final String DEFAULT_TRACER_NAME = "default-tracer"; public static final RuntimeCapability<Void> OPENTRACING_CAPABILITY = RuntimeCapability.Builder .of(OPENTRACING_CAPABILITY_NAME) .addRequirements(WELD_CAPABILITY_NAME, MICROPROFILE_CONFIG_CAPABILITY_NAME) .build(); public static final RuntimeCapability<Void> TRACER_CAPABILITY = RuntimeCapability.Builder .of(TRACER_CAPABILITY_NAME, true) .build(); public static final SimpleAttributeDefinition DEFAULT_TRACER = SimpleAttributeDefinitionBuilder .create(DEFAULT_TRACER_NAME, ModelType.STRING, true) .setCapabilityReference(TRACER_CAPABILITY_NAME) .setRestartAllServices() .build(); static final AttributeDefinition[] ATTRIBUTES = {DEFAULT_TRACER}; protected SubsystemDefinition() { super(new SimpleResourceDefinition.Parameters(SubsystemExtension.SUBSYSTEM_PATH, SubsystemExtension.getResourceDescriptionResolver()) .setAddHandler(new ModelOnlyAddStepHandler(ATTRIBUTES)) .setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE) .setCapabilities(OPENTRACING_CAPABILITY) ); } @Override public void registerChildren(ManagementResourceRegistration resourceRegistration) { super.registerChildren(resourceRegistration); resourceRegistration.registerSubModel(new JaegerTracerConfigurationDefinition()); } @Override public void registerOperations(ManagementResourceRegistration resourceRegistration) { super.registerOperations(resourceRegistration); MigrateOperation.registerOperations(resourceRegistration, getResourceDescriptionResolver()); } @Override public void registerAttributes(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerReadWriteAttribute(DEFAULT_TRACER, null, new ModelOnlyWriteAttributeHandler(DEFAULT_TRACER)); } }
4,192
48.916667
103
java
null
wildfly-main/legacy/opentracing-extension/src/main/java/org/wildfly/extension/microprofile/opentracing/TracerAttributes.java
/* * Copyright 2019 JBoss by Red Hat. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.microprofile.opentracing; import org.jboss.as.controller.PropertiesAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.StringListAttributeDefinition; import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition; import org.jboss.as.controller.client.helpers.MeasurementUnit; import org.jboss.as.controller.operations.validation.StringAllowedValuesValidator; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; /** * Tracer attribute definitions. * * @author Emmanuel Hugonnet (c) 2019 Red Hat, Inc. */ public class TracerAttributes { static final String OUTBOUND_SOCKET_BINDING_CAPABILITY_NAME = "org.wildfly.network.outbound-socket-binding"; private static final String[] ALLOWED_SAMPLER_TYPE = {"const", "probabilistic", "ratelimiting", "remote"}; public static final StringListAttributeDefinition PROPAGATION = StringListAttributeDefinition.Builder.of(TracerConfigurationConstants.PROPAGATION) .setAllowNullElement(false) .setRequired(false) .setValidator(new StringAllowedValuesValidator("JAEGER", "B3")) .setAttributeGroup("codec-configuration") .setAllowExpression(true) .setRestartAllServices() .build(); public static final SimpleAttributeDefinition SAMPLER_TYPE = SimpleAttributeDefinitionBuilder.create(TracerConfigurationConstants.SAMPLER_TYPE, ModelType.STRING, true) .setValidator(new StringAllowedValuesValidator(ALLOWED_SAMPLER_TYPE)) .setDefaultValue(new ModelNode("remote")) .setAttributeGroup("sampler-configuration") .setAllowExpression(true) .setRestartAllServices() .build(); public static final SimpleAttributeDefinition SAMPLER_PARAM = SimpleAttributeDefinitionBuilder.create(TracerConfigurationConstants.SAMPLER_PARAM, ModelType.DOUBLE, true) .setAttributeGroup("sampler-configuration") .setAllowExpression(true) .setRestartAllServices() .build(); public static final SimpleAttributeDefinition SAMPLER_MANAGER_HOST_PORT = SimpleAttributeDefinitionBuilder.create(TracerConfigurationConstants.SAMPLER_MANAGER_HOST_PORT, ModelType.STRING, true) .setAttributeGroup("sampler-configuration") .setAllowExpression(true) .setRestartAllServices() .build(); public static final SimpleAttributeDefinition SENDER_BINDING = SimpleAttributeDefinitionBuilder.create(TracerConfigurationConstants.SENDER_AGENT_BINDING, ModelType.STRING, true) .setAttributeGroup("sender-configuration") .setCapabilityReference(OUTBOUND_SOCKET_BINDING_CAPABILITY_NAME) .addAccessConstraint(SensitiveTargetAccessConstraintDefinition.SOCKET_BINDING_REF) .setRestartAllServices() .build(); public static final SimpleAttributeDefinition SENDER_ENDPOINT = SimpleAttributeDefinitionBuilder.create(TracerConfigurationConstants.SENDER_ENDPOINT, ModelType.STRING, true) .setAttributeGroup("sender-configuration") .setAllowExpression(true) .setRestartAllServices() .build(); public static final SimpleAttributeDefinition SENDER_AUTH_TOKEN = SimpleAttributeDefinitionBuilder.create(TracerConfigurationConstants.SENDER_AUTH_TOKEN, ModelType.STRING, true) .setAttributeGroup("sender-configuration") .setAllowExpression(true) .setRestartAllServices() .build(); public static final SimpleAttributeDefinition SENDER_AUTH_USER = SimpleAttributeDefinitionBuilder.create(TracerConfigurationConstants.SENDER_AUTH_USER, ModelType.STRING, true) .setAttributeGroup("sender-configuration") .setAllowExpression(true) .setRestartAllServices() .build(); public static final SimpleAttributeDefinition SENDER_AUTH_PASSWORD = SimpleAttributeDefinitionBuilder.create(TracerConfigurationConstants.SENDER_AUTH_PASSWORD, ModelType.STRING, true) .setAttributeGroup("sender-configuration") .setAllowExpression(true) .setRestartAllServices() .build(); public static final SimpleAttributeDefinition REPORTER_LOG_SPANS = SimpleAttributeDefinitionBuilder.create(TracerConfigurationConstants.REPORTER_LOG_SPANS, ModelType.BOOLEAN, true) .setAttributeGroup("reporter-configuration") .setAllowExpression(true) .setRestartAllServices() .build(); public static final SimpleAttributeDefinition REPORTER_FLUSH_INTERVAL = SimpleAttributeDefinitionBuilder.create(TracerConfigurationConstants.REPORTER_FLUSH_INTERVAL, ModelType.INT, true) .setAttributeGroup("reporter-configuration") .setAllowExpression(true) .setMeasurementUnit(MeasurementUnit.MILLISECONDS) .setRestartAllServices() .build(); public static final SimpleAttributeDefinition REPORTER_MAX_QUEUE_SIZE = SimpleAttributeDefinitionBuilder.create(TracerConfigurationConstants.REPORTER_MAX_QUEUE_SIZE, ModelType.INT, true) .setAttributeGroup("reporter-configuration") .setAllowExpression(true) .setRestartAllServices() .build(); public static final SimpleAttributeDefinition TRACEID_128BIT = SimpleAttributeDefinitionBuilder.create(TracerConfigurationConstants.TRACEID_128BIT, ModelType.BOOLEAN, true) .setDefaultValue(ModelNode.FALSE) .setAllowExpression(true) .setRestartAllServices() .build(); public static final PropertiesAttributeDefinition TRACER_TAGS = new PropertiesAttributeDefinition.Builder(TracerConfigurationConstants.TRACER_TAGS, true) .setAllowExpression(true) .setRestartAllServices() .build(); }
6,631
53.360656
197
java
null
wildfly-main/legacy/opentracing-extension/src/main/java/org/wildfly/extension/microprofile/opentracing/TracingDeploymentDefinition.java
/* * Copyright 2019 JBoss by Red Hat. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.microprofile.opentracing; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.ModelOnlyResourceDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.dmr.ModelType; /** * Runtime resource definition for the OpenTracing configuration of the deployment. * @author Emmanuel Hugonnet (c) 2019 Red Hat, Inc. */ public class TracingDeploymentDefinition extends ModelOnlyResourceDefinition { public static final AttributeDefinition TRACER_CONFIGURATION_NAME = new SimpleAttributeDefinitionBuilder( TracerConfigurationConstants.TRACER_CONFIGURATION_NAME, ModelType.STRING, true) .setStorageRuntime() .build(); public static final AttributeDefinition TRACER_CONFIGURATION = new SimpleAttributeDefinitionBuilder( TracerConfigurationConstants.TRACER_CONFIGURATION, ModelType.OBJECT, true) .setStorageRuntime() .build(); TracingDeploymentDefinition() { super(new Parameters(SubsystemExtension.SUBSYSTEM_PATH, SubsystemExtension.getResourceDescriptionResolver()) .setFeature(false).setRuntime()); } @Override public void registerAttributes(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerReadOnlyAttribute(TRACER_CONFIGURATION_NAME, null); resourceRegistration.registerReadOnlyAttribute(TRACER_CONFIGURATION, null); } }
2,169
42.4
118
java
null
wildfly-main/legacy/opentracing-extension/src/main/java/org/wildfly/extension/microprofile/opentracing/SubsystemExtension.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.opentracing; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import java.util.Collections; import java.util.Set; import org.jboss.as.controller.ExtensionContext; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PersistentResourceXMLParser; import org.jboss.as.controller.SubsystemRegistration; import org.jboss.as.controller.descriptions.ResourceDescriptionResolver; import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver; import org.jboss.as.controller.extension.AbstractLegacyExtension; import org.jboss.as.controller.parsing.ExtensionParsingContext; import org.jboss.as.controller.registry.ManagementResourceRegistration; public class SubsystemExtension extends AbstractLegacyExtension { public static final String SUBSYSTEM_NAME = "microprofile-opentracing-smallrye"; public static final String EXTENSION_NAME = "org.wildfly.extension.microprofile.opentracing-smallrye"; protected static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME); private static final String RESOURCE_NAME = SubsystemExtension.class.getPackage().getName() + ".LocalDescriptions"; protected static final ModelVersion VERSION_1_0_0 = ModelVersion.create(1, 0, 0); protected static final ModelVersion VERSION_2_0_0 = ModelVersion.create(2, 0, 0); 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 PersistentResourceXMLParser PARSER = SubsytemParser_3_0.INSTANCE; public static final String NAMESPACE = SubsytemParser_3_0.OPENTRACING_NAMESPACE; public SubsystemExtension() { super(EXTENSION_NAME, SUBSYSTEM_NAME); } static ResourceDescriptionResolver getResourceDescriptionResolver(final String... keyPrefix) { return getResourceDescriptionResolver(false, keyPrefix); } static ResourceDescriptionResolver getResourceDescriptionResolver(final boolean useUnprefixedChildTypes, final String... keyPrefix) { StringBuilder prefix = new StringBuilder(SUBSYSTEM_NAME); for (String kp : keyPrefix) { if (prefix.length() > 0) { prefix.append('.'); } prefix.append(kp); } return new StandardResourceDescriptionResolver(prefix.toString(), RESOURCE_NAME, SubsystemExtension.class.getClassLoader(), true, useUnprefixedChildTypes); } @Override protected Set<ManagementResourceRegistration> initializeLegacyModel(final ExtensionContext context) { final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION); subsystem.registerXMLElementWriter(PARSER); final ManagementResourceRegistration registration = subsystem.registerSubsystemModel(new SubsystemDefinition()); subsystem.registerDeploymentModel(new TracingDeploymentDefinition()); return Collections.singleton(registration); } @Override public void initializeLegacyParsers(ExtensionParsingContext context) { context.setSubsystemXmlMapping(SUBSYSTEM_NAME, SubsytemParser_1_0.NAMESPACE, SubsytemParser_1_0.INSTANCE); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, SubsytemParser_2_0.OPENTRACING_NAMESPACE, SubsytemParser_2_0.INSTANCE); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, NAMESPACE, PARSER); } }
4,595
48.419355
163
java
null
wildfly-main/legacy/opentracing-extension/src/main/java/org/wildfly/extension/microprofile/opentracing/TracingExtensionLogger.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.opentracing; import static org.jboss.logging.Logger.Level.INFO; 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; @MessageLogger(projectCode = "WFLYTRACEXT", length = 4) public interface TracingExtensionLogger extends BasicLogger { TracingExtensionLogger ROOT_LOGGER = Logger.getMessageLogger(TracingExtensionLogger.class, TracingExtensionLogger.class.getPackage().getName()); @LogMessage(level = INFO) @Message(id = 1, value = "Activating MicroProfile OpenTracing Subsystem") void activatingSubsystem(); /* // no longer used @LogMessage(level = DEBUG) @Message(id = 2, value = "MicroProfile OpenTracing Subsystem is processing deployment") void processingDeployment(); @LogMessage(level = DEBUG) @Message(id = 3, value = "The deployment does not have Jakarta Contexts and Dependency Injection enabled. Skipping MicroProfile OpenTracing integration.") void noCdiDeployment(); @LogMessage(level = DEBUG) @Message(id = 4, value = "Deriving service name based on the deployment unit's name: %s") void serviceNameDerivedFromDeploymentUnit(String serviceName); @LogMessage(level = DEBUG) @Message(id = 5, value = "Registering the TracerInitializer filter") void registeringTracerInitializer(); @Message(id = 6, value = "Deployment %s requires use of the '%s' capability but it is not currently registered") String deploymentRequiresCapability(String deploymentName, String capabilityName); @LogMessage(level = DEBUG) @Message(id = 7, value = "No module found for deployment %s for resolving the tracer.") void tracerResolverDeployementModuleNotFound(String deployment); @LogMessage(level = ERROR) @Message(id = 8, value = "Error using tracer resolver to resolve the tracer.") void errorResolvingTracer(@Cause Exception ex); */ //9, 10 and 11 are taken downstream /* @Message(id = 9, value = "") OperationFailedException seeDownstream(); @Message(id = 10, value = "") String seeDownstream(); @Message(id = 11, value = "") OperationFailedException seeDownstream(); */ // no longer used // @LogMessage(level = WARN) // @Message(id = 12, value="No Jaeger endpoint or sender-binding configured. Installing a no-op sender") // void senderNotConfigured(); @Message(id = 13, value = "The migrate operation cannot be performed: the server must be in admin-only mode") OperationFailedException migrateOperationAllowedOnlyInAdminOnly(); @Message(id = 14, value = "Migration failed. See results for more details.") String migrationFailed(); }
3,912
39.760417
158
java
null
wildfly-main/legacy/opentracing-extension/src/main/java/org/wildfly/extension/microprofile/opentracing/JaegerTracerConfigurationDefinition.java
/* * Copyright 2019 JBoss by Red Hat. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.microprofile.opentracing; import static org.wildfly.extension.microprofile.opentracing.SubsystemDefinition.TRACER_CAPABILITY; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.PROPAGATION; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.REPORTER_FLUSH_INTERVAL; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.REPORTER_LOG_SPANS; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.REPORTER_MAX_QUEUE_SIZE; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SAMPLER_MANAGER_HOST_PORT; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SAMPLER_PARAM; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SAMPLER_TYPE; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SENDER_AUTH_PASSWORD; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SENDER_AUTH_TOKEN; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SENDER_AUTH_USER; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SENDER_BINDING; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.SENDER_ENDPOINT; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.TRACEID_128BIT; import static org.wildfly.extension.microprofile.opentracing.TracerAttributes.TRACER_TAGS; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.ModelOnlyAddStepHandler; import org.jboss.as.controller.ModelOnlyResourceDefinition; import org.jboss.as.controller.OperationStepHandler; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.ReloadRequiredRemoveStepHandler; import org.jboss.as.controller.ReloadRequiredWriteAttributeHandler; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.registry.ManagementResourceRegistration; /** * * @author Emmanuel Hugonnet (c) 2019 Red Hat, Inc. */ public class JaegerTracerConfigurationDefinition extends ModelOnlyResourceDefinition { public static final PathElement TRACER_CONFIGURATION_PATH = PathElement.pathElement("jaeger-tracer"); public static final AttributeDefinition[] ATTRIBUTES = {PROPAGATION, SAMPLER_TYPE, SAMPLER_PARAM, SAMPLER_MANAGER_HOST_PORT, SENDER_BINDING, SENDER_ENDPOINT, SENDER_AUTH_TOKEN, SENDER_AUTH_USER, SENDER_AUTH_PASSWORD, REPORTER_LOG_SPANS, REPORTER_FLUSH_INTERVAL, REPORTER_MAX_QUEUE_SIZE, TRACER_TAGS, TRACEID_128BIT}; private static final OperationStepHandler WRITE_HANDLER = new ReloadRequiredWriteAttributeHandler(ATTRIBUTES); public JaegerTracerConfigurationDefinition() { super(new SimpleResourceDefinition.Parameters(TRACER_CONFIGURATION_PATH, SubsystemExtension.getResourceDescriptionResolver("tracer")) .setAddHandler(new ModelOnlyAddStepHandler(ATTRIBUTES)) .setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE) .setCapabilities(TRACER_CAPABILITY) ); } @Override public void registerAttributes(ManagementResourceRegistration resourceRegistration) { for(AttributeDefinition att : ATTRIBUTES) { resourceRegistration.registerReadWriteAttribute(att, null, WRITE_HANDLER); } } }
4,032
52.773333
141
java
null
wildfly-main/legacy/opentracing-extension/src/main/java/org/wildfly/extension/microprofile/opentracing/MigrateOperation.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.opentracing; import static org.jboss.as.controller.OperationContext.Stage.MODEL; import static org.jboss.as.controller.PathAddress.pathAddress; import static org.jboss.as.controller.PathElement.pathElement; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXTENSION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.wildfly.extension.microprofile.opentracing.SubsystemExtension.EXTENSION_NAME; import static org.wildfly.extension.microprofile.opentracing.SubsystemExtension.SUBSYSTEM_NAME; import static org.wildfly.extension.microprofile.opentracing.TracingExtensionLogger.ROOT_LOGGER; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.OperationStepHandler; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.ProcessType; import org.jboss.as.controller.RunningMode; import org.jboss.as.controller.SimpleMapAttributeDefinition; import org.jboss.as.controller.SimpleOperationDefinitionBuilder; import org.jboss.as.controller.StringListAttributeDefinition; import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition; import org.jboss.as.controller.descriptions.ResourceDescriptionResolver; import org.jboss.as.controller.operations.MultistepUtil; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.OperationEntry; import org.jboss.as.controller.registry.Resource; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; /** * Operation to migrate from the legacy MicroProfile subsystem to new MicroProfile Telemetry subsystem. * * @author <a href=mailto:[email protected]>Jason Lee</a> */ public class MigrateOperation implements OperationStepHandler { private static final String OPENTELEMETRY_EXTENSION = "org.wildfly.extension.opentelemetry"; private static final PathAddress OPENTRACING_EXTENSION_ELEMENT = pathAddress(pathElement(EXTENSION, EXTENSION_NAME)); private static final PathAddress OPENTRACING_SUBSYSTEM_ELEMENT = pathAddress(pathElement(SUBSYSTEM, SUBSYSTEM_NAME)); private static final PathElement OPENTELEMETRY_EXTENSION_ELEMENT = PathElement.pathElement(EXTENSION, OPENTELEMETRY_EXTENSION); private static final PathElement OPENTELEMETRY_SUBSYSTEM_ELEMENT = PathElement.pathElement(SUBSYSTEM, "opentelemetry"); private static final String MIGRATE = "migrate"; private static final String MIGRATION_WARNINGS = "migration-warnings"; private static final String MIGRATION_ERROR = "migration-error"; private static final String MIGRATION_OPERATIONS = "migration-operations"; private static final String DESCRIBE_MIGRATION = "describe-migration"; static final StringListAttributeDefinition MIGRATION_WARNINGS_ATTR = new StringListAttributeDefinition.Builder(MIGRATION_WARNINGS) .setRequired(false) .build(); static final SimpleMapAttributeDefinition MIGRATION_ERROR_ATTR = new SimpleMapAttributeDefinition.Builder(MIGRATION_ERROR, ModelType.OBJECT, true) .setValueType(ModelType.OBJECT) .setRequired(false) .build(); private final boolean describe; private MigrateOperation(boolean describe) { this.describe = describe; } static void registerOperations(ManagementResourceRegistration registry, ResourceDescriptionResolver resourceDescriptionResolver) { registry.registerOperationHandler(new SimpleOperationDefinitionBuilder(MIGRATE, resourceDescriptionResolver) .setReplyParameters(MIGRATION_WARNINGS_ATTR, MIGRATION_ERROR_ATTR) .setAccessConstraints(SensitiveTargetAccessConstraintDefinition.READ_WHOLE_CONFIG) .build(), new MigrateOperation(false)); registry.registerOperationHandler(new SimpleOperationDefinitionBuilder(DESCRIBE_MIGRATION, resourceDescriptionResolver) .setReplyParameters(MIGRATION_WARNINGS_ATTR, MIGRATION_ERROR_ATTR) .setAccessConstraints(SensitiveTargetAccessConstraintDefinition.READ_WHOLE_CONFIG) .setReadOnly() .build(), new MigrateOperation(true)); } @Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { if (!describe && context.getRunningMode() != RunningMode.ADMIN_ONLY) { throw ROOT_LOGGER.migrateOperationAllowedOnlyInAdminOnly(); } final PathAddress subsystemsAddress = context.getCurrentAddress().getParent(); final Map<PathAddress, ModelNode> migrateOperations = new LinkedHashMap<>(); if (!context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS, false).hasChild(OPENTELEMETRY_EXTENSION_ELEMENT)) { addOpenTelemetryExtension(context, migrateOperations); } context.addStep((operationContext, modelNode) -> { addOpenTelemetrySubsystem(context, migrateOperations); final PathAddress opentracingAddress = subsystemsAddress.append(OPENTRACING_SUBSYSTEM_ELEMENT); removeOpentracingSubsystem(opentracingAddress, migrateOperations, context.getProcessType() == ProcessType.STANDALONE_SERVER); if (describe) { // :describe-migration operation // for describe-migration operation, do nothing and return the list of operations that would // be executed in the composite operation final Collection<ModelNode> values = migrateOperations.values(); ModelNode result = new ModelNode(); result.get(MIGRATION_OPERATIONS).set(values); result.get(MIGRATION_WARNINGS).set(new ModelNode().setEmptyList()); context.getResult().set(result); } else { // :migrate operation // invoke an OSH on a composite operation with all the migration operations final Map<PathAddress, ModelNode> migrateOpResponses = migrateSubsystems(context, migrateOperations); context.completeStep((resultAction, context1, operation1) -> { final ModelNode result = new ModelNode(); result.get(MIGRATION_WARNINGS).set(new ModelNode().setEmptyList()); if (resultAction == OperationContext.ResultAction.ROLLBACK) { for (Map.Entry<PathAddress, ModelNode> entry : migrateOpResponses.entrySet()) { if (entry.getValue().hasDefined(FAILURE_DESCRIPTION)) { ModelNode desc = new ModelNode(); desc.get(OP).set(migrateOperations.get(entry.getKey())); desc.get(RESULT).set(entry.getValue()); result.get(MIGRATION_ERROR).set(desc); break; } } context1.getFailureDescription().set(new ModelNode(ROOT_LOGGER.migrationFailed())); } context1.getResult().set(result); }); } }, MODEL); } private void addOpenTelemetryExtension(final OperationContext context, final Map<PathAddress, ModelNode> migrateOperations) { final PathAddress extensionAddress = PathAddress.EMPTY_ADDRESS.append(OPENTELEMETRY_EXTENSION_ELEMENT); OperationEntry addEntry = context.getRootResourceRegistration().getOperationEntry(extensionAddress, ADD); final ModelNode addOperation = Util.createAddOperation(extensionAddress); if (describe) { migrateOperations.put(extensionAddress, addOperation); } else { context.addStep(context.getResult().get(extensionAddress.toString()), addOperation, addEntry.getOperationHandler(), MODEL); } } private void addOpenTelemetrySubsystem(final OperationContext context, final Map<PathAddress, ModelNode> migrateOperations) { Resource root = context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS, false); if (root.hasChild(OPENTELEMETRY_SUBSYSTEM_ELEMENT)) { return; // subsystem is already added, nothing to do } PathAddress address = pathAddress(OPENTELEMETRY_SUBSYSTEM_ELEMENT); final ModelNode operation = Util.createAddOperation(address); migrateOperations.put(address, operation); } private void removeOpentracingSubsystem(final PathAddress address, final Map<PathAddress, ModelNode> migrateOperations, boolean standalone) { ModelNode removeLegacySubsystemOperation = Util.createRemoveOperation(address); migrateOperations.put(address, removeLegacySubsystemOperation); if (standalone) { removeLegacySubsystemOperation = Util.createRemoveOperation(OPENTRACING_EXTENSION_ELEMENT); migrateOperations.put(OPENTRACING_EXTENSION_ELEMENT, removeLegacySubsystemOperation); } } private Map<PathAddress, ModelNode> migrateSubsystems(OperationContext context, final Map<PathAddress, ModelNode> migrationOperations) throws OperationFailedException { final Map<PathAddress, ModelNode> result = new LinkedHashMap<>(); MultistepUtil.recordOperationSteps(context, migrationOperations, result); return result; } }
11,519
51.844037
137
java
null
wildfly-main/legacy/opentracing-extension/src/main/java/org/wildfly/extension/microprofile/opentracing/SubsytemParser_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.opentracing; import org.jboss.as.controller.PersistentResourceXMLDescription; import org.jboss.as.controller.PersistentResourceXMLParser; import static org.jboss.as.controller.PersistentResourceXMLDescription.builder; public class SubsytemParser_1_0 extends PersistentResourceXMLParser { public static final String NAMESPACE = "urn:wildfly:microprofile-opentracing-smallrye:1.0"; static final PersistentResourceXMLParser INSTANCE = new SubsytemParser_1_0(); private static final PersistentResourceXMLDescription xmlDescription; static { xmlDescription = builder(SubsystemExtension.SUBSYSTEM_PATH, NAMESPACE) .addAttributes() .build(); } @Override public PersistentResourceXMLDescription getParserDescription() { return xmlDescription; } }
1,893
38.458333
95
java
null
wildfly-main/legacy/opentracing-extension/src/main/java/org/wildfly/extension/microprofile/opentracing/TracerConfigurationConstants.java
/* * Copyright 2019 JBoss by Red Hat. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.microprofile.opentracing; /** * * @author Emmanuel Hugonnet (c) 2019 Red Hat, Inc. */ public class TracerConfigurationConstants { public static final String TRACER_CONFIGURATION = "tracer-configuration"; public static final String TRACER_CONFIGURATION_NAME = "tracer-configuration-name"; public static final String PROPAGATION = "propagation"; public static final String SAMPLER_TYPE = "sampler-type"; public static final String SAMPLER_PARAM = "sampler-param"; public static final String SAMPLER_MANAGER_HOST_PORT = "sampler-manager-host-port"; public static final String SENDER_AGENT_BINDING = "sender-binding"; public static final String SENDER_ENDPOINT = "sender-endpoint"; public static final String SENDER_AUTH_TOKEN = "sender-auth-token"; public static final String SENDER_AUTH_USER = "sender-auth-user"; public static final String SENDER_AUTH_PASSWORD = "sender-auth-password"; public static final String REPORTER_LOG_SPANS = "reporter-log-spans"; public static final String REPORTER_FLUSH_INTERVAL = "reporter-flush-interval"; public static final String REPORTER_MAX_QUEUE_SIZE = "reporter-max-queue-size"; public static final String TRACEID_128BIT = "tracer_id_128bit"; public static final String TRACER_TAGS = "tags"; }
1,937
41.130435
87
java
null
wildfly-main/legacy/keycloak/src/test/java/org/keycloak/subsystem/adapter/extension/SubsystemParsingTestCase.java
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other 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.keycloak.subsystem.adapter.extension; import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest; import org.jboss.as.subsystem.test.AdditionalInitialization; import org.jboss.as.subsystem.test.KernelServices; import org.jboss.dmr.ModelNode; import org.junit.Assert; import org.junit.Test; import java.io.IOException; /** * Tests all management expects for subsystem, parsing, marshaling, model definition and other * Here is an example that allows you a fine grained controller over what is tested and how. So it can give you ideas what can be done and tested. * If you have no need for advanced testing of subsystem you look at {@link SubsystemBaseParsingTestCase} that testes same stuff but most of the code * is hidden inside of test harness * * @author <a href="[email protected]">Kabir Khan</a> * @author Tomaz Cerar * @author <a href="[email protected]">Marko Strukelj</a> */ public class SubsystemParsingTestCase extends AbstractSubsystemBaseTest { public SubsystemParsingTestCase() { super(KeycloakExtension.SUBSYSTEM_NAME, new KeycloakExtension()); } @Override protected String getSubsystemXml() throws IOException { return readResource("keycloak-1.2.xml"); } @Override protected String getSubsystemXsdPath() throws Exception { return "schema/wildfly-keycloak_1_2.xsd"; } /** * Checks if the subsystem is still capable of reading a configuration that uses version 1.1 of the schema. * * @throws Exception if an error occurs while running the test. */ @Test public void testSubsystem1_1() throws Exception { KernelServices servicesA = super.createKernelServicesBuilder(createAdditionalInitialization()) .setSubsystemXml(readResource("keycloak-1.1.xml")).build(); Assert.assertTrue("Subsystem boot failed!", servicesA.isSuccessfulBoot()); ModelNode modelA = servicesA.readWholeModel(); super.validateModel(modelA); } protected AdditionalInitialization createAdditionalInitialization() { return AdditionalInitialization.ADMIN_ONLY_HC; } }
2,818
38.152778
149
java
null
wildfly-main/legacy/keycloak/src/test/java/org/keycloak/subsystem/adapter/extension/MigrateOperationTestCase.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.keycloak.subsystem.adapter.extension; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXTENSION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.keycloak.subsystem.adapter.extension.KeycloakExtension.SUBSYSTEM_NAME; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationDefinition; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.OperationStepHandler; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.ProcessType; import org.jboss.as.controller.ReloadRequiredRemoveStepHandler; import org.jboss.as.controller.RunningMode; import org.jboss.as.controller.SimpleOperationDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.capability.registry.RuntimeCapabilityRegistry; import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver; import org.jboss.as.controller.descriptions.common.ControllerResolver; import org.jboss.as.controller.extension.ExtensionRegistry; import org.jboss.as.controller.extension.ExtensionRegistryType; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.Resource; import org.jboss.as.subsystem.test.AbstractSubsystemTest; import org.jboss.as.subsystem.test.AdditionalInitialization; import org.jboss.as.subsystem.test.KernelServices; import org.jboss.dmr.ModelNode; import org.junit.Test; import org.wildfly.extension.elytron.oidc.ElytronOidcExtension; /** * Test case for the keycloak migrate op. * * @author <a href="mailto:[email protected]">Farah Juma</a> */ public class MigrateOperationTestCase extends AbstractSubsystemTest { public static final String ELYTRON_OIDC_SUBSYSTEM_NAME = "elytron-oidc-client"; public MigrateOperationTestCase() { super(SUBSYSTEM_NAME, new KeycloakExtension()); } @Test public void testMigrateDefaultKeycloakConfig() throws Exception { // default config is empty String subsystemXml = readResource("keycloak-subsystem-migration-default-config.xml"); NewSubsystemAdditionalInitialization additionalInitialization = new NewSubsystemAdditionalInitialization(); KernelServices services = createKernelServicesBuilder(additionalInitialization).setSubsystemXml(subsystemXml).build(); ModelNode model = services.readWholeModel(); assertFalse(additionalInitialization.extensionAdded); assertTrue(model.get(SUBSYSTEM, SUBSYSTEM_NAME).isDefined()); assertFalse(model.get(SUBSYSTEM, ELYTRON_OIDC_SUBSYSTEM_NAME).isDefined()); ModelNode migrateOp = new ModelNode(); migrateOp.get(OP).set("migrate"); migrateOp.get(OP_ADDR).add(SUBSYSTEM, SUBSYSTEM_NAME); ModelNode response = services.executeOperation(migrateOp); checkOutcome(response); ModelNode warnings = response.get(RESULT, "migration-warnings"); assertEquals(warnings.toString(), 0, warnings.asList().size()); model = services.readWholeModel(); assertTrue(additionalInitialization.extensionAdded); assertFalse(model.get(SUBSYSTEM, SUBSYSTEM_NAME).isDefined()); assertTrue(model.get(SUBSYSTEM, ELYTRON_OIDC_SUBSYSTEM_NAME).isDefined()); ModelNode newSubsystem = model.get(SUBSYSTEM, ELYTRON_OIDC_SUBSYSTEM_NAME); ModelNode realm = newSubsystem.get("realm"); assertFalse(realm.isDefined()); ModelNode secureDeployment = newSubsystem.get("secure-deployment"); assertFalse(secureDeployment.isDefined()); ModelNode secureServer = newSubsystem.get("secure-server"); assertFalse(secureServer.isDefined()); } @Test public void testMigrateNonEmptyKeycloakConfig() throws Exception { String subsystemXml = readResource("keycloak-subsystem-migration-non-empty-config.xml"); NewSubsystemAdditionalInitialization additionalInitialization = new NewSubsystemAdditionalInitialization(); KernelServices services = createKernelServicesBuilder(additionalInitialization).setSubsystemXml(subsystemXml).build(); ModelNode model = services.readWholeModel(); assertFalse(additionalInitialization.extensionAdded); assertTrue(model.get(SUBSYSTEM, SUBSYSTEM_NAME).isDefined()); assertFalse(model.get(SUBSYSTEM, ELYTRON_OIDC_SUBSYSTEM_NAME).isDefined()); ModelNode migrateOp = new ModelNode(); migrateOp.get(OP).set("migrate"); migrateOp.get(OP_ADDR).add(SUBSYSTEM, SUBSYSTEM_NAME); ModelNode response = services.executeOperation(migrateOp); checkOutcome(response); ModelNode warnings = response.get(RESULT, "migration-warnings"); assertEquals(warnings.toString(), 0, warnings.asList().size()); model = services.readWholeModel(); assertTrue(additionalInitialization.extensionAdded); assertFalse(model.get(SUBSYSTEM, SUBSYSTEM_NAME).isDefined()); assertTrue(model.get(SUBSYSTEM, ELYTRON_OIDC_SUBSYSTEM_NAME).isDefined()); ModelNode newSubsystem = model.get(SUBSYSTEM, ELYTRON_OIDC_SUBSYSTEM_NAME); ModelNode masterRealm = newSubsystem.get("realm", "master"); assertTrue(masterRealm.isDefined()); assertEquals("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4siLKUew0WYxdtq6/rwk4Uj/4amGFFnE/yzIxQVU0PUqz3QBRVkUWpDj0K6ZnS5nzJV/y6DHLEy7hjZTdRDphyF1sq09aDOYnVpzu8o2sIlMM8q5RnUyEfIyUZqwo8pSZDJ90fS0s+IDUJNCSIrAKO3w1lqZDHL6E/YFHXyzkvQIDAQAB", masterRealm.get("realm-public-key").asString()); assertEquals("http://localhost:8080/auth", masterRealm.get("auth-server-url").asString()); assertEquals("truststore.jks", masterRealm.get("truststore").asString()); assertEquals("secret", masterRealm.get("truststore-password").asString()); assertEquals("EXTERNAL", masterRealm.get("ssl-required").asString()); assertEquals(443, masterRealm.get("confidential-port").asInt()); assertFalse(masterRealm.get("allow-any-hostname").asBoolean()); assertTrue(masterRealm.get("disable-trust-manager").asBoolean()); assertEquals(20, masterRealm.get("connection-pool-size").asInt()); assertEquals(2000, masterRealm.get("socket-timeout-millis").asInt()); assertEquals(5000, masterRealm.get("connection-ttl-millis").asInt()); assertEquals(3000, masterRealm.get("connection-timeout-millis").asInt()); assertTrue(masterRealm.get("enable-cors").asBoolean()); assertEquals("keys.jks", masterRealm.get("client-keystore").asString()); assertEquals("secret", masterRealm.get("client-keystore-password").asString()); assertEquals("secret", masterRealm.get("client-key-password").asString()); assertEquals(600, masterRealm.get("cors-max-age").asInt()); assertEquals("X-Custom", masterRealm.get("cors-allowed-headers").asString()); assertEquals("PUT,POST,DELETE,GET", masterRealm.get("cors-allowed-methods").asString()); assertFalse(masterRealm.get("expose-token").asBoolean()); assertFalse(masterRealm.get("always-refresh-token").asBoolean()); assertTrue(masterRealm.get("register-node-at-startup").asBoolean()); assertEquals(60, masterRealm.get("register-node-period").asInt()); assertEquals("session", masterRealm.get("token-store").asString()); assertEquals("sub", masterRealm.get("principal-attribute").asString()); assertEquals("http://localhost:9000", masterRealm.get("proxy-url").asString()); ModelNode jbossInfraRealm = newSubsystem.get("realm", "jboss-infra"); assertTrue(jbossInfraRealm.isDefined()); assertEquals("http://localhost:8080/auth", jbossInfraRealm.get("auth-server-url").asString()); assertEquals("Content-Encoding", jbossInfraRealm.get("cors-exposed-headers").asString()); assertTrue(jbossInfraRealm.get("autodetect-bearer-only").asBoolean()); assertFalse(jbossInfraRealm.get("ignore-oauth-query-parameter").asBoolean()); assertFalse(jbossInfraRealm.get("verify-token-audience").asBoolean()); ModelNode secretCredentialDeployment = newSubsystem.get("secure-deployment", "secret-credential-app.war"); assertTrue(secretCredentialDeployment.isDefined()); assertEquals("master", secretCredentialDeployment.get("realm").asString()); assertEquals("secret-credential-app", secretCredentialDeployment.get("resource").asString()); assertTrue(secretCredentialDeployment.get("use-resource-role-mappings").asBoolean()); assertFalse(secretCredentialDeployment.get("turn-off-change-session-id-on-login").asBoolean()); assertEquals(10, secretCredentialDeployment.get("token-minimum-time-to-live").asInt()); assertEquals(20, secretCredentialDeployment.get("min-time-between-jwks-requests").asInt()); assertEquals(3600, secretCredentialDeployment.get("public-key-cache-ttl").asInt()); assertEquals("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4siLKUew0WYxdtq6/rwk4Uj/4amGFFnE/yzIxQVU0PUqz3QBRVkUWpDj0K6ZnS5nzJV/y6DHLEy7hjZTdRDphyF1sq09aDOYnVpzu8o2sIlMM8q5RnUyEfIyUZqwo8pSZDJ90fS0s+IDUJNCSIrAKO3w1lqZDHL6E/YFHXyzkvQIDAQAB", secretCredentialDeployment.get("realm-public-key").asString()); assertEquals("http://localhost:8080/auth", secretCredentialDeployment.get("auth-server-url").asString()); assertEquals("EXTERNAL", secretCredentialDeployment.get("ssl-required").asString()); assertEquals(443, secretCredentialDeployment.get("confidential-port").asInt()); assertEquals("http://localhost:9000", secretCredentialDeployment.get("proxy-url").asString()); assertTrue(secretCredentialDeployment.get("verify-token-audience").asBoolean()); assertEquals("0aa31d98-e0aa-404c-b6e0-e771dba1e798", secretCredentialDeployment.get("credential", "secret").get("secret").asString()); assertEquals("api/$1/", secretCredentialDeployment.get("redirect-rewrite-rule", "^/wsmaster/api/(.*)$").get("replacement").asString()); ModelNode jwtCredentialDeployment = newSubsystem.get("secure-deployment", "jwt-credential-app.war"); assertTrue(jwtCredentialDeployment.isDefined()); assertEquals("master", jwtCredentialDeployment.get("realm").asString()); assertEquals("jwt-credential-app", jwtCredentialDeployment.get("resource").asString()); assertTrue(jwtCredentialDeployment.get("use-resource-role-mappings").asBoolean()); assertEquals("/", jwtCredentialDeployment.get("adapter-state-cookie-path").asString()); assertEquals("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4siLKUew0WYxdtq6/rwk4Uj/4amGFFnE/yzIxQVU0PUqz3QBRVkUWpDj0K6ZnS5nzJV/y6DHLEy7hjZTdRDphyF1sq09aDOYnVpzu8o2sIlMM8q5RnUyEfIyUZqwo8pSZDJ90fS0s+IDUJNCSIrAKO3w1lqZDHL6E/YFHXyzkvQIDAQAB", jwtCredentialDeployment.get("realm-public-key").asString()); assertEquals("http://localhost:8080/auth", jwtCredentialDeployment.get("auth-server-url").asString()); ModelNode jwtCredential = jwtCredentialDeployment.get("credential", "jwt"); assertEquals("/tmp/keystore.jks", jwtCredential.get("client-keystore-file").asString()); assertEquals("keyPassword", jwtCredential.get("client-key-password").asString()); assertEquals("keystorePassword", jwtCredential.get("client-keystore-password").asString()); assertEquals("keyAlias", jwtCredential.get("client-key-alias").asString()); assertEquals("JKS", jwtCredential.get("client-keystore-type").asString()); assertEquals("api/$1/", secretCredentialDeployment.get("redirect-rewrite-rule", "^/wsmaster/api/(.*)$").get("replacement").asString()); ModelNode secureServer = newSubsystem.get("secure-server"); assertFalse(secureServer.isDefined()); } @Test public void testMigrateNonEmptyKeycloakConfigWithSecureServerConfig() throws Exception { String subsystemXml = readResource("keycloak-subsystem-migration-with-secure-server-config.xml"); NewSubsystemAdditionalInitialization additionalInitialization = new NewSubsystemAdditionalInitialization(); KernelServices services = createKernelServicesBuilder(additionalInitialization).setSubsystemXml(subsystemXml).build(); ModelNode model = services.readWholeModel(); assertFalse(additionalInitialization.extensionAdded); assertTrue(model.get(SUBSYSTEM, SUBSYSTEM_NAME).isDefined()); assertFalse(model.get(SUBSYSTEM, ELYTRON_OIDC_SUBSYSTEM_NAME).isDefined()); ModelNode migrateOp = new ModelNode(); migrateOp.get(OP).set("migrate"); migrateOp.get(OP_ADDR).add(SUBSYSTEM, SUBSYSTEM_NAME); ModelNode response = services.executeOperation(migrateOp); checkOutcome(response); ModelNode warnings = response.get(RESULT, "migration-warnings"); assertEquals(warnings.toString(), 0, warnings.asList().size()); model = services.readWholeModel(); assertTrue(additionalInitialization.extensionAdded); assertFalse(model.get(SUBSYSTEM, SUBSYSTEM_NAME).isDefined()); assertTrue(model.get(SUBSYSTEM, ELYTRON_OIDC_SUBSYSTEM_NAME).isDefined()); ModelNode newSubsystem = model.get(SUBSYSTEM, ELYTRON_OIDC_SUBSYSTEM_NAME); ModelNode masterRealm = newSubsystem.get("realm", "master"); assertTrue(masterRealm.isDefined()); ModelNode jbossInfraRealm = newSubsystem.get("realm", "jboss-infra"); assertTrue(jbossInfraRealm.isDefined()); ModelNode secureDeployment = newSubsystem.get("secure-deployment", "web-console.war"); assertTrue(secureDeployment.isDefined()); secureDeployment = newSubsystem.get("secure-deployment", "wildfly-management"); assertTrue(secureDeployment.isDefined()); assertEquals("jboss-infra", secureDeployment.get("realm").asString()); assertEquals("wildfly-management", secureDeployment.get("resource").asString()); assertTrue(secureDeployment.get("bearer-only").asBoolean()); assertEquals("EXTERNAL", secureDeployment.get("ssl-required").asString()); assertEquals("preferred_username", secureDeployment.get("principal-attribute").asString()); ModelNode secureServer = newSubsystem.get("secure-server", "wildfly-console"); assertTrue(secureServer.isDefined()); assertEquals("jboss-infra", secureServer.get("realm").asString()); assertEquals("wildfly-console", secureServer.get("resource").asString()); assertTrue(secureServer.get("public-client").asBoolean()); assertEquals("/", secureServer.get("adapter-state-cookie-path").asString()); assertEquals("EXTERNAL", secureServer.get("ssl-required").asString()); assertEquals(443, secureServer.get("confidential-port").asInt()); assertEquals("http://localhost:9000", secureServer.get("proxy-url").asString()); } private static class NewSubsystemAdditionalInitialization extends AdditionalInitialization { ElytronOidcExtension newSubsystem = new ElytronOidcExtension(); boolean extensionAdded = false; @Override protected void initializeExtraSubystemsAndModel(ExtensionRegistry extensionRegistry, Resource rootResource, ManagementResourceRegistration rootRegistration, RuntimeCapabilityRegistry capabilityRegistry) { final OperationDefinition removeExtension = new SimpleOperationDefinitionBuilder("remove", new StandardResourceDescriptionResolver("test", "test", getClass().getClassLoader())) .build(); PathElement keycloakExtension = PathElement.pathElement(EXTENSION, "org.keycloak.keycloak-adapter-subsystem"); rootRegistration.registerSubModel(new SimpleResourceDefinition(keycloakExtension, ControllerResolver.getResolver(EXTENSION))) .registerOperationHandler(removeExtension, ReloadRequiredRemoveStepHandler.INSTANCE); rootResource.registerChild(keycloakExtension, Resource.Factory.create()); PathElement elytronExtension = PathElement.pathElement(EXTENSION, "org.wildfly.extension.elytron"); rootRegistration.registerSubModel(new SimpleResourceDefinition(elytronExtension, ControllerResolver.getResolver(EXTENSION))) .registerOperationHandler(removeExtension, ReloadRequiredRemoveStepHandler.INSTANCE); rootResource.registerChild(elytronExtension, Resource.Factory.create()); rootRegistration.registerSubModel(new SimpleResourceDefinition(PathElement.pathElement(EXTENSION), ControllerResolver.getResolver(EXTENSION), new OperationStepHandler() { @Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { if (! extensionAdded) { extensionAdded = true; newSubsystem.initialize(extensionRegistry.getExtensionContext("org.wildfly.extension.elytron-oidc-client", rootRegistration, ExtensionRegistryType.SERVER)); } } }, null)); registerCapabilities(capabilityRegistry, "org.wildfly.security.elytron"); } @Override protected ProcessType getProcessType() { return ProcessType.HOST_CONTROLLER; } @Override protected RunningMode getRunningMode() { return RunningMode.ADMIN_ONLY; } } }
18,993
59.490446
304
java
null
wildfly-main/legacy/keycloak/src/main/java/org/keycloak/subsystem/adapter/extension/RealmDefinition.java
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other 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.keycloak.subsystem.adapter.extension; import org.jboss.as.controller.ModelOnlyAddStepHandler; import org.jboss.as.controller.ModelOnlyResourceDefinition; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SimpleAttributeDefinition; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Defines attributes and operations for the Realm * * @author Stan Silvert [email protected] (C) 2013 Red Hat Inc. */ public class RealmDefinition extends ModelOnlyResourceDefinition { public static final String TAG_NAME = "realm"; protected static final List<SimpleAttributeDefinition> REALM_ONLY_ATTRIBUTES = new ArrayList<SimpleAttributeDefinition>(); static { } protected static final List<SimpleAttributeDefinition> ALL_ATTRIBUTES = new ArrayList<SimpleAttributeDefinition>(); static { ALL_ATTRIBUTES.addAll(REALM_ONLY_ATTRIBUTES); ALL_ATTRIBUTES.addAll(SharedAttributeDefinitons.ATTRIBUTES); } protected static final SimpleAttributeDefinition[] ALL_ATTRIBUTES_ARRAY = ALL_ATTRIBUTES.toArray(new SimpleAttributeDefinition[ALL_ATTRIBUTES.size()]); private static final Map<String, SimpleAttributeDefinition> DEFINITION_LOOKUP = new HashMap<String, SimpleAttributeDefinition>(); static { for (SimpleAttributeDefinition def : ALL_ATTRIBUTES) { DEFINITION_LOOKUP.put(def.getXmlName(), def); } } public RealmDefinition() { super(PathElement.pathElement("realm"), KeycloakExtension.getResourceDescriptionResolver("realm"), new ModelOnlyAddStepHandler(ALL_ATTRIBUTES_ARRAY), ALL_ATTRIBUTES_ARRAY ); } public static SimpleAttributeDefinition lookup(String name) { return DEFINITION_LOOKUP.get(name); } }
2,547
35.927536
155
java
null
wildfly-main/legacy/keycloak/src/main/java/org/keycloak/subsystem/adapter/extension/SharedAttributeDefinitons.java
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other 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.keycloak.subsystem.adapter.extension; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.operations.validation.IntRangeValidator; import org.jboss.as.controller.operations.validation.LongRangeValidator; import org.jboss.as.controller.operations.validation.StringLengthValidator; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import java.util.ArrayList; import java.util.List; /** * Defines attributes that can be present in both a realm and an application (secure-deployment). * * @author Stan Silvert [email protected] (C) 2013 Red Hat Inc. */ public class SharedAttributeDefinitons { protected static final SimpleAttributeDefinition REALM_PUBLIC_KEY = new SimpleAttributeDefinitionBuilder("realm-public-key", ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition AUTH_SERVER_URL = new SimpleAttributeDefinitionBuilder("auth-server-url", ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition SSL_REQUIRED = new SimpleAttributeDefinitionBuilder("ssl-required", ModelType.STRING, true) .setAllowExpression(true) .setDefaultValue(new ModelNode("external")) .build(); protected static final SimpleAttributeDefinition ALLOW_ANY_HOSTNAME = new SimpleAttributeDefinitionBuilder("allow-any-hostname", ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition DISABLE_TRUST_MANAGER = new SimpleAttributeDefinitionBuilder("disable-trust-manager", ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition TRUSTSTORE = new SimpleAttributeDefinitionBuilder("truststore", ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition TRUSTSTORE_PASSWORD = new SimpleAttributeDefinitionBuilder("truststore-password", ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition CONNECTION_POOL_SIZE = new SimpleAttributeDefinitionBuilder("connection-pool-size", ModelType.INT, true) .setAllowExpression(true) .setValidator(new IntRangeValidator(0, true)) .build(); protected static final SimpleAttributeDefinition SOCKET_TIMEOUT = new SimpleAttributeDefinitionBuilder("socket-timeout-millis", ModelType.LONG, true) .setAllowExpression(true) .setValidator(new LongRangeValidator(-1L, true)) .build(); protected static final SimpleAttributeDefinition CONNECTION_TTL = new SimpleAttributeDefinitionBuilder("connection-ttl-millis", ModelType.LONG, true) .setAllowExpression(true) .setValidator(new LongRangeValidator(-1L, true)) .build(); protected static final SimpleAttributeDefinition CONNECTION_TIMEOUT = new SimpleAttributeDefinitionBuilder("connection-timeout-millis", ModelType.LONG, true) .setAllowExpression(true) .setValidator(new LongRangeValidator(-1L, true)) .build(); protected static final SimpleAttributeDefinition ENABLE_CORS = new SimpleAttributeDefinitionBuilder("enable-cors", ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition CLIENT_KEYSTORE = new SimpleAttributeDefinitionBuilder("client-keystore", ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition CLIENT_KEYSTORE_PASSWORD = new SimpleAttributeDefinitionBuilder("client-keystore-password", ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition CLIENT_KEY_PASSWORD = new SimpleAttributeDefinitionBuilder("client-key-password", ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition CORS_MAX_AGE = new SimpleAttributeDefinitionBuilder("cors-max-age", ModelType.INT, true) .setAllowExpression(true) .setValidator(new IntRangeValidator(-1, true)) .build(); protected static final SimpleAttributeDefinition CORS_ALLOWED_HEADERS = new SimpleAttributeDefinitionBuilder("cors-allowed-headers", ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition CORS_ALLOWED_METHODS = new SimpleAttributeDefinitionBuilder("cors-allowed-methods", ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition CORS_EXPOSED_HEADERS = new SimpleAttributeDefinitionBuilder("cors-exposed-headers", ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition EXPOSE_TOKEN = new SimpleAttributeDefinitionBuilder("expose-token", ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition AUTH_SERVER_URL_FOR_BACKEND_REQUESTS = new SimpleAttributeDefinitionBuilder("auth-server-url-for-backend-requests", ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition ALWAYS_REFRESH_TOKEN = new SimpleAttributeDefinitionBuilder("always-refresh-token", ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition REGISTER_NODE_AT_STARTUP = new SimpleAttributeDefinitionBuilder("register-node-at-startup", ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition REGISTER_NODE_PERIOD = new SimpleAttributeDefinitionBuilder("register-node-period", ModelType.INT, true) .setAllowExpression(true) .setValidator(new IntRangeValidator(-1, true)) .build(); protected static final SimpleAttributeDefinition TOKEN_STORE = new SimpleAttributeDefinitionBuilder("token-store", ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition PRINCIPAL_ATTRIBUTE = new SimpleAttributeDefinitionBuilder("principal-attribute", ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition AUTODETECT_BEARER_ONLY = new SimpleAttributeDefinitionBuilder("autodetect-bearer-only", ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition IGNORE_OAUTH_QUERY_PARAMETER = new SimpleAttributeDefinitionBuilder("ignore-oauth-query-parameter", ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition CONFIDENTIAL_PORT = new SimpleAttributeDefinitionBuilder("confidential-port", ModelType.INT, true) .setAllowExpression(true) .setDefaultValue(new ModelNode(8443)) .build(); protected static final SimpleAttributeDefinition PROXY_URL = new SimpleAttributeDefinitionBuilder("proxy-url", ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition VERIFY_TOKEN_AUDIENCE = new SimpleAttributeDefinitionBuilder("verify-token-audience", ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final List<SimpleAttributeDefinition> ATTRIBUTES = new ArrayList<SimpleAttributeDefinition>(); static { ATTRIBUTES.add(REALM_PUBLIC_KEY); ATTRIBUTES.add(AUTH_SERVER_URL); ATTRIBUTES.add(TRUSTSTORE); ATTRIBUTES.add(TRUSTSTORE_PASSWORD); ATTRIBUTES.add(SSL_REQUIRED); ATTRIBUTES.add(CONFIDENTIAL_PORT); ATTRIBUTES.add(ALLOW_ANY_HOSTNAME); ATTRIBUTES.add(DISABLE_TRUST_MANAGER); ATTRIBUTES.add(CONNECTION_POOL_SIZE); ATTRIBUTES.add(SOCKET_TIMEOUT); ATTRIBUTES.add(CONNECTION_TTL); ATTRIBUTES.add(CONNECTION_TIMEOUT); ATTRIBUTES.add(ENABLE_CORS); ATTRIBUTES.add(CLIENT_KEYSTORE); ATTRIBUTES.add(CLIENT_KEYSTORE_PASSWORD); ATTRIBUTES.add(CLIENT_KEY_PASSWORD); ATTRIBUTES.add(CORS_MAX_AGE); ATTRIBUTES.add(CORS_ALLOWED_HEADERS); ATTRIBUTES.add(CORS_ALLOWED_METHODS); ATTRIBUTES.add(CORS_EXPOSED_HEADERS); ATTRIBUTES.add(EXPOSE_TOKEN); ATTRIBUTES.add(AUTH_SERVER_URL_FOR_BACKEND_REQUESTS); ATTRIBUTES.add(ALWAYS_REFRESH_TOKEN); ATTRIBUTES.add(REGISTER_NODE_AT_STARTUP); ATTRIBUTES.add(REGISTER_NODE_PERIOD); ATTRIBUTES.add(TOKEN_STORE); ATTRIBUTES.add(PRINCIPAL_ATTRIBUTE); ATTRIBUTES.add(AUTODETECT_BEARER_ONLY); ATTRIBUTES.add(IGNORE_OAUTH_QUERY_PARAMETER); ATTRIBUTES.add(PROXY_URL); ATTRIBUTES.add(VERIFY_TOKEN_AUDIENCE); } private static boolean isSet(ModelNode attributes, SimpleAttributeDefinition def) { ModelNode attribute = attributes.get(def.getName()); if (def.getType() == ModelType.BOOLEAN) { return attribute.isDefined() && attribute.asBoolean(); } return attribute.isDefined() && !attribute.asString().isEmpty(); } }
12,981
51.772358
115
java
null
wildfly-main/legacy/keycloak/src/main/java/org/keycloak/subsystem/adapter/extension/RedirecRewritetRuleDefinition.java
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other 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.keycloak.subsystem.adapter.extension; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.ModelOnlyAddStepHandler; import org.jboss.as.controller.ModelOnlyResourceDefinition; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.operations.validation.StringLengthValidator; import org.jboss.dmr.ModelType; /** * * @author sblanc */ public class RedirecRewritetRuleDefinition extends ModelOnlyResourceDefinition { public static final String TAG_NAME = "redirect-rewrite-rule"; protected static final AttributeDefinition VALUE = new SimpleAttributeDefinitionBuilder("value", ModelType.STRING, false) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, false, true)) .build(); public RedirecRewritetRuleDefinition() { super(PathElement.pathElement(TAG_NAME), KeycloakExtension.getResourceDescriptionResolver(TAG_NAME), new ModelOnlyAddStepHandler(VALUE), VALUE); } }
1,834
35.7
87
java
null
wildfly-main/legacy/keycloak/src/main/java/org/keycloak/subsystem/adapter/extension/KeycloakSubsystemDefinition.java
/* * Copyright 2020 Red Hat, Inc. and/or its affiliates * and other 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.keycloak.subsystem.adapter.extension; import static org.keycloak.subsystem.adapter.extension.KeycloakExtension.REALM_DEFINITION; import static org.keycloak.subsystem.adapter.extension.KeycloakExtension.SECURE_DEPLOYMENT_DEFINITION; import static org.keycloak.subsystem.adapter.extension.KeycloakExtension.SECURE_SERVER_DEFINITION; import org.jboss.as.controller.ModelOnlyAddStepHandler; import org.jboss.as.controller.ModelOnlyResourceDefinition; import org.jboss.as.controller.registry.ManagementResourceRegistration; /** * Definition of subsystem=keycloak. * * @author Stan Silvert [email protected] (C) 2013 Red Hat Inc. */ public class KeycloakSubsystemDefinition extends ModelOnlyResourceDefinition { protected KeycloakSubsystemDefinition() { super(KeycloakExtension.SUBSYSTEM_PATH, KeycloakExtension.getResourceDescriptionResolver("subsystem"), new ModelOnlyAddStepHandler() ); } @Override public void registerChildren(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerSubModel(REALM_DEFINITION); resourceRegistration.registerSubModel(SECURE_DEPLOYMENT_DEFINITION); resourceRegistration.registerSubModel(SECURE_SERVER_DEFINITION); } @Override public void registerOperations(ManagementResourceRegistration resourceRegistration) { super.registerOperations(resourceRegistration); MigrateOperation.registerOperations(resourceRegistration, KeycloakExtension.getResourceDescriptionResolver()); } }
2,252
39.963636
118
java
null
wildfly-main/legacy/keycloak/src/main/java/org/keycloak/subsystem/adapter/extension/CredentialDefinition.java
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other 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.keycloak.subsystem.adapter.extension; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.ModelOnlyAddStepHandler; import org.jboss.as.controller.ModelOnlyResourceDefinition; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.operations.validation.StringLengthValidator; import org.jboss.dmr.ModelType; /** * Defines attributes and operations for a credential. * * @author Stan Silvert [email protected] (C) 2013 Red Hat Inc. */ public class CredentialDefinition extends ModelOnlyResourceDefinition { public static final String TAG_NAME = "credential"; protected static final AttributeDefinition VALUE = new SimpleAttributeDefinitionBuilder("value", ModelType.STRING, false) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, false, true)) .build(); public CredentialDefinition() { super(PathElement.pathElement(TAG_NAME), KeycloakExtension.getResourceDescriptionResolver(TAG_NAME), new ModelOnlyAddStepHandler(VALUE), VALUE); } }
1,907
37.16
87
java
null
wildfly-main/legacy/keycloak/src/main/java/org/keycloak/subsystem/adapter/extension/SecureServerDefinition.java
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other 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.keycloak.subsystem.adapter.extension; /** * Defines attributes and operations for a secure-deployment. * * @author Stan Silvert [email protected] (C) 2013 Red Hat Inc. */ final class SecureServerDefinition extends AbstractAdapterConfigurationDefinition { public static final String TAG_NAME = "secure-server"; SecureServerDefinition() { super(TAG_NAME, ALL_ATTRIBUTES_ARRAY); } }
1,096
33.28125
83
java
null
wildfly-main/legacy/keycloak/src/main/java/org/keycloak/subsystem/adapter/extension/KeycloakExtension.java
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other 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.keycloak.subsystem.adapter.extension; import org.jboss.as.controller.ExtensionContext; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.ResourceDefinition; import org.jboss.as.controller.SubsystemRegistration; import org.jboss.as.controller.descriptions.ResourceDescriptionResolver; import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver; import org.jboss.as.controller.extension.AbstractLegacyExtension; import org.jboss.as.controller.parsing.ExtensionParsingContext; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.keycloak.subsystem.adapter.logging.KeycloakLogger; import java.util.Collections; import java.util.Set; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; /** * Main Extension class for the subsystem. * * @author Stan Silvert [email protected] (C) 2013 Red Hat Inc. */ public final class KeycloakExtension extends AbstractLegacyExtension { public static final String SUBSYSTEM_NAME = "keycloak"; public static final String NAMESPACE_1_1 = "urn:jboss:domain:keycloak:1.1"; public static final String NAMESPACE_1_2 = "urn:jboss:domain:keycloak:1.2"; public static final String CURRENT_NAMESPACE = NAMESPACE_1_2; private static final KeycloakSubsystemParser PARSER = new KeycloakSubsystemParser(); static final PathElement PATH_SUBSYSTEM = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME); private static final String RESOURCE_NAME = KeycloakExtension.class.getPackage().getName() + ".LocalDescriptions"; private static final ModelVersion MGMT_API_VERSION = ModelVersion.create(1,1,0); static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME); private static final ResourceDefinition KEYCLOAK_SUBSYSTEM_RESOURCE = new KeycloakSubsystemDefinition(); static final RealmDefinition REALM_DEFINITION = new RealmDefinition(); static final SecureDeploymentDefinition SECURE_DEPLOYMENT_DEFINITION = new SecureDeploymentDefinition(); static final SecureServerDefinition SECURE_SERVER_DEFINITION = new SecureServerDefinition(); static final CredentialDefinition CREDENTIAL_DEFINITION = new CredentialDefinition(); static final RedirecRewritetRuleDefinition REDIRECT_RULE_DEFINITON = new RedirecRewritetRuleDefinition(); public KeycloakExtension() { super("org.keycloak.keycloak-adapter-subsystem", SUBSYSTEM_NAME); } public static ResourceDescriptionResolver getResourceDescriptionResolver(final String... keyPrefix) { StringBuilder prefix = new StringBuilder(SUBSYSTEM_NAME); for (String kp : keyPrefix) { prefix.append('.').append(kp); } return new StandardResourceDescriptionResolver(prefix.toString(), RESOURCE_NAME, KeycloakExtension.class.getClassLoader(), true, false); } /** * {@inheritDoc} */ @Override protected void initializeLegacyParsers(final ExtensionParsingContext context) { context.setSubsystemXmlMapping(SUBSYSTEM_NAME, KeycloakExtension.NAMESPACE_1_1, PARSER); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, KeycloakExtension.NAMESPACE_1_2, PARSER); } /** * {@inheritDoc} */ @Override protected Set<ManagementResourceRegistration> initializeLegacyModel(final ExtensionContext context) { KeycloakLogger.ROOT_LOGGER.debug("Activating Keycloak Extension"); final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, MGMT_API_VERSION); ManagementResourceRegistration registration = subsystem.registerSubsystemModel(KEYCLOAK_SUBSYSTEM_RESOURCE); subsystem.registerXMLElementWriter(PARSER); return Collections.singleton(registration); } }
4,524
47.655914
144
java
null
wildfly-main/legacy/keycloak/src/main/java/org/keycloak/subsystem/adapter/extension/AbstractAdapterConfigurationDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016 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.keycloak.subsystem.adapter.extension; import static org.keycloak.subsystem.adapter.extension.KeycloakExtension.CREDENTIAL_DEFINITION; import static org.keycloak.subsystem.adapter.extension.KeycloakExtension.REDIRECT_RULE_DEFINITON; import org.jboss.as.controller.ModelOnlyAddStepHandler; import org.jboss.as.controller.ModelOnlyResourceDefinition; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.operations.validation.IntRangeValidator; import org.jboss.as.controller.operations.validation.StringLengthValidator; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Defines attributes and operations for a secure-deployment. * * @author Stan Silvert [email protected] (C) 2013 Red Hat Inc. */ abstract class AbstractAdapterConfigurationDefinition extends ModelOnlyResourceDefinition { protected static final SimpleAttributeDefinition REALM = new SimpleAttributeDefinitionBuilder("realm", ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition RESOURCE = new SimpleAttributeDefinitionBuilder("resource", ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition USE_RESOURCE_ROLE_MAPPINGS = new SimpleAttributeDefinitionBuilder("use-resource-role-mappings", ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition BEARER_ONLY = new SimpleAttributeDefinitionBuilder("bearer-only", ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition ENABLE_BASIC_AUTH = new SimpleAttributeDefinitionBuilder("enable-basic-auth", ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition PUBLIC_CLIENT = new SimpleAttributeDefinitionBuilder("public-client", ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition TURN_OFF_CHANGE_SESSION = new SimpleAttributeDefinitionBuilder("turn-off-change-session-id-on-login", ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition TOKEN_MINIMUM_TIME_TO_LIVE = new SimpleAttributeDefinitionBuilder("token-minimum-time-to-live", ModelType.INT, true) .setValidator(new IntRangeValidator(-1, true)) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition MIN_TIME_BETWEEN_JWKS_REQUESTS = new SimpleAttributeDefinitionBuilder("min-time-between-jwks-requests", ModelType.INT, true) .setValidator(new IntRangeValidator(-1, true)) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition PUBLIC_KEY_CACHE_TTL = new SimpleAttributeDefinitionBuilder("public-key-cache-ttl", ModelType.INT, true) .setAllowExpression(true) .setValidator(new IntRangeValidator(-1, true)) .build(); protected static final SimpleAttributeDefinition ADAPTER_STATE_COOKIE_PATH = new SimpleAttributeDefinitionBuilder("adapter-state-cookie-path", ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); static final List<SimpleAttributeDefinition> DEPLOYMENT_ONLY_ATTRIBUTES = new ArrayList<SimpleAttributeDefinition>(); static { DEPLOYMENT_ONLY_ATTRIBUTES.add(REALM); DEPLOYMENT_ONLY_ATTRIBUTES.add(RESOURCE); DEPLOYMENT_ONLY_ATTRIBUTES.add(USE_RESOURCE_ROLE_MAPPINGS); DEPLOYMENT_ONLY_ATTRIBUTES.add(BEARER_ONLY); DEPLOYMENT_ONLY_ATTRIBUTES.add(ENABLE_BASIC_AUTH); DEPLOYMENT_ONLY_ATTRIBUTES.add(PUBLIC_CLIENT); DEPLOYMENT_ONLY_ATTRIBUTES.add(TURN_OFF_CHANGE_SESSION); DEPLOYMENT_ONLY_ATTRIBUTES.add(TOKEN_MINIMUM_TIME_TO_LIVE); DEPLOYMENT_ONLY_ATTRIBUTES.add(MIN_TIME_BETWEEN_JWKS_REQUESTS); DEPLOYMENT_ONLY_ATTRIBUTES.add(PUBLIC_KEY_CACHE_TTL); DEPLOYMENT_ONLY_ATTRIBUTES.add(ADAPTER_STATE_COOKIE_PATH); } static final List<SimpleAttributeDefinition> ALL_ATTRIBUTES = new ArrayList(); static { ALL_ATTRIBUTES.addAll(DEPLOYMENT_ONLY_ATTRIBUTES); ALL_ATTRIBUTES.addAll(SharedAttributeDefinitons.ATTRIBUTES); } static final SimpleAttributeDefinition[] ALL_ATTRIBUTES_ARRAY = ALL_ATTRIBUTES.toArray(new SimpleAttributeDefinition[ALL_ATTRIBUTES.size()]); static final Map<String, SimpleAttributeDefinition> XML_ATTRIBUTES = new HashMap<String, SimpleAttributeDefinition>(); static { for (SimpleAttributeDefinition def : ALL_ATTRIBUTES) { XML_ATTRIBUTES.put(def.getXmlName(), def); } } private static final Map<String, SimpleAttributeDefinition> DEFINITION_LOOKUP = new HashMap<String, SimpleAttributeDefinition>(); static { for (SimpleAttributeDefinition def : ALL_ATTRIBUTES) { DEFINITION_LOOKUP.put(def.getXmlName(), def); } } protected AbstractAdapterConfigurationDefinition(String name, SimpleAttributeDefinition[] attributes) { super(PathElement.pathElement(name), KeycloakExtension.getResourceDescriptionResolver(name), new ModelOnlyAddStepHandler(attributes), attributes ); } public static SimpleAttributeDefinition lookup(String name) { return DEFINITION_LOOKUP.get(name); } @Override public void registerChildren(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerSubModel(CREDENTIAL_DEFINITION); resourceRegistration.registerSubModel(REDIRECT_RULE_DEFINITON); } }
7,775
47.298137
145
java
null
wildfly-main/legacy/keycloak/src/main/java/org/keycloak/subsystem/adapter/extension/MigrateOperation.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.keycloak.subsystem.adapter.extension; import static org.jboss.as.controller.OperationContext.Stage.MODEL; import static org.jboss.as.controller.PathAddress.pathAddress; import static org.jboss.as.controller.PathElement.pathElement; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADDRESS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXTENSION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MODULE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION; import static org.jboss.as.controller.operations.common.Util.createAddOperation; import static org.jboss.as.controller.operations.common.Util.createOperation; import static org.jboss.as.controller.operations.common.Util.createRemoveOperation; import static org.keycloak.subsystem.adapter.logging.KeycloakLogger.ROOT_LOGGER; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.OperationStepHandler; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.ProcessType; import org.jboss.as.controller.RunningMode; import org.jboss.as.controller.SimpleMapAttributeDefinition; import org.jboss.as.controller.SimpleOperationDefinitionBuilder; import org.jboss.as.controller.StringListAttributeDefinition; import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition; import org.jboss.as.controller.descriptions.ResourceDescriptionResolver; import org.jboss.as.controller.operations.MultistepUtil; import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.OperationEntry; import org.jboss.as.controller.registry.Resource; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.dmr.Property; /** * Operation to migrate from the legacy keycloak subsystem to the elytron-oidc-client subsystem. * * <p/> * This operation must be performed when the server is in admin-only mode. * <p/> * * <p> * Internally, the operation: * <p/> * * <ul> * <li>queries the description of the entire keycloak subsystem by invoking the :describe operation. * This returns a list of :add operations for each keycloak resource.</li> * <li>:add the new org.wildfly.extension.elytron-oidc-client extension if necessary</li> * <li>for each keycloak resource, transform the :add operations to add the corresponding resource to the * new elytron-oidc-client subsystem. In this step, changes to the resources model are taken into account</li> * <li>:remove the keycloak subsystem</li> * </ul> * * <p/> * * The companion <code>:describe-migration</code> operation will return a list of all the actual operations that would * be performed during the invocation of the <code>:migrate</code> operation. * <p/> * * Note that all new operation addresses are generated for standalone mode. If this is a domain mode server then the * addresses are fixed after they have been generated * * @author <a href="mailto:[email protected]">Farah Juma</a> */ public class MigrateOperation implements OperationStepHandler { private static final String ELYTRON_OIDC_EXTENSION = "org.wildfly.extension.elytron-oidc-client"; private static final String ELYTRON_OIDC = "elytron-oidc-client"; private static final String KEYCLOAK_EXTENSION = "org.keycloak.keycloak-adapter-subsystem"; private static final PathAddress KEYCLOAK_EXTENSION_ADDRESS = pathAddress(pathElement(EXTENSION, KEYCLOAK_EXTENSION)); private static final OperationStepHandler DESCRIBE_MIGRATION_INSTANCE = new MigrateOperation(true); private static final OperationStepHandler MIGRATE_INSTANCE = new MigrateOperation(false); private static final String MIGRATE = "migrate"; private static final String MIGRATION_WARNINGS = "migration-warnings"; private static final String MIGRATION_ERROR = "migration-error"; private static final String MIGRATION_OPERATIONS = "migration-operations"; private static final String DESCRIBE_MIGRATION = "describe-migration"; private static final String SECRET = "secret"; private static final String REPLACEMENT = "replacement"; static final StringListAttributeDefinition MIGRATION_WARNINGS_ATTR = new StringListAttributeDefinition.Builder(MIGRATION_WARNINGS) .setRequired(false) .build(); static final SimpleMapAttributeDefinition MIGRATION_ERROR_ATTR = new SimpleMapAttributeDefinition.Builder(MIGRATION_ERROR, ModelType.OBJECT, true) .setValueType(ModelType.OBJECT) .setRequired(false) .build(); private final boolean describe; private MigrateOperation(boolean describe) { this.describe = describe; } static void registerOperations(ManagementResourceRegistration registry, ResourceDescriptionResolver resourceDescriptionResolver) { registry.registerOperationHandler(new SimpleOperationDefinitionBuilder(MIGRATE, resourceDescriptionResolver) .setReplyParameters(MIGRATION_WARNINGS_ATTR, MIGRATION_ERROR_ATTR) .setAccessConstraints(SensitiveTargetAccessConstraintDefinition.READ_WHOLE_CONFIG) .build(), MigrateOperation.MIGRATE_INSTANCE); registry.registerOperationHandler(new SimpleOperationDefinitionBuilder(DESCRIBE_MIGRATION, resourceDescriptionResolver) .setReplyParameters(MIGRATION_WARNINGS_ATTR) .setAccessConstraints(SensitiveTargetAccessConstraintDefinition.READ_WHOLE_CONFIG) .setReadOnly() .build(), MigrateOperation.DESCRIBE_MIGRATION_INSTANCE); } @Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { if (! describe && context.getRunningMode() != RunningMode.ADMIN_ONLY) { throw ROOT_LOGGER.migrateOperationAllowedOnlyInAdminOnly(); } final List<String> warnings = new ArrayList<>(); // node containing the description (list of add operations) of the legacy subsystem final ModelNode legacyModelAddOps = new ModelNode(); // preserve the order of insertion of the add operations for the new subsystem. final Map<PathAddress, ModelNode> migrationOperations = new LinkedHashMap<>(); // invoke an OSH to describe the legacy keycloak subsystem describeLegacyKeycloakResources(context, legacyModelAddOps); // invoke an OSH to add the elytron-oidc-client extension if necessary addElytronOidcExtension(context, migrationOperations, describe); context.addStep(new OperationStepHandler() { @Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { // transform the legacy add operations and put them in migrationOperations transformResources(context, legacyModelAddOps, migrationOperations, warnings); // add the /subsystem=keycloak:remove operation removeKeycloak(migrationOperations, context.getProcessType() == ProcessType.STANDALONE_SERVER); PathAddress parentAddress = context.getCurrentAddress().getParent(); fixAddressesForDomainMode(parentAddress, migrationOperations); if (describe) { // :describe-migration operation returns the list of operations that would be executed in the composite operation final Collection<ModelNode> values = migrationOperations.values(); ModelNode result = new ModelNode(); fillWarnings(result, warnings); result.get(MIGRATION_OPERATIONS).set(values); context.getResult().set(result); } else { // :migrate operation invokes an OSH on a composite operation with all the migration operations final Map<PathAddress, ModelNode> migrateOpResponses = migrateSubsystems(context, migrationOperations); context.completeStep(new OperationContext.ResultHandler() { @Override public void handleResult(OperationContext.ResultAction resultAction, OperationContext context, ModelNode operation) { final ModelNode result = new ModelNode(); fillWarnings(result, warnings); if (resultAction == OperationContext.ResultAction.ROLLBACK) { for (Map.Entry<PathAddress, ModelNode> entry : migrateOpResponses.entrySet()) { if (entry.getValue().hasDefined(FAILURE_DESCRIPTION)) { //we check for failure description, as every node has 'failed', but one //the real error has a failure description //we break when we find the first one, as there will only ever be one failure //as the op stops after the first failure ModelNode desc = new ModelNode(); desc.get(OP).set(migrationOperations.get(entry.getKey())); desc.get(RESULT).set(entry.getValue()); result.get(MIGRATION_ERROR).set(desc); break; } } context.getFailureDescription().set(ROOT_LOGGER.migrationFailed()); } context.getResult().set(result); } }); } } }, MODEL); } private void describeLegacyKeycloakResources(OperationContext context, ModelNode legacyModelDescription) { ModelNode describeLegacySubsystem = createOperation(GenericSubsystemDescribeHandler.DEFINITION, context.getCurrentAddress()); context.addStep(legacyModelDescription, describeLegacySubsystem, GenericSubsystemDescribeHandler.INSTANCE, MODEL, true); } /** * Attempt to add the elytron-oidc-client extension. If it's already present, nothing is done. */ private void addElytronOidcExtension(OperationContext context, Map<PathAddress, ModelNode> migrationOperations, boolean describe) { Resource root = context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS, false); if (root.getChildrenNames(EXTENSION).contains(ELYTRON_OIDC_EXTENSION)) { return; // extension is already added, nothing to do } PathAddress extensionAddress = pathAddress(EXTENSION, ELYTRON_OIDC_EXTENSION); OperationEntry addEntry = context.getRootResourceRegistration().getOperationEntry(extensionAddress, ADD); ModelNode addOperation = createAddOperation(extensionAddress); addOperation.get(MODULE).set(ELYTRON_OIDC_EXTENSION); if (describe) { migrationOperations.put(extensionAddress, addOperation); } else { context.addStep(context.getResult().get(extensionAddress.toString()), addOperation, addEntry.getOperationHandler(), MODEL); } } private void transformResources(OperationContext context, final ModelNode legacyModelDescription, final Map<PathAddress, ModelNode> newAddOperations, List<String> warnings) throws OperationFailedException { List<String> credentialNames = new ArrayList<>(); for (ModelNode legacyAddOp : legacyModelDescription.get(RESULT).asList()) { final ModelNode newAddOp = legacyAddOp.clone(); ModelNode legacyAddress = legacyAddOp.get(OP_ADDR); ModelNode newAddress = transformAddress(legacyAddress.clone(), context); if (! newAddress.isDefined()) { continue; } newAddOp.get(OP_ADDR).set(newAddress); PathAddress address = PathAddress.pathAddress(newAddress); if (newAddress.asList().size() > 2) { // element 0 is subsystem=elytron-oidc-client String childType = address.getElement(2).getKey(); if (childType.equals(CredentialDefinition.TAG_NAME)) { migrateCredential(newAddOp, address.getElement(2).getValue(), credentialNames); } else if (childType.equals(RedirecRewritetRuleDefinition.TAG_NAME)) { migrateRedirectRewriteRule(newAddOp); } } newAddOperations.put(address, newAddOp); } } private ModelNode transformAddress(ModelNode legacyAddress, OperationContext context) { ModelNode newAddress = new ModelNode(); if (legacyAddress.asPropertyList().size() == 1) { Resource root = context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS, false); if (root.getChildrenNames(SUBSYSTEM).contains(ELYTRON_OIDC)) { return new ModelNode(); // elytron-oidc-client subsystem is already present, no need to add it } } for (Property segment : legacyAddress.asPropertyList()) { final Property newSegment; switch (segment.getName()) { case SUBSYSTEM: newSegment = new Property(SUBSYSTEM, new ModelNode(ELYTRON_OIDC)); break; default: newSegment = segment; } newAddress.add(newSegment); } return newAddress; } private void removeKeycloak(Map<PathAddress, ModelNode> migrationOperations, boolean standalone) { PathAddress subsystemAddress = pathAddress(KeycloakExtension.PATH_SUBSYSTEM); ModelNode removeOperation = createRemoveOperation(subsystemAddress); migrationOperations.put(subsystemAddress, removeOperation); if (standalone) { removeOperation = createRemoveOperation(KEYCLOAK_EXTENSION_ADDRESS); migrationOperations.put(KEYCLOAK_EXTENSION_ADDRESS, removeOperation); } } private Map<PathAddress, ModelNode> migrateSubsystems(OperationContext context, final Map<PathAddress, ModelNode> migrationOperations) throws OperationFailedException { final Map<PathAddress, ModelNode> result = new LinkedHashMap<>(); MultistepUtil.recordOperationSteps(context, migrationOperations, result); return result; } /** * In domain mode, the subsystems are under /profile=XXX. * This method fixes the address by prepending the addresses (that start with /subsystem) with the current * operation parent so that is works both in standalone (parent = EMPTY_ADDRESS) and domain mode * (parent = /profile=XXX). */ private void fixAddressesForDomainMode(PathAddress parentAddress, Map<PathAddress, ModelNode> migrationOperations) { // in standalone mode, do nothing if (parentAddress.size() == 0) { return; } // use a linked hash map to preserve operations order Map<PathAddress, ModelNode> fixedMigrationOperations = new LinkedHashMap<>(migrationOperations); migrationOperations.clear(); for (Map.Entry<PathAddress, ModelNode> entry : fixedMigrationOperations.entrySet()) { PathAddress fixedAddress = parentAddress.append(entry.getKey()); entry.getValue().get(ADDRESS).set(fixedAddress.toModelNode()); migrationOperations.put(fixedAddress, entry.getValue()); } } private void fillWarnings(ModelNode result, List<String> warnings) { ModelNode rw = new ModelNode().setEmptyList(); for (String warning : warnings) { rw.add(warning); } result.get(MIGRATION_WARNINGS).set(rw); } private void migrateCredential(ModelNode newOp, String credentialType, List<String> credentialNames) { // complex legacy credential types will be of the form name:attribute (e.g., jwt.client-key-password) // (each credential attribute type was previously a resource, need to update the op to set attributes // for the credential resource instead) String[] nameAndType = credentialType.split("\\."); String name = nameAndType[0]; boolean useWriteAttributeOp = false; if (credentialNames.contains(name)) { useWriteAttributeOp = true; } else { credentialNames.add(name); } switch (name) { case SECRET: updateOp(newOp, SECRET, useWriteAttributeOp); break; default: String type = nameAndType[1]; updateOp(newOp, type, useWriteAttributeOp); newOp.get(ADDRESS).asList().get(2).get(CredentialDefinition.TAG_NAME).set(name); break; } } private void migrateRedirectRewriteRule(ModelNode newAddOp) { // <redirect-rewrite-rule name="..." replacement="VALUE"/> instead of <redirect-rewrite-rule name="...">VALUE</redirect-rewrite-rule> newAddOp.get(REPLACEMENT).set(newAddOp.get(VALUE).asString()); newAddOp.remove(VALUE); } private void updateOp(ModelNode newOp, String attributeName, boolean useWriteAttributeOp) { if (useWriteAttributeOp) { newOp.get(OP).set(WRITE_ATTRIBUTE_OPERATION); newOp.get(NAME).set(attributeName); } else { newOp.get(attributeName).set(newOp.get(VALUE).asString()); newOp.remove(VALUE); } } }
19,882
50.913838
172
java
null
wildfly-main/legacy/keycloak/src/main/java/org/keycloak/subsystem/adapter/extension/SecureDeploymentDefinition.java
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other 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.keycloak.subsystem.adapter.extension; /** * Defines attributes and operations for a secure-deployment. * * @author Stan Silvert [email protected] (C) 2013 Red Hat Inc. */ final class SecureDeploymentDefinition extends AbstractAdapterConfigurationDefinition { static final String TAG_NAME = "secure-deployment"; public SecureDeploymentDefinition() { super(TAG_NAME, ALL_ATTRIBUTES_ARRAY); } }
1,109
32.636364
87
java
null
wildfly-main/legacy/keycloak/src/main/java/org/keycloak/subsystem/adapter/extension/KeycloakSubsystemParser.java
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other 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.keycloak.subsystem.adapter.extension; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; 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.dmr.Property; import org.jboss.staxmapper.XMLElementReader; import org.jboss.staxmapper.XMLElementWriter; import org.jboss.staxmapper.XMLExtendedStreamReader; import org.jboss.staxmapper.XMLExtendedStreamWriter; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * The subsystem parser, which uses stax to read and write to and from xml */ class KeycloakSubsystemParser implements XMLStreamConstants, XMLElementReader<List<ModelNode>>, XMLElementWriter<SubsystemMarshallingContext> { /** * {@inheritDoc} */ @Override public void readElement(final XMLExtendedStreamReader reader, final List<ModelNode> list) throws XMLStreamException { // Require no attributes ParseUtils.requireNoAttributes(reader); ModelNode addKeycloakSub = Util.createAddOperation(PathAddress.pathAddress(KeycloakExtension.PATH_SUBSYSTEM)); list.add(addKeycloakSub); while (reader.hasNext() && nextTag(reader) != END_ELEMENT) { if (reader.getLocalName().equals(RealmDefinition.TAG_NAME)) { readRealm(reader, list); } else if (reader.getLocalName().equals(SecureDeploymentDefinition.TAG_NAME)) { readDeployment(reader, list); } else if (reader.getLocalName().equals(SecureServerDefinition.TAG_NAME)) { readSecureServer(reader, list); } } } // used for debugging private int nextTag(XMLExtendedStreamReader reader) throws XMLStreamException { return reader.nextTag(); } private void readRealm(XMLExtendedStreamReader reader, List<ModelNode> list) throws XMLStreamException { String realmName = readNameAttribute(reader); ModelNode addRealm = new ModelNode(); addRealm.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD); PathAddress addr = PathAddress.pathAddress(PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, KeycloakExtension.SUBSYSTEM_NAME), PathElement.pathElement(RealmDefinition.TAG_NAME, realmName)); addRealm.get(ModelDescriptionConstants.OP_ADDR).set(addr.toModelNode()); while (reader.hasNext() && nextTag(reader) != END_ELEMENT) { String tagName = reader.getLocalName(); SimpleAttributeDefinition def = RealmDefinition.lookup(tagName); if (def == null) throw new XMLStreamException("Unknown realm tag " + tagName); def.parseAndSetParameter(reader.getElementText(), addRealm, reader); } list.add(addRealm); } private void readDeployment(XMLExtendedStreamReader reader, List<ModelNode> resourcesToAdd) throws XMLStreamException { readSecureResource(KeycloakExtension.SECURE_DEPLOYMENT_DEFINITION.TAG_NAME, KeycloakExtension.SECURE_DEPLOYMENT_DEFINITION, reader, resourcesToAdd); } private void readSecureServer(XMLExtendedStreamReader reader, List<ModelNode> resourcesToAdd) throws XMLStreamException { readSecureResource(KeycloakExtension.SECURE_SERVER_DEFINITION.TAG_NAME, KeycloakExtension.SECURE_SERVER_DEFINITION, reader, resourcesToAdd); } private void readSecureResource(String tagName, AbstractAdapterConfigurationDefinition resource, XMLExtendedStreamReader reader, List<ModelNode> resourcesToAdd) throws XMLStreamException { String name = readNameAttribute(reader); ModelNode addSecureDeployment = new ModelNode(); addSecureDeployment.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD); PathAddress addr = PathAddress.pathAddress(PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, KeycloakExtension.SUBSYSTEM_NAME), PathElement.pathElement(tagName, name)); addSecureDeployment.get(ModelDescriptionConstants.OP_ADDR).set(addr.toModelNode()); List<ModelNode> credentialsToAdd = new ArrayList<ModelNode>(); List<ModelNode> redirectRulesToAdd = new ArrayList<ModelNode>(); while (reader.hasNext() && nextTag(reader) != END_ELEMENT) { String localName = reader.getLocalName(); if (localName.equals(CredentialDefinition.TAG_NAME)) { readCredential(reader, addr, credentialsToAdd); continue; } if (localName.equals(RedirecRewritetRuleDefinition.TAG_NAME)) { readRewriteRule(reader, addr, redirectRulesToAdd); continue; } SimpleAttributeDefinition def = resource.lookup(localName); if (def == null) throw new XMLStreamException("Unknown secure-deployment tag " + localName); def.parseAndSetParameter(reader.getElementText(), addSecureDeployment, reader); } // Must add credentials after the deployment is added. resourcesToAdd.add(addSecureDeployment); resourcesToAdd.addAll(credentialsToAdd); resourcesToAdd.addAll(redirectRulesToAdd); } public void readCredential(XMLExtendedStreamReader reader, PathAddress parent, List<ModelNode> credentialsToAdd) throws XMLStreamException { String name = readNameAttribute(reader); Map<String, String> values = new HashMap<>(); String textValue = null; while (reader.hasNext()) { int next = reader.next(); if (next == CHARACTERS) { // text value of credential element (like for "secret" ) String text = reader.getText(); if (text == null || text.trim().isEmpty()) { continue; } textValue = text; } else if (next == START_ELEMENT) { String key = reader.getLocalName(); reader.next(); String value = reader.getText(); reader.next(); values.put(key, value); } else if (next == END_ELEMENT) { break; } } if (textValue != null) { ModelNode addCredential = getCredentialToAdd(parent, name, textValue); credentialsToAdd.add(addCredential); } else { for (Map.Entry<String, String> entry : values.entrySet()) { ModelNode addCredential = getCredentialToAdd(parent, name + "." + entry.getKey(), entry.getValue()); credentialsToAdd.add(addCredential); } } } public void readRewriteRule(XMLExtendedStreamReader reader, PathAddress parent, List<ModelNode> rewriteRuleToToAdd) throws XMLStreamException { String name = readNameAttribute(reader); Map<String, String> values = new HashMap<>(); String textValue = null; while (reader.hasNext()) { int next = reader.next(); if (next == CHARACTERS) { // text value of redirect rule element String text = reader.getText(); if (text == null || text.trim().isEmpty()) { continue; } textValue = text; } else if (next == START_ELEMENT) { String key = reader.getLocalName(); reader.next(); String value = reader.getText(); reader.next(); values.put(key, value); } else if (next == END_ELEMENT) { break; } } if (textValue != null) { ModelNode addRedirectRule = getRedirectRuleToAdd(parent, name, textValue); rewriteRuleToToAdd.add(addRedirectRule); } else { for (Map.Entry<String, String> entry : values.entrySet()) { ModelNode addRedirectRule = getRedirectRuleToAdd(parent, name + "." + entry.getKey(), entry.getValue()); rewriteRuleToToAdd.add(addRedirectRule); } } } private ModelNode getCredentialToAdd(PathAddress parent, String name, String value) { ModelNode addCredential = new ModelNode(); addCredential.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD); PathAddress addr = PathAddress.pathAddress(parent, PathElement.pathElement(CredentialDefinition.TAG_NAME, name)); addCredential.get(ModelDescriptionConstants.OP_ADDR).set(addr.toModelNode()); addCredential.get(CredentialDefinition.VALUE.getName()).set(value); return addCredential; } private ModelNode getRedirectRuleToAdd(PathAddress parent, String name, String value) { ModelNode addRedirectRule = new ModelNode(); addRedirectRule.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD); PathAddress addr = PathAddress.pathAddress(parent, PathElement.pathElement(RedirecRewritetRuleDefinition.TAG_NAME, name)); addRedirectRule.get(ModelDescriptionConstants.OP_ADDR).set(addr.toModelNode()); addRedirectRule.get(RedirecRewritetRuleDefinition.VALUE.getName()).set(value); return addRedirectRule; } // expects that the current tag will have one single attribute called "name" private String readNameAttribute(XMLExtendedStreamReader reader) throws XMLStreamException { String name = null; for (int i = 0; i < reader.getAttributeCount(); i++) { String attr = reader.getAttributeLocalName(i); if (attr.equals("name")) { name = reader.getAttributeValue(i); continue; } throw ParseUtils.unexpectedAttribute(reader, i); } if (name == null) { throw ParseUtils.missingRequired(reader, Collections.singleton("name")); } return name; } /** * {@inheritDoc} */ @Override public void writeContent(final XMLExtendedStreamWriter writer, final SubsystemMarshallingContext context) throws XMLStreamException { context.startSubsystemElement(KeycloakExtension.CURRENT_NAMESPACE, false); writeRealms(writer, context); writeSecureDeployments(writer, context); writeSecureServers(writer, context); writer.writeEndElement(); } private void writeRealms(XMLExtendedStreamWriter writer, SubsystemMarshallingContext context) throws XMLStreamException { if (!context.getModelNode().get(RealmDefinition.TAG_NAME).isDefined()) { return; } for (Property realm : context.getModelNode().get(RealmDefinition.TAG_NAME).asPropertyList()) { writer.writeStartElement(RealmDefinition.TAG_NAME); writer.writeAttribute("name", realm.getName()); ModelNode realmElements = realm.getValue(); for (AttributeDefinition element : RealmDefinition.ALL_ATTRIBUTES) { element.marshallAsElement(realmElements, writer); } writer.writeEndElement(); } } private void writeSecureDeployments(XMLExtendedStreamWriter writer, SubsystemMarshallingContext context) throws XMLStreamException { writeSecureResource(SecureDeploymentDefinition.TAG_NAME, SecureDeploymentDefinition.ALL_ATTRIBUTES, writer, context); } private void writeSecureServers(XMLExtendedStreamWriter writer, SubsystemMarshallingContext context) throws XMLStreamException { writeSecureResource(SecureServerDefinition.TAG_NAME, SecureServerDefinition.ALL_ATTRIBUTES, writer, context); } private void writeSecureResource(String tagName, List<SimpleAttributeDefinition> attributes, XMLExtendedStreamWriter writer, SubsystemMarshallingContext context) throws XMLStreamException { if (!context.getModelNode().get(tagName).isDefined()) { return; } for (Property deployment : context.getModelNode().get(tagName).asPropertyList()) { writer.writeStartElement(tagName); writer.writeAttribute("name", deployment.getName()); ModelNode deploymentElements = deployment.getValue(); for (AttributeDefinition element : attributes) { element.marshallAsElement(deploymentElements, writer); } ModelNode credentials = deploymentElements.get(CredentialDefinition.TAG_NAME); if (credentials.isDefined()) { writeCredentials(writer, credentials); } ModelNode redirectRewriteRule = deploymentElements.get(RedirecRewritetRuleDefinition.TAG_NAME); if (redirectRewriteRule.isDefined()) { writeRedirectRules(writer, redirectRewriteRule); } writer.writeEndElement(); } } private void writeCredentials(XMLExtendedStreamWriter writer, ModelNode credentials) throws XMLStreamException { Map<String, Object> parsed = new LinkedHashMap<>(); for (Property credential : credentials.asPropertyList()) { String credName = credential.getName(); String credValue = credential.getValue().get(CredentialDefinition.VALUE.getName()).asString(); if (credName.contains(".")) { String[] parts = credName.split("\\."); String provider = parts[0]; String propKey = parts[1]; Map<String, String> currentProviderMap = (Map<String, String>) parsed.get(provider); if (currentProviderMap == null) { currentProviderMap = new LinkedHashMap<>(); parsed.put(provider, currentProviderMap); } currentProviderMap.put(propKey, credValue); } else { parsed.put(credName, credValue); } } for (Map.Entry<String, Object> entry : parsed.entrySet()) { writer.writeStartElement(CredentialDefinition.TAG_NAME); writer.writeAttribute("name", entry.getKey()); Object value = entry.getValue(); if (value instanceof String) { writeCharacters(writer, (String) value); } else { Map<String, String> credentialProps = (Map<String, String>) value; for (Map.Entry<String, String> prop : credentialProps.entrySet()) { writer.writeStartElement(prop.getKey()); writeCharacters(writer, prop.getValue()); writer.writeEndElement(); } } writer.writeEndElement(); } } private void writeRedirectRules(XMLExtendedStreamWriter writer, ModelNode redirectRules) throws XMLStreamException { Map<String, Object> parsed = new LinkedHashMap<>(); for (Property redirectRule : redirectRules.asPropertyList()) { String ruleName = redirectRule.getName(); String ruleValue = redirectRule.getValue().get(RedirecRewritetRuleDefinition.VALUE.getName()).asString(); parsed.put(ruleName, ruleValue); } for (Map.Entry<String, Object> entry : parsed.entrySet()) { writer.writeStartElement(RedirecRewritetRuleDefinition.TAG_NAME); writer.writeAttribute("name", entry.getKey()); Object value = entry.getValue(); if (value instanceof String) { writeCharacters(writer, (String) value); } else { Map<String, String> redirectRulesProps = (Map<String, String>) value; for (Map.Entry<String, String> prop : redirectRulesProps.entrySet()) { writer.writeStartElement(prop.getKey()); writeCharacters(writer, prop.getValue()); writer.writeEndElement(); } } writer.writeEndElement(); } } // code taken from org.jboss.as.controller.AttributeMarshaller private void writeCharacters(XMLExtendedStreamWriter writer, String content) throws XMLStreamException { if (content.indexOf('\n') > -1) { // Multiline content. Use the overloaded variant that staxmapper will format writer.writeCharacters(content); } else { // Staxmapper will just output the chars without adding newlines if this is used char[] chars = content.toCharArray(); writer.writeCharacters(chars, 0, chars.length); } } }
17,771
44.922481
193
java
null
wildfly-main/legacy/keycloak/src/main/java/org/keycloak/subsystem/adapter/logging/KeycloakLogger.java
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other 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.keycloak.subsystem.adapter.logging; import org.jboss.as.controller.OperationFailedException; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * This interface to be fleshed out later when error messages are fully externalized. * * @author Stan Silvert [email protected] (C) 2013 Red Hat Inc. */ @MessageLogger(projectCode = "KEYCLOAK") public interface KeycloakLogger extends BasicLogger { /** * A logger with a category of the package name. */ KeycloakLogger ROOT_LOGGER = Logger.getMessageLogger(KeycloakLogger.class, "org.jboss.keycloak"); //@LogMessage(level = INFO) //@Message(value = "Keycloak subsystem override for deployment %s") //void deploymentSecured(String deployment); @Message(id = 1, value = "The migrate operation can not be performed: the server must be in admin-only mode") OperationFailedException migrateOperationAllowedOnlyInAdminOnly(); @Message(id = 2, value = "Migration failed, see results for more details.") String migrationFailed(); }
1,835
36.469388
113
java
null
wildfly-main/legacy/jsr77/src/test/java/org/jboss/as/jsr77/subsystem/JSR77ManagementSubsystemTestCase.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.jsr77.subsystem; import java.io.IOException; import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest; import org.jboss.as.subsystem.test.AdditionalInitialization; /** * @author <a href="[email protected]">Kabir Khan</a> */ public class JSR77ManagementSubsystemTestCase extends AbstractSubsystemBaseTest { public JSR77ManagementSubsystemTestCase() { super(JSR77ManagementExtension.SUBSYSTEM_NAME, new JSR77ManagementExtension()); } @Override protected String getSubsystemXml() throws IOException { return "<subsystem xmlns=\"urn:jboss:domain:jsr77:1.0\"/>"; } @Override protected String getSubsystemXsdPath() throws Exception { return "schema/jboss-as-jsr77_1_0.xsd"; } @Override protected AdditionalInitialization createAdditionalInitialization() { return AdditionalInitialization.ADMIN_ONLY_HC; } }
1,926
35.358491
87
java
null
wildfly-main/legacy/jsr77/src/main/java/org/jboss/as/jsr77/subsystem/JSR77ManagementRootResource.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.jsr77.subsystem; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.ModelOnlyAddStepHandler; import org.jboss.as.controller.ModelOnlyRemoveStepHandler; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import java.util.Collection; import java.util.Collections; /** * @author <a href="[email protected]">Kabir Khan</a> */ public class JSR77ManagementRootResource extends PersistentResourceDefinition { JSR77ManagementRootResource() { super(new SimpleResourceDefinition.Parameters( PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, JSR77ManagementExtension.SUBSYSTEM_NAME), JSR77ManagementExtension.getResourceDescriptionResolver(JSR77ManagementExtension.SUBSYSTEM_NAME) ) .setAddHandler(new ModelOnlyAddStepHandler()) .setRemoveHandler(ModelOnlyRemoveStepHandler.INSTANCE) .setDeprecatedSince(JSR77ManagementExtension.CURRENT_MODEL_VERSION) ); } @Override public Collection<AttributeDefinition> getAttributes() { return Collections.emptyList(); } }
2,367
39.827586
122
java
null
wildfly-main/legacy/jsr77/src/main/java/org/jboss/as/jsr77/subsystem/JSR77ManagementExtension.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.jsr77.subsystem; import java.util.Collections; import java.util.Set; import org.jboss.as.controller.ExtensionContext; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.PersistentResourceXMLDescription; import org.jboss.as.controller.PersistentResourceXMLParser; import org.jboss.as.controller.SubsystemRegistration; import org.jboss.as.controller.descriptions.ResourceDescriptionResolver; import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver; import org.jboss.as.controller.extension.AbstractLegacyExtension; import org.jboss.as.controller.parsing.ExtensionParsingContext; import org.jboss.as.controller.registry.ManagementResourceRegistration; /** * * @author <a href="[email protected]">Kabir Khan</a> */ public class JSR77ManagementExtension extends AbstractLegacyExtension { public static final String NAMESPACE = "urn:jboss:domain:jsr77:1.0"; public static final String SUBSYSTEM_NAME = "jsr77"; private static final String RESOURCE_NAME = JSR77ManagementExtension.class.getPackage().getName() + ".LocalDescriptions"; static final ModelVersion CURRENT_MODEL_VERSION = ModelVersion.create(1, 0, 0); static ResourceDescriptionResolver getResourceDescriptionResolver(final String keyPrefix) { return new StandardResourceDescriptionResolver(keyPrefix, RESOURCE_NAME, JSR77ManagementExtension.class.getClassLoader(), true, true); } private final J2EEManagementSubsystemParser parser = new J2EEManagementSubsystemParser(); public JSR77ManagementExtension() { super("org.jboss.as.jsr77", SUBSYSTEM_NAME); } /** * {@inheritDoc} */ @Override protected Set<ManagementResourceRegistration> initializeLegacyModel(ExtensionContext context) { final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION); // Register the root subsystem resource. final ManagementResourceRegistration rootResource = subsystem.registerSubsystemModel(new JSR77ManagementRootResource()); subsystem.registerXMLElementWriter(parser); return Collections.singleton(rootResource); } /** {@inheritDoc} */ @Override protected void initializeLegacyParsers(ExtensionParsingContext context) { context.setSubsystemXmlMapping(SUBSYSTEM_NAME, NAMESPACE, () -> parser); } static class J2EEManagementSubsystemParser extends PersistentResourceXMLParser { private static PersistentResourceXMLDescription xmlDescription; static { xmlDescription = PersistentResourceXMLDescription.builder(new JSR77ManagementRootResource().getPathElement(), JSR77ManagementExtension.NAMESPACE) .build(); } @Override public PersistentResourceXMLDescription getParserDescription() { return xmlDescription; } } }
3,939
40.041667
157
java
null
wildfly-main/connector/src/test/java/org/jboss/as/connector/annotations/repository/jandex/AnnotationsTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008-2009, 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.connector.annotations.repository.jandex; import org.jboss.jca.common.annotations.Annotations; import org.jboss.jca.common.api.validator.ValidateException; import org.jboss.jca.common.spi.annotations.repository.Annotation; import org.jboss.jca.common.spi.annotations.repository.AnnotationRepository; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.nio.file.Paths; import java.util.Collection; import java.util.List; import org.jboss.jandex.Index; import org.jboss.jandex.Indexer; import org.jboss.vfs.VFS; import org.jboss.vfs.VFSUtils; import org.jboss.vfs.VirtualFile; import org.jboss.vfs.VisitorAttributes; import org.jboss.vfs.util.SuffixMatchFilter; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import com.google.common.io.Files; import com.google.common.io.MoreFiles; import com.google.common.io.RecursiveDeleteOption; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; /** * Test cases for the annotations handling * * @author <a href="mailto:[email protected]">Jesper Pedersen</a> * @author <a href="mailto:[email protected]">Jeff Zhang</a> */ public class AnnotationsTestCase { /** * Annotations */ private Annotations annotations; private static final String MULTIANNO_TARGET = "./target/test-classes/ra16inoutmultianno.rar"; @Before public void setup() throws IOException { Files.createParentDirs( new File(MULTIANNO_TARGET + "/org/jboss/as/connector/deployers/spec/rars/ra16inoutmultianno/sample.file")); annotations = new Annotations(); } @After public void tearDown() throws IOException { MoreFiles.deleteRecursively(Paths.get(MULTIANNO_TARGET, "org"), RecursiveDeleteOption.ALLOW_INSECURE); annotations = null; } /** * Process: Null arguemnt for annotation repository * * @throws Throwable throwable exception */ @Test(expected = ValidateException.class) public void testProcessNullAnnotationRepository() throws Throwable { annotations.process(null, null, null); } /** * Process: Connector -- verification of the processConnector method * * @throws Throwable throwable exception */ @Test public void testProcessConnector() throws Throwable { // Test prep File srcRars = new File("./target/test-classes/org/jboss/as/connector/deployers/spec/rars"); File srcRa16 = new File("./target/test-classes/org/jboss/as/connector/deployers/spec/rars/ra16inoutmultianno"); final String destRars = MULTIANNO_TARGET + "/org/jboss/as/connector/deployers/spec/rars"; final String destRa16 = MULTIANNO_TARGET + "/org/jboss/as/connector/deployers/spec/rars/ra16inoutmultianno"; for (File srcFile : srcRars.listFiles()) { if (!srcFile.isDirectory()) { Files.copy(srcFile, new File(destRars + "/" + srcFile.getName())); } } for (File srcFile : srcRa16.listFiles()) { if (!srcFile.isDirectory()) { Files.copy(srcFile, new File(destRa16 + "/" + srcFile.getName())); } } URI uri = getURI("/ra16inoutmultianno.rar"); final VirtualFile virtualFile = VFS.getChild(uri); final Indexer indexer = new Indexer(); final List<VirtualFile> classChildren = virtualFile .getChildren(new SuffixMatchFilter(".class", VisitorAttributes.RECURSE_LEAVES_ONLY)); for (VirtualFile classFile : classChildren) { System.out.println("testProcessConnector: adding " + classFile.getPathName()); InputStream inputStream = null; try { inputStream = classFile.openStream(); indexer.index(inputStream); } finally { VFSUtils.safeClose(inputStream); } } final Index index = indexer.complete(); AnnotationRepository ar = new JandexAnnotationRepositoryImpl(index, Thread.currentThread().getContextClassLoader()); Collection<Annotation> values = ar.getAnnotation(jakarta.resource.spi.Connector.class); assertNotNull(values); assertEquals(1, values.size()); // Test run try { annotations.process(ar, null, Thread.currentThread().getContextClassLoader()); } catch (Throwable t) { t.printStackTrace(); fail(t.getMessage()); } } /** * Process: Connector -- verification of the processConnector method * * @throws Throwable throwable exception */ @Test(expected = ValidateException.class) public void testProcessConnectorFailTooManyConnectors() throws Throwable { // Test prep AnnotationRepository ar = null; try { File srcRars = new File("./target/test-classes/org/jboss/as/connector/deployers/spec/rars"); File srcRa16 = new File("./target/test-classes/org/jboss/as/connector/deployers/spec/rars/ra16inoutmultianno"); File srcStandalone = new File("./target/test-classes/org/jboss/as/connector/deployers/spec/rars/rastandalone"); final String destRars = MULTIANNO_TARGET + "/org/jboss/as/connector/deployers/spec/rars"; final String destRa16 = MULTIANNO_TARGET + "/org/jboss/as/connector/deployers/spec/rars/ra16inoutmultianno"; final String destStandalone = MULTIANNO_TARGET + "/org/jboss/as/connector/deployers/spec/rars/rastandalone"; Files.createParentDirs(new File(destStandalone + "/sample.file")); for (File srcFile : srcRars.listFiles()) { if (!srcFile.isDirectory()) { Files.copy(srcFile, new File(destRars + "/" + srcFile.getName())); } } for (File srcFile : srcRa16.listFiles()) { if (!srcFile.isDirectory()) { Files.copy(srcFile, new File(destRa16 + "/" + srcFile.getName())); } } for (File srcFile : srcStandalone.listFiles()) { if (!srcFile.isDirectory()) { Files.copy(srcFile, new File(destStandalone + "/" + srcFile.getName())); } } URI uri = getURI("/ra16inoutmultianno.rar"); final VirtualFile virtualFile = VFS.getChild(uri); final Indexer indexer = new Indexer(); final List<VirtualFile> classChildren = virtualFile .getChildren(new SuffixMatchFilter(".class", VisitorAttributes.RECURSE_LEAVES_ONLY)); for (VirtualFile classFile : classChildren) { System.out.println("testProcessConnectorFailTooManyConnectors: adding " + classFile.getPathName()); InputStream inputStream = null; try { inputStream = classFile.openStream(); indexer.index(inputStream); } finally { VFSUtils.safeClose(inputStream); } } final Index index = indexer.complete(); ar = new JandexAnnotationRepositoryImpl(index, Thread.currentThread().getContextClassLoader()); } catch (Throwable e) { e.printStackTrace(); fail("Test preparation error " + e.getMessage()); } Collection<Annotation> values = ar.getAnnotation(jakarta.resource.spi.Connector.class); assertNotNull(values); assertEquals(2, values.size()); // Test run annotations.process(ar, null, Thread.currentThread().getContextClassLoader()); } /** * Process: Connector -- verification of the processConnector method * * @throws Throwable throwable exception */ @Ignore("JBJCA-1435: The current validation in IronJacamar is not correct, the testcase here is.") @Test(expected = ValidateException.class) public void testProcessConnectorFailNoConnector() throws Throwable { // Test prep AnnotationRepository ar = null; try { File srcRars = new File("./target/test-classes/org/jboss/as/connector/deployers/spec/rars"); File srcRa16 = new File("./target/test-classes/org/jboss/as/connector/deployers/spec/rars/ra16inoutmultianno"); final String destRars = MULTIANNO_TARGET + "/org/jboss/as/connector/deployers/spec/rars"; final String destRa16 = MULTIANNO_TARGET + "/org/jboss/as/connector/deployers/spec/rars/ra16inoutmultianno"; for (File srcFile : srcRars.listFiles()) { if (!srcFile.isDirectory() && !"BaseResourceAdapter.class".equals(srcFile.getName())) { Files.copy(srcFile, new File(destRars + "/" + srcFile.getName())); } } for (File srcFile : srcRa16.listFiles()) { if (!srcFile.isDirectory() && !"TestResourceAdapter.class".equals(srcFile.getName())) { Files.copy(srcFile, new File(destRa16 + "/" + srcFile.getName())); } } URI uri = getURI("/ra16inoutmultianno.rar"); final VirtualFile virtualFile = VFS.getChild(uri); final Indexer indexer = new Indexer(); final List<VirtualFile> classChildren = virtualFile .getChildren(new SuffixMatchFilter(".class", VisitorAttributes.RECURSE_LEAVES_ONLY)); for (VirtualFile classFile : classChildren) { System.out.println("testProcessConnectorFailNoConnector: adding " + classFile.getPathName()); InputStream inputStream = null; try { inputStream = classFile.openStream(); indexer.index(inputStream); } finally { VFSUtils.safeClose(inputStream); } } final Index index = indexer.complete(); ar = new JandexAnnotationRepositoryImpl(index, Thread.currentThread().getContextClassLoader()); } catch (Throwable e) { e.printStackTrace(); fail("Test preparation error " + e.getMessage()); } Collection<Annotation> values = ar.getAnnotation(jakarta.resource.spi.Connector.class); assertNull(values); // Test run annotations.process(ar, null, Thread.currentThread().getContextClassLoader()); } /** * Process: Connector -- verification of the processConnector method * * @throws Throwable throwable exception */ public void testProcessConnectorManualSpecConnector() throws Throwable { // Test prep AnnotationRepository ar = null; try { File srcRars = new File("./target/test-classes/org/jboss/as/connector/deployers/spec/rars"); File srcRa16 = new File("./target/test-classes/org/jboss/as/connector/deployers/spec/rars/ra16inoutmultianno"); final String destRars = MULTIANNO_TARGET + "/org/jboss/as/connector/deployers/spec/rars"; final String destRa16 = MULTIANNO_TARGET + "/org/jboss/as/connector/deployers/spec/rars/ra16inoutmultianno"; for (File srcFile : srcRars.listFiles()) { if (!srcFile.isDirectory()) { Files.copy(srcFile, new File(destRars + "/" + srcFile.getName())); } } for (File srcFile : srcRa16.listFiles()) { if (!srcFile.isDirectory() && !"TestResourceAdapter.class".equals(srcFile.getName())) { Files.copy(srcFile, new File(destRa16 + "/" + srcFile.getName())); } } URI uri = getURI("/ra16inoutmultianno.rar"); final VirtualFile virtualFile = VFS.getChild(uri); final Indexer indexer = new Indexer(); final List<VirtualFile> classChildren = virtualFile .getChildren(new SuffixMatchFilter(".class", VisitorAttributes.RECURSE_LEAVES_ONLY)); for (VirtualFile classFile : classChildren) { System.out.println("testProcessConnectorFailNoConnector: adding " + classFile.getPathName()); InputStream inputStream = null; try { inputStream = classFile.openStream(); indexer.index(inputStream); } finally { VFSUtils.safeClose(inputStream); } } final Index index = indexer.complete(); ar = new JandexAnnotationRepositoryImpl(index, Thread.currentThread().getContextClassLoader()); } catch (Throwable e) { e.printStackTrace(); fail("Test preparation error " + e.getMessage()); } Collection<Annotation> values = ar.getAnnotation(jakarta.resource.spi.Connector.class); assertNull(values); // Test run annotations.process(ar, "org.jboss.as.connector.deployers.spec.rars.BaseResourceAdapter", Thread.currentThread().getContextClassLoader()); } /** * Get the URL for a test archive * * @param archive The name of the test archive * @return The URL to the archive * @throws Throwable throwable exception */ public URI getURI(String archive) throws Throwable { return this.getClass().getResource(archive).toURI(); } }
14,625
43.321212
146
java
null
wildfly-main/connector/src/test/java/org/jboss/as/connector/deployers/spec/rars/BaseActivationSpec.java
/* * IronJacamar, a Java EE Connector Architecture implementation * Copyright 2009, Red Hat Inc, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * 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.connector.deployers.spec.rars; import jakarta.resource.ResourceException; import jakarta.resource.spi.ActivationSpec; import jakarta.resource.spi.InvalidPropertyException; import jakarta.resource.spi.ResourceAdapter; import org.jboss.logging.Logger; /** * BaseActivationSpec * * @author <a href="mailto:[email protected]">Jeff Zhang</a> */ public class BaseActivationSpec implements ActivationSpec { private static Logger log = Logger.getLogger(BaseActivationSpec.class); /** * This method may be called by a deployment tool to validate the overall activation configuration information provided by * the endpoint deployer. * * @throws InvalidPropertyException indicates invalid configuration property settings. */ @SuppressWarnings(value = { "deprecation" }) public void validate() throws InvalidPropertyException { log.debug("call validate"); } /** * Get the associated <code>ResourceAdapter</code> object. * * @return the associated <code>ResourceAdapter</code> object. */ public ResourceAdapter getResourceAdapter() { log.debug("call getResourceAdapter"); return null; } /** * Associate this object with a <code>ResourceAdapter</code> object. * * @param ra <code>ResourceAdapter</code> object to be associated with. * * @throws ResourceException generic exception. */ public void setResourceAdapter(ResourceAdapter ra) throws ResourceException { log.debug("call setResourceAdapter"); } }
2,627
34.04
126
java
null
wildfly-main/connector/src/test/java/org/jboss/as/connector/deployers/spec/rars/BaseCciConnection.java
/* * IronJacamar, a Java EE Connector Architecture implementation * Copyright 2009, Red Hat Inc, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * 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.connector.deployers.spec.rars; import jakarta.resource.ResourceException; import jakarta.resource.cci.Connection; import jakarta.resource.cci.ConnectionMetaData; import jakarta.resource.cci.Interaction; import jakarta.resource.cci.LocalTransaction; import jakarta.resource.cci.ResultSetInfo; /** * BaseCciConnection * * @author <a href="mailto:[email protected]">Jeff Zhang</a>. * @version $Revision: $ */ public class BaseCciConnection implements Connection { /* * close * * @see jakarta.resource.cci.Connection#close() */ @Override public void close() throws ResourceException { } /* * createInteraction * * @see jakarta.resource.cci.Connection#createInteraction() */ @Override public Interaction createInteraction() throws ResourceException { return null; } /* * getLocalTransaction * * @see jakarta.resource.cci.Connection#getLocalTransaction() */ @Override public LocalTransaction getLocalTransaction() throws ResourceException { return null; } /* * getMetaData * * @see jakarta.resource.cci.Connection#getMetaData() */ @Override public ConnectionMetaData getMetaData() throws ResourceException { return null; } /* * getResultSetInfo * * @see jakarta.resource.cci.Connection#getResultSetInfo() */ @Override public ResultSetInfo getResultSetInfo() throws ResourceException { return null; } }
2,593
27.822222
76
java
null
wildfly-main/connector/src/test/java/org/jboss/as/connector/deployers/spec/rars/BaseReference.java
/* * IronJacamar, a Java EE Connector Architecture implementation * Copyright 2009, Red Hat Inc, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * 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.connector.deployers.spec.rars; import javax.naming.Reference; /** * BaseReference * * @author <a href="mailto:[email protected]">Jeff Zhang</a>. */ public class BaseReference extends Reference { /** * serialVersionUID */ private static final long serialVersionUID = 1L; /** * Contains the fully-qualified name of the class of the object to which this Reference refers. * * @param className class name * @see java.lang.Class#getName */ public BaseReference(String className) { super(className); } }
1,641
32.510204
99
java
null
wildfly-main/connector/src/test/java/org/jboss/as/connector/deployers/spec/rars/BaseConnectionManager.java
/* * IronJacamar, a Java EE Connector Architecture implementation * Copyright 2010, Red Hat Inc, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.connector.deployers.spec.rars; import jakarta.resource.ResourceException; import jakarta.resource.spi.ConnectionManager; import jakarta.resource.spi.ConnectionRequestInfo; import jakarta.resource.spi.ManagedConnectionFactory; import org.jboss.logging.Logger; /** * BaseConnectionManager * * @author <a href="mailto:[email protected]">Jesper Pedersen</a>. * @version $Revision: $ */ public class BaseConnectionManager implements ConnectionManager { private static final long serialVersionUID = 1L; private static Logger log = Logger.getLogger(BaseConnectionManager.class); /** * Constructor */ public BaseConnectionManager() { } /** * Allocate a connection * * @param mcf The managed connection factory * @param cri The connection request information * @return The connection * @exception ResourceException Thrown if an error occurs */ public Object allocateConnection(ManagedConnectionFactory mcf, ConnectionRequestInfo cri) throws ResourceException { log.trace("allocateConnection " + mcf + " " + cri); return null; } }
2,200
35.683333
120
java
null
wildfly-main/connector/src/test/java/org/jboss/as/connector/deployers/spec/rars/BaseManagedConnectionFactory.java
/* * IronJacamar, a Java EE Connector Architecture implementation * Copyright 2009, Red Hat Inc, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * 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.connector.deployers.spec.rars; import java.io.PrintWriter; import java.util.Set; import jakarta.resource.ResourceException; import jakarta.resource.spi.ConnectionManager; import jakarta.resource.spi.ConnectionRequestInfo; import jakarta.resource.spi.ManagedConnection; import jakarta.resource.spi.ManagedConnectionFactory; import jakarta.resource.spi.ResourceAdapter; import jakarta.resource.spi.ResourceAdapterAssociation; import javax.security.auth.Subject; import org.jboss.logging.Logger; /** * BaseManagedConnectionFactory * * @author <a href="mailto:[email protected]">Jeff Zhang</a>. */ public class BaseManagedConnectionFactory implements ManagedConnectionFactory, ResourceAdapterAssociation { private static final long serialVersionUID = 1L; private static Logger log = Logger.getLogger(BaseManagedConnectionFactory.class); private ResourceAdapter ra; private PrintWriter logwriter; /** * Constructor */ public BaseManagedConnectionFactory() { ra = null; logwriter = null; } /** * Creates a Connection Factory instance. * * @param cxManager ConnectionManager to be associated with created EIS connection factory instance * @return EIS-specific Connection Factory instance or jakarta.resource.cci.ConnectionFactory instance * @throws ResourceException Generic exception */ public Object createConnectionFactory(ConnectionManager cxManager) throws ResourceException { if (ra == null) throw new IllegalStateException("RA is null"); log.debug("call createConnectionFactory"); return new BaseCciConnectionFactory(); } /** * Creates a Connection Factory instance. * * @return EIS-specific Connection Factory instance or jakarta.resource.cci.ConnectionFactory instance * @throws ResourceException Generic exception */ public Object createConnectionFactory() throws ResourceException { if (ra == null) throw new IllegalStateException("RA is null"); log.debug("call createConnectionFactory"); return createConnectionFactory(new BaseConnectionManager()); } /** * Creates a new physical connection to the underlying EIS resource manager. * * @param subject Caller's security information * @param cxRequestInfo Additional resource adapter specific connection request information * @throws ResourceException generic exception * @return ManagedConnection instance */ public ManagedConnection createManagedConnection(Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException { if (ra == null) throw new IllegalStateException("RA is null"); log.debug("call createManagedConnection"); return null; } /** * Returns a matched connection from the candidate set of connections. * * @param connectionSet candidate connection set * @param subject caller's security information * @param cxRequestInfo additional resource adapter specific connection request information * * @throws ResourceException generic exception * @return ManagedConnection if resource adapter finds an acceptable match otherwise null **/ public ManagedConnection matchManagedConnections(Set connectionSet, Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException { if (ra == null) throw new IllegalStateException("RA is null"); log.debug("call matchManagedConnections"); return null; } /** * Get the log writer for this ManagedConnectionFactory instance. * * @return PrintWriter * @throws ResourceException generic exception */ public PrintWriter getLogWriter() throws ResourceException { log.debug("call getLogWriter"); return logwriter; } /** * Set the log writer for this ManagedConnectionFactory instance. * </p> * * @param out PrintWriter - an out stream for error logging and tracing * @throws ResourceException generic exception */ public void setLogWriter(PrintWriter out) throws ResourceException { log.debug("call setLogWriter"); logwriter = out; } /** * Get the resource adapter * * @return The handle */ public ResourceAdapter getResourceAdapter() { log.debug("call getResourceAdapter"); return ra; } /** * Set the resource adapter * * @param ra The handle */ public void setResourceAdapter(ResourceAdapter ra) { log.debugf("call setResourceAdapter(%s)", ra); this.ra = ra; } /** * Hash code * * @return The hash */ @Override public int hashCode() { return 42; } /** * Equals * * @param other The other object * @return True if equal; otherwise false */ public boolean equals(Object other) { if (other == null) return false; return getClass().equals(other.getClass()); } }
6,202
31.820106
125
java
null
wildfly-main/connector/src/test/java/org/jboss/as/connector/deployers/spec/rars/TestConnectionInterface.java
/* * IronJacamar, a Java EE Connector Architecture implementation * Copyright 2009, Red Hat Inc, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * 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.connector.deployers.spec.rars; /** * TestConnectionInterface * * @author <a href="mailto:[email protected]">Jeff Zhang</a> */ public interface TestConnectionInterface { /** * CallMe **/ public void callMe(); }
1,306
34.324324
70
java
null
wildfly-main/connector/src/test/java/org/jboss/as/connector/deployers/spec/rars/BaseCciConnectionFactory.java
/* * IronJacamar, a Java EE Connector Architecture implementation * Copyright 2009, Red Hat Inc, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * 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.connector.deployers.spec.rars; import javax.naming.NamingException; import javax.naming.Reference; import jakarta.resource.ResourceException; import jakarta.resource.cci.Connection; import jakarta.resource.cci.ConnectionFactory; import jakarta.resource.cci.ConnectionSpec; import jakarta.resource.cci.RecordFactory; import jakarta.resource.cci.ResourceAdapterMetaData; import jakarta.resource.spi.ManagedConnectionFactory; /** * BaseCciConnectionFactory * * @author <a href="mailto:[email protected]">Jeff Zhang</a>. */ public class BaseCciConnectionFactory implements ConnectionFactory { /** * serialVersionUID */ private static final long serialVersionUID = 1L; /** * Reference */ private Reference reference; /** * ManagedConnectionFactory */ private ManagedConnectionFactory mcf; /** * * Create a new BaseCciConnectionFactory. * * @param cf ManagedConnectionFactory, which creates this */ public BaseCciConnectionFactory(ManagedConnectionFactory cf) { mcf = cf; } /** * * Create a new BaseCciConnectionFactory. * */ public BaseCciConnectionFactory() { mcf = null; } /** * * get ManagedConnectionFactory * * @return ManagedConnectionFactory */ public ManagedConnectionFactory getMcf() { return mcf; } /* * getConnection * * @see jakarta.resource.cci.ConnectionFactory#getConnection() */ @Override public Connection getConnection() throws ResourceException { return new BaseCciConnection(); } /* * getConnection * * @see jakarta.resource.cci.ConnectionFactory#getConnection(jakarta.resource.cci.ConnectionSpec) */ @Override public Connection getConnection(ConnectionSpec properties) throws ResourceException { return new BaseCciConnection(); } /* * getMetaData * * @see jakarta.resource.cci.ConnectionFactory#getMetaData() */ @Override public ResourceAdapterMetaData getMetaData() throws ResourceException { return null; } /* * getRecordFactory * * @see jakarta.resource.cci.ConnectionFactory#getRecordFactory() */ @Override public RecordFactory getRecordFactory() throws ResourceException { return null; } /* * getReference * * @see javax.naming.Referenceable#getReference() */ @Override public Reference getReference() throws NamingException { if (reference == null) reference = new BaseReference(this.getClass().getName()); return reference; } /* * setReference * * @see jakarta.resource.Referenceable#setReference(javax.naming.Reference) */ @Override public void setReference(Reference reference) { this.reference = reference; } }
3,995
26
101
java
null
wildfly-main/connector/src/test/java/org/jboss/as/connector/deployers/spec/rars/BaseResourceAdapter.java
/* * IronJacamar, a Java EE Connector Architecture implementation * Copyright 2009, Red Hat Inc, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * 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.connector.deployers.spec.rars; import jakarta.resource.ResourceException; import jakarta.resource.spi.ActivationSpec; import jakarta.resource.spi.BootstrapContext; import jakarta.resource.spi.ResourceAdapter; import jakarta.resource.spi.ResourceAdapterInternalException; import jakarta.resource.spi.endpoint.MessageEndpointFactory; import javax.transaction.xa.XAResource; import org.jboss.logging.Logger; /** * BaseResourceAdapter * * @author <a href="mailto:[email protected]">Jeff Zhang</a>. * @version $Revision: $ */ public class BaseResourceAdapter implements ResourceAdapter { private static Logger log = Logger.getLogger(BaseResourceAdapter.class); /** * This is called during the activation of a message endpoint. * * @param endpointFactory a message endpoint factory instance. * @param spec an activation spec JavaBean instance. * @throws ResourceException generic exception */ public void endpointActivation(MessageEndpointFactory endpointFactory, ActivationSpec spec) throws ResourceException { log.debug("call endpointActivation"); } /** * This is called when a message endpoint is deactivated. * * @param endpointFactory a message endpoint factory instance. * @param spec an activation spec JavaBean instance. */ public void endpointDeactivation(MessageEndpointFactory endpointFactory, ActivationSpec spec) { log.debug("call endpointDeactivation"); } /** * This method is called by the application server during crash recovery. * * @param specs an array of ActivationSpec JavaBeans * @throws ResourceException generic exception * @return an array of XAResource objects */ public XAResource[] getXAResources(ActivationSpec[] specs) throws ResourceException { log.debug("call getXAResources"); return null; } /** * This is called when a resource adapter instance is bootstrapped. * * @param ctx a bootstrap context containing references * @throws ResourceAdapterInternalException indicates bootstrap failure. */ public void start(BootstrapContext ctx) throws ResourceAdapterInternalException { log.debug("call start"); } /** * This is called when a resource adapter instance is undeployed or during application server shutdown. */ public void stop() { log.debug("call stop"); } /** * Hash code * * @return The hash */ @Override public int hashCode() { return super.hashCode(); } /** * Equals * * @param other The other object * @return True if equal; otherwise false */ public boolean equals(Object other) { return super.equals(other); } }
3,862
32.017094
122
java
null
wildfly-main/connector/src/test/java/org/jboss/as/connector/deployers/spec/rars/TestConnection.java
/* * IronJacamar, a Java EE Connector Architecture implementation * Copyright 2009, Red Hat Inc, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * 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.connector.deployers.spec.rars; import org.jboss.logging.Logger; /** * TestConnection * * @author <a href="mailto:[email protected]">Jeff Zhang</a> */ public class TestConnection implements TestConnectionInterface { private static Logger log = Logger.getLogger(TestConnection.class); /** * CallMe **/ public void callMe() { log.debug("call callMe"); } }
1,467
33.139535
71
java
null
wildfly-main/connector/src/test/java/org/jboss/as/connector/deployers/spec/rars/MessageListener.java
/* * IronJacamar, a Java EE Connector Architecture implementation * Copyright 2009, Red Hat Inc, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * 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.connector.deployers.spec.rars; /** * MessageListener * * @author <a href="mailto:[email protected]">Jeff Zhang</a> */ public interface MessageListener { /** * receive message * * @param msg String. */ public void onMessage(String msg); }
1,342
35.297297
70
java
null
wildfly-main/connector/src/test/java/org/jboss/as/connector/deployers/spec/rars/BaseManagedConnection.java
/* * IronJacamar, a Java EE Connector Architecture implementation * Copyright 2009, Red Hat Inc, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * 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.connector.deployers.spec.rars; import java.io.PrintWriter; import jakarta.resource.ResourceException; import jakarta.resource.spi.ConnectionEventListener; import jakarta.resource.spi.ConnectionRequestInfo; import jakarta.resource.spi.LocalTransaction; import jakarta.resource.spi.ManagedConnection; import jakarta.resource.spi.ManagedConnectionMetaData; import javax.security.auth.Subject; import javax.transaction.xa.XAResource; import org.jboss.logging.Logger; /** * BaseManagedConnection. * * @author <a href="mailto:[email protected]">Jeff Zhang</a> */ public class BaseManagedConnection implements ManagedConnection { private static Logger log = Logger.getLogger(BaseManagedConnection.class); /** * Adds a connection event listener to the ManagedConnection instance. * * @param listener a new ConnectionEventListener to be registered **/ public void addConnectionEventListener(ConnectionEventListener listener) { log.debug("call addConnectionEventListener"); } /** * Used by the container to change the association of an application-level connection handle with a ManagedConneciton * instance. * * @param connection Application-level connection handle * * @throws ResourceException Failed to associate the connection handle with this ManagedConnection instance **/ public void associateConnection(Object connection) throws ResourceException { log.debug("call associateConnection"); } /** * Application server calls this method to force any cleanup on the ManagedConnection instance. * * @throws ResourceException generic exception if operation fails **/ public void cleanup() throws ResourceException { log.debug("call cleanup"); } /** * Destroys the physical connection to the underlying resource manager. * * @throws ResourceException generic exception if operation failed **/ public void destroy() throws ResourceException { log.debug("call destroy"); } /** * Creates a new connection handle for the underlying physical connection represented by the ManagedConnection instance. * * @param subject security context as JAAS subject * @param cxRequestInfo ConnectionRequestInfo instance * @return generic Object instance representing the connection handle. * @throws ResourceException generic exception if operation fails * **/ public Object getConnection(Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException { log.debug("call getConnection"); return null; } /** * Returns an <code>jakarta.resource.spi.LocalTransaction</code> instance. * * @return LocalTransaction instance * * @throws ResourceException generic exception if operation fails **/ public LocalTransaction getLocalTransaction() throws ResourceException { log.debug("call getLocalTransaction"); return null; } /** * Gets the log writer for this ManagedConnection instance. * * @return Character ourput stream associated with this Managed- Connection instance * * @throws ResourceException generic exception if operation fails **/ public PrintWriter getLogWriter() throws ResourceException { log.debug("call getLogWriter"); return null; } /** * <p> * Gets the metadata information for this connection's underlying EIS resource manager instance. * * @return ManagedConnectionMetaData instance * * @throws ResourceException generic exception if operation fails **/ public ManagedConnectionMetaData getMetaData() throws ResourceException { log.debug("call destroy"); return null; } /** * Returns an <code>javax.transaction.xa.XAresource</code> instance. * * @return XAResource instance * * @throws ResourceException generic exception if operation fails **/ public XAResource getXAResource() throws ResourceException { log.debug("call getXAResource"); return null; } /** * Removes an already registered connection event listener from the ManagedConnection instance. * * @param listener already registered connection event listener to be removed **/ public void removeConnectionEventListener(ConnectionEventListener listener) { log.debug("call removeConnectionEventListener"); } /** * Sets the log writer for this ManagedConnection instance. * * @param out Character Output stream to be associated * * @throws ResourceException generic exception if operation fails **/ public void setLogWriter(PrintWriter out) throws ResourceException { log.debug("call setLogWriter"); } }
5,933
33.103448
124
java
null
wildfly-main/connector/src/test/java/org/jboss/as/connector/deployers/spec/rars/rastandalone/Test2ResourceAdapter.java
/* * IronJacamar, a Java EE Connector Architecture implementation * Copyright 2009, Red Hat Inc, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * 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.connector.deployers.spec.rars.rastandalone; import org.jboss.as.connector.deployers.spec.rars.BaseResourceAdapter; import org.jboss.as.connector.deployers.spec.rars.ra16inoutmultianno.TestAdminObjectInterface; import jakarta.resource.spi.AdministeredObject; import jakarta.resource.spi.AuthenticationMechanism; import jakarta.resource.spi.AuthenticationMechanism.CredentialInterface; import jakarta.resource.spi.ConfigProperty; import jakarta.resource.spi.Connector; import jakarta.resource.spi.SecurityPermission; import jakarta.resource.spi.TransactionSupport; /** * Test2ResourceAdapter * * @author <a href="mailto:[email protected]">Jeff Zhang</a> */ @Connector(description = { "Test RA" }, displayName = { "displayName" }, smallIcon = { "smallIcon" }, largeIcon = { "largeIcon" }, vendorName = "Red Hat Inc", eisType = "Test RA", version = "0.1", licenseDescription = { "licenseDescription" }, licenseRequired = true, reauthenticationSupport = true, authMechanisms = { @AuthenticationMechanism(credentialInterface = CredentialInterface.PasswordCredential) }, securityPermissions = { @SecurityPermission(permissionSpec = "permissionSpec") }, transactionSupport = TransactionSupport.TransactionSupportLevel.LocalTransaction) // TODO API has not been updated requiredWorkContexts = null @AdministeredObject(adminObjectInterfaces = TestAdminObjectInterface.class) public class Test2ResourceAdapter extends BaseResourceAdapter { @ConfigProperty(type = String.class, defaultValue = "JCA") private String myStringProperty; /** * @param myStringProperty the myStringProperty to set */ public void setMyStringProperty(String myStringProperty) { this.myStringProperty = myStringProperty; } /** * @return the myStringProperty */ public String getMyStringProperty() { return myStringProperty; } }
3,018
45.446154
171
java
null
wildfly-main/connector/src/test/java/org/jboss/as/connector/deployers/spec/rars/ra16inoutmultianno/TestManagedConnection.java
/* * IronJacamar, a Java EE Connector Architecture implementation * Copyright 2009, Red Hat Inc, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * 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.connector.deployers.spec.rars.ra16inoutmultianno; import org.jboss.as.connector.deployers.spec.rars.BaseManagedConnection; /** * TestManagedConnection * * @author <a href="mailto:[email protected]">Jeff Zhang</a> */ public class TestManagedConnection extends BaseManagedConnection { }
1,363
39.117647
72
java
null
wildfly-main/connector/src/test/java/org/jboss/as/connector/deployers/spec/rars/ra16inoutmultianno/TestManagedConnectionFactory.java
/* * IronJacamar, a Java EE Connector Architecture implementation * Copyright 2009, Red Hat Inc, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * 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.connector.deployers.spec.rars.ra16inoutmultianno; import jakarta.resource.spi.ConfigProperty; import jakarta.resource.spi.ConnectionDefinition; import jakarta.resource.spi.ManagedConnection; import org.jboss.as.connector.deployers.spec.rars.BaseManagedConnectionFactory; import org.jboss.as.connector.deployers.spec.rars.TestConnection; import org.jboss.as.connector.deployers.spec.rars.TestConnectionInterface; /** * TestManagedConnectionFactory * * @author <a href="mailto:[email protected]">Jeff Zhang</a> */ @ConnectionDefinition(connectionFactory = ManagedConnection.class, connectionFactoryImpl = TestManagedConnection.class, connection = TestConnectionInterface.class, connectionImpl = TestConnection.class) public class TestManagedConnectionFactory extends BaseManagedConnectionFactory { private static final long serialVersionUID = 1L; @ConfigProperty(type = String.class, defaultValue = "JCA") private String myStringProperty; /** * @param myStringProperty the myStringProperty to set */ public void setMyStringProperty(String myStringProperty) { this.myStringProperty = myStringProperty; } /** * @return the myStringProperty */ public String getMyStringProperty() { return myStringProperty; } }
2,359
39.689655
202
java
null
wildfly-main/connector/src/test/java/org/jboss/as/connector/deployers/spec/rars/ra16inoutmultianno/TestResourceAdapter.java
/* * IronJacamar, a Java EE Connector Architecture implementation * Copyright 2009, Red Hat Inc, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * 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.connector.deployers.spec.rars.ra16inoutmultianno; import org.jboss.as.connector.deployers.spec.rars.BaseResourceAdapter; import jakarta.resource.spi.AdministeredObject; import jakarta.resource.spi.AuthenticationMechanism; import jakarta.resource.spi.AuthenticationMechanism.CredentialInterface; import jakarta.resource.spi.ConfigProperty; import jakarta.resource.spi.Connector; import jakarta.resource.spi.SecurityPermission; import jakarta.resource.spi.TransactionSupport; /** * TestResourceAdapter * * @author <a href="mailto:[email protected]">Jeff Zhang</a> */ @Connector(description = { "Test RA" }, displayName = { "displayName" }, smallIcon = { "smallIcon" }, largeIcon = { "largeIcon" }, vendorName = "Red Hat Inc", eisType = "Test RA", version = "0.1", licenseDescription = { "licenseDescription" }, licenseRequired = true, reauthenticationSupport = true, authMechanisms = { @AuthenticationMechanism(credentialInterface = CredentialInterface.PasswordCredential) }, securityPermissions = { @SecurityPermission(permissionSpec = "permissionSpec") }, transactionSupport = TransactionSupport.TransactionSupportLevel.LocalTransaction) // TODO API has not been updated requiredWorkContexts = null @AdministeredObject(adminObjectInterfaces = TestAdminObjectInterface.class) public class TestResourceAdapter extends BaseResourceAdapter { @ConfigProperty(type = String.class, defaultValue = "JCA") private String myStringProperty; /** * @param myStringProperty the myStringProperty to set */ public void setMyStringProperty(String myStringProperty) { this.myStringProperty = myStringProperty; } /** * @return the myStringProperty */ public String getMyStringProperty() { return myStringProperty; } }
2,927
44.75
171
java
null
wildfly-main/connector/src/test/java/org/jboss/as/connector/deployers/spec/rars/ra16inoutmultianno/TestAdminObjectInterface.java
/* * IronJacamar, a Java EE Connector Architecture implementation * Copyright 2009, Red Hat Inc, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * 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.connector.deployers.spec.rars.ra16inoutmultianno; /** * * @author <a href="mailto:[email protected]">Jeff Zhang</a> */ public interface TestAdminObjectInterface { }
1,241
39.064516
70
java
null
wildfly-main/connector/src/test/java/org/jboss/as/connector/deployers/spec/rars/ra16inoutmultianno/TestActivationSpec.java
/* * IronJacamar, a Java EE Connector Architecture implementation * Copyright 2009, Red Hat Inc, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * 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.connector.deployers.spec.rars.ra16inoutmultianno; import org.jboss.as.connector.deployers.spec.rars.BaseActivationSpec; import jakarta.resource.spi.Activation; /** * TestActivationSpec * * @author <a href="mailto:[email protected]">Jeff Zhang</a> * @version $Revision: $ */ @Activation(messageListeners = {}) public class TestActivationSpec extends BaseActivationSpec { }
1,452
37.236842
70
java
null
wildfly-main/connector/src/test/java/org/jboss/as/connector/subsystems/complextestcases/AbstractComplexSubsystemTestCase.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.connector.subsystems.complextestcases; import org.jboss.as.controller.Extension; import org.jboss.as.subsystem.test.AbstractSubsystemTest; import org.jboss.as.subsystem.test.AdditionalInitialization; import org.jboss.as.subsystem.test.KernelServices; import org.jboss.dmr.ModelNode; import org.junit.Assert; /** * * @author <a href="[email protected]">Vladimir Rastseluev</a> */ public abstract class AbstractComplexSubsystemTestCase extends AbstractSubsystemTest { public AbstractComplexSubsystemTestCase(final String mainSubsystemName, final Extension mainExtension) { super(mainSubsystemName, mainExtension); } public ModelNode getModel(String resourceFileName, String archiveName) throws Exception { return getModel(resourceFileName, true, archiveName); } public ModelNode getModel(String resourceFileName) throws Exception { return getModel(resourceFileName, true, null); } public ModelNode getModel(String resourceFileName, boolean checkMarshalledXML, String archiveName) throws Exception { String xml = readResource(resourceFileName); KernelServices services = createKernelServicesBuilder(AdditionalInitialization.MANAGEMENT) .setSubsystemXml(xml) .build(); ModelNode model = services.readWholeModel(); // Marshal the xml to see that it is the same as before String marshalled = services.getPersistedSubsystemXml(); if (checkMarshalledXML) Assert.assertEquals(normalizeXML(xml), normalizeXML(marshalled)); services = createKernelServicesBuilder(AdditionalInitialization.MANAGEMENT) .setSubsystemXml(marshalled) .build(); // Check that the model looks the same ModelNode modelReloaded = services.readWholeModel(); compare(model, modelReloaded); assertRemoveSubsystemResources(services); return model; } }
3,014
36.6875
121
java
null
wildfly-main/connector/src/test/java/org/jboss/as/connector/subsystems/complextestcases/ParseUtils.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.connector.subsystems.complextestcases; import java.util.Enumeration; import java.util.Properties; import org.jboss.dmr.ModelNode; import org.junit.Assert; /**Common utility class for parsing operation tests * * @author <a href="[email protected]">Vladimir Rastseluev</a> */ public class ParseUtils { /** * Returns common properties for both XA and Non-XA datasource * @param indiName */ public static Properties commonDsProperties(String jndiName){ Properties params=new Properties(); //attributes params.put("use-java-context","true"); params.put("spy","false"); params.put("use-ccm","true"); params.put("jndi-name", jndiName); //common elements params.put("driver-name","h2"); params.put("new-connection-sql","select 1"); params.put("transaction-isolation","TRANSACTION_READ_COMMITTED"); params.put("url-delimiter",":"); params.put("url-selector-strategy-class-name","someClass"); //pool params.put("min-pool-size","1"); params.put("max-pool-size","5"); params.put("pool-prefill","true"); params.put("pool-use-strict-min","true"); params.put("flush-strategy","EntirePool"); //security params.put("user-name","sa"); params.put("password","sa"); params.put("reauth-plugin-class-name","someClass1"); //validation params.put("valid-connection-checker-class-name","someClass2"); params.put("check-valid-connection-sql","select 1"); params.put("validate-on-match","true"); params.put("background-validation","true"); params.put("background-validation-millis","2000"); params.put("use-fast-fail","true"); params.put("stale-connection-checker-class-name","someClass3"); params.put("exception-sorter-class-name","someClass4"); //time-out params.put("blocking-timeout-wait-millis","20000"); params.put("idle-timeout-minutes","4"); params.put("set-tx-query-timeout","true"); params.put("query-timeout","120"); params.put("use-try-lock","100"); params.put("allocation-retry","2"); params.put("allocation-retry-wait-millis","3000"); //statement params.put("track-statements","nowarn"); params.put("prepared-statements-cache-size","30"); params.put("share-prepared-statements","true"); return params; } /** * Returns properties for complex XA datasource * @param indiName */ public static Properties xaDsProperties(String jndiName){ Properties params=commonDsProperties(jndiName); //attributes //common params.put("xa-datasource-class","org.jboss.as.connector.subsystems.datasources.ModifiableXaDataSource"); //xa-pool params.put("same-rm-override","true"); params.put("interleaving","true"); params.put("no-tx-separate-pool","true"); params.put("pad-xid","true"); params.put("wrap-xa-resource","true"); //time-out params.put("xa-resource-timeout","120"); //recovery params.put("no-recovery","false"); params.put("recovery-plugin-class-name","someClass5"); params.put("recovery-username","sa"); params.put("recovery-password","sa"); return params; } /** * Returns properties for non XA datasource * @param jndiName */ public static Properties nonXaDsProperties(String jndiName){ Properties params=commonDsProperties(jndiName); //attributes params.put("jta","false"); //common params.put("driver-class","org.hsqldb.jdbcDriver"); params.put("datasource-class","org.jboss.as.connector.subsystems.datasources.ModifiableDataSource"); params.put("connection-url","jdbc:h2:mem:test;DB_CLOSE_DELAY=-1"); return params; } /** * Returns common properties for resource-adapter element */ public static Properties raCommonProperties(){ Properties params=new Properties(); params.put("archive","some.rar"); params.put("transaction-support","XATransaction"); params.put("bootstrap-context","someContext"); return params; } /** * Returns properties for RA connection-definition element */ public static Properties raConnectionProperties(){ Properties params=new Properties(); //attributes params.put("use-java-context","false"); params.put("class-name","Class1"); params.put("use-ccm","true"); params.put("jndi-name", "java:jboss/name1"); params.put("enabled","false"); //pool params.put("min-pool-size","1"); params.put("max-pool-size","5"); params.put("pool-prefill","true"); params.put("pool-use-strict-min","true"); params.put("flush-strategy","IdleConnections"); //xa-pool params.put("same-rm-override","true"); params.put("interleaving","true"); params.put("no-tx-separate-pool","true"); params.put("pad-xid","true"); params.put("wrap-xa-resource","true"); //security params.put("security-application","true"); //validation params.put("background-validation","true"); params.put("background-validation-millis","5000"); params.put("use-fast-fail","true"); //time-out params.put("blocking-timeout-wait-millis","5000"); params.put("idle-timeout-minutes","4"); params.put("allocation-retry","2"); params.put("allocation-retry-wait-millis","3000"); params.put("xa-resource-timeout","300"); //recovery params.put("no-recovery","false"); params.put("recovery-plugin-class-name","someClass2"); params.put("recovery-username","sa"); params.put("recovery-password","sa-pass"); return params; } /** * Returns properties for RA admin-object element */ public static Properties raAdminProperties(){ Properties params=new Properties(); //attributes params.put("use-java-context","false"); params.put("class-name","Class3"); params.put("jndi-name", "java:jboss/Name3"); params.put("enabled","true"); return params; } /** * Sets parameters for DMR operation * @param operation * @param params */ public static void setOperationParams(ModelNode operation,Properties params){ String str; Enumeration<?> e = params.propertyNames(); while (e.hasMoreElements()) { str=(String)e.nextElement(); operation.get(str).set(params.getProperty(str)); } } /** * Adds properties of Extension type to the operation * TODO: not implemented jet in DMR */ public static void addExtensionProperties(ModelNode operation){ /* operation.get("reauth-plugin-properties","Property").set("A"); operation.get("valid-connection-checker-properties","Property").set("B"); operation.get("stale-connect,roperties","Property").set("C"); operation.get("exception-sorter-properties","Property").set("D"); */ /*final ModelNode sourcePropertiesAddress = address.clone(); sourcePropertiesAddress.add("reauth-plugin-properties", "Property"); sourcePropertiesAddress.protect(); final ModelNode sourcePropertyOperation = new ModelNode(); sourcePropertyOperation.get(OP).set("add"); sourcePropertyOperation.get(OP_ADDR).set(sourcePropertiesAddress); sourcePropertyOperation.get("value").set("A"); execute(sourcePropertyOperation);*/ } /** * Controls if result of reparsing contains certain parameters * @param model * @param params */ public static void checkModelParams(ModelNode node, Properties params){ String str; StringBuffer sb = new StringBuffer(); String par,child; Enumeration<?> e = params.propertyNames(); while (e.hasMoreElements()) { str=(String)e.nextElement(); par=params.getProperty(str); if (node.get(str) == null) { sb.append("Parameter <"+str+"> is not set, but must be set to '"+par+"' \n"); } else{ child= node.get(str).asString(); if (!child.equals(par)) { sb.append("Parameter <"+str+"> is set to '"+child+"', but must be set to '"+par+"' \n"); } } } if (sb.length()>0) Assert.fail("There are parsing errors:\n"+sb.toString()+"Parsed configuration:\n"+node); } }
9,854
36.329545
115
java
null
wildfly-main/connector/src/test/java/org/jboss/as/connector/subsystems/complextestcases/ComplexResourceAdaptersSubsystemTestCase.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.connector.subsystems.complextestcases; import java.util.Properties; import org.jboss.as.connector.subsystems.resourceadapters.ResourceAdaptersExtension; import org.jboss.dmr.ModelNode; import org.junit.Assert; import org.junit.Test; /** * * @author <a href="[email protected]">Vladimir Rastseluev</a> */ public class ComplexResourceAdaptersSubsystemTestCase extends AbstractComplexSubsystemTestCase { public ComplexResourceAdaptersSubsystemTestCase() { super(ResourceAdaptersExtension.SUBSYSTEM_NAME, new ResourceAdaptersExtension()); } @Test public void testResourceAdapters() throws Exception { ModelNode model = getModel("ra.xml", "some.rar"); if (model == null) return; // Check model.. Properties params = ParseUtils.raCommonProperties(); ModelNode raCommonModel = model.get("subsystem", "resource-adapters", "resource-adapter", "myRA"); ParseUtils.checkModelParams(raCommonModel, params); Assert.assertEquals(raCommonModel.asString(), "A", raCommonModel.get("config-properties", "Property", "value") .asString()); Assert.assertEquals(raCommonModel.get("beanvalidationgroups").asString(), "[\"Class0\",\"Class00\"]", raCommonModel.get("beanvalidationgroups").asString()); params = ParseUtils.raAdminProperties(); ModelNode raAdminModel = raCommonModel.get("admin-objects", "Pool2"); ParseUtils.checkModelParams(raAdminModel, params); Assert.assertEquals(raAdminModel.asString(), "D", raAdminModel.get("config-properties", "Property", "value").asString()); params = ParseUtils.raConnectionProperties(); ModelNode raConnModel = raCommonModel.get("connection-definitions", "Pool1"); ParseUtils.checkModelParams(raConnModel, params); Assert.assertEquals(raConnModel.asString(), "B", raConnModel.get("config-properties", "Property", "value").asString()); Assert.assertEquals(raConnModel.asString(), "C", raConnModel.get("recovery-plugin-properties", "Property").asString()); } @Test public void testResourceAdapterWith2ConDefAnd2AdmObj() throws Exception { getModel("ra2.xml", false, "multiple.rar"); } }
3,302
43.04
129
java
null
wildfly-main/connector/src/test/java/org/jboss/as/connector/subsystems/complextestcases/ComplexJcaSubsystemTestCase.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.connector.subsystems.complextestcases; import org.jboss.as.connector.subsystems.jca.JcaExtension; import org.junit.Test; /** * * @author <a href="[email protected]">Vladimir Rastseluev</a> */ public class ComplexJcaSubsystemTestCase extends AbstractComplexSubsystemTestCase { public ComplexJcaSubsystemTestCase() { super(JcaExtension.SUBSYSTEM_NAME, new JcaExtension()); } @Test public void testModel() throws Exception { getModel("jca.xml"); } @Test public void testMinModel() throws Exception { getModel("minimal-jca.xml"); } }
1,655
30.245283
83
java
null
wildfly-main/connector/src/test/java/org/jboss/as/connector/subsystems/complextestcases/ComplexDatasourceSubsystemTestCase.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.connector.subsystems.complextestcases; import java.util.Properties; import org.jboss.as.connector.subsystems.datasources.DataSourcesExtension; import org.jboss.dmr.ModelNode; import org.junit.Assert; import org.junit.Test; /** * * @author <a href="[email protected]">Vladimir Rastseluev</a> */ //@Ignore public class ComplexDatasourceSubsystemTestCase extends AbstractComplexSubsystemTestCase { public ComplexDatasourceSubsystemTestCase() { super(DataSourcesExtension.SUBSYSTEM_NAME, new DataSourcesExtension()); } @Test public void testDatasource() throws Exception{ ModelNode model = getModel("datasource.xml",false,null); //Check model.. final String complexDs = "complexDs"; final String complexDsJndi = "java:jboss/datasources/" + complexDs; Properties params= ParseUtils.nonXaDsProperties(complexDsJndi); ModelNode modelDs=model.get("subsystem", "datasources","data-source",complexDs+"_Pool"); ParseUtils.checkModelParams(modelDs, params); Assert.assertEquals(modelDs.asString(),"UTF-8",modelDs.get("connection-properties","char.encoding","value").asString()); Assert.assertEquals(modelDs.asString(),"Property2",modelDs.get("valid-connection-checker-properties","name").asString()); Assert.assertEquals(modelDs.asString(),"Property4",modelDs.get("exception-sorter-properties","name").asString()); Assert.assertEquals(modelDs.asString(),"Property3",modelDs.get("stale-connection-checker-properties","name").asString()); Assert.assertEquals(modelDs.asString(),"Property1",modelDs.get("reauth-plugin-properties","name").asString()); final String complexXaDs = "complexXaDs"; final String complexXaDsJndi = "java:jboss/xa-datasources/" + complexXaDs; params= ParseUtils.xaDsProperties(complexXaDsJndi); ModelNode modelXaDs=model.get("subsystem", "datasources","xa-data-source",complexXaDs+"_Pool"); ParseUtils.checkModelParams(modelXaDs, params); Assert.assertEquals(modelXaDs.asString(),"jdbc:h2:mem:test",modelXaDs.get("xa-datasource-properties","URL","value").asString()); Assert.assertEquals(modelXaDs.asString(),"Property2",modelXaDs.get("valid-connection-checker-properties","name").asString()); Assert.assertEquals(modelXaDs.asString(),"Property4",modelXaDs.get("exception-sorter-properties","name").asString()); Assert.assertEquals(modelXaDs.asString(),"Property3",modelXaDs.get("stale-connection-checker-properties","name").asString()); Assert.assertEquals(modelXaDs.asString(),"Property1",modelXaDs.get("reauth-plugin-properties","name").asString()); Assert.assertEquals(modelXaDs.asString(),"Property5",modelXaDs.get("recovery-plugin-properties","name").asString()); Assert.assertEquals(modelXaDs.asString(),"Property6",modelXaDs.get("recovery-plugin-properties","name1").asString()); } @Test public void testJDBCDriver() throws Exception{ ModelNode model = getModel("datasource.xml",false,null); ModelNode h2MainModuleDriver = model.get("subsystem", "datasources", "jdbc-driver", "h2"); ModelNode h2TestModuleDriver = model.get("subsystem", "datasources", "jdbc-driver", "h2test"); Assert.assertEquals(h2MainModuleDriver.asString(),"com.h2database.h2",h2MainModuleDriver.get("driver-module-name").asString()); Assert.assertEquals(h2MainModuleDriver.asString(),"org.h2.jdbcx.JdbcDataSource",h2MainModuleDriver.get("driver-xa-datasource-class-name").asString()); Assert.assertFalse(h2MainModuleDriver.get("module-slot").isDefined()); Assert.assertEquals(h2TestModuleDriver.asString(),"com.h2database.h2",h2TestModuleDriver.get("driver-module-name").asString()); Assert.assertEquals(h2TestModuleDriver.asString(),"org.h2.jdbcx.JdbcDataSource",h2TestModuleDriver.get("driver-xa-datasource-class-name").asString()); Assert.assertEquals(h2TestModuleDriver.asString(),"test",h2TestModuleDriver.get("module-slot").asString()); } }
5,088
57.494253
158
java