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/pojo/src/main/java/org/jboss/as/pojo/service/BeanUtils.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.pojo.service;
import org.jboss.as.pojo.logging.PojoLogger;
import org.jboss.as.pojo.descriptor.BeanMetaDataConfig;
import org.jboss.as.pojo.descriptor.ConstructorConfig;
import org.jboss.as.pojo.descriptor.FactoryConfig;
import org.jboss.as.pojo.descriptor.LifecycleConfig;
import org.jboss.as.pojo.descriptor.PropertyConfig;
import org.jboss.as.pojo.descriptor.ValueConfig;
import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex;
import org.jboss.modules.Module;
import org.jboss.msc.service.StartException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* Bean utils.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public final class BeanUtils {
/**
* Instantiate bean.
*
* @param beanConfig the bean metadata config, must not be null
* @param beanInfo the bean info, can be null if enough info
* @param index the reflection index, must not be null
* @param module the current CL module, must not be null
* @return new bean instance
* @throws Throwable for any error
*/
public static Object instantiateBean(BeanMetaDataConfig beanConfig, BeanInfo beanInfo, DeploymentReflectionIndex index, Module module) throws Throwable {
Joinpoint instantiateJoinpoint = null;
ValueConfig[] parameters = new ValueConfig[0];
String[] types = Configurator.NO_PARAMS_TYPES;
ConstructorConfig ctorConfig = beanConfig.getConstructor();
if (ctorConfig != null) {
parameters = ctorConfig.getParameters();
types = Configurator.getTypes(parameters);
String factoryClass = ctorConfig.getFactoryClass();
FactoryConfig factory = ctorConfig.getFactory();
if (factoryClass != null || factory != null) {
String factoryMethod = ctorConfig.getFactoryMethod();
if (factoryMethod == null)
throw PojoLogger.ROOT_LOGGER.missingFactoryMethod(beanConfig);
if (factoryClass != null) {
// static factory
Class<?> factoryClazz = Class.forName(factoryClass, false, module.getClassLoader());
Method method = Configurator.findMethod(index, factoryClazz, factoryMethod, types, true, true, true);
MethodJoinpoint mj = new MethodJoinpoint(method);
mj.setTarget(() -> null); // null, since this is static call
mj.setParameters(parameters);
instantiateJoinpoint = mj;
} else if (factory != null) {
ReflectionJoinpoint rj = new ReflectionJoinpoint(factory.getBeanInfo(), factoryMethod, types);
// null type is ok, as this should be plain injection
rj.setTarget(() -> factory.getValue(null));
rj.setParameters(parameters);
instantiateJoinpoint = rj;
}
}
}
// plain bean's ctor
if (instantiateJoinpoint == null) {
if (beanInfo == null)
throw new StartException(PojoLogger.ROOT_LOGGER.missingBeanInfo(beanConfig));
Constructor ctor = (types.length == 0) ? beanInfo.getConstructor() : beanInfo.findConstructor(types);
ConstructorJoinpoint constructorJoinpoint = new ConstructorJoinpoint(ctor);
constructorJoinpoint.setParameters(parameters);
instantiateJoinpoint = constructorJoinpoint;
}
return instantiateJoinpoint.dispatch();
}
/**
* Configure bean.
*
* @param beanConfig the bean metadata config, must not be null
* @param beanInfo the bean info, can be null if enough info
* @param module the current CL module, must not be null
* @param bean the bean instance
* @param nullify do we nullify property
* @throws Throwable for any error
*/
public static void configure(BeanMetaDataConfig beanConfig, BeanInfo beanInfo, Module module, Object bean, boolean nullify) throws Throwable {
Set<PropertyConfig> properties = beanConfig.getProperties();
if (properties != null) {
List<PropertyConfig> used = new ArrayList<PropertyConfig>();
for (PropertyConfig pc : properties) {
try {
configure(beanInfo, module, bean, pc, nullify);
used.add(pc);
} catch (Throwable t) {
if (nullify == false) {
for (PropertyConfig upc : used) {
try {
configure(beanInfo, module, bean,upc, true);
} catch (Throwable ignored) {
}
}
throw new StartException(t);
}
}
}
}
}
/**
* Dispatch lifecycle joinpoint.
*
* @param beanInfo the bean info
* @param bean the bean instance
* @param config the lifecycle config
* @param defaultMethod the default method
* @throws Throwable for any error
*/
public static void dispatchLifecycleJoinpoint(BeanInfo beanInfo, Object bean, LifecycleConfig config, String defaultMethod) throws Throwable {
if (config != null && config.isIgnored())
return;
Joinpoint joinpoint = createJoinpoint(beanInfo, bean, config, defaultMethod);
if (joinpoint != null)
joinpoint.dispatch();
}
private static Joinpoint createJoinpoint(BeanInfo beanInfo, Object bean, LifecycleConfig config, String defaultMethod) {
Method method;
ValueConfig[] params = null;
if (config == null) {
try {
method = beanInfo.getMethod(defaultMethod);
} catch (Exception t) {
PojoLogger.ROOT_LOGGER.tracef(t, "Ignoring default %s invocation.", defaultMethod);
return null;
}
} else {
String methodName = config.getMethodName();
if (methodName == null) {
methodName = defaultMethod;
}
ValueConfig[] parameters = config.getParameters();
String[] types = Configurator.getTypes(parameters);
method = beanInfo.findMethod(methodName, types);
params = parameters;
}
MethodJoinpoint joinpoint = new MethodJoinpoint(method);
joinpoint.setTarget(() -> bean);
joinpoint.setParameters(params);
return joinpoint;
}
private static void configure(BeanInfo beanInfo, Module module, Object bean, PropertyConfig pc, boolean nullify) throws Throwable {
ValueConfig value = pc.getValue();
Class<?> clazz = null;
String type = pc.getType(); // check property
if (type == null)
type = value.getType(); // check value
if (type != null)
clazz = module.getClassLoader().loadClass(type);
Method setter = beanInfo.getSetter(pc.getPropertyName(), clazz);
MethodJoinpoint joinpoint = new MethodJoinpoint(setter);
ValueConfig param = (nullify == false) ? value : null;
joinpoint.setParameters(new ValueConfig[]{param});
joinpoint.setTarget(() -> bean);
joinpoint.dispatch();
}
}
| 8,513
| 41.358209
| 157
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/service/InstalledPojoPhase.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.pojo.service;
import org.jboss.as.pojo.BeanState;
/**
* POJO installed phase.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class InstalledPojoPhase extends AbstractPojoPhase {
@Override
protected BeanState getLifecycleState() {
return BeanState.INSTALLED;
}
@Override
protected AbstractPojoPhase createNextPhase() {
return null;
}
}
| 1,457
| 32.906977
| 70
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/service/ConfiguredPojoPhase.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.pojo.service;
import org.jboss.as.pojo.BeanState;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* POJO configured phase.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class ConfiguredPojoPhase extends AbstractPojoPhase {
@Override
protected BeanState getLifecycleState() {
return BeanState.CONFIGURED;
}
@Override
protected AbstractPojoPhase createNextPhase() {
return new CreateDestroyPojoPhase();
}
protected void configure(boolean nullify) throws Throwable {
BeanUtils.configure(getBeanConfig(), getBeanInfo(), getModule(), getBean(), nullify);
}
@Override
protected void startInternal(StartContext context) throws StartException {
try {
configure(false);
} catch (StartException t) {
throw t;
} catch (Throwable t) {
throw new StartException(t);
}
super.startInternal(context);
}
@Override
protected void stopInternal(StopContext context) {
super.stopInternal(context);
try {
configure(true);
} catch (Throwable ignored) {
}
}
}
| 2,307
| 31.507042
| 93
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/service/ReflectionJoinpoint.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.pojo.service;
import java.lang.reflect.Method;
/**
* Reflection joinpoint.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class ReflectionJoinpoint extends TargetJoinpoint {
private final BeanInfo beanInfo;
private final String methodName;
private final String[] types;
public ReflectionJoinpoint(BeanInfo beanInfo, String methodName) {
this(beanInfo, methodName, null);
}
public ReflectionJoinpoint(BeanInfo beanInfo, String methodName, String[] types) {
this.beanInfo = beanInfo;
this.methodName = methodName;
this.types = types;
}
@Override
public Object dispatch() throws Throwable {
String[] pts = types;
if (pts == null)
pts = Configurator.getTypes(getParameters());
Object target = getTarget().getValue();
Method method = beanInfo.findMethod(methodName, pts);
return method.invoke(target, toObjects(method.getGenericParameterTypes()));
}
}
| 2,056
| 34.465517
| 86
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/service/DescribedPojoPhase.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.pojo.service;
import org.jboss.as.pojo.BeanState;
import org.jboss.as.pojo.logging.PojoLogger;
import org.jboss.as.pojo.descriptor.BeanMetaDataConfig;
import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
/**
* POJO described phase.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class DescribedPojoPhase extends AbstractPojoPhase {
public DescribedPojoPhase(DeploymentReflectionIndex index, BeanMetaDataConfig beanConfig) {
setIndex(index);
setBeanConfig(beanConfig);
}
/**
* Expose alias registration against service builder.
*
* @param serviceBuilder the service builder
*/
public void registerAliases(ServiceBuilder serviceBuilder) {
registerAliases(serviceBuilder, getLifecycleState());
}
@Override
protected BeanState getLifecycleState() {
return BeanState.DESCRIBED;
}
@Override
protected AbstractPojoPhase createNextPhase() {
return new InstantiatedPojoPhase(this);
}
@SuppressWarnings("unchecked")
protected void startInternal(StartContext context) throws StartException {
try {
setModule(getBeanConfig().getModule().getInjectedModule().getValue());
String beanClass = getBeanConfig().getBeanClass();
if (beanClass != null) {
Class clazz = Class.forName(beanClass, false, getModule().getClassLoader());
setBeanInfo(new DefaultBeanInfo(getIndex(), clazz));
}
} catch (Exception e) {
throw new StartException(e);
}
super.startInternal(context);
}
public BeanInfo getValue() throws IllegalStateException, IllegalArgumentException {
BeanInfo beanInfo = getBeanInfo();
if (beanInfo == null)
throw new IllegalStateException(PojoLogger.ROOT_LOGGER.missingBeanInfo(getBeanConfig()));
return beanInfo;
}
}
| 3,128
| 35.811765
| 101
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/service/TargetJoinpoint.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.pojo.service;
import org.jboss.msc.value.Value;
/**
* Target joinpoint; keeps target.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public abstract class TargetJoinpoint extends AbstractJoinpoint {
private Value<Object> target;
public Value<Object> getTarget() {
return target;
}
public void setTarget(Value<Object> target) {
this.target = target;
}
}
| 1,465
| 33.093023
| 70
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/service/FieldGetJoinpoint.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.pojo.service;
import java.lang.reflect.Field;
/**
* Field get joinpoint.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class FieldGetJoinpoint extends FieldJoinpoint {
public FieldGetJoinpoint(Field field) {
super(field);
}
@Override
public Object dispatch() throws Throwable {
return getField().get(getTarget().getValue());
}
}
| 1,448
| 33.5
| 70
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/service/CreateDestroyPojoPhase.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.pojo.service;
import org.jboss.as.pojo.BeanState;
import org.jboss.as.pojo.descriptor.LifecycleConfig;
/**
* POJO create/destroy phase.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class CreateDestroyPojoPhase extends LifecyclePojoPhase {
@Override
protected BeanState getLifecycleState() {
return BeanState.CREATE;
}
@Override
protected AbstractPojoPhase createNextPhase() {
return new StartStopPojoPhase();
}
@Override
protected LifecycleConfig getUpConfig() {
return getBeanConfig().getCreate();
}
@Override
protected LifecycleConfig getDownConfig() {
return getBeanConfig().getDestroy();
}
@Override
protected String defaultUp() {
return "create";
}
@Override
protected String defaultDown() {
return "destroy";
}
}
| 1,927
| 29.125
| 70
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/service/Joinpoint.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.pojo.service;
/**
* Invoke a method or ctor.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
interface Joinpoint {
/**
* Dispatch this action.
*
* @return dispatch result
* @throws Throwable for any error
*/
Object dispatch() throws Throwable;
}
| 1,351
| 33.666667
| 70
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/service/AbstractJoinpoint.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.pojo.service;
import org.jboss.as.pojo.logging.PojoLogger;
import org.jboss.as.pojo.descriptor.ValueConfig;
import java.lang.reflect.Type;
/**
* Abstract joinpoint; keep parameters.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public abstract class AbstractJoinpoint implements Joinpoint {
private ValueConfig[] parameters;
protected Object[] toObjects(Type[] types) {
if (parameters == null || parameters.length == 0)
return new Object[0];
if (types == null || types.length != parameters.length)
throw PojoLogger.ROOT_LOGGER.wrongTypeSize();
try {
Object[] result = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
if (parameters[i] != null)
result[i] = Configurator.convertValue(Configurator.toClass(types[i]), parameters[i].getValue(types[i]), true, true);
}
return result;
} catch (Throwable t) {
throw new IllegalArgumentException(t);
}
}
protected ValueConfig[] getParameters() {
return parameters;
}
public void setParameters(ValueConfig[] parameters) {
this.parameters = parameters;
}
}
| 2,310
| 34.015152
| 136
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/service/Configurator.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.pojo.service;
import org.jboss.as.pojo.logging.PojoLogger;
import org.jboss.as.pojo.descriptor.ValueConfig;
import org.jboss.as.server.deployment.reflect.ClassReflectionIndex;
import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex;
import org.jboss.common.beans.property.PropertiesValueResolver;
import java.beans.PropertyEditor;
import java.beans.PropertyEditorManager;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collection;
/**
* Configuration util.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class Configurator {
/**
* No parameter types
*/
public static final String[] NO_PARAMS_TYPES = new String[0];
/**
* Turn type into class.
*
* @param type the type
* @return class
*/
public static Class<?> toClass(Type type) {
if (type instanceof Class) {
return (Class) type;
} else if (type instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) type;
return toClass(pt.getRawType());
} else {
throw PojoLogger.ROOT_LOGGER.unknownType(type);
}
}
/**
* Convert a value
*
* @param clazz the class
* @param value the value
* @param replaceProperties whether to replace system properties
* @param trim whether to trim string value
* @return the value or null if there is no editor
* @throws Throwable for any error
*/
@SuppressWarnings("unchecked")
public static Object convertValue(Class<?> clazz, Object value, boolean replaceProperties, boolean trim) throws Throwable {
if (clazz == null)
return value;
if (value == null)
return null;
Class<?> valueClass = value.getClass();
// If we have a string, trim and replace any system properties when requested
if (valueClass == String.class) {
String string = (String) value;
if (trim)
string = string.trim();
if (replaceProperties)
value = PropertiesValueResolver.replaceProperties(string);
}
if (clazz.isAssignableFrom(valueClass))
return value;
// First see if this is an Enum
if (clazz.isEnum()) {
Class<? extends Enum> eclazz = clazz.asSubclass(Enum.class);
return Enum.valueOf(eclazz, value.toString());
}
// Next look for a property editor
if (valueClass == String.class) {
PropertyEditor editor = PropertyEditorManager.findEditor(clazz);
if (editor != null) {
editor.setAsText((String) value);
return editor.getValue();
}
}
// Try a static clazz.valueOf(value)
try {
Method method = clazz.getMethod("valueOf", valueClass);
int modifiers = method.getModifiers();
if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)
&& clazz.isAssignableFrom(method.getReturnType()))
return method.invoke(null, value);
} catch (Exception ignored) {
}
if (valueClass == String.class) {
try {
Constructor constructor = clazz.getConstructor(valueClass);
if (Modifier.isPublic(constructor.getModifiers()))
return constructor.newInstance(value);
} catch (Exception ignored) {
}
}
return value;
}
/**
* Get types from values.
*
* @param values the values
* @return the values' types
*/
public static String[] getTypes(ValueConfig[] values) {
if (values == null || values.length == 0)
return NO_PARAMS_TYPES;
String[] types = new String[values.length];
for (int i =0; i < types.length; i++)
types[i] = values[i].getType();
return types;
}
/**
* Find method info
*
* @param index the deployment reflection index
* @param classInfo the class info
* @param name the method name
* @param paramTypes the parameter types
* @param isStatic must the method be static
* @param isPublic must the method be public
* @param strict is strict about method modifiers
* @return the method info
* @throws IllegalArgumentException when no such method
*/
@SuppressWarnings("unchecked")
public static Method findMethod(DeploymentReflectionIndex index, Class classInfo, String name, String[] paramTypes, boolean isStatic, boolean isPublic, boolean strict) throws IllegalArgumentException {
if (name == null)
throw PojoLogger.ROOT_LOGGER.nullName();
if (classInfo == null)
throw PojoLogger.ROOT_LOGGER.nullClassInfo();
if (paramTypes == null)
paramTypes = NO_PARAMS_TYPES;
Class current = classInfo;
while (current != null) {
ClassReflectionIndex cri = index.getClassIndex(classInfo);
Method result = locateMethod(cri, name, paramTypes, isStatic, isPublic, strict);
if (result != null)
return result;
current = current.getSuperclass();
}
throw PojoLogger.ROOT_LOGGER.methodNotFound(name, Arrays.toString(paramTypes), classInfo.getName());
}
/**
* Find method info
*
* @param classInfo the class info
* @param name the method name
* @param paramTypes the parameter types
* @param isStatic must the method be static
* @param isPublic must the method be public
* @param strict is strict about method modifiers
* @return the method info or null if not found
*/
@SuppressWarnings("unchecked")
private static Method locateMethod(ClassReflectionIndex classInfo, String name, String[] paramTypes, boolean isStatic, boolean isPublic, boolean strict) {
Collection<Method> methods = classInfo.getMethods();
if (methods != null) {
for (Method method : methods) {
if (name.equals(method.getName()) &&
equals(paramTypes, method.getParameterTypes()) &&
(strict == false || (Modifier.isStatic(method.getModifiers()) == isStatic && Modifier.isPublic(method.getModifiers()) == isPublic)))
return method;
}
}
return null;
}
/**
* Test whether type names are equal to type infos
*
* @param typeNames the type names
* @param typeInfos the type infos
* @return true when they are equal
*/
public static boolean equals(String[] typeNames, Class<?>[] typeInfos) {
if (simpleCheck(typeNames, typeInfos) == false)
return false;
for (int i = 0; i < typeNames.length; ++i) {
if (typeNames[i] != null && typeNames[i].equals(typeInfos[i].getName()) == false)
return false;
}
return true;
}
/**
* A simple null and length check.
*
* @param typeNames the type names
* @param typeInfos the type infos
* @return false if either argument is null or lengths differ, else true
*/
protected static boolean simpleCheck(String[] typeNames, Class<?>[] typeInfos) {
return typeNames != null && typeInfos != null && typeNames.length == typeInfos.length;
}
}
| 8,730
| 34.930041
| 205
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/service/DefaultBeanInfo.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.pojo.service;
import org.jboss.as.pojo.logging.PojoLogger;
import org.jboss.as.server.deployment.reflect.ClassReflectionIndex;
import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* Default bean info.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
@SuppressWarnings({"unchecked"})
public class DefaultBeanInfo<T> implements BeanInfo<T> {
private final List<ClassReflectionIndex> indexes = new ArrayList<ClassReflectionIndex>();
private final Class beanClass;
private DeploymentReflectionIndex index;
private Class currentClass;
public DefaultBeanInfo(DeploymentReflectionIndex index, Class<T> beanClass) {
this.index = index;
this.beanClass = beanClass;
this.currentClass = beanClass;
}
/**
* Do lazy lookup.
*
* @param lookup the lookup
* @param start the start
* @param depth the depth
* @return reflection index result
*/
protected <U> U lookup(Lookup<U> lookup, int start, int depth) {
int size;
synchronized (indexes) {
size = indexes.size();
for (int i = start; i < depth && i < size; i++) {
U result = lookup.lookup(indexes.get(i));
if (result != null)
return result;
}
}
if (currentClass == null)
return null;
synchronized (indexes) {
ClassReflectionIndex cri = index.getClassIndex(currentClass);
indexes.add(cri);
currentClass = currentClass.getSuperclass();
}
return lookup(lookup, size, depth);
}
public Constructor<T> getConstructor(final String... parameterTypes) {
return lookup(
new Lookup<Constructor<T>>() {
public Constructor<T> lookup(ClassReflectionIndex index) {
final Constructor ctor = index.getConstructor(parameterTypes);
if (ctor == null)
throw PojoLogger.ROOT_LOGGER.ctorNotFound(Arrays.toString(parameterTypes), beanClass.getName());
return ctor;
}
}, 0, 1);
}
@Override
public Constructor<T> findConstructor(final String... parameterTypes) {
return lookup(new Lookup<Constructor<T>>() {
@Override
public Constructor<T> lookup(ClassReflectionIndex index) {
final Collection<Constructor<?>> ctors = index.getConstructors();
for (Constructor c : ctors) {
if (Configurator.equals(parameterTypes, c.getParameterTypes()))
return c;
}
throw PojoLogger.ROOT_LOGGER.ctorNotFound(Arrays.toString(parameterTypes), beanClass.getName());
}
}, 0, 1);
}
@Override
public Field getField(final String name) {
final Field lookup = lookup(new Lookup<Field>() {
@Override
public Field lookup(ClassReflectionIndex index) {
return index.getField(name);
}
}, 0, Integer.MAX_VALUE);
if (lookup == null)
throw PojoLogger.ROOT_LOGGER.fieldNotFound(name, beanClass.getName());
return lookup;
}
@Override
public Method getMethod(final String name, final String... parameterTypes) {
final Method lookup = lookup(new Lookup<Method>() {
@Override
public Method lookup(ClassReflectionIndex index) {
Collection<Method> methods = index.getMethods(name, parameterTypes);
int size = methods.size();
switch (size) {
case 0:
return null;
case 1:
return methods.iterator().next();
default:
throw PojoLogger.ROOT_LOGGER.ambiguousMatch(methods, name, beanClass.getName());
}
}
}, 0, Integer.MAX_VALUE);
if (lookup == null)
throw PojoLogger.ROOT_LOGGER.methodNotFound(name, Arrays.toString(parameterTypes), beanClass.getName());
return lookup;
}
@Override
public Method findMethod(String name, String... parameterTypes) {
return Configurator.findMethod(index, beanClass, name, parameterTypes, false, true, true);
}
@Override
public Method getGetter(final String propertyName, final Class<?> type) {
final boolean isBoolean = Boolean.TYPE.equals(type);
final String name = ((isBoolean) ? "is" : "get") + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1);
final Method result = lookup(new Lookup<Method>() {
@Override
public Method lookup(ClassReflectionIndex index) {
Collection<Method> methods = index.getAllMethods(name, 0);
if (type == null) {
if (methods.size() == 1)
return methods.iterator().next();
else
return null;
}
for (Method m : methods) {
Class<?> pt = m.getReturnType();
if (pt.isAssignableFrom(type))
return m;
}
return null;
}
}, 0, Integer.MAX_VALUE);
if (result == null)
throw PojoLogger.ROOT_LOGGER.getterNotFound(type, beanClass.getName());
return result;
}
@Override
public Method getSetter(final String propertyName, final Class<?> type) {
final String name = "set" + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1);
final Method result = lookup(new Lookup<Method>() {
@Override
public Method lookup(ClassReflectionIndex index) {
Collection<Method> methods = index.getAllMethods(name, 1);
if (type == null) {
if (methods.size() == 1)
return methods.iterator().next();
else
return null;
}
for (Method m : methods) {
Class<?> pt = m.getParameterTypes()[0];
if (pt.isAssignableFrom(type))
return m;
}
return null;
}
}, 0, Integer.MAX_VALUE);
if (result == null)
throw PojoLogger.ROOT_LOGGER.setterNotFound(type, beanClass.getName());
return result;
}
private interface Lookup<U> {
U lookup(ClassReflectionIndex index);
}
}
| 7,981
| 37.191388
| 133
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/service/StartStopPojoPhase.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.pojo.service;
import org.jboss.as.pojo.BeanState;
import org.jboss.as.pojo.descriptor.LifecycleConfig;
/**
* POJO start/stop phase.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class StartStopPojoPhase extends LifecyclePojoPhase {
@Override
protected BeanState getLifecycleState() {
return BeanState.START;
}
@Override
protected AbstractPojoPhase createNextPhase() {
return new InstalledPojoPhase();
}
@Override
protected LifecycleConfig getUpConfig() {
return getBeanConfig().getStart();
}
@Override
protected LifecycleConfig getDownConfig() {
return getBeanConfig().getStop();
}
@Override
protected String defaultUp() {
return "start";
}
@Override
protected String defaultDown() {
return "stop";
}
}
| 1,909
| 29.31746
| 70
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/service/InstantiatedPojoPhase.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.pojo.service;
import org.jboss.as.pojo.BeanState;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
/**
* POJO instantiated phase.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class InstantiatedPojoPhase extends AbstractPojoPhase {
private final DescribedPojoPhase describedPojoPhase;
public InstantiatedPojoPhase(DescribedPojoPhase describedPojoPhase) {
this.describedPojoPhase = describedPojoPhase;
}
@Override
protected BeanState getLifecycleState() {
return BeanState.INSTANTIATED;
}
@Override
protected AbstractPojoPhase createNextPhase() {
return new ConfiguredPojoPhase();
}
@Override
protected void startInternal(StartContext context) throws StartException {
try {
BeanInfo beanInfo = getBeanInfo();
setBean(BeanUtils.instantiateBean(getBeanConfig(), beanInfo, getIndex(), getModule()));
if (beanInfo == null) {
//noinspection unchecked
beanInfo = new DefaultBeanInfo(getIndex(), getBean().getClass());
setBeanInfo(beanInfo);
// set so describe service has its value
describedPojoPhase.setBeanInfo(beanInfo);
}
} catch (StartException t) {
throw t;
} catch (Throwable t) {
throw new StartException(t);
}
super.startInternal(context);
}
}
| 2,535
| 34.71831
| 99
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/service/TypeBeanStateKey.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.pojo.service;
import org.jboss.as.pojo.BeanState;
/**
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
class TypeBeanStateKey {
private final Class<?> type;
private final BeanState state;
public TypeBeanStateKey(Class<?> type, BeanState state) {
this.type = type;
this.state = state;
}
@Override
public int hashCode() {
return type.hashCode() + 7 * state.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof TypeBeanStateKey == false)
return false;
TypeBeanStateKey tbsk = (TypeBeanStateKey) obj;
return type.equals(tbsk.type) && state == tbsk.state;
}
}
| 1,753
| 32.09434
| 70
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/service/LifecyclePojoPhase.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.pojo.service;
import org.jboss.as.pojo.descriptor.LifecycleConfig;
import org.jboss.as.pojo.logging.PojoLogger;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* POJO lifecycle phase.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public abstract class LifecyclePojoPhase extends AbstractPojoPhase {
protected abstract LifecycleConfig getUpConfig();
protected abstract LifecycleConfig getDownConfig();
protected abstract String defaultUp();
protected abstract String defaultDown();
protected void dispatchJoinpoint(LifecycleConfig config, String defaultMethod) throws Throwable {
BeanUtils.dispatchLifecycleJoinpoint(getBeanInfo(), getBean(), config, defaultMethod);
}
@Override
protected void startInternal(StartContext context) throws StartException {
try {
dispatchJoinpoint(getUpConfig(), defaultUp());
} catch (Throwable t) {
throw new StartException(t);
}
super.startInternal(context);
}
@Override
protected void stopInternal(StopContext context) {
super.stopInternal(context);
try {
dispatchJoinpoint(getDownConfig(), defaultDown());
} catch (Throwable t) {
PojoLogger.ROOT_LOGGER.debugf(t, "Exception at %s phase.", defaultDown());
}
}
}
| 2,477
| 36.545455
| 101
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/service/InstancesService.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.pojo.service;
import org.jboss.as.pojo.BeanState;
import org.jboss.as.pojo.logging.PojoLogger;
import org.jboss.as.pojo.descriptor.BeanMetaDataConfig;
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.ServiceRegistry;
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 java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Available instances per type
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
@SuppressWarnings({"SynchronizationOnLocalVariableOrMethodParameter"})
final class InstancesService implements Service<Set<Object>> {
private final Class<?> type;
private final Set<Object> instances = new HashSet<Object>(); // we do own locking, per type (service is also per type)
private static Map<TypeBeanStateKey, Set<Object>> beans = new HashMap<TypeBeanStateKey, Set<Object>>();
private static Map<TypeBeanStateKey, List<Callback>> incallbacks = new HashMap<TypeBeanStateKey, List<Callback>>();
private static Map<TypeBeanStateKey, List<Callback>> uncallbacks = new HashMap<TypeBeanStateKey, List<Callback>>();
private InstancesService(Class<?> type) {
this.type = type;
}
/**
* Add bean instance.
*
* @param registry the service registry
* @param target the service target
* @param state the bean state
* @param bean the bean
* @throws StartException for any error
*/
static void addInstance(ServiceRegistry registry, ServiceTarget target, BeanState state, Object bean) throws StartException {
addInstance(registry, target, state, bean.getClass(), bean);
}
/**
* Remove bean instance.
*
* @param registry the service registry
* @param state the bean state
* @param bean the bean
*/
static void removeInstance(ServiceRegistry registry, BeanState state, Object bean) {
removeInstance(registry, state, bean.getClass(), bean);
}
/**
* Add incallback.
*
* @param callback the callback
*/
static void addIncallback(Callback callback) {
addCallback(incallbacks, callback);
}
/**
* Add uncallback.
*
* @param callback the callback
*/
static void addUncallback(Callback callback) {
addCallback(uncallbacks, callback);
}
/**
* Remove incallback.
*
* @param callback the callback
*/
static void removeIncallback(Callback callback) {
removeCallback(incallbacks, callback);
}
/**
* Remove uncallback.
*
* @param callback the callback
*/
static void removeUncallback(Callback callback) {
removeCallback(uncallbacks, callback);
}
private static void addCallback(Map<TypeBeanStateKey, List<Callback>> map, Callback callback) {
final Class<?> type = callback.getType();
synchronized (type) {
if (map == incallbacks) {
try {
callback.dispatch(); // check all previous
} catch (Throwable t) {
PojoLogger.ROOT_LOGGER.errorAtIncallback(callback, t);
}
}
TypeBeanStateKey key = new TypeBeanStateKey(type, callback.getState());
List<Callback> callbacks = map.get(key);
if (callbacks == null) {
callbacks = new ArrayList<Callback>();
map.put(key, callbacks);
}
callbacks.add(callback);
}
}
private static void removeCallback(Map<TypeBeanStateKey, List<Callback>> map, Callback callback) {
final Class<?> type = callback.getType();
synchronized (type) {
TypeBeanStateKey key = new TypeBeanStateKey(type, callback.getState());
List<Callback> callbacks = map.get(key);
if (callbacks != null) {
callbacks.remove(callback);
if (callbacks.isEmpty())
map.remove(key);
}
if (map == uncallbacks) {
try {
callback.dispatch(); // try all remaining
} catch (Throwable t) {
PojoLogger.ROOT_LOGGER.errorAtUncallback(callback, t);
}
}
}
}
private static void invokeCallbacks(Map<TypeBeanStateKey, List<Callback>> map, BeanState state, final Class<?> clazz, Object bean) {
synchronized (clazz) {
TypeBeanStateKey key = new TypeBeanStateKey(clazz, state);
List<Callback> callbacks = map.get(key);
if (callbacks != null) {
for (Callback c : callbacks) {
try {
c.dispatch(bean);
} catch (Throwable t) {
PojoLogger.ROOT_LOGGER.invokingCallback(c, t);
}
}
}
}
}
private static void addInstance(ServiceRegistry registry, ServiceTarget target, BeanState state, final Class<?> clazz, Object bean) throws StartException {
if (clazz == null)
return;
ServiceName name = BeanMetaDataConfig.toInstancesName(clazz, state);
ServiceBuilder<Set<Object>> builder = target.addService(name, new InstancesService(clazz));
InstancesService service = putIfAbsent(registry, name, builder);
synchronized (clazz) {
service.instances.add(bean);
TypeBeanStateKey key = new TypeBeanStateKey(clazz, state);
if (beans.containsKey(key) == false)
beans.put(key, service.instances);
invokeCallbacks(incallbacks, state, clazz, bean);
}
addInstance(registry, target, state, clazz.getSuperclass(), bean);
Class<?>[] ifaces = clazz.getInterfaces();
for (Class<?> iface : ifaces)
addInstance(registry, target, state, iface, bean);
}
private static InstancesService putIfAbsent(ServiceRegistry registry, ServiceName name, ServiceBuilder builder) throws StartException {
for (; ; ) {
try {
ServiceController sc = registry.getService(name);
if (sc == null) {
sc = builder.install();
}
return (InstancesService) sc.getService();
} catch (DuplicateServiceException ignored) {
} catch (Exception e) {
throw new StartException(e);
}
}
}
private static void removeInstance(ServiceRegistry registry, BeanState state, final Class<?> clazz, Object bean) {
if (clazz == null)
return;
ServiceController controller = registry.getService(BeanMetaDataConfig.toInstancesName(clazz, state));
if (controller != null) {
InstancesService service = (InstancesService) controller.getService();
synchronized (clazz) {
service.instances.remove(bean);
invokeCallbacks(uncallbacks, state, clazz, bean);
if (service.instances.isEmpty()) {
beans.remove(new TypeBeanStateKey(clazz, state));
controller.setMode(ServiceController.Mode.REMOVE);
}
}
}
removeInstance(registry, state, clazz.getSuperclass(), bean);
Class<?>[] ifaces = clazz.getInterfaces();
for (Class<?> iface : ifaces)
removeInstance(registry, state, iface, bean);
}
@Override
public void start(StartContext context) throws StartException {
}
@Override
public void stop(StopContext context) {
}
@Override
public Set<Object> getValue() throws IllegalStateException, IllegalArgumentException {
synchronized (type) {
return Collections.unmodifiableSet(instances);
}
}
static Set<Object> getBeans(Class<?> type, BeanState state) {
synchronized (type) {
TypeBeanStateKey key = new TypeBeanStateKey(type, state);
Set<Object> objects = beans.get(key);
return (objects != null) ? Collections.unmodifiableSet(objects) : Collections.emptySet();
}
}
}
| 9,671
| 35.089552
| 159
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/service/Callback.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.pojo.service;
import org.jboss.as.pojo.BeanState;
import org.jboss.as.pojo.logging.PojoLogger;
import org.jboss.as.pojo.descriptor.CallbackConfig;
import org.jboss.as.pojo.descriptor.ValueConfig;
import java.lang.reflect.Method;
/**
* Simple callback.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class Callback {
private final BeanInfo beanInfo;
private final Object bean;
private final CallbackConfig config;
private Method method;
public Callback(BeanInfo beanInfo, Object bean, CallbackConfig config) {
this.beanInfo = beanInfo;
this.bean = bean;
this.config = config;
}
protected Method getMethod() {
if (method == null) {
final Method m = beanInfo.findMethod(config.getMethodName(), config.getSignature());
if (m.getParameterCount() != 1)
throw PojoLogger.ROOT_LOGGER.illegalParameterLength(m);
method = m;
}
return method;
}
public Class<?> getType() {
return getMethod().getParameterTypes()[0];
}
public BeanState getState() {
return config.getState();
}
public void dispatch() throws Throwable {
for (Object bean : InstancesService.getBeans(getType(), getState()))
dispatch(bean);
}
public void dispatch(final Object dependency) throws Throwable {
MethodJoinpoint joinpoint = new MethodJoinpoint(getMethod());
joinpoint.setTarget(() -> bean);
ValueConfig param = new ValueConfig() {
protected Object getClassValue(Class<?> type) {
return dependency;
}
};
joinpoint.setParameters(new ValueConfig[]{param});
joinpoint.dispatch();
}
@Override
public int hashCode() {
return config.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Callback == false)
return false;
Callback callback = (Callback) obj;
return config.equals(callback.config);
}
}
| 3,127
| 30.918367
| 96
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/service/ConstructorJoinpoint.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.pojo.service;
import java.lang.reflect.Constructor;
/**
* Ctor joinpoint.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class ConstructorJoinpoint extends AbstractJoinpoint {
private final Constructor ctor;
public ConstructorJoinpoint(Constructor ctor) {
this.ctor = ctor;
}
@Override
public Object dispatch() throws Throwable {
return ctor.newInstance(toObjects(ctor.getGenericParameterTypes()));
}
}
| 1,526
| 33.704545
| 76
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/service/FieldJoinpoint.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.pojo.service;
import java.lang.reflect.Field;
/**
* Field joinpoint.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public abstract class FieldJoinpoint extends TargetJoinpoint {
private final Field field;
public FieldJoinpoint(Field field) {
this.field = field;
}
protected Field getField() {
return field;
}
}
| 1,424
| 32.139535
| 70
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/service/FieldSetJoinpoint.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.pojo.service;
import org.jboss.as.pojo.logging.PojoLogger;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Arrays;
/**
* Field set joinpoint.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class FieldSetJoinpoint extends FieldJoinpoint {
public FieldSetJoinpoint(Field field) {
super(field);
}
@Override
public Object dispatch() throws Throwable {
Object[] params = toObjects(new Type[]{getField().getGenericType()});
if (params == null || params.length != 1)
throw PojoLogger.ROOT_LOGGER.illegalParameterLength(Arrays.toString(params));
getField().set(getTarget().getValue(), params[0]);
return null;
}
}
| 1,794
| 34.196078
| 89
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/service/MethodJoinpoint.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.pojo.service;
import java.lang.reflect.Method;
/**
* Method joinpoint.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class MethodJoinpoint extends TargetJoinpoint {
private final Method method;
public MethodJoinpoint(Method method) {
this.method = method;
}
@Override
public Object dispatch() throws Throwable {
return method.invoke(getTarget().getValue(), toObjects(method.getGenericParameterTypes()));
}
}
| 1,532
| 33.840909
| 99
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/api/BeanFactory.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.pojo.api;
/**
* Simple bean factory interface.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public interface BeanFactory {
/**
* Create new bean.
*
* @return new bean
* @throws Throwable for any error
*/
Object create() throws Throwable;
}
| 1,348
| 33.589744
| 70
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/logging/PojoLogger.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.pojo.logging;
import org.jboss.as.pojo.descriptor.BeanMetaDataConfig;
import org.jboss.as.pojo.descriptor.ConfigVisitorNode;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
import org.jboss.msc.service.StartException;
import org.jboss.vfs.VirtualFile;
import static org.jboss.logging.Logger.Level.INFO;
import static org.jboss.logging.Logger.Level.WARN;
import java.util.Set;
/**
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
@MessageLogger(projectCode = "WFLYPOJO", length = 4)
public interface PojoLogger extends BasicLogger {
/**
* A logger with a category of the package name.
*/
PojoLogger ROOT_LOGGER = Logger.getMessageLogger(PojoLogger.class, "org.jboss.as.pojo");
/**
* Log old namespace usage.
*
* @param namespace the namespace
*/
@LogMessage(level = INFO)
@Message(id = 1, value = "Found legacy bean/pojo namespace: %s - might be missing some xml features (potential exceptions).")
void oldNamespace(Object namespace);
/**
* Error at uninstall.
*
* @param joinpoint the joinpoint
* @param cause the cause of the error.
*/
@LogMessage(level = WARN)
@Message(id = 2, value = "Ignoring uninstall action on target: %s")
void ignoreUninstallError(Object joinpoint, @Cause Throwable cause);
/**
* Error invoking callback.
*
* @param callback the callback
* @param cause the cause of the error.
*/
@LogMessage(level = WARN)
@Message(id = 3, value = "Error invoking callback: %s")
void invokingCallback(Object callback, @Cause Throwable cause);
/**
* Error at incallback.
*
* @param callback the callback
* @param cause the cause of the error.
*/
@LogMessage(level = WARN)
@Message(id = 4, value = "Error invoking incallback: %s")
void errorAtIncallback(Object callback, @Cause Throwable cause);
/**
* Error at uncallback.
*
* @param callback the callback
* @param cause the cause of the error.
*/
@LogMessage(level = WARN)
@Message(id = 5, value = "Error invoking uncallback: %s")
void errorAtUncallback(Object callback, @Cause Throwable cause);
/**
* No Module instance found in attachments.
*
* @param unit the current deployment unit
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 6, value = "Failed to get module attachment for %s")
DeploymentUnitProcessingException noModuleFound(DeploymentUnit unit);
/**
* Missing reflection index.
*
* @param unit the current deployment unit
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 7, value = "Missing deployment reflection index for %s")
DeploymentUnitProcessingException missingReflectionIndex(DeploymentUnit unit);
/**
* Parsing failure.
*
* @param file the beans xml file
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 8, value = "Failed to parse POJO xml [ %s ]")
DeploymentUnitProcessingException failedToParse(VirtualFile file);
// /**
// * Cannot instantiate new instance
// *
// * @param cause the cause
// * @return a {@link IllegalArgumentException} for the error.
// */
// @Message(id = 9, value = "Cannot instantiate new instance.")
// IllegalArgumentException cannotInstantiate(@Cause Throwable cause);
/**
* Cannot instantiate new collection instance
*
* @param cause the cause
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 10, value = "Cannot instantiate new collection instance.")
IllegalArgumentException cannotInstantiateCollection(@Cause Throwable cause);
/**
* Cannot instantiate new map instance
*
* @param cause the cause
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 11, value = "Cannot instantiate new map instance.")
IllegalArgumentException cannotInstantiateMap(@Cause Throwable cause);
/**
* Too dynamic to determine type.
*
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 12, value = "Too dynamic to determine injected type from factory!")
IllegalArgumentException tooDynamicFromFactory();
/**
* Too dynamic to determine type.
*
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 13, value = "Too dynamic to determine injected type from dependency!")
IllegalArgumentException tooDynamicFromDependency();
/**
* Not a value node.
*
* @param previous previous node
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 14, value = "Previous node is not a value config: %s")
IllegalArgumentException notValueConfig(ConfigVisitorNode previous);
/**
* Null factory method.
*
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 15, value = "Null factory method!")
IllegalArgumentException nullFactoryMethod();
/**
* Null bean info.
*
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 16, value = "Null bean info!")
IllegalArgumentException nullBeanInfo();
/**
* Invalid match size.
*
* @param set whole set
* @param type the type to match
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 17, value = "Invalid number of type instances match: %s, type: %s")
IllegalArgumentException invalidMatchSize(Set set, Class type);
/**
* Cannot determine injected type.
*
* @param info the info
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 18, value = "Cannot determine injected type: %s, try setting class attribute (if available).")
IllegalArgumentException cannotDetermineInjectedType(String info);
/**
* Null or empty alias.
*
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 19, value = "Null or empty alias.")
IllegalArgumentException nullOrEmptyAlias();
/**
* Null or empty dependency.
*
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 20, value = "Null or empty dependency.")
IllegalArgumentException nullOrEmptyDependency();
/**
* Missing value.
*
* @return a message
*/
@Message(id = 21, value = "Missing value")
String missingValue();
/**
* Missing mode value.
*
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 22, value = "Null value")
IllegalArgumentException nullValue();
/**
* Missing mode value.
*
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 23, value = "Null name")
IllegalArgumentException nullName();
/**
* Missing method name.
*
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 24, value = "Null method name!")
IllegalArgumentException nullMethodName();
/**
* Unknown type.
*
* @param type the type
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 25, value = "Unknown type: %s")
IllegalArgumentException unknownType(Object type);
/**
* Illegal parameter length.
*
* @param info the info
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 26, value = "Illegal parameter length: %s")
IllegalArgumentException illegalParameterLength(Object info);
/**
* Missing factory method.
*
* @param beanConfig bean config
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 27, value = "Missing factory method in ctor configuration: %s")
StartException missingFactoryMethod(BeanMetaDataConfig beanConfig);
/**
* Missing bean info.
*
* @param beanConfig bean config
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 28, value = "Missing bean info, set bean's class attribute: %s")
String missingBeanInfo(BeanMetaDataConfig beanConfig);
/**
* Wrong type size.
*
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 29, value = "Wrong types size, doesn't match parameters!")
IllegalArgumentException wrongTypeSize();
/**
* Null class info.
*
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 30, value = "Null ClassInfo!")
IllegalArgumentException nullClassInfo();
/**
* Ctor not found.
*
* @param args the args
* @param clazz the class
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 31, value = "No such constructor: %s for class %s.")
IllegalArgumentException ctorNotFound(Object args, String clazz);
/**
* Method not found.
*
* @param name the method name
* @param args the args
* @param clazz the class
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 32, value = "Method not found %s%s for class %s.")
IllegalArgumentException methodNotFound(String name, Object args, String clazz);
/**
* Getter not found.
*
* @param type the type
* @param clazz the class
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 33, value = "No such getter: %s on class %s.")
IllegalArgumentException getterNotFound(Class<?> type, String clazz);
/**
* Setter not found.
*
* @param type the type
* @param clazz the class
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 34, value = "No such setter: %s on class %s.")
IllegalArgumentException setterNotFound(Class<?> type, String clazz);
/**
* Ambiguous match.
*
* @param info the info
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 35, value = "Ambiguous match %s.")
IllegalArgumentException ambiguousMatch(Object info);
/**
* Ambiguous match.
*
* @param info the info
* @param name the name
* @param clazz the class
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 36, value = "Ambiguous match of %s for name %s on class %s.")
IllegalArgumentException ambiguousMatch(Object info, String name, String clazz);
/**
* Field not found.
*
* @param name the method name
* @param clazz the class
* @return a {@link IllegalArgumentException} for the error.
*/
@Message(id = 37, value = "Field not found %s for class %s.")
IllegalArgumentException fieldNotFound(String name, String clazz);
/**
* Parsing exception.
*
* @param beansXml the beans xml file
* @param cause the cause
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 38, value = "Exception while parsing POJO descriptor file: %s")
DeploymentUnitProcessingException parsingException(VirtualFile beansXml, @Cause Throwable cause);
}
| 12,918
| 31.378446
| 129
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/KernelDeploymentXmlDescriptorParser.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.pojo.descriptor;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.pojo.BeanState;
import org.jboss.as.pojo.ParseResult;
import org.jboss.as.pojo.logging.PojoLogger;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLExtendedStreamReader;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequired;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
/**
* Parse Microcontainer jboss-beans.xml.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class KernelDeploymentXmlDescriptorParser implements XMLElementReader<ParseResult<KernelDeploymentXmlDescriptor>>, XMLStreamConstants {
private enum Element {
BEAN("bean"),
BEAN_FACTORY("bean-factory"),
CLASSLOADER("classloader"),
CONSTRUCTOR("constructor"),
FACTORY("factory"),
PROPERTY("property"),
VALUE("value"),
INJECT("inject"),
VALUE_FACTORY("value-factory"),
PARAMETER("parameter"),
DEPENDS("depends"),
ALIAS("alias"),
ANNOTATION("annotation"),
CREATE("create"),
START("start"),
STOP("stop"),
DESTROY("destroy"),
INSTALL("install"),
UNINSTALL("uninstall"),
INCALLBACK("incallback"),
UNCALLBACK("uncallback"),
LIST("list"),
SET("set"),
MAP("map"),
ENTRY("entry"),
KEY("key"),
UNKNOWN(null);
private final String localPart;
private static final Map<String, Element> QNAME_MAP = new HashMap<String, Element>();
static {
for (Element element : Element.values()) {
QNAME_MAP.put(element.localPart, element);
}
}
private Element(final String localPart) {
this.localPart = localPart;
}
static Element of(String localPart) {
final Element element = QNAME_MAP.get(localPart);
return element == null ? UNKNOWN : element;
}
}
private enum Attribute {
MODE("mode"),
NAME("name"),
TYPE("type"),
VALUE("value"),
TRIM("trim"),
REPLACE("replace"),
BEAN("bean"),
SERVICE("service"),
PROPERTY("property"),
CLASS("class"),
ELEMENT("elementClass"),
KEY_ELEMENT("keyClass"),
VALUE_ELEMENT("valueClass"),
METHOD("method"),
IGNORED("ignored"),
SIGNATURE("signature"),
FACTORY_CLASS("factory-class"),
FACTORY_METHOD("factory-method"),
FACTORY_CLASS_LEGACY("factoryClass"),
FACTORY_METHOD_LEGACY("factoryMethod"),
STATE("state"),
TARGET_STATE("targetState"),
UNKNOWN(null);
private final String localPart;
private static final Map<String, Attribute> QNAME_MAP = new HashMap<String, Attribute>();
static {
for (Attribute attribute : Attribute.values()) {
QNAME_MAP.put(attribute.localPart, attribute);
}
}
private Attribute(final String localPart) {
this.localPart = localPart;
}
static Attribute of(String localPart) {
final Attribute attribute = QNAME_MAP.get(localPart);
return attribute == null ? UNKNOWN : attribute;
}
}
private final BeanDeploymentSchema schema;
public KernelDeploymentXmlDescriptorParser(BeanDeploymentSchema schema) {
this.schema = schema;
}
@Override
public void readElement(XMLExtendedStreamReader reader, ParseResult<KernelDeploymentXmlDescriptor> value) throws XMLStreamException {
final KernelDeploymentXmlDescriptor kernelDeploymentXmlDescriptor = new KernelDeploymentXmlDescriptor();
final List<BeanMetaDataConfig> beansConfigs = new ArrayList<BeanMetaDataConfig>();
kernelDeploymentXmlDescriptor.setBeans(beansConfigs);
value.setResult(kernelDeploymentXmlDescriptor);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String attributeName = reader.getAttributeLocalName(i);
final Attribute attribute = Attribute.of(attributeName);
final String attributeValue = reader.getAttributeValue(i);
switch (attribute) {
case MODE:
kernelDeploymentXmlDescriptor.setMode(ModeConfig.of(attributeValue));
break;
}
}
while (reader.hasNext()) {
switch (reader.nextTag()) {
case COMMENT:
break;
case END_ELEMENT:
return;
case START_ELEMENT:
switch (Element.of(reader.getLocalName())) {
case BEAN:
beansConfigs.add(parseBean(reader));
break;
case BEAN_FACTORY:
BeanMetaDataConfig bean = parseBean(reader);
beansConfigs.add(toBeanFactory(bean));
kernelDeploymentXmlDescriptor.incrementBeanFactoryCount();
break;
case UNKNOWN:
throw unexpectedElement(reader);
}
break;
}
}
}
private BeanMetaDataConfig toBeanFactory(final BeanMetaDataConfig bean) {
return new BeanFactoryMetaDataConfig(bean);
}
private BeanMetaDataConfig parseBean(final XMLExtendedStreamReader reader) throws XMLStreamException {
BeanMetaDataConfig beanConfig = new BeanMetaDataConfig();
final int count = reader.getAttributeCount();
final Set<Attribute> required = EnumSet.of(Attribute.NAME);
for (int i = 0; i < count; i++) {
final Attribute attribute = Attribute.of(reader.getAttributeLocalName(i));
required.remove(attribute);
final String attributeValue = reader.getAttributeValue(i);
switch (attribute) {
case NAME:
beanConfig.setName(attributeValue);
break;
case CLASS:
beanConfig.setBeanClass(attributeValue);
break;
case MODE:
beanConfig.setMode(ModeConfig.of(attributeValue));
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (required.isEmpty() == false) {
throw missingRequired(reader, required);
}
while (reader.hasNext()) {
switch (reader.nextTag()) {
case COMMENT:
break;
case END_ELEMENT:
return beanConfig;
case START_ELEMENT:
switch (Element.of(reader.getLocalName())) {
case ALIAS:
Set<String> aliases = beanConfig.getAliases();
if (aliases == null) {
aliases = new HashSet<String>();
beanConfig.setAliases(aliases);
}
aliases.add(parseAlias(reader));
break;
case CLASSLOADER:
beanConfig.setModule(parseModuleConfig(reader));
break;
case CONSTRUCTOR:
beanConfig.setConstructor(parseConstructor(reader));
break;
case PROPERTY:
Set<PropertyConfig> properties = beanConfig.getProperties();
if (properties == null) {
properties = new HashSet<PropertyConfig>();
beanConfig.setProperties(properties);
}
properties.add(parseProperty(reader));
break;
case INSTALL:
List<InstallConfig> installs = beanConfig.getInstalls();
if (installs == null) {
installs = new ArrayList<InstallConfig>();
beanConfig.setInstalls(installs);
}
installs.add(parseInstall(reader));
break;
case UNINSTALL:
List<InstallConfig> uninstalls = beanConfig.getUninstalls();
if (uninstalls == null) {
uninstalls = new ArrayList<InstallConfig>();
beanConfig.setUninstalls(uninstalls);
}
uninstalls.add(parseInstall(reader));
break;
case INCALLBACK:
List<CallbackConfig> incallbacks = beanConfig.getIncallbacks();
if (incallbacks == null) {
incallbacks = new ArrayList<CallbackConfig>();
beanConfig.setIncallbacks(incallbacks);
}
incallbacks.add(parseCallback(reader));
break;
case UNCALLBACK:
List<CallbackConfig> uncallbacks = beanConfig.getUncallbacks();
if (uncallbacks == null) {
uncallbacks = new ArrayList<CallbackConfig>();
beanConfig.setUncallbacks(uncallbacks);
}
uncallbacks.add(parseCallback(reader));
break;
case DEPENDS:
Set<DependsConfig> depends = beanConfig.getDepends();
if (depends == null) {
depends = new HashSet<DependsConfig>();
beanConfig.setDepends(depends);
}
depends.add(parseDepends(reader));
break;
case CREATE:
beanConfig.setCreate(parseLifecycle(reader, "create"));
break;
case START:
beanConfig.setStart(parseLifecycle(reader, "start"));
break;
case STOP:
beanConfig.setStop(parseLifecycle(reader, "stop"));
break;
case DESTROY:
beanConfig.setDestroy(parseLifecycle(reader, "destroy"));
break;
case UNKNOWN:
throw unexpectedElement(reader);
}
break;
}
}
throw unexpectedElement(reader);
}
private String parseAlias(final XMLExtendedStreamReader reader) throws XMLStreamException {
final String alias = parseTextElement(reader);
if (alias == null || alias.trim().length() == 0)
throw PojoLogger.ROOT_LOGGER.nullOrEmptyAlias();
return alias;
}
private ConstructorConfig parseConstructor(final XMLExtendedStreamReader reader) throws XMLStreamException {
final ConstructorConfig ctorConfig = new ConstructorConfig();
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final Attribute attribute = Attribute.of(reader.getAttributeLocalName(i));
final String attributeValue = reader.getAttributeValue(i);
switch (attribute) {
case FACTORY_CLASS:
case FACTORY_CLASS_LEGACY:
ctorConfig.setFactoryClass(attributeValue);
break;
case FACTORY_METHOD:
case FACTORY_METHOD_LEGACY:
ctorConfig.setFactoryMethod(attributeValue);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
List<ValueConfig> parameters = new ArrayList<ValueConfig>();
while (reader.hasNext()) {
switch (reader.next()) {
case END_ELEMENT:
ctorConfig.setParameters(parameters.toArray(new ValueConfig[parameters.size()]));
return ctorConfig;
case START_ELEMENT:
switch (Element.of(reader.getLocalName())) {
case FACTORY:
ctorConfig.setFactory(parseFactory(reader));
break;
case PARAMETER:
ValueConfig p = parseParameter(reader);
p.setIndex(parameters.size());
parameters.add(p);
break;
default:
throw unexpectedElement(reader);
}
}
}
throw unexpectedElement(reader);
}
private ModuleConfig parseModuleConfig(final XMLExtendedStreamReader reader) throws XMLStreamException {
final ModuleConfig moduleConfig = new ModuleConfig();
final int count = reader.getAttributeCount();
final Set<Attribute> required = EnumSet.of(Attribute.NAME);
for (int i = 0; i < count; i++) {
final Attribute attribute = Attribute.of(reader.getAttributeLocalName(i));
required.remove(attribute);
final String attributeValue = reader.getAttributeValue(i);
switch (attribute) {
case NAME:
moduleConfig.setModuleName(attributeValue);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (required.isEmpty() == false) {
throw missingRequired(reader, required);
}
return moduleConfig;
}
private PropertyConfig parseProperty(final XMLExtendedStreamReader reader) throws XMLStreamException {
final PropertyConfig property = new PropertyConfig();
final Set<Attribute> required = EnumSet.of(Attribute.NAME);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final Attribute attribute = Attribute.of(reader.getAttributeLocalName(i));
required.remove(attribute);
final String attributeValue = reader.getAttributeValue(i);
switch (attribute) {
case NAME:
property.setPropertyName(attributeValue);
break;
case CLASS:
property.setType(attributeValue);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (required.isEmpty() == false) {
throw missingRequired(reader, required);
}
while (reader.hasNext()) {
switch (reader.next()) {
case END_ELEMENT:
return property;
case START_ELEMENT:
switch (Element.of(reader.getLocalName())) {
case VALUE:
property.setValue(parseValue(reader));
break;
case INJECT:
property.setValue(parseInject(reader));
break;
case VALUE_FACTORY:
property.setValue(parseValueFactory(reader));
break;
case LIST:
property.setValue(parseList(reader));
break;
case SET:
property.setValue(parseSet(reader));
break;
case MAP:
property.setValue(parseMap(reader));
break;
default:
throw unexpectedElement(reader);
}
}
}
throw unexpectedElement(reader);
}
private InstallConfig parseInstall(final XMLExtendedStreamReader reader) throws XMLStreamException {
final InstallConfig installConfig = new InstallConfig();
final Set<Attribute> required = EnumSet.of(Attribute.METHOD);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final Attribute attribute = Attribute.of(reader.getAttributeLocalName(i));
required.remove(attribute);
final String attributeValue = reader.getAttributeValue(i);
switch (attribute) {
case STATE:
installConfig.setWhenRequired(BeanState.valueOf(attributeValue.toUpperCase(Locale.ENGLISH)));
break;
case TARGET_STATE:
installConfig.setDependencyState(BeanState.valueOf(attributeValue.toUpperCase(Locale.ENGLISH)));
break;
case BEAN:
installConfig.setDependency(attributeValue);
break;
case METHOD:
installConfig.setMethodName(attributeValue);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (required.isEmpty() == false) {
throw missingRequired(reader, required);
}
List<ValueConfig> parameters = new ArrayList<ValueConfig>();
while (reader.hasNext()) {
switch (reader.next()) {
case END_ELEMENT:
installConfig.setParameters(parameters.toArray(new ValueConfig[parameters.size()]));
return installConfig;
case START_ELEMENT:
switch (Element.of(reader.getLocalName())) {
case PARAMETER:
ValueConfig p = parseParameter(reader);
p.setIndex(parameters.size());
parameters.add(p);
break;
default:
throw unexpectedElement(reader);
}
}
}
throw unexpectedElement(reader);
}
private CallbackConfig parseCallback(final XMLExtendedStreamReader reader) throws XMLStreamException {
final CallbackConfig callbackConfig = new CallbackConfig();
final Set<Attribute> required = EnumSet.of(Attribute.METHOD);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final Attribute attribute = Attribute.of(reader.getAttributeLocalName(i));
required.remove(attribute);
final String attributeValue = reader.getAttributeValue(i);
switch (attribute) {
case STATE:
callbackConfig.setWhenRequired(BeanState.valueOf(attributeValue.toUpperCase(Locale.ENGLISH)));
break;
case TARGET_STATE:
callbackConfig.setState(BeanState.valueOf(attributeValue.toUpperCase(Locale.ENGLISH)));
break;
case METHOD:
callbackConfig.setMethodName(attributeValue);
break;
case SIGNATURE:
callbackConfig.setSignature(attributeValue);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (required.isEmpty() == false) {
throw missingRequired(reader, required);
}
while (reader.hasNext()) {
switch (reader.next()) {
case END_ELEMENT:
return callbackConfig;
}
}
throw unexpectedElement(reader);
}
private DependsConfig parseDepends(final XMLExtendedStreamReader reader) throws XMLStreamException {
final DependsConfig dependsConfig = new DependsConfig();
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final Attribute attribute = Attribute.of(reader.getAttributeLocalName(i));
final String attributeValue = reader.getAttributeValue(i);
switch (attribute) {
case STATE:
dependsConfig.setWhenRequired(BeanState.valueOf(attributeValue.toUpperCase(Locale.ENGLISH)));
break;
case TARGET_STATE:
dependsConfig.setDependencyState(BeanState.valueOf(attributeValue.toUpperCase(Locale.ENGLISH)));
break;
case SERVICE:
dependsConfig.setService(Boolean.parseBoolean(attributeValue));
break;
default:
throw unexpectedAttribute(reader, i);
}
}
String dependency = parseTextElement(reader);
if (dependency == null || dependency.trim().length() == 0)
throw PojoLogger.ROOT_LOGGER.nullOrEmptyDependency();
dependsConfig.setDependency(dependency);
return dependsConfig;
}
private LifecycleConfig parseLifecycle(final XMLExtendedStreamReader reader, String defaultMethodName) throws XMLStreamException {
final LifecycleConfig lifecycleConfig = new LifecycleConfig();
lifecycleConfig.setMethodName(defaultMethodName); // set default
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final Attribute attribute = Attribute.of(reader.getAttributeLocalName(i));
final String attributeValue = reader.getAttributeValue(i);
switch (attribute) {
case METHOD:
lifecycleConfig.setMethodName(attributeValue);
break;
case IGNORED:
lifecycleConfig.setIgnored(Boolean.parseBoolean(attributeValue));
break;
default:
throw unexpectedAttribute(reader, i);
}
}
List<ValueConfig> parameters = new ArrayList<ValueConfig>();
while (reader.hasNext()) {
switch (reader.next()) {
case END_ELEMENT:
lifecycleConfig.setParameters(parameters.toArray(new ValueConfig[parameters.size()]));
return lifecycleConfig;
case START_ELEMENT:
switch (Element.of(reader.getLocalName())) {
case PARAMETER:
ValueConfig p = parseParameter(reader);
p.setIndex(parameters.size());
parameters.add(p);
break;
default:
throw unexpectedElement(reader);
}
}
}
throw unexpectedElement(reader);
}
private ValueConfig parseParameter(final XMLExtendedStreamReader reader) throws XMLStreamException {
ValueConfig valueConfig = null;
String type = null;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final Attribute attribute = Attribute.of(reader.getAttributeLocalName(i));
final String attributeValue = reader.getAttributeValue(i);
switch (attribute) {
case CLASS:
type = attributeValue;
break;
default:
throw unexpectedAttribute(reader, i);
}
}
while (reader.hasNext()) {
switch (reader.next()) {
case CHARACTERS:
final StringValueConfig svc = new StringValueConfig();
svc.setValue(reader.getText());
valueConfig = svc;
break;
case END_ELEMENT:
if (valueConfig == null)
throw new XMLStreamException(PojoLogger.ROOT_LOGGER.missingValue(), reader.getLocation());
if (valueConfig.getType() == null)
valueConfig.setType(type);
return valueConfig;
case START_ELEMENT:
switch (Element.of(reader.getLocalName())) {
case VALUE:
valueConfig = parseValue(reader);
break;
case INJECT:
valueConfig = parseInject(reader);
break;
case VALUE_FACTORY:
valueConfig = parseValueFactory(reader);
break;
case LIST:
valueConfig = parseList(reader);
break;
case SET:
valueConfig = parseSet(reader);
break;
case MAP:
valueConfig = parseMap(reader);
break;
default:
throw unexpectedElement(reader);
}
}
}
throw unexpectedElement(reader);
}
private InjectedValueConfig parseInject(final XMLExtendedStreamReader reader) throws XMLStreamException {
final InjectedValueConfig injectedValueConfig = new InjectedValueConfig();
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final Attribute attribute = Attribute.of(reader.getAttributeLocalName(i));
final String attributeValue = reader.getAttributeValue(i);
switch (attribute) {
case BEAN:
injectedValueConfig.setBean(attributeValue);
break;
case STATE:
injectedValueConfig.setState(BeanState.valueOf(attributeValue.toUpperCase(Locale.ENGLISH)));
break;
case SERVICE:
injectedValueConfig.setService(attributeValue);
break;
case PROPERTY:
injectedValueConfig.setProperty(attributeValue);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
while (reader.hasNext()) {
switch (reader.next()) {
case END_ELEMENT:
return injectedValueConfig;
}
}
throw unexpectedElement(reader);
}
private FactoryConfig parseFactory(final XMLExtendedStreamReader reader) throws XMLStreamException {
final FactoryConfig factoryConfig = new FactoryConfig();
final Set<Attribute> required = EnumSet.of(Attribute.BEAN);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final Attribute attribute = Attribute.of(reader.getAttributeLocalName(i));
required.remove(attribute);
final String attributeValue = reader.getAttributeValue(i);
switch (attribute) {
case BEAN:
factoryConfig.setBean(attributeValue);
break;
case STATE:
factoryConfig.setState(BeanState.valueOf(attributeValue.toUpperCase(Locale.ENGLISH)));
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (required.isEmpty() == false) {
throw missingRequired(reader, required);
}
while (reader.hasNext()) {
switch (reader.next()) {
case END_ELEMENT:
return factoryConfig;
}
}
throw unexpectedElement(reader);
}
private ValueConfig parseList(final XMLExtendedStreamReader reader) throws XMLStreamException {
return parseCollection(reader, new ListConfig());
}
private ValueConfig parseSet(final XMLExtendedStreamReader reader) throws XMLStreamException {
return parseCollection(reader, new SetConfig());
}
private ValueConfig parseCollection(final XMLExtendedStreamReader reader, CollectionConfig config) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final Attribute attribute = Attribute.of(reader.getAttributeLocalName(i));
final String attributeValue = reader.getAttributeValue(i);
switch (attribute) {
case CLASS:
config.setType(attributeValue);
break;
case ELEMENT:
config.setElementType(attributeValue);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
while (reader.hasNext()) {
switch (reader.next()) {
case END_ELEMENT:
return config;
case START_ELEMENT:
switch (Element.of(reader.getLocalName())) {
case VALUE:
config.addValue(parseValue(reader));
break;
case INJECT:
config.addValue(parseInject(reader));
break;
case VALUE_FACTORY:
config.addValue(parseValueFactory(reader));
break;
case LIST:
config.addValue(parseList(reader));
break;
case SET:
config.addValue(parseSet(reader));
break;
case MAP:
config.addValue(parseMap(reader));
break;
default:
throw unexpectedElement(reader);
}
}
}
throw unexpectedElement(reader);
}
private ValueConfig parseMap(final XMLExtendedStreamReader reader) throws XMLStreamException {
MapConfig mapConfig = new MapConfig();
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final Attribute attribute = Attribute.of(reader.getAttributeLocalName(i));
final String attributeValue = reader.getAttributeValue(i);
switch (attribute) {
case CLASS:
mapConfig.setType(attributeValue);
break;
case KEY_ELEMENT:
mapConfig.setKeyType(attributeValue);
break;
case VALUE_ELEMENT:
mapConfig.setValueType(attributeValue);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
while (reader.hasNext()) {
switch (reader.next()) {
case END_ELEMENT:
return mapConfig;
case START_ELEMENT:
switch (Element.of(reader.getLocalName())) {
case ENTRY:
ValueConfig[] entry = parseEntry(reader);
mapConfig.put(entry[0], entry[1]);
break;
default:
throw unexpectedElement(reader);
}
}
}
throw unexpectedElement(reader);
}
private ValueConfig[] parseEntry(final XMLExtendedStreamReader reader) throws XMLStreamException {
ValueConfig[] entry = new ValueConfig[2];
while (reader.hasNext()) {
switch (reader.next()) {
case END_ELEMENT:
return entry;
case START_ELEMENT:
switch (Element.of(reader.getLocalName())) {
case KEY:
entry[0] = parseValueValue(reader);
break;
case VALUE:
entry[1] = parseValueValue(reader);
break;
default:
throw unexpectedElement(reader);
}
}
}
throw unexpectedElement(reader);
}
private ValueConfig parseValueValue(final XMLExtendedStreamReader reader) throws XMLStreamException {
ValueConfig value = null;
while (reader.hasNext()) {
switch (reader.next()) {
case END_ELEMENT:
if (value == null)
throw new XMLStreamException(PojoLogger.ROOT_LOGGER.missingValue(), reader.getLocation());
return value;
case START_ELEMENT:
switch (Element.of(reader.getLocalName())) {
case VALUE:
value = parseValue(reader);
break;
case INJECT:
value = parseInject(reader);
break;
case VALUE_FACTORY:
value = parseValueFactory(reader);
break;
case LIST:
value = parseList(reader);
break;
case SET:
value = parseSet(reader);
break;
case MAP:
value = parseMap(reader);
break;
default:
throw unexpectedElement(reader);
}
break;
case CHARACTERS:
StringValueConfig svc = new StringValueConfig();
svc.setValue(reader.getText());
value = svc;
break;
}
}
throw unexpectedElement(reader);
}
private ValueFactoryConfig parseValueFactory(final XMLExtendedStreamReader reader) throws XMLStreamException {
final ValueFactoryConfig valueFactoryConfig = new ValueFactoryConfig();
final Set<Attribute> required = EnumSet.of(Attribute.BEAN, Attribute.METHOD);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final Attribute attribute = Attribute.of(reader.getAttributeLocalName(i));
required.remove(attribute);
final String attributeValue = reader.getAttributeValue(i);
switch (attribute) {
case BEAN:
valueFactoryConfig.setBean(attributeValue);
break;
case METHOD:
valueFactoryConfig.setMethod(attributeValue);
break;
case STATE:
valueFactoryConfig.setState(BeanState.valueOf(attributeValue.toUpperCase(Locale.ENGLISH)));
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (required.isEmpty() == false) {
throw missingRequired(reader, required);
}
List<ValueConfig> parameters = new ArrayList<ValueConfig>();
while (reader.hasNext()) {
switch (reader.next()) {
case END_ELEMENT:
valueFactoryConfig.setParameters(parameters.toArray(new ValueConfig[parameters.size()]));
return valueFactoryConfig;
case START_ELEMENT:
switch (Element.of(reader.getLocalName())) {
case PARAMETER:
ValueConfig p = parseParameter(reader);
p.setIndex(parameters.size());
parameters.add(p);
break;
default:
throw unexpectedElement(reader);
}
}
}
throw unexpectedElement(reader);
}
private ValueConfig parseValue(final XMLExtendedStreamReader reader) throws XMLStreamException {
final StringValueConfig valueConfig = new StringValueConfig();
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final Attribute attribute = Attribute.of(reader.getAttributeLocalName(i));
final String attributeValue = reader.getAttributeValue(i);
switch (attribute) {
case CLASS:
valueConfig.setType(attributeValue);
break;
case REPLACE:
valueConfig.setReplaceProperties(Boolean.parseBoolean(attributeValue));
break;
case TRIM:
valueConfig.setTrim(Boolean.parseBoolean(attributeValue));
break;
default:
throw unexpectedAttribute(reader, i);
}
}
valueConfig.setValue(parseTextElement(reader));
return valueConfig;
}
private String parseTextElement(final XMLExtendedStreamReader reader) throws XMLStreamException {
String value = null;
while (reader.hasNext()) {
switch (reader.next()) {
case END_ELEMENT:
return value;
case CHARACTERS:
value = reader.getText();
break;
default:
throw unexpectedElement(reader);
}
}
throw unexpectedElement(reader);
}
}
| 40,233
| 40.013252
| 142
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/BeanFactoryMetaDataConfig.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.pojo.descriptor;
import org.jboss.as.pojo.BeanState;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
/**
* The legacy bean factory meta data.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class BeanFactoryMetaDataConfig extends BeanMetaDataConfig implements Serializable {
private static final long serialVersionUID = 1L;
private final BeanMetaDataConfig bean;
public BeanFactoryMetaDataConfig(BeanMetaDataConfig bean) {
this.bean = bean;
setName(bean.getName());
bean.setName(getName() + "_Bean");
setBeanClass(BaseBeanFactory.class.getName());
ModuleConfig moduleConfig = new ModuleConfig();
moduleConfig.setModuleName("org.jboss.as.pojo");
setModule(moduleConfig);
PropertyConfig pc = new PropertyConfig();
pc.setPropertyName("bmd");
ValueConfig vc = new ValueConfig() {
protected Object getClassValue(Class<?> type) {
return BeanFactoryMetaDataConfig.this.bean;
}
};
pc.setValue(vc);
setProperties(Collections.singleton(pc));
LifecycleConfig ignoredLifecycle = new LifecycleConfig();
ignoredLifecycle.setIgnored(true);
setCreate(ignoredLifecycle);
setStart(ignoredLifecycle);
setStop(ignoredLifecycle);
setDestroy(ignoredLifecycle);
}
@Override
protected void addChildren(ConfigVisitor visitor, List<ConfigVisitorNode> nodes) {
nodes.add(bean); // always check bean meta data
BeanState state = visitor.getState();
if (state == BeanState.NOT_INSTALLED)
nodes.add(getModule());
if (state == BeanState.INSTANTIATED)
nodes.addAll(getProperties());
}
}
| 2,860
| 35.21519
| 91
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/StringValueConfig.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.pojo.descriptor;
import org.jboss.as.pojo.logging.PojoLogger;
import org.jboss.as.pojo.service.Configurator;
/**
* String value.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class StringValueConfig extends ValueConfig {
private static final long serialVersionUID = 1L;
private String value;
private boolean replaceProperties;
private boolean trim;
private Class<?> clazz;
@Override
public void visit(ConfigVisitor visitor) {
if (getType() != null) {
try {
clazz = visitor.getModule().getClassLoader().loadClass(getType());
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException(e);
}
}
}
@Override
protected Object getClassValue(Class<?> type) {
if (type == null)
type = clazz;
if (type == null)
throw PojoLogger.ROOT_LOGGER.cannotDetermineInjectedType(toString());
try {
return Configurator.convertValue(type, value, replaceProperties, trim);
} catch (Throwable t) {
throw new IllegalArgumentException(t);
}
}
public void setValue(String value) {
this.value = value;
}
public void setReplaceProperties(boolean replaceProperties) {
this.replaceProperties = replaceProperties;
}
public void setTrim(boolean trim) {
this.trim = trim;
}
}
| 2,507
| 31.153846
| 83
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/ModeConfig.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.pojo.descriptor;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.jboss.as.pojo.logging.PojoLogger;
import org.jboss.msc.service.ServiceController;
/**
* Mode config.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public enum ModeConfig {
ACTIVE("active", ServiceController.Mode.ACTIVE),
PASSIVE("passive", ServiceController.Mode.PASSIVE),
ON_DEMAND("on demand", ServiceController.Mode.ON_DEMAND),
NEVER("never", ServiceController.Mode.NEVER);
private static final Map<String, ModeConfig> MAP = new HashMap<String, ModeConfig>();
static {
for(ModeConfig mode : values()) {
MAP.put(mode.value, mode);
}
}
private final String value;
private final ServiceController.Mode mode;
private ModeConfig(final String value, final ServiceController.Mode mode) {
this.value = value;
this.mode = mode;
}
public ServiceController.Mode getMode() {
return mode;
}
static ModeConfig of(String value) {
if (value == null)
throw PojoLogger.ROOT_LOGGER.nullValue();
final ModeConfig controllerMode = MAP.get(value.toLowerCase(Locale.ENGLISH));
return controllerMode == null ? PASSIVE : controllerMode;
}
}
| 2,351
| 32.126761
| 89
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/ListConfig.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.pojo.descriptor;
import java.util.ArrayList;
import java.util.Collection;
/**
* List meta data.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class ListConfig extends CollectionConfig {
private static final long serialVersionUID = 1L;
@Override
protected Collection<Object> createDefaultInstance() {
return new ArrayList<Object>();
}
}
| 1,451
| 35.3
| 70
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/AbstractConfigVisitorNode.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.pojo.descriptor;
import org.jboss.as.pojo.service.BeanInfo;
import org.jboss.as.pojo.service.DefaultBeanInfo;
import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
/**
* Abstract config visitor node.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public abstract class AbstractConfigVisitorNode implements ConfigVisitorNode, TypeProvider {
public void visit(ConfigVisitor visitor) {
visitor.visit(this);
}
/**
* Add children as needed.
*
* @param visitor the current visitor
* @param nodes the nodes list to add to
*/
protected void addChildren(ConfigVisitor visitor, List<ConfigVisitorNode> nodes) {
}
public Iterable<ConfigVisitorNode> getChildren(ConfigVisitor visitor) {
List<ConfigVisitorNode> nodes = new ArrayList<ConfigVisitorNode>();
addChildren(visitor, nodes);
return nodes;
}
/**
* Get temp bean info.
*
* @param visitor the visitor
* @param className the class name
* @return bean info
*/
protected static BeanInfo getTempBeanInfo(ConfigVisitor visitor, String className) {
return getTempBeanInfo(visitor, getType(visitor, className));
}
/**
* Get temp bean info.
*
* @param visitor the visitor
* @param clazz the class
* @return bean info
*/
@SuppressWarnings({"unchecked"})
protected static BeanInfo getTempBeanInfo(ConfigVisitor visitor, Class<?> clazz) {
return new DefaultBeanInfo(visitor.getReflectionIndex(), clazz);
}
/**
* Get temp bean info.
*
* @param clazz the class
* @return bean info
*/
@SuppressWarnings({"unchecked"})
protected static BeanInfo getTempBeanInfo(Class<?> clazz) {
return new DefaultBeanInfo(DeploymentReflectionIndex.create(), clazz);
}
/**
* Load class.
*
* @param visitor the visitor
* @param className the class name
* @return class or null if null class name
*/
protected static Class<?> getType(ConfigVisitor visitor, String className) {
if (className != null) {
try {
return visitor.getModule().getClassLoader().loadClass(className);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
return null;
}
/**
* Get component type.
*
* @param type the type
* @param index the component index
* @return component's class or null if cannot be determined
*/
static Type getComponentType(ParameterizedType type, int index) {
Type[] tp = type.getActualTypeArguments();
if (index + 1 > tp.length)
return null;
return tp[index];
}
@Override
public Class<?> getType(ConfigVisitor visitor, ConfigVisitorNode previous) {
Deque<ConfigVisitorNode> nodes = visitor.getCurrentNodes();
if (nodes.isEmpty())
throw new IllegalArgumentException("Cannot determine type - insufficient info on configuration!");
ConfigVisitorNode current = nodes.pop();
try {
if (current instanceof TypeProvider) {
return TypeProvider.class.cast(current).getType(visitor, current);
} else {
return getType(visitor, current);
}
} finally {
nodes.push(current);
}
}
}
| 4,653
| 30.876712
| 110
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/KernelDeploymentXmlDescriptor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.pojo.descriptor;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.server.deployment.AttachmentList;
import java.io.Serializable;
import java.util.List;
/**
* The object representation of a legacy "jboss-beans.xml" descriptor file.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class KernelDeploymentXmlDescriptor implements Serializable {
private static final long serialVersionUID = 1L;
public static final AttachmentKey<AttachmentList<KernelDeploymentXmlDescriptor>> ATTACHMENT_KEY = AttachmentKey.createList(KernelDeploymentXmlDescriptor.class);
private List<BeanMetaDataConfig> beans;
private ModeConfig mode;
private int beanFactoriesCount;
public List<BeanMetaDataConfig> getBeans() {
return beans;
}
public void setBeans(List<BeanMetaDataConfig> beans) {
this.beans = beans;
}
public ModeConfig getMode() {
return mode;
}
public void setMode(ModeConfig mode) {
this.mode = mode;
}
public int getBeanFactoriesCount() {
return beanFactoriesCount;
}
public void incrementBeanFactoryCount() {
beanFactoriesCount++;
}
}
| 2,261
| 32.264706
| 164
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/DefaultConfigVisitor.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.pojo.descriptor;
import org.jboss.as.pojo.BeanState;
import org.jboss.as.pojo.service.BeanInfo;
import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
/**
* Default config visitor.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
* @author <a href="mailto:ropalka@jboss.org">Richard Opalka</a>
*/
public class DefaultConfigVisitor extends AbstractConfigVisitor {
private final ServiceBuilder builder;
private final BeanState state;
private final Module module;
private final DeploymentReflectionIndex index;
private final BeanInfo beanInfo;
public DefaultConfigVisitor(ServiceBuilder builder, BeanState state, Module module, DeploymentReflectionIndex index) {
this(builder, state, module, index, null);
}
public DefaultConfigVisitor(ServiceBuilder builder, BeanState state, Module module, DeploymentReflectionIndex index, BeanInfo beanInfo) {
this.builder = builder;
this.state = state;
this.module = module;
this.index = index;
this.beanInfo = beanInfo;
}
@Override
public BeanState getState() {
return state;
}
@Override
public Module getModule() {
return module;
}
@Override
public Module loadModule(ModuleIdentifier identifier) {
try {
return module.getModule(identifier);
} catch (Throwable t) {
throw new IllegalArgumentException(t);
}
}
@Override
public DeploymentReflectionIndex getReflectionIndex() {
return index;
}
@Override
public BeanInfo getBeanInfo() {
return beanInfo;
}
@Override
public void addDependency(ServiceName name) {
builder.requires(name);
}
@Override
public void addDependency(ServiceName name, Injector injector) {
builder.addDependency(name, Object.class, injector);
}
@Override
public void addDependency(String bean, BeanState state) {
if (state != BeanState.DESCRIBED)
builder.requires(BeanMetaDataConfig.toBeanName(bean, BeanState.DESCRIBED));
builder.requires(BeanMetaDataConfig.toBeanName(bean, state));
}
@Override
public void addDependency(String bean, BeanState state, Injector injector) {
if (state != BeanState.DESCRIBED)
builder.requires(BeanMetaDataConfig.toBeanName(bean, BeanState.DESCRIBED));
builder.addDependency(BeanMetaDataConfig.toBeanName(bean, state), Object.class, injector);
}
}
| 3,777
| 32.732143
| 141
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/LifecycleConfig.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.pojo.descriptor;
import org.jboss.as.pojo.logging.PojoLogger;
import org.jboss.as.pojo.service.BeanInfo;
import org.jboss.as.pojo.service.Configurator;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
/**
* Lifecycle meta data.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class LifecycleConfig extends AbstractConfigVisitorNode implements Serializable {
private static final long serialVersionUID = 1L;
private String methodName;
private ValueConfig[] parameters;
private boolean ignored;
@Override
protected void addChildren(ConfigVisitor visitor, List<ConfigVisitorNode> nodes) {
if (parameters != null)
nodes.addAll(Arrays.asList(parameters));
}
@Override
public Class<?> getType(ConfigVisitor visitor, ConfigVisitorNode previous) {
if (previous instanceof ValueConfig == false)
throw PojoLogger.ROOT_LOGGER.notValueConfig(previous);
ValueConfig vc = (ValueConfig) previous;
BeanInfo beanInfo = visitor.getBeanInfo();
Method m = beanInfo.findMethod(methodName, Configurator.getTypes(parameters));
return m.getParameterTypes()[vc.getIndex()];
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public ValueConfig[] getParameters() {
return parameters;
}
public void setParameters(ValueConfig[] parameters) {
this.parameters = parameters;
}
public boolean isIgnored() {
return ignored;
}
public void setIgnored(boolean ignored) {
this.ignored = ignored;
}
}
| 2,814
| 31.732558
| 88
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/TypeProvider.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.pojo.descriptor;
/**
* Type provider spi.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public interface TypeProvider {
/**
* Try getting type off config.
*
* @param visitor the current config visitor
* @param previous previous config visitor node
* @return type
*/
Class<?> getType(ConfigVisitor visitor, ConfigVisitorNode previous);
}
| 1,449
| 35.25
| 72
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/ConfigVisitor.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.pojo.descriptor;
import org.jboss.as.pojo.BeanState;
import org.jboss.as.pojo.service.BeanInfo;
import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.ServiceName;
import java.util.Deque;
/**
* Config visitor.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public interface ConfigVisitor {
/**
* Visit node's children.
*
* @param node the config node
*/
void visit(ConfigVisitorNode node);
/**
* Get current nodes.
*
* @return the current nodes
*/
Deque<ConfigVisitorNode> getCurrentNodes();
/**
* Get current state.
*
* @return the state
*/
BeanState getState();
/**
* Get module for this visitor.
*
* @return the classloader
*/
Module getModule();
/**
* Load module.
*
* @param identifier the module identifier
* @return loaded module
*/
Module loadModule(ModuleIdentifier identifier);
/**
* Get reflection index.
*
* @return the reflection index
*/
DeploymentReflectionIndex getReflectionIndex();
/**
* Get bean info.
*
* @return the bean info
*/
BeanInfo getBeanInfo();
/**
* Add dependency.
*
* @param name the dependency name
*/
void addDependency(ServiceName name);
/**
* Add dependency.
*
* @param name the dependency name
* @param injector the injector
*/
void addDependency(ServiceName name, Injector injector);
/**
* Add bean dependency.
*
* @param bean the dependency name
* @param state the required bean state
*/
void addDependency(String bean, BeanState state);
/**
* Add bean dependency.
*
* @param bean the dependency name
* @param state the required bean state
* @param injector the injector
*/
void addDependency(String bean, BeanState state, Injector injector);
}
| 3,175
| 24.821138
| 72
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/DependsConfig.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.pojo.descriptor;
import org.jboss.as.pojo.BeanState;
import org.jboss.msc.service.ServiceName;
import java.io.Serializable;
/**
* The legacy depends meta data.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class DependsConfig extends AbstractConfigVisitorNode implements Serializable {
private static final long serialVersionUID = 1L;
private String dependency;
private BeanState whenRequired = BeanState.INSTALLED;
private BeanState dependencyState;
private boolean service;
@Override
public void visit(ConfigVisitor visitor) {
if (visitor.getState().equals(whenRequired)) {
if (service)
visitor.addDependency(ServiceName.parse(dependency));
else
visitor.addDependency(dependency, dependencyState);
}
}
public void setDependency(String dependency) {
this.dependency = dependency;
}
public void setWhenRequired(BeanState whenRequired) {
this.whenRequired = whenRequired;
}
public void setDependencyState(BeanState dependencyState) {
this.dependencyState = dependencyState;
}
public void setService(boolean service) {
this.service = service;
}
}
| 2,310
| 32.985294
| 86
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/CollectionConfig.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.pojo.descriptor;
import org.jboss.as.pojo.logging.PojoLogger;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Collection meta data.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public abstract class CollectionConfig extends ValueConfig implements Serializable {
private static final long serialVersionUID = 1L;
/** The element type */
protected String elementType;
private List<ValueConfig> values = new ArrayList<ValueConfig>();
private Class<?> collectionType;
private Class<?> componentType;
protected abstract Collection<Object> createDefaultInstance();
@SuppressWarnings({"unchecked"})
protected Collection<Object> createInstance() {
try {
if (collectionType != null) {
return (Collection<Object>) collectionType.newInstance();
} else {
return createDefaultInstance();
}
} catch (Exception e) {
throw PojoLogger.ROOT_LOGGER.cannotInstantiateCollection(e);
}
}
@Override
public void visit(ConfigVisitor visitor) {
collectionType = getType(visitor, getType());
componentType = getType(visitor, elementType);
super.visit(visitor);
}
@Override
protected void addChildren(ConfigVisitor visitor, List<ConfigVisitorNode> nodes) {
nodes.addAll(values);
}
protected Object getPtValue(ParameterizedType type) {
Type ct = componentType;
if (ct == null && type != null)
ct = getComponentType(type, 0);
Collection<Object> result = createInstance();
for (ValueConfig vc : values) {
result.add(vc.getValue(ct));
}
return result;
}
protected Object getClassValue(Class<?> type) {
Collection<Object> result = createInstance();
for (ValueConfig vc : values) {
result.add(vc.getValue(componentType));
}
return result;
}
public void setElementType(String elementType) {
this.elementType = elementType;
}
public void addValue(ValueConfig value) {
values.add(value);
}
}
| 3,355
| 31.901961
| 86
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/InstallConfig.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.pojo.descriptor;
import org.jboss.as.pojo.BeanState;
import org.jboss.as.pojo.logging.PojoLogger;
import org.jboss.as.pojo.service.BeanInfo;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.value.InjectedValue;
/**
* Install meta data.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class InstallConfig extends LifecycleConfig {
private static final long serialVersionUID = 1L;
private final transient InjectedValue<BeanInfo> beanInfo = new InjectedValue<BeanInfo>();
private final transient InjectedValue<Object> bean = new InjectedValue<Object>();
private String dependency;
private BeanState whenRequired = BeanState.INSTALLED;
private BeanState dependencyState;
@Override
public void visit(ConfigVisitor visitor) {
if (visitor.getState().next() == whenRequired) {
if (dependency != null) {
visitor.addDependency(dependency, BeanState.DESCRIBED, getBeanInfo());
ServiceName name = BeanMetaDataConfig.toBeanName(dependency, dependencyState);
visitor.addDependency(name, getBean()); // direct name, since we have describe already
}
super.visit(visitor);
}
}
@Override
public Class<?> getType(ConfigVisitor visitor, ConfigVisitorNode previous) {
if (dependency != null)
throw PojoLogger.ROOT_LOGGER.tooDynamicFromDependency();
return super.getType(visitor, previous);
}
public String getDependency() {
return dependency;
}
public void setDependency(String dependency) {
this.dependency = dependency;
}
public BeanState getWhenRequired() {
return whenRequired;
}
public void setWhenRequired(BeanState whenRequired) {
this.whenRequired = whenRequired;
}
public void setDependencyState(BeanState dependencyState) {
this.dependencyState = dependencyState;
}
public InjectedValue<BeanInfo> getBeanInfo() {
return beanInfo;
}
public InjectedValue<Object> getBean() {
return bean;
}
}
| 3,181
| 33.215054
| 102
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/ConfigVisitorNode.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.pojo.descriptor;
/**
* Config visitor node.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public interface ConfigVisitorNode {
/**
* Visit metadata node.
* e.g. add dependencies to service builder.
*
* @param visitor the config visitor
*/
void visit(ConfigVisitor visitor);
/**
* Get children.
*
* @param visitor the current visitor
* @return the config node children
*/
Iterable<ConfigVisitorNode> getChildren(ConfigVisitor visitor);
}
| 1,578
| 32.595745
| 70
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/ModuleConfig.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.pojo.descriptor;
import org.jboss.as.server.moduleservice.ServiceModuleLoader;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.value.InjectedValue;
import java.io.Serializable;
/**
* The module meta data.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class ModuleConfig extends AbstractConfigVisitorNode implements Serializable {
private static final long serialVersionUID = 1L;
private String moduleName;
private final InjectedValue<Module> injectedModule = new InjectedValue<Module>();
@Override
public void visit(ConfigVisitor visitor) {
if (moduleName != null) {
ModuleIdentifier identifier = ModuleIdentifier.fromString(moduleName);
if (moduleName.startsWith(ServiceModuleLoader.MODULE_PREFIX)) {
ServiceName serviceName = ServiceModuleLoader.moduleServiceName(identifier);
visitor.addDependency(serviceName, getInjectedModule());
} else {
Module dm = visitor.loadModule(identifier);
getInjectedModule().setValue(() -> dm);
}
} else {
getInjectedModule().setValue(() -> visitor.getModule());
}
// no children, no need to visit
}
public String getModuleName() {
return moduleName;
}
public void setModuleName(String moduleName) {
this.moduleName = moduleName;
}
public InjectedValue<Module> getInjectedModule() {
return injectedModule;
}
}
| 2,659
| 35.944444
| 92
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/BeanDeploymentSchema.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.pojo.descriptor;
import java.util.List;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.xml.IntVersionSchema;
import org.jboss.as.controller.xml.VersionedNamespace;
import org.jboss.as.controller.xml.XMLElementSchema;
import org.jboss.as.pojo.ParseResult;
import org.jboss.as.pojo.logging.PojoLogger;
import org.jboss.staxmapper.IntVersion;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* Enumerates supported namespaces of the POJO deployment descriptor.
* @author Paul Ferraro
*/
public enum BeanDeploymentSchema implements XMLElementSchema<BeanDeploymentSchema, ParseResult<KernelDeploymentXmlDescriptor>> {
VERSION_1_0("bean-deployer", 1),
VERSION_2_0("bean-deployer", 2),
VERSION_7_0("pojo", 7),
;
static final BeanDeploymentSchema CURRENT = VERSION_7_0;
private final VersionedNamespace<IntVersion, BeanDeploymentSchema> namespace;
BeanDeploymentSchema(String nss, int major) {
this.namespace = IntVersionSchema.createURN(List.of(IntVersionSchema.JBOSS_IDENTIFIER, nss), new IntVersion(major));
}
@Override
public VersionedNamespace<IntVersion, BeanDeploymentSchema> getNamespace() {
return this.namespace;
}
@Override
public String getLocalName() {
return "deployment";
}
@Override
public void readElement(XMLExtendedStreamReader reader, ParseResult<KernelDeploymentXmlDescriptor> result) throws XMLStreamException {
if (!this.since(CURRENT)) {
PojoLogger.ROOT_LOGGER.oldNamespace(this.namespace.getUri());
}
new KernelDeploymentXmlDescriptorParser(this).readElement(reader, result);
}
}
| 2,719
| 36.260274
| 138
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/MapConfig.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.pojo.descriptor;
import org.jboss.as.pojo.logging.PojoLogger;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Map meta data.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class MapConfig extends ValueConfig implements Serializable {
private static final long serialVersionUID = 1L;
protected String keyType;
protected String valueType;
private Map<ValueConfig, ValueConfig> map = new HashMap<ValueConfig, ValueConfig>();
private Class<?> mapType;
private Class<?> keyClass;
private Class<?> valueClass;
@SuppressWarnings({"unchecked"})
protected Map<Object, Object> createInstance() {
try {
if (mapType != null) {
return (Map<Object, Object>) mapType.newInstance();
} else {
return new HashMap();
}
} catch (Exception e) {
throw PojoLogger.ROOT_LOGGER.cannotInstantiateMap(e);
}
}
@Override
public void visit(ConfigVisitor visitor) {
mapType = getType(visitor, getType());
keyClass = getType(visitor, keyType);
valueClass = getType(visitor, valueType);
super.visit(visitor);
}
@Override
protected void addChildren(ConfigVisitor visitor, List<ConfigVisitorNode> nodes) {
nodes.addAll(map.keySet());
nodes.addAll(map.values());
}
protected Object getPtValue(ParameterizedType type) {
Type kt = keyClass;
if (kt == null && type != null)
kt = getComponentType(type, 0);
Type vt = valueClass;
if (vt == null && type != null)
vt = getComponentType(type, 1);
Map<Object, Object> result = createInstance();
for (Map.Entry<ValueConfig, ValueConfig> entry : map.entrySet()) {
result.put(entry.getKey().getValue(kt), entry.getValue().getValue(vt));
}
return result;
}
protected Object getClassValue(Class<?> type) {
Map<Object, Object> result = createInstance();
for (Map.Entry<ValueConfig, ValueConfig> entry : map.entrySet()) {
result.put(entry.getKey().getValue(keyClass), entry.getValue().getValue(valueClass));
}
return result;
}
public void put(ValueConfig key, ValueConfig value) {
map.put(key, value);
}
public void setKeyType(String keyType) {
this.keyType = keyType;
}
public void setValueType(String valueType) {
this.valueType = valueType;
}
}
| 3,705
| 32.089286
| 97
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/ValueFactoryConfig.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.pojo.descriptor;
import org.jboss.as.pojo.service.ReflectionJoinpoint;
import java.util.Arrays;
import java.util.List;
/**
* Value factory value.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class ValueFactoryConfig extends FactoryConfig {
private static final long serialVersionUID = 1L;
private String method;
private ValueConfig[] parameters;
protected Object getClassValue(Class<?> type) {
try {
ReflectionJoinpoint joinpoint = new ReflectionJoinpoint(beanInfo.getValue(), method);
joinpoint.setTarget(value);
joinpoint.setParameters(parameters);
return joinpoint.dispatch();
} catch (Throwable t) {
throw new IllegalArgumentException(t);
}
}
@Override
protected void addChildren(ConfigVisitor visitor, List<ConfigVisitorNode> nodes) {
if (parameters != null) {
nodes.addAll(Arrays.asList(parameters));
}
}
public void setMethod(String method) {
this.method = method;
}
public void setParameters(ValueConfig[] parameters) {
this.parameters = parameters;
}
}
| 2,227
| 32.253731
| 97
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/FactoryConfig.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.pojo.descriptor;
import org.jboss.as.pojo.BeanState;
import org.jboss.as.pojo.logging.PojoLogger;
import org.jboss.as.pojo.service.BeanInfo;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.value.InjectedValue;
/**
* Factory value.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class FactoryConfig extends ValueConfig {
private static final long serialVersionUID = 1L;
private String bean;
private BeanState state;
protected final transient InjectedValue<BeanInfo> beanInfo = new InjectedValue<BeanInfo>();
protected final transient InjectedValue<Object> value = new InjectedValue<Object>();
protected Object getClassValue(Class<?> type) {
return value.getValue();
}
@Override
public void visit(ConfigVisitor visitor) {
if (bean != null) {
visitor.addDependency(bean, BeanState.DESCRIBED, beanInfo);
ServiceName name = BeanMetaDataConfig.toBeanName(bean, state);
visitor.addDependency(name, value); // direct name, since we have describe already
}
super.visit(visitor);
}
public Class<?> getType(ConfigVisitor visitor, ConfigVisitorNode previous) {
throw PojoLogger.ROOT_LOGGER.tooDynamicFromFactory();
}
public void setBean(String dependency) {
this.bean = dependency;
}
public void setState(BeanState state) {
this.state = state;
}
public BeanInfo getBeanInfo() {
return beanInfo.getValue();
}
}
| 2,574
| 33.333333
| 95
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/BaseBeanFactory.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.pojo.descriptor;
import org.jboss.as.pojo.api.BeanFactory;
import org.jboss.as.pojo.service.BeanInfo;
import org.jboss.as.pojo.service.BeanUtils;
import org.jboss.as.pojo.service.DefaultBeanInfo;
import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex;
import org.jboss.modules.Module;
import java.security.AccessController;
import java.security.PrivilegedAction;
/**
* Base bean factory.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class BaseBeanFactory implements BeanFactory {
private BeanMetaDataConfig bmd;
@SuppressWarnings("unchecked")
public Object create() throws Throwable {
Module module = bmd.getModule().getInjectedModule().getValue();
final SecurityManager sm = System.getSecurityManager();
ClassLoader moduleClassLoader;
if (sm == null) {
moduleClassLoader = module.getClassLoader();
} else {
moduleClassLoader = AccessController.doPrivileged((PrivilegedAction<ClassLoader>) () -> module.getClassLoader());
}
Class<?> beanClass = moduleClassLoader.loadClass(bmd.getBeanClass());
DeploymentReflectionIndex index;
if (sm == null) {
index = DeploymentReflectionIndex.create();
} else {
index = AccessController.doPrivileged((PrivilegedAction<DeploymentReflectionIndex>) () -> DeploymentReflectionIndex.create());
}
BeanInfo beanInfo = new DefaultBeanInfo(index, beanClass);
Object result = BeanUtils.instantiateBean(bmd, beanInfo, index, module);
BeanUtils.configure(bmd, beanInfo, module, result, false);
BeanUtils.dispatchLifecycleJoinpoint(beanInfo, result, bmd.getCreate(), "create");
BeanUtils.dispatchLifecycleJoinpoint(beanInfo, result, bmd.getStart(), "start");
return result;
}
public void setBmd(BeanMetaDataConfig bmd) {
this.bmd = bmd;
}
}
| 2,984
| 39.890411
| 138
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/ConstructorConfig.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.pojo.descriptor;
import org.jboss.as.pojo.logging.PojoLogger;
import org.jboss.as.pojo.service.BeanInfo;
import org.jboss.as.pojo.service.Configurator;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
/**
* Ctor meta data.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class ConstructorConfig extends AbstractConfigVisitorNode implements Serializable {
private static final long serialVersionUID = 1L;
private String factoryClass;
private String factoryMethod;
private FactoryConfig factory;
private ValueConfig[] parameters;
@Override
protected void addChildren(ConfigVisitor visitor, List<ConfigVisitorNode> nodes) {
if (factory != null)
nodes.add(factory);
if (parameters != null)
nodes.addAll(Arrays.asList(parameters));
}
@Override
public Class<?> getType(ConfigVisitor visitor, ConfigVisitorNode previous) {
if (factory != null)
throw PojoLogger.ROOT_LOGGER.tooDynamicFromFactory();
if (previous instanceof ValueConfig == false)
throw PojoLogger.ROOT_LOGGER.notValueConfig(previous);
ValueConfig vc = (ValueConfig) previous;
if (factoryClass != null) {
if (factoryMethod == null)
throw PojoLogger.ROOT_LOGGER.nullFactoryMethod();
BeanInfo beanInfo = getTempBeanInfo(visitor, factoryClass);
Method m = beanInfo.findMethod(factoryMethod, Configurator.getTypes(parameters));
return m.getParameterTypes()[vc.getIndex()];
} else {
BeanInfo beanInfo = visitor.getBeanInfo();
if (beanInfo == null)
throw PojoLogger.ROOT_LOGGER.nullBeanInfo();
Constructor ctor = beanInfo.findConstructor(Configurator.getTypes(parameters));
return ctor.getParameterTypes()[vc.getIndex()];
}
}
public String getFactoryClass() {
return factoryClass;
}
public void setFactoryClass(String factoryClass) {
this.factoryClass = factoryClass;
}
public String getFactoryMethod() {
return factoryMethod;
}
public void setFactoryMethod(String factoryMethod) {
this.factoryMethod = factoryMethod;
}
public FactoryConfig getFactory() {
return factory;
}
public void setFactory(FactoryConfig factory) {
this.factory = factory;
}
public ValueConfig[] getParameters() {
return parameters;
}
public void setParameters(ValueConfig[] parameters) {
this.parameters = parameters;
}
}
| 3,759
| 32.873874
| 93
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/CallbackConfig.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.pojo.descriptor;
import org.jboss.as.pojo.BeanState;
import java.io.Serializable;
/**
* Callback meta data.
* Atm this is simplified version of what we had in JBossAS5/6.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class CallbackConfig extends AbstractConfigVisitorNode implements Serializable {
private static final long serialVersionUID = 1L;
private String methodName;
private BeanState whenRequired = BeanState.INSTALLED;
private BeanState state = BeanState.INSTALLED;
private String signature;
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public BeanState getWhenRequired() {
return whenRequired;
}
public void setWhenRequired(BeanState whenRequired) {
this.whenRequired = whenRequired;
}
public BeanState getState() {
return state;
}
public void setState(BeanState state) {
this.state = state;
}
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
}
| 2,268
| 29.662162
| 87
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/BeanMetaDataConfig.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.pojo.descriptor;
import org.jboss.as.pojo.BeanState;
import org.jboss.msc.service.ServiceName;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
/**
* The legacy bean meta data.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class BeanMetaDataConfig extends AbstractConfigVisitorNode implements Serializable {
private static final long serialVersionUID = 1L;
/** Name prefix of all POJO-style beans. */
private static final ServiceName JBOSS_POJO = ServiceName.JBOSS.append("pojo");
/**
* Get MC bean name.
*
* @param name the original bean name
* @param state the state
* @return bean service name
*/
public static ServiceName toBeanName(String name, BeanState state) {
if (state == null)
state = BeanState.INSTALLED;
return JBOSS_POJO.append(name).append(state.name());
}
/**
* To instances name.
*
* @param clazz the class
* @param state the bean state
* @return unique instance name
*/
public static ServiceName toInstancesName(Class<?> clazz, BeanState state) {
String clName;
ClassLoader classLoader = clazz.getClassLoader();
if (classLoader != null)
clName = classLoader.toString();
else
clName = "SystemClassLoader";
if (state == null)
state = BeanState.INSTALLED;
return JBOSS_POJO.append(clName, clazz.getName(), state.name());
}
private String name;
private String beanClass;
private Set<String> aliases;
private ModeConfig mode;
private ModuleConfig module;
private ConstructorConfig constructor;
private Set<PropertyConfig> properties;
private LifecycleConfig create;
private LifecycleConfig start;
private LifecycleConfig stop;
private LifecycleConfig destroy;
private List<InstallConfig> installs;
private List<InstallConfig> uninstalls;
private List<CallbackConfig> incallbacks;
private List<CallbackConfig> uncallbacks;
private Set<DependsConfig> depends;
@Override
public void visit(ConfigVisitor visitor) {
if (module == null)
module = new ModuleConfig();
super.visit(visitor);
}
protected void addChildren(ConfigVisitor visitor, List<ConfigVisitorNode> nodes) {
BeanState state = visitor.getState();
if (state == BeanState.NOT_INSTALLED)
nodes.add(module);
if (constructor != null && state == BeanState.DESCRIBED)
nodes.add(constructor);
if (properties != null && state == BeanState.INSTANTIATED)
nodes.addAll(properties);
if (create != null && state == BeanState.CONFIGURED)
nodes.add(create);
if (destroy != null && state == BeanState.CONFIGURED)
nodes.add(destroy);
if (start != null && state == BeanState.CREATE)
nodes.add(start);
if (stop != null && state == BeanState.CREATE)
nodes.add(stop);
if (installs != null)
nodes.addAll(installs);
if (uninstalls != null)
nodes.addAll(uninstalls);
if (incallbacks != null)
nodes.addAll(incallbacks);
if (uncallbacks != null)
nodes.addAll(uncallbacks);
if (depends != null)
nodes.addAll(depends);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBeanClass() {
return beanClass;
}
public void setBeanClass(String beanClass) {
this.beanClass = beanClass;
}
public Set<String> getAliases() {
return aliases;
}
public void setAliases(Set<String> aliases) {
this.aliases = aliases;
}
public ModeConfig getMode() {
if (mode == null)
mode = ModeConfig.PASSIVE;
return mode;
}
public void setMode(ModeConfig mode) {
this.mode = mode;
}
public ModuleConfig getModule() {
return module;
}
public void setModule(ModuleConfig module) {
this.module = module;
}
public ConstructorConfig getConstructor() {
return constructor;
}
public void setConstructor(ConstructorConfig constructor) {
this.constructor = constructor;
}
public Set<PropertyConfig> getProperties() {
return properties;
}
public void setProperties(Set<PropertyConfig> properties) {
this.properties = properties;
}
public LifecycleConfig getCreate() {
return create;
}
public void setCreate(LifecycleConfig create) {
this.create = create;
}
public LifecycleConfig getStart() {
return start;
}
public void setStart(LifecycleConfig start) {
this.start = start;
}
public LifecycleConfig getStop() {
return stop;
}
public void setStop(LifecycleConfig stop) {
this.stop = stop;
}
public LifecycleConfig getDestroy() {
return destroy;
}
public void setDestroy(LifecycleConfig destroy) {
this.destroy = destroy;
}
public List<InstallConfig> getInstalls() {
return installs;
}
public void setInstalls(List<InstallConfig> installs) {
this.installs = installs;
}
public List<InstallConfig> getUninstalls() {
return uninstalls;
}
public void setUninstalls(List<InstallConfig> uninstalls) {
this.uninstalls = uninstalls;
}
public List<CallbackConfig> getIncallbacks() {
return incallbacks;
}
public void setIncallbacks(List<CallbackConfig> incallbacks) {
this.incallbacks = incallbacks;
}
public List<CallbackConfig> getUncallbacks() {
return uncallbacks;
}
public void setUncallbacks(List<CallbackConfig> uncallbacks) {
this.uncallbacks = uncallbacks;
}
public Set<DependsConfig> getDepends() {
return depends;
}
public void setDepends(Set<DependsConfig> depends) {
this.depends = depends;
}
}
| 7,221
| 26.88417
| 91
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/ValueConfig.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.pojo.descriptor;
import org.jboss.as.pojo.logging.PojoLogger;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* Value meta data.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public abstract class ValueConfig extends AbstractConfigVisitorNode implements Serializable {
private static final long serialVersionUID = 1L;
private String type;
private int index = -1;
/**
* Get value.
*
* @param type the type
* @return value
*/
public Object getValue(Type type) {
if (type == null || (type instanceof Class)) {
return getClassValue((Class) type);
} else if (type instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) type;
return getPtValue(pt);
} else {
throw PojoLogger.ROOT_LOGGER.unknownType(type);
}
}
/**
* Get value.
*
* @param type the parameterized type
* @return value
*/
protected Object getPtValue(ParameterizedType type) {
return getValue(type.getRawType());
}
/**
* Get value, use type to narrow down exact value.
*
* @param type the injection point type
* @return value
*/
protected abstract Object getClassValue(Class<?> type);
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
| 2,678
| 28.119565
| 93
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/InjectedValueConfig.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.pojo.descriptor;
import org.jboss.as.pojo.BeanState;
import org.jboss.as.pojo.logging.PojoLogger;
import org.jboss.as.pojo.service.BeanInfo;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.value.InjectedValue;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;
/**
* Injected value.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class InjectedValueConfig extends ValueConfig {
private static final long serialVersionUID = 1L;
private String bean;
private BeanState state;
private String service;
private String property;
private final transient InjectedValue<BeanInfo> beanInfo = new InjectedValue<BeanInfo>();
private final transient InjectedValue<Object> value = new InjectedValue<Object>();
protected Object getClassValue(Class<?> type) {
Object result = value.getValue();
if (result instanceof Set) {
Set set = (Set) result;
if (set.size() != 1)
throw PojoLogger.ROOT_LOGGER.invalidMatchSize(set, type);
result = set.iterator().next();
}
if (property != null) {
Method getter = getBeanInfo(result).getGetter(property, type);
try {
return getter.invoke(result);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(e);
} catch (InvocationTargetException e) {
throw new IllegalArgumentException(e);
}
} else {
return result;
}
}
@SuppressWarnings({"unchecked"})
protected BeanInfo getBeanInfo(Object bean) {
BeanInfo bi = beanInfo.getOptionalValue();
if (bi == null) {
bi = getTempBeanInfo(bean.getClass());
}
return bi;
}
@Override
public void visit(ConfigVisitor visitor) {
if (bean != null) {
visitor.addDependency(bean, BeanState.DESCRIBED, beanInfo);
ServiceName name = BeanMetaDataConfig.toBeanName(bean, state);
visitor.addDependency(name, value); // direct name, since we have describe already
} else if (service != null) {
visitor.addDependency(ServiceName.parse(service), value);
} else {
Class<?> type = getType(visitor, getType());
if (type == null)
type = getType(visitor, this);
if (type == null)
throw PojoLogger.ROOT_LOGGER.cannotDetermineInjectedType(toString());
ServiceName instancesName = BeanMetaDataConfig.toInstancesName(type, state);
visitor.addDependency(instancesName, value);
}
}
public void setBean(String dependency) {
this.bean = dependency;
}
public void setState(BeanState state) {
this.state = state;
}
public void setService(String service) {
this.service = service;
}
public void setProperty(String property) {
this.property = property;
}
}
| 4,121
| 33.932203
| 94
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/SetConfig.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.pojo.descriptor;
import java.util.Collection;
import java.util.HashSet;
/**
* Set meta data.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class SetConfig extends CollectionConfig {
private static final long serialVersionUID = 1L;
@Override
protected Collection<Object> createDefaultInstance() {
return new HashSet<Object>();
}
}
| 1,445
| 35.15
| 70
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/PropertyConfig.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.pojo.descriptor;
import org.jboss.as.pojo.logging.PojoLogger;
import org.jboss.as.pojo.service.BeanInfo;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.List;
/**
* Property meta data.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public class PropertyConfig extends AbstractConfigVisitorNode implements Serializable {
private static final long serialVersionUID = 1L;
private String propertyName;
private String type;
private ValueConfig value;
private transient BeanInfo beanInfo;
public void visit(ConfigVisitor visitor) {
if (value == null)
throw PojoLogger.ROOT_LOGGER.nullValue();
this.beanInfo = visitor.getBeanInfo();
super.visit(visitor);
}
@Override
protected void addChildren(ConfigVisitor visitor, List<ConfigVisitorNode> nodes) {
nodes.add(value);
}
@Override
public Class<?> getType(ConfigVisitor visitor, ConfigVisitorNode previous) {
Class<?> clazz = getType(visitor, type);
if (clazz == null) {
Method m = beanInfo.getGetter(propertyName, null);
return m.getReturnType();
}
return clazz;
}
public String getPropertyName() {
return propertyName;
}
public void setPropertyName(String propertyName) {
this.propertyName = propertyName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public ValueConfig getValue() {
return value;
}
public void setValue(ValueConfig value) {
this.value = value;
}
}
| 2,733
| 29.377778
| 87
|
java
|
null |
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/descriptor/AbstractConfigVisitor.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.pojo.descriptor;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* Abstract config visitor.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
public abstract class AbstractConfigVisitor implements ConfigVisitor {
private Deque<ConfigVisitorNode> nodes = new ArrayDeque<ConfigVisitorNode>();
public void visit(ConfigVisitorNode node) {
nodes.push(node);
try {
for (ConfigVisitorNode child : node.getChildren(this)) {
child.visit(this);
}
} finally {
nodes.pop();
}
}
/**
* Get current nodes.
*
* @return the current nodes
*/
public Deque<ConfigVisitorNode> getCurrentNodes() {
return nodes;
}
}
| 1,812
| 31.375
| 81
|
java
|
null |
wildfly-main/transactions/src/test/java/org/jboss/as/txn/TestWildFlyTSR.java
|
package org.jboss.as.txn;
import static org.junit.Assert.assertTrue;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.NotSupportedException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Synchronization;
import jakarta.transaction.SystemException;
import jakarta.transaction.TransactionManager;
import jakarta.transaction.TransactionSynchronizationRegistry;
import com.arjuna.ats.arjuna.common.arjPropertyManager;
import com.arjuna.ats.internal.jta.transaction.arjunacore.jca.XATerminatorImple;
import org.jboss.as.txn.service.internal.tsr.TransactionSynchronizationRegistryWrapper;
import org.jboss.tm.XAResourceRecovery;
import org.jboss.tm.XAResourceRecoveryRegistry;
import org.junit.Test;
import com.arjuna.ats.jta.common.jtaPropertyManager;
import org.wildfly.transaction.client.ContextTransactionManager;
import org.wildfly.transaction.client.LocalTransactionContext;
import org.wildfly.transaction.client.provider.jboss.JBossLocalTransactionProvider;
public class TestWildFlyTSR {
boolean innerSyncCalled = false;
@Test
public void test() throws NotSupportedException, SystemException, SecurityException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
jtaPropertyManager.getJTAEnvironmentBean().setTransactionManagerClassName("com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionManagerImple");
arjPropertyManager.getObjectStoreEnvironmentBean().setObjectStoreDir(System.getProperty("ObjectStoreEnvironmentBean.objectStoreDir"));
final TransactionSynchronizationRegistry tsr =
new TransactionSynchronizationRegistryWrapper();
final JBossLocalTransactionProvider.Builder builder = JBossLocalTransactionProvider.builder();
builder.setTransactionManager(com.arjuna.ats.jta.TransactionManager.transactionManager());
builder.setExtendedJBossXATerminator(new XATerminatorImple());
builder.setXAResourceRecoveryRegistry(new XAResourceRecoveryRegistry() {
@Override
public void addXAResourceRecovery(XAResourceRecovery xaResourceRecovery) {}
@Override public void removeXAResourceRecovery(XAResourceRecovery xaResourceRecovery) {}
});
LocalTransactionContext.getContextManager().setGlobalDefault(new LocalTransactionContext(
builder.build()
));
TransactionManager transactionManager = ContextTransactionManager.getInstance();
transactionManager.begin();
tsr.registerInterposedSynchronization(new Synchronization() {
@Override
public void beforeCompletion() {
tsr.registerInterposedSynchronization(new Synchronization() {
@Override
public void beforeCompletion() {
innerSyncCalled = true;
}
@Override
public void afterCompletion(int status) {
}
});
}
@Override
public void afterCompletion(int status) {
}
});
transactionManager.commit();
assertTrue(innerSyncCalled);
}
}
| 3,306
| 42.513158
| 184
|
java
|
null |
wildfly-main/transactions/src/test/java/org/jboss/as/txn/subsystem/RemoveProcessUUIDOperationFixer.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
import java.io.Serializable;
import org.jboss.as.model.test.OperationFixer;
import org.jboss.dmr.ModelNode;
/**
*
* @author <a href="mailto:kabir.khan@jboss.com">Kabir Khan</a>
*/
public class RemoveProcessUUIDOperationFixer implements OperationFixer, Serializable {
private static final long serialVersionUID = 1L;
static final transient RemoveProcessUUIDOperationFixer INSTANCE = new RemoveProcessUUIDOperationFixer();
private RemoveProcessUUIDOperationFixer(){
}
@Override
public ModelNode fixOperation(ModelNode operation) {
if (operation.hasDefined("process-id-uuid") && operation.get("process-id-uuid").asString() .equals("false")){
operation.remove("process-id-uuid");
}
return operation;
}
}
| 1,832
| 36.408163
| 117
|
java
|
null |
wildfly-main/transactions/src/test/java/org/jboss/as/txn/subsystem/TransactionSubsystemTestCase.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.txn.subsystem;
import java.io.IOException;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.model.test.ModelTestUtils;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
import com.arjuna.ats.arjuna.coordinator.TxStats;
/**
* @author <a href="kabir.khan@jboss.com">Kabir Khan</a>
*/
public class TransactionSubsystemTestCase extends AbstractSubsystemBaseTest {
public TransactionSubsystemTestCase() {
super(TransactionExtension.SUBSYSTEM_NAME, new TransactionExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource("subsystem.xml");
}
@Override
protected String getSubsystemXsdPath() throws Exception {
return "schema/wildfly-txn_6_0.xsd";
}
@Override
protected void compareXml(String configId, String original, String marshalled) throws Exception {
String transformed = ModelTestUtils.normalizeXML(
original.replace("enable-statistics", "statistics-enabled")
.replace("use-hornetq-store", "use-journal-store"));
super.compareXml(configId, transformed, marshalled, true);
}
@Test
public void testExpressions() throws Exception {
standardSubsystemTest("full-expressions.xml");
}
@Test
public void testMinimalConfig() throws Exception {
standardSubsystemTest("minimal.xml");
}
@Test
public void testJdbcStore() throws Exception {
standardSubsystemTest("jdbc-store.xml");
}
@Test
public void testCmr() throws Exception {
standardSubsystemTest("cmr.xml");
}
@Test
public void testJdbcStoreMinimal() throws Exception {
standardSubsystemTest("jdbc-store-minimal.xml");
}
@Test
public void testJdbcStoreExpressions() throws Exception {
standardSubsystemTest("jdbc-store-expressions.xml");
}
@Test
public void testParser_EAP_6_4() throws Exception {
standardSubsystemTest("full-1.5.0.xml");
}
@Test
public void testParser_EAP_7_0() throws Exception {
standardSubsystemTest("full-3.0.0.xml");
}
@Test
public void testParser_EAP_7_1() throws Exception {
standardSubsystemTest("full-4.0.0.xml");
}
@Test
public void testParser_EAP_7_2() throws Exception {
standardSubsystemTest("full-5.0.0.xml");
}
@Test
public void testParser_EAP_7_3() throws Exception {
standardSubsystemTest("full-5.1.0.xml");
}
@Test
public void testParser_EAP_7_4() throws Exception {
standardSubsystemTest("full.xml");
}
@Test
public void testTxStats() throws Exception {
// Parse the subsystem xml and install into the first controller
final String subsystemXml = getSubsystemXml();
final KernelServices kernelServices = super.createKernelServicesBuilder(createAdditionalInitialization()).setSubsystemXml(subsystemXml).build();
Assert.assertTrue("Subsystem boot failed!", kernelServices.isSuccessfulBoot());
// Reads stats
ModelNode operation = createReadAttributeOperation(CommonAttributes.NUMBER_OF_SYSTEM_ROLLBACKS);
ModelNode result = kernelServices.executeOperation(operation);
Assert.assertEquals("success", result.get("outcome").asString());
Assert.assertEquals(TxStats.getInstance().getNumberOfSystemRollbacks(), result.get(ModelDescriptionConstants.RESULT).asLong());
operation = createReadAttributeOperation(CommonAttributes.AVERAGE_COMMIT_TIME);
result = kernelServices.executeOperation(operation);
Assert.assertEquals("success", result.get("outcome").asString());
Assert.assertEquals(TxStats.getInstance().getAverageCommitTime(), result.get(ModelDescriptionConstants.RESULT).asLong());
}
@Test
public void testAsyncIOExpressions() throws Exception {
standardSubsystemTest("async-io-expressions.xml");
}
private ModelNode createReadAttributeOperation(String name) {
final ModelNode address = new ModelNode();
address.add(ModelDescriptionConstants.SUBSYSTEM, getMainSubsystemName());
final ModelNode operation = new ModelNode();
operation.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION);
operation.get(ModelDescriptionConstants.OP_ADDR).set(address);
operation.get(ModelDescriptionConstants.NAME).set(name);
return operation;
}
}
| 5,703
| 34.65
| 152
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/iiop/tm/InboundTransactionCurrentImpl.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.iiop.tm;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import org.omg.CORBA.LocalObject;
import org.wildfly.transaction.client.ContextTransactionManager;
import org.wildfly.transaction.client.LocalTransactionContext;
public class InboundTransactionCurrentImpl extends LocalObject implements InboundTransactionCurrent {
private static final long serialVersionUID = - 7415245830690060507L;
public Transaction getCurrentTransaction() {
final LocalTransactionContext current = LocalTransactionContext.getCurrent();
try {
current.importProviderTransaction();
} catch (SystemException e) {
throw new RuntimeException("InboundTransactionCurrentImpl unable to determine inbound transaction context", e);
}
try {
return ContextTransactionManager.getInstance().suspend();
} catch (SystemException e) {
throw new RuntimeException("InboundTransactionCurrentImpl unable to suspend inbound transaction context", e);
}
}
}
| 2,110
| 40.392157
| 123
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/iiop/tm/InboundTransactionCurrent.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss 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.iiop.tm;
import jakarta.transaction.Transaction;
import org.omg.CORBA.Current;
/**
* Interface to be implemented by a CORBA OTS provider for integration with
* JBossAS. The CORBA OTS provider must (i) create an object that implements
* this interface and (ii) register an initial reference for that object
* with the JBossAS ORB, under name "InboundTransactionCurrent".
* <p/>
* Step (ii) above should be done by a call
* <code>orbInitInfo.register_initial_reference</code> within the
* <code>pre_init</code> method of an
* <code>org.omg.PortableInterceptor.ORBInitializer</code>,
* which will probably be also the initializer that registers a server request
* interceptor for the OTS provider.
*
* @author <a href="mailto:reverbel@ime.usp.br">Francisco Reverbel</a>
* @version $Revision$
*/
public interface InboundTransactionCurrent extends Current {
String NAME = "InboundTransactionCurrent";
/**
* Gets the Transaction instance associated with the current incoming
* request. This method should be called only by code that handles incoming
* requests; its return value is undefined in the case of a call issued
* outside of a request scope.
*
* @return the jakarta.transaction.Transaction instance associated with the
* current incoming request, or null if that request was not issued
* within the scope of some transaction.
*/
Transaction getCurrentTransaction();
}
| 2,496
| 40.616667
| 79
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/iiop/tm/InboundTransactionCurrentInitializer.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.iiop.tm;
import org.omg.CORBA.LocalObject;
import org.omg.PortableInterceptor.ORBInitInfo;
import org.omg.PortableInterceptor.ORBInitInfoPackage.InvalidName;
import org.omg.PortableInterceptor.ORBInitializer;
public class InboundTransactionCurrentInitializer extends LocalObject implements ORBInitializer {
public void pre_init(ORBInitInfo info) {
try {
// Create and register the InboundTransactionCurrent implementation class
info.register_initial_reference(InboundTransactionCurrent.NAME, new InboundTransactionCurrentImpl());
} catch (InvalidName e) {
throw new RuntimeException("Could not register initial " +
"reference for InboundTransactionCurrent implementation: " + e, e);
}
}
public void post_init(ORBInitInfo info) {
}
}
| 1,871
| 40.6
| 113
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/service/XATerminatorService.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.txn.service;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.tm.JBossXATerminator;
/**
* The XATerminator service.
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
* @author <a href="mailto:gytis@redhat.com">Gytis Trikleris</a>
*/
public final class XATerminatorService implements Service<JBossXATerminator> {
private final JBossXATerminator value;
public XATerminatorService(final JBossXATerminator value) {
this.value = value;
}
public void start(final StartContext context) throws StartException {
}
public void stop(final StopContext context) {
}
public JBossXATerminator getValue() throws IllegalStateException {
return TxnServices.notNull(value);
}
}
| 1,925
| 34.018182
| 78
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/service/TransactionSynchronizationRegistryService.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.txn.service;
import static org.jboss.as.txn.subsystem.TransactionSubsystemRootResourceDefinition.TRANSACTION_SYNCHRONIZATION_REGISTRY_CAPABILITY;
import jakarta.transaction.TransactionSynchronizationRegistry;
import org.jboss.as.controller.CapabilityServiceTarget;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
/**
* Service that exposes the TransactionSynchronizationRegistry
*
* @author Stuart Douglas
* @author <a href="mailto:ropalka@redhat.com">Richard Opalka</a>
*/
public class TransactionSynchronizationRegistryService implements Service<TransactionSynchronizationRegistry> {
/** @deprecated Use the "org.wildfly.transactions.transaction-synchronization-registry" capability */
@Deprecated
public static final ServiceName SERVICE_NAME = TxnServices.JBOSS_TXN_SYNCHRONIZATION_REGISTRY;
/** Non-deprecated service name only for use within the subsystem */
@SuppressWarnings("deprecation")
public static final ServiceName INTERNAL_SERVICE_NAME = TxnServices.JBOSS_TXN_SYNCHRONIZATION_REGISTRY;
private final InjectedValue<com.arjuna.ats.jbossatx.jta.TransactionManagerService> injectedArjunaTM = new InjectedValue<com.arjuna.ats.jbossatx.jta.TransactionManagerService>();
private TransactionSynchronizationRegistryService() {
}
public static void addService(final CapabilityServiceTarget target) {
TransactionSynchronizationRegistryService service = new TransactionSynchronizationRegistryService();
ServiceBuilder<?> serviceBuilder = target.addCapability(TRANSACTION_SYNCHRONIZATION_REGISTRY_CAPABILITY);
serviceBuilder.setInstance(service);
serviceBuilder.requires(TxnServices.JBOSS_TXN_LOCAL_TRANSACTION_CONTEXT);
serviceBuilder.addDependency(ArjunaTransactionManagerService.SERVICE_NAME, com.arjuna.ats.jbossatx.jta.TransactionManagerService.class, service.injectedArjunaTM);
serviceBuilder.addAliases(INTERNAL_SERVICE_NAME);
serviceBuilder.install();
}
@Override
public void start(final StartContext startContext) {
// noop
}
@Override
public void stop(final StopContext stopContext) {
// noop
}
@Override
public TransactionSynchronizationRegistry getValue() throws IllegalStateException {
return injectedArjunaTM.getValue().getTransactionSynchronizationRegistry();
}
}
| 3,599
| 43.444444
| 181
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/service/TransactionManagerService.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.txn.service;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.jboss.tm.usertx.UserTransactionRegistry;
import org.wildfly.security.manager.WildFlySecurityManager;
import org.wildfly.transaction.client.AbstractTransaction;
import org.wildfly.transaction.client.AssociationListener;
import org.wildfly.transaction.client.ContextTransactionManager;
import org.wildfly.transaction.client.CreationListener;
import org.wildfly.transaction.client.LocalTransactionContext;
import jakarta.transaction.TransactionManager;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Service responsible for getting the {@link TransactionManager}.
*
* @author Thomas.Diesler@jboss.com
* @since 29-Oct-2010
*/
public class TransactionManagerService implements Service<TransactionManager> {
/** @deprecated Use the "org.wildfly.transactions.global-default-local-provider" capability to confirm existence of a local provider
* and org.wildfly.transaction.client.ContextTransactionManager to obtain a TransactionManager reference. */
@Deprecated
public static final ServiceName SERVICE_NAME = TxnServices.JBOSS_TXN_TRANSACTION_MANAGER;
/** Non-deprecated service name only for use within the subsystem */
@SuppressWarnings("deprecation")
public static final ServiceName INTERNAL_SERVICE_NAME = TxnServices.JBOSS_TXN_TRANSACTION_MANAGER;
private InjectedValue<UserTransactionRegistry> registryInjector = new InjectedValue<>();
private TransactionManagerService() {
}
public static ServiceController<TransactionManager> addService(final ServiceTarget target) {
final TransactionManagerService service = new TransactionManagerService();
ServiceBuilder<TransactionManager> serviceBuilder = target.addService(INTERNAL_SERVICE_NAME, service);
// This is really a dependency on the global context. TODO: Break this later; no service is needed for TM really
serviceBuilder.requires(TxnServices.JBOSS_TXN_LOCAL_TRANSACTION_CONTEXT);
serviceBuilder.addDependency(UserTransactionRegistryService.SERVICE_NAME, UserTransactionRegistry.class, service.registryInjector);
return serviceBuilder.install();
}
public void start(final StartContext context) throws StartException {
final UserTransactionRegistry registry = registryInjector.getValue();
LocalTransactionContext.getCurrent().registerCreationListener((txn, createdBy) -> {
if (createdBy == CreationListener.CreatedBy.USER_TRANSACTION) {
if (WildFlySecurityManager.isChecking()) {
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
txn.registerAssociationListener(new AssociationListener() {
private final AtomicBoolean first = new AtomicBoolean();
public void associationChanged(final AbstractTransaction t, final boolean a) {
if (a && first.compareAndSet(false, true)) registry.userTransactionStarted();
}
});
return null;
});
} else {
txn.registerAssociationListener(new AssociationListener() {
private final AtomicBoolean first = new AtomicBoolean();
public void associationChanged(final AbstractTransaction t, final boolean a) {
if (a && first.compareAndSet(false, true)) registry.userTransactionStarted();
}
});
}
}
});
}
@Override
public void stop(final StopContext stopContext) {
// noop
}
@Override
public TransactionManager getValue() throws IllegalStateException {
return ContextTransactionManager.getInstance();
}
}
| 5,376
| 45.353448
| 139
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/service/JBossContextXATerminatorService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.service;
import org.jboss.as.txn.integration.JBossContextXATerminator;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.jboss.tm.JBossXATerminator;
import org.wildfly.transaction.client.LocalTransactionContext;
/**
* The XATerminator service for wildfly transaction client XATerminator.
*
* @author <a href="mailto:ochaloup@redhat.com">Ondrej Chaloupka</a>
*/
public final class JBossContextXATerminatorService implements Service<JBossContextXATerminator> {
private volatile JBossContextXATerminator value;
private final InjectedValue<JBossXATerminator> jbossXATerminatorInjector = new InjectedValue<>();
private final InjectedValue<LocalTransactionContext> localTransactionContextInjector = new InjectedValue<>();
public void start(final StartContext context) throws StartException {
this.value = new JBossContextXATerminator(
localTransactionContextInjector.getValue(), jbossXATerminatorInjector.getValue());
}
public void stop(final StopContext context) {
this.value = null;
}
public InjectedValue<LocalTransactionContext> getLocalTransactionContextInjector() {
return localTransactionContextInjector;
}
public InjectedValue<JBossXATerminator> getJBossXATerminatorInjector() {
return jbossXATerminatorInjector;
}
public JBossContextXATerminator getValue() throws IllegalStateException {
return TxnServices.notNull(value);
}
}
| 2,669
| 37.695652
| 113
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/service/CoreEnvironmentService.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.jboss.as.txn.service;
import org.jboss.as.network.SocketBinding;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import com.arjuna.ats.arjuna.common.CoreEnvironmentBean;
import com.arjuna.ats.arjuna.common.CoreEnvironmentBeanException;
import com.arjuna.ats.arjuna.common.arjPropertyManager;
import com.arjuna.ats.arjuna.utils.Process;
import com.arjuna.ats.internal.arjuna.utils.UuidProcessId;
import java.util.function.Supplier;
/**
* An msc service for setting up the
* @author Scott stark (sstark@redhat.com) (C) 2011 Red Hat Inc.
* @version $Revision:$
*/
public class CoreEnvironmentService implements Service<CoreEnvironmentBean> {
/** A dependency on a socket binding for the socket process id */
private final Supplier<SocketBinding> socketBindingSupplier;
private final String nodeIdentifier;
public CoreEnvironmentService(final String nodeIdentifier, final Supplier<SocketBinding> socketBindingSupplier) {
this.nodeIdentifier = nodeIdentifier;
this.socketBindingSupplier = socketBindingSupplier;
}
@Override
public CoreEnvironmentBean getValue() throws IllegalStateException, IllegalArgumentException {
CoreEnvironmentBean coreEnvironmentBean = arjPropertyManager.getCoreEnvironmentBean();
return coreEnvironmentBean;
}
@Override
public void start(StartContext context) throws StartException {
// Global configuration.
final CoreEnvironmentBean coreEnvironmentBean = arjPropertyManager.getCoreEnvironmentBean();
if(coreEnvironmentBean.getProcessImplementationClassName() == null) {
UuidProcessId id = new UuidProcessId();
coreEnvironmentBean.setProcessImplementation(id);
}
try {
coreEnvironmentBean.setNodeIdentifier(nodeIdentifier);
} catch (CoreEnvironmentBeanException e) {
throw new StartException(e.getCause());
}
// Setup the socket process id if there is a binding
SocketBinding binding = socketBindingSupplier.get();
if(binding != null) {
int port = binding.getPort();
coreEnvironmentBean.setSocketProcessIdPort(port);
}
}
@Override
public void stop(StopContext context) {
}
public int getSocketProcessIdMaxPorts() {
return getValue().getSocketProcessIdMaxPorts();
}
public void setSocketProcessIdMaxPorts(int socketProcessIdMaxPorts) {
getValue().setSocketProcessIdMaxPorts(socketProcessIdMaxPorts);
}
public void setProcessImplementationClassName(String clazz) {
getValue().setProcessImplementationClassName(clazz);
}
public void setProcessImplementation(Process instance) {
getValue().setProcessImplementation(instance);
}
}
| 3,877
| 38.171717
| 118
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/service/UserTransactionBindingService.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.txn.service;
import jakarta.transaction.UserTransaction;
import org.jboss.as.naming.ContextListAndJndiViewManagedReferenceFactory;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.naming.service.BinderService;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.value.InjectedValue;
/**
* A special type of {@link BinderService} used to bind {@link jakarta.transaction.UserTransaction} instances. This
* {@link UserTransactionBindingService} checks the permission to access the UserTransaction} before handing out the
* {@link jakarta.transaction.UserTransaction} instance from its {@link #getValue()} method.
*
* @author Jaikiran Pai
* @author Eduardo Martins
*/
public class UserTransactionBindingService extends BinderService {
private final InjectedValue<UserTransactionAccessControlService> accessControlService = new InjectedValue<UserTransactionAccessControlService>();
public UserTransactionBindingService(final String name) {
super(name);
}
@Override
public synchronized ManagedReferenceFactory getValue() throws IllegalStateException {
final ManagedReferenceFactory value = super.getValue();
if (value == null) {
return null;
}
// wrap the real factory in the one that controls access
return new ContextListAndJndiViewManagedReferenceFactory() {
@Override
public String getJndiViewInstanceValue() {
return UserTransaction.class.getSimpleName();
}
@Override
public String getInstanceClassName() {
return UserTransaction.class.getName();
}
@Override
public ManagedReference getReference() {
accessControlService.getValue().authorizeAccess();
return value.getReference();
}
};
}
public Injector<UserTransactionAccessControlService> getUserTransactionAccessControlServiceInjector() {
return accessControlService;
}
}
| 3,141
| 37.317073
| 149
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/service/ArjunaRecoveryManagerService.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.txn.service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;
import com.arjuna.ats.internal.jta.recovery.arjunacore.SubordinateAtomicActionRecoveryModule;
import com.arjuna.ats.internal.jta.recovery.jts.JCAServerTransactionRecoveryModule;
import org.jboss.as.controller.ProcessStateNotifier;
import org.jboss.as.network.ManagedBinding;
import org.jboss.as.network.SocketBinding;
import org.jboss.as.network.SocketBindingManager;
import org.jboss.as.server.suspend.SuspendController;
import org.jboss.as.txn.logging.TransactionLogger;
import org.jboss.as.txn.suspend.RecoverySuspendController;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.omg.CORBA.ORB;
import com.arjuna.ats.arjuna.common.RecoveryEnvironmentBean;
import com.arjuna.ats.arjuna.common.recoveryPropertyManager;
import com.arjuna.ats.internal.arjuna.recovery.AtomicActionRecoveryModule;
import com.arjuna.ats.internal.arjuna.recovery.ExpiredTransactionStatusManagerScanner;
import com.arjuna.ats.internal.jta.recovery.arjunacore.CommitMarkableResourceRecordRecoveryModule;
import com.arjuna.ats.internal.jts.recovery.contact.ExpiredContactScanner;
import com.arjuna.ats.internal.jts.recovery.transactions.ExpiredServerScanner;
import com.arjuna.ats.internal.jts.recovery.transactions.ExpiredToplevelScanner;
import com.arjuna.ats.internal.jts.recovery.transactions.ServerTransactionRecoveryModule;
import com.arjuna.ats.internal.jts.recovery.transactions.TopLevelTransactionRecoveryModule;
import com.arjuna.ats.internal.txoj.recovery.TORecoveryModule;
import com.arjuna.ats.jbossatx.jta.RecoveryManagerService;
import com.arjuna.orbportability.internal.utils.PostInitLoader;
/**
* A service responsible for exposing the proprietary Arjuna {@link RecoveryManagerService}.
*
* @author John Bailey
* @author Scott Stark (sstark@redhat.com) (C) 2011 Red Hat Inc.
*/
public class ArjunaRecoveryManagerService implements Service<RecoveryManagerService> {
/** @deprecated Use the "org.wildfly.transactions.xa-resource-recovery-registry" capability */
@Deprecated
@SuppressWarnings("deprecation")
public static final ServiceName SERVICE_NAME = TxnServices.JBOSS_TXN_ARJUNA_RECOVERY_MANAGER;
private final Consumer<RecoveryManagerService> consumer;
private final Supplier<ORB> orbSupplier;
private final Supplier<SocketBinding> recoveryBindingSupplier;
private final Supplier<SocketBinding> statusBindingSupplier;
private final Supplier<SuspendController> suspendControllerSupplier;
private final Supplier<ProcessStateNotifier> processStateSupplier;
private RecoveryManagerService recoveryManagerService;
private RecoverySuspendController recoverySuspendController;
private boolean recoveryListener;
private final boolean jts;
private final Supplier<SocketBindingManager> bindingManagerSupplier;
public ArjunaRecoveryManagerService(final Consumer<RecoveryManagerService> consumer,
final Supplier<SocketBinding> recoveryBindingSupplier,
final Supplier<SocketBinding> statusBindingSupplier,
final Supplier<SocketBindingManager> bindingManagerSupplier,
final Supplier<SuspendController> suspendControllerSupplier,
final Supplier<ProcessStateNotifier> processStateSupplier,
final Supplier<ORB> orbSupplier,
final boolean recoveryListener, final boolean jts) {
this.consumer = consumer;
this.recoveryBindingSupplier = recoveryBindingSupplier;
this.statusBindingSupplier = statusBindingSupplier;
this.suspendControllerSupplier = suspendControllerSupplier;
this.bindingManagerSupplier = bindingManagerSupplier;
this.processStateSupplier = processStateSupplier;
this.recoveryListener = recoveryListener;
this.orbSupplier = orbSupplier;
this.jts = jts;
}
public synchronized void start(StartContext context) throws StartException {
// Recovery env bean
final RecoveryEnvironmentBean recoveryEnvironmentBean = recoveryPropertyManager.getRecoveryEnvironmentBean();
final SocketBinding recoveryBinding = recoveryBindingSupplier.get();
recoveryEnvironmentBean.setRecoveryInetAddress(recoveryBinding.getSocketAddress().getAddress());
recoveryEnvironmentBean.setRecoveryPort(recoveryBinding.getSocketAddress().getPort());
final SocketBinding statusBinding = statusBindingSupplier.get();
recoveryEnvironmentBean.setTransactionStatusManagerInetAddress(statusBinding.getSocketAddress().getAddress());
recoveryEnvironmentBean.setTransactionStatusManagerPort(statusBinding.getSocketAddress().getPort());
recoveryEnvironmentBean.setRecoveryListener(recoveryListener);
if (recoveryListener){
ManagedBinding binding = ManagedBinding.Factory.createSimpleManagedBinding(recoveryBinding);
bindingManagerSupplier.get().getNamedRegistry().registerBinding(binding);
}
final List<String> recoveryExtensions = new ArrayList<String>();
recoveryExtensions.add(CommitMarkableResourceRecordRecoveryModule.class.getName()); // must be first
recoveryExtensions.add(AtomicActionRecoveryModule.class.getName());
recoveryExtensions.add(TORecoveryModule.class.getName());
recoveryExtensions.add(SubordinateAtomicActionRecoveryModule.class.getName());
final List<String> expiryScanners;
if (System.getProperty("RecoveryEnvironmentBean.expiryScannerClassNames") != null ||
System.getProperty("com.arjuna.ats.arjuna.common.RecoveryEnvironmentBean.expiryScannerClassNames") != null) {
expiryScanners = recoveryEnvironmentBean.getExpiryScannerClassNames();
} else {
expiryScanners = new ArrayList<String>();
expiryScanners.add(ExpiredTransactionStatusManagerScanner.class.getName());
}
if (!jts) {
recoveryExtensions.add(com.arjuna.ats.internal.jta.recovery.arjunacore.XARecoveryModule.class.getName());
recoveryEnvironmentBean.setRecoveryModuleClassNames(recoveryExtensions);
recoveryEnvironmentBean.setExpiryScannerClassNames(expiryScanners);
recoveryEnvironmentBean.setRecoveryActivators(null);
final RecoveryManagerService recoveryManagerService = new RecoveryManagerService();
try {
recoveryManagerService.create();
} catch (Exception e) {
throw TransactionLogger.ROOT_LOGGER.managerStartFailure(e, "Recovery");
}
recoveryManagerService.start();
this.recoveryManagerService = recoveryManagerService;
} else {
final ORB orb = orbSupplier.get();
new PostInitLoader(PostInitLoader.generateORBPropertyName("com.arjuna.orbportability.orb"), orb);
recoveryExtensions.add(TopLevelTransactionRecoveryModule.class.getName());
recoveryExtensions.add(ServerTransactionRecoveryModule.class.getName());
recoveryExtensions.add(JCAServerTransactionRecoveryModule.class.getName());
recoveryExtensions.add(com.arjuna.ats.internal.jta.recovery.jts.XARecoveryModule.class.getName());
expiryScanners.add(ExpiredContactScanner.class.getName());
expiryScanners.add(ExpiredToplevelScanner.class.getName());
expiryScanners.add(ExpiredServerScanner.class.getName());
recoveryEnvironmentBean.setRecoveryModuleClassNames(recoveryExtensions);
recoveryEnvironmentBean.setExpiryScannerClassNames(expiryScanners);
recoveryEnvironmentBean.setRecoveryActivatorClassNames(Collections.singletonList(com.arjuna.ats.internal.jts.orbspecific.recovery.RecoveryEnablement.class.getName()));
try {
final RecoveryManagerService recoveryManagerService = new com.arjuna.ats.jbossatx.jts.RecoveryManagerService(orb);
recoveryManagerService.create();
recoveryManagerService.start();
this.recoveryManagerService = recoveryManagerService;
} catch (Exception e) {
throw TransactionLogger.ROOT_LOGGER.managerStartFailure(e, "Recovery");
}
}
recoverySuspendController = new RecoverySuspendController(recoveryManagerService);
processStateSupplier.get().addPropertyChangeListener(recoverySuspendController);
suspendControllerSupplier.get().registerActivity(recoverySuspendController);
consumer.accept(recoveryManagerService);
}
public synchronized void stop(StopContext context) {
consumer.accept(null);
suspendControllerSupplier.get().unRegisterActivity(recoverySuspendController);
processStateSupplier.get().removePropertyChangeListener(recoverySuspendController);
try {
recoveryManagerService.stop();
} catch (Exception e) {
// todo log
}
recoveryManagerService.destroy();
recoveryManagerService = null;
recoverySuspendController = null;
}
public synchronized RecoveryManagerService getValue() throws IllegalStateException, IllegalArgumentException {
return recoveryManagerService;
}
}
| 10,757
| 51.478049
| 179
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/service/UserTransactionAccessControlService.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.txn.service;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* Allows enabling/disabling access to the {@link jakarta.transaction.UserTransaction} at runtime. Typically, components (like the
* Jakarta Enterprise Beans component), at runtime, based on a certain criteria decide whether or not access to the
* {@link jakarta.transaction.UserTransaction} is allowed during an invocation associated with a thread. The
* {@link UserTransactionService} and the {@link UserTransactionBindingService} which are responsible for handing out the
* {@link jakarta.transaction.UserTransaction} use this service to decide whether or not they should hand out the
* {@link jakarta.transaction.UserTransaction}
*
* @author Jaikiran Pai
* @author Eduardo Martins
*/
public class UserTransactionAccessControlService implements Service<UserTransactionAccessControlService> {
public static final ServiceName SERVICE_NAME = TxnServices.JBOSS_TXN.append("UserTransactionAccessControlService");
private UserTransactionAccessControl accessControl;
@Override
public void start(StartContext context) throws StartException {
}
@Override
public void stop(StopContext context) {
}
@Override
public UserTransactionAccessControlService getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
/**
*
* @return
*/
public UserTransactionAccessControl getAccessControl() {
return accessControl;
}
/**
*
* @param accessControl
*/
public void setAccessControl(UserTransactionAccessControl accessControl) {
this.accessControl = accessControl;
}
/**
* Authorize access of user transaction
*/
public void authorizeAccess() {
final UserTransactionAccessControl accessControl = this.accessControl;
if(accessControl != null) {
accessControl.authorizeAccess();
}
}
}
| 3,159
| 35.321839
| 130
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/service/RemotingTransactionServiceService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.service;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.jboss.remoting3.Endpoint;
import org.jboss.remoting3.Registration;
import org.jboss.remoting3.ServiceRegistrationException;
import org.wildfly.transaction.client.LocalTransactionContext;
import org.wildfly.transaction.client.provider.remoting.RemotingTransactionService;
/**
* The service providing the Remoting transaction service.
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
*/
public final class RemotingTransactionServiceService implements Service<RemotingTransactionService> {
private final InjectedValue<LocalTransactionContext> localTransactionContextInjector = new InjectedValue<>();
private final InjectedValue<Endpoint> endpointInjector = new InjectedValue<>();
private volatile RemotingTransactionService value;
private volatile Registration registration;
public RemotingTransactionServiceService() {
}
public void start(final StartContext context) throws StartException {
final RemotingTransactionService remotingTransactionService = RemotingTransactionService.builder().setEndpoint(endpointInjector.getValue()).setTransactionContext(localTransactionContextInjector.getValue()).build();
try {
registration = remotingTransactionService.register();
} catch (ServiceRegistrationException e) {
throw new StartException(e);
}
value = remotingTransactionService;
}
public void stop(final StopContext context) {
value = null;
registration.close();
}
public InjectedValue<LocalTransactionContext> getLocalTransactionContextInjector() {
return localTransactionContextInjector;
}
public InjectedValue<Endpoint> getEndpointInjector() {
return endpointInjector;
}
public RemotingTransactionService getValue() throws IllegalStateException, IllegalArgumentException {
return value;
}
}
| 3,171
| 39.666667
| 222
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/service/UserTransactionRegistryService.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.txn.service;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.tm.usertx.UserTransactionRegistry;
/**
* Service responsible for exposing a {@link UserTransactionRegistry} instance.
*
* @author John Bailey
*/
public class UserTransactionRegistryService implements Service<UserTransactionRegistry> {
public static final ServiceName SERVICE_NAME = TxnServices.JBOSS_TXN_USER_TRANSACTION_REGISTRY;
private UserTransactionRegistry userTransactionRegistry;
public synchronized void start(StartContext context) throws StartException {
userTransactionRegistry = new UserTransactionRegistry();
}
public synchronized void stop(StopContext context) {
userTransactionRegistry = null;
}
public synchronized UserTransactionRegistry getValue() throws IllegalStateException, IllegalArgumentException {
return userTransactionRegistry;
}
}
| 2,111
| 37.4
| 115
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/service/UserTransactionService.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.txn.service;
import jakarta.transaction.UserTransaction;
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.StopContext;
import org.wildfly.transaction.client.LocalUserTransaction;
/**
* Service responsible for getting the {@link UserTransaction}.
*
* @author Thomas.Diesler@jboss.com
* @since 29-Oct-2010
*/
public class UserTransactionService implements Service<UserTransaction> {
/** @deprecated Use the "org.wildfly.transactions.global-default-local-provider" capability to confirm existence of a local provider
* and org.wildfly.transaction.client.LocalTransactionContext to obtain a UserTransaction reference. */
@Deprecated
public static final ServiceName SERVICE_NAME = TxnServices.JBOSS_TXN_USER_TRANSACTION;
/** Non-deprecated service name only for use within the subsystem */
@SuppressWarnings("deprecation")
public static final ServiceName INTERNAL_SERVICE_NAME = TxnServices.JBOSS_TXN_USER_TRANSACTION;
private static final UserTransactionService INSTANCE = new UserTransactionService();
private UserTransactionService() {
}
public static ServiceController<UserTransaction> addService(final ServiceTarget target) {
ServiceBuilder<UserTransaction> serviceBuilder = target.addService(INTERNAL_SERVICE_NAME, INSTANCE);
serviceBuilder.requires(TxnServices.JBOSS_TXN_LOCAL_TRANSACTION_CONTEXT);
return serviceBuilder.install();
}
@Override
public void start(final StartContext startContext) {
// noop
}
@Override
public void stop(final StopContext stopContext) {
// noop
}
@Override
public UserTransaction getValue() throws IllegalStateException {
return LocalUserTransaction.getInstance();
}
}
| 3,046
| 38.571429
| 136
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/service/ArjunaObjectStoreEnvironmentService.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.txn.service;
import org.jboss.as.controller.services.path.PathManager;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import com.arjuna.ats.arjuna.common.ObjectStoreEnvironmentBean;
import com.arjuna.ats.internal.arjuna.objectstore.hornetq.HornetqJournalEnvironmentBean;
import com.arjuna.common.internal.util.propertyservice.BeanPopulator;
/**
* Configures the {@link ObjectStoreEnvironmentBean}s using an injected path.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class ArjunaObjectStoreEnvironmentService implements Service<Void> {
private final InjectedValue<PathManager> pathManagerInjector = new InjectedValue<PathManager>();
private final boolean useJournalStore;
private final boolean enableAsyncIO;
private final String path;
private final String pathRef;
private final boolean useJdbcStore;
private final String dataSourceJndiName;
private final JdbcStoreConfig jdbcSoreConfig;
private volatile PathManager.Callback.Handle callbackHandle;
public ArjunaObjectStoreEnvironmentService(final boolean useJournalStore, final boolean enableAsyncIO, final String path, final String pathRef, final boolean useJdbcStore, final String dataSourceJndiName, final JdbcStoreConfig jdbcSoreConfig) {
this.useJournalStore = useJournalStore;
this.enableAsyncIO = enableAsyncIO;
this.path = path;
this.pathRef = pathRef;
this.useJdbcStore = useJdbcStore;
this.dataSourceJndiName = dataSourceJndiName;
this.jdbcSoreConfig = jdbcSoreConfig;
}
@Override
public Void getValue() throws IllegalStateException, IllegalArgumentException {
return null;
}
@Override
public void start(StartContext context) throws StartException {
callbackHandle = pathManagerInjector.getValue().registerCallback(pathRef, PathManager.ReloadServerCallback.create(), PathManager.Event.UPDATED, PathManager.Event.REMOVED);
String objectStoreDir = pathManagerInjector.getValue().resolveRelativePathEntry(path, pathRef);
final ObjectStoreEnvironmentBean defaultActionStoreObjectStoreEnvironmentBean =
BeanPopulator.getNamedInstance(ObjectStoreEnvironmentBean.class, null);
if(useJournalStore) {
HornetqJournalEnvironmentBean hornetqJournalEnvironmentBean = BeanPopulator.getDefaultInstance(
HornetqJournalEnvironmentBean.class
);
hornetqJournalEnvironmentBean.setAsyncIO(enableAsyncIO);
hornetqJournalEnvironmentBean.setStoreDir(objectStoreDir+"/HornetqObjectStore");
defaultActionStoreObjectStoreEnvironmentBean.setObjectStoreType(
"com.arjuna.ats.internal.arjuna.objectstore.hornetq.HornetqObjectStoreAdaptor"
);
} else {
defaultActionStoreObjectStoreEnvironmentBean.setObjectStoreDir(objectStoreDir);
}
final ObjectStoreEnvironmentBean stateStoreObjectStoreEnvironmentBean =
BeanPopulator.getNamedInstance(ObjectStoreEnvironmentBean.class, "stateStore");
stateStoreObjectStoreEnvironmentBean.setObjectStoreDir(objectStoreDir);
final ObjectStoreEnvironmentBean communicationStoreObjectStoreEnvironmentBean =
BeanPopulator.getNamedInstance(ObjectStoreEnvironmentBean.class, "communicationStore");
communicationStoreObjectStoreEnvironmentBean.setObjectStoreDir(objectStoreDir);
if(useJdbcStore) {
defaultActionStoreObjectStoreEnvironmentBean.setObjectStoreType("com.arjuna.ats.internal.arjuna.objectstore.jdbc.JDBCStore");
stateStoreObjectStoreEnvironmentBean.setObjectStoreType("com.arjuna.ats.internal.arjuna.objectstore.jdbc.JDBCStore");
communicationStoreObjectStoreEnvironmentBean.setObjectStoreType("com.arjuna.ats.internal.arjuna.objectstore.jdbc.JDBCStore");
defaultActionStoreObjectStoreEnvironmentBean.setJdbcAccess("com.arjuna.ats.internal.arjuna.objectstore.jdbc.accessors.DataSourceJDBCAccess;datasourceName=" + dataSourceJndiName);
stateStoreObjectStoreEnvironmentBean.setJdbcAccess("com.arjuna.ats.internal.arjuna.objectstore.jdbc.accessors.DataSourceJDBCAccess;datasourceName=" + dataSourceJndiName);
communicationStoreObjectStoreEnvironmentBean.setJdbcAccess("com.arjuna.ats.internal.arjuna.objectstore.jdbc.accessors.DataSourceJDBCAccess;datasourceName=" + dataSourceJndiName);
defaultActionStoreObjectStoreEnvironmentBean.setTablePrefix(jdbcSoreConfig.getActionTablePrefix());
stateStoreObjectStoreEnvironmentBean.setTablePrefix(jdbcSoreConfig.getStateTablePrefix());
communicationStoreObjectStoreEnvironmentBean.setTablePrefix(jdbcSoreConfig.getCommunicationTablePrefix());
defaultActionStoreObjectStoreEnvironmentBean.setDropTable(jdbcSoreConfig.isActionDropTable());
stateStoreObjectStoreEnvironmentBean.setDropTable(jdbcSoreConfig.isStateDropTable());
communicationStoreObjectStoreEnvironmentBean.setDropTable(jdbcSoreConfig.isCommunicationDropTable());
}
}
@Override
public void stop(StopContext context) {
callbackHandle.remove();
}
public InjectedValue<PathManager> getPathManagerInjector() {
return pathManagerInjector;
}
public static final class JdbcStoreConfig {
private final String actionTablePrefix;
private final boolean actionDropTable;
private final String stateTablePrefix;
private final boolean stateDropTable;
private final String communicationTablePrefix;
private final boolean communicationDropTable;
private JdbcStoreConfig(final String actionTablePrefix, final boolean actionDropTable, final String stateTablePrefix, final boolean stateDropTable, final String communicationTablePrefix, final boolean communicationDropTable) {
this.actionTablePrefix = actionTablePrefix;
this.actionDropTable = actionDropTable;
this.stateTablePrefix = stateTablePrefix;
this.stateDropTable = stateDropTable;
this.communicationTablePrefix = communicationTablePrefix;
this.communicationDropTable = communicationDropTable;
}
public String getActionTablePrefix() {
return actionTablePrefix;
}
public boolean isActionDropTable() {
return actionDropTable;
}
public String getStateTablePrefix() {
return stateTablePrefix;
}
public boolean isStateDropTable() {
return stateDropTable;
}
public String getCommunicationTablePrefix() {
return communicationTablePrefix;
}
public boolean isCommunicationDropTable() {
return communicationDropTable;
}
}
public static final class JdbcStoreConfigBulder {
private String actionTablePrefix;
private boolean actionDropTable;
private String stateTablePrefix;
private boolean stateDropTable;
private String communicationTablePrefix;
private boolean communicationDropTable;
public JdbcStoreConfigBulder setActionTablePrefix(String actionTablePrefix) {
this.actionTablePrefix = actionTablePrefix;
return this;
}
public JdbcStoreConfigBulder setActionDropTable(boolean actionDropTable) {
this.actionDropTable = actionDropTable;
return this;
}
public JdbcStoreConfigBulder setStateTablePrefix(String stateTablePrefix) {
this.stateTablePrefix = stateTablePrefix;
return this;
}
public JdbcStoreConfigBulder setStateDropTable(boolean stateDropTable) {
this.stateDropTable = stateDropTable;
return this;
}
public JdbcStoreConfigBulder setCommunicationTablePrefix(String communicationTablePrefix) {
this.communicationTablePrefix = communicationTablePrefix;
return this;
}
public JdbcStoreConfigBulder setCommunicationDropTable(boolean communicationDropTable) {
this.communicationDropTable = communicationDropTable;
return this;
}
public JdbcStoreConfig build() {
return new JdbcStoreConfig(actionTablePrefix, actionDropTable, stateTablePrefix, stateDropTable, communicationTablePrefix, communicationDropTable);
}
}
}
| 9,728
| 43.222727
| 248
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/service/CMResourceService.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.txn.service;
import java.util.List;
import java.util.Map;
import com.arjuna.ats.jta.common.JTAEnvironmentBean;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
/**
* Sets up the CMR related properties in {@link JTAEnvironmentBean}
*
* @author Stefano Maestri
*/
public class CMResourceService implements Service<Void> {
private final String jndiName;
private final String tableName;
private final Boolean immediateCleanup;
private final Integer batchSize;
private final InjectedValue<JTAEnvironmentBean> jtaEnvironmentBean = new InjectedValue<>();
public CMResourceService(String jndiName, String tableName, Boolean immediateCleanup, Integer batchSize) {
this.jndiName = jndiName;
this.tableName = tableName;
this.immediateCleanup = immediateCleanup;
this.batchSize = batchSize;
}
@Override
public void start(StartContext context) throws StartException {
final JTAEnvironmentBean jtaBean = jtaEnvironmentBean.getValue();
synchronized (jtaBean) {
List<String> connectableResourceJNDINames = jtaBean.getCommitMarkableResourceJNDINames();
Map<String, String> connectableResourceTableNameMap = jtaBean.getCommitMarkableResourceTableNameMap();
Map<String, Boolean> performImmediateCleanupOfConnectableResourceBranchesMap = jtaBean.getPerformImmediateCleanupOfCommitMarkableResourceBranchesMap();
Map<String, Integer> connectableResourceRecordDeleteBatchSizeMap = jtaBean.getCommitMarkableResourceRecordDeleteBatchSizeMap();
connectableResourceJNDINames.add(jndiName);
connectableResourceTableNameMap.put(jndiName, tableName);
performImmediateCleanupOfConnectableResourceBranchesMap.put(jndiName, immediateCleanup);
connectableResourceRecordDeleteBatchSizeMap.put(jndiName, batchSize);
jtaBean.setCommitMarkableResourceJNDINames(connectableResourceJNDINames);
jtaBean.setCommitMarkableResourceTableNameMap(connectableResourceTableNameMap);
jtaBean.setPerformImmediateCleanupOfCommitMarkableResourceBranchesMap(performImmediateCleanupOfConnectableResourceBranchesMap);
jtaBean.setCommitMarkableResourceRecordDeleteBatchSizeMap(connectableResourceRecordDeleteBatchSizeMap);
}
}
@Override
public void stop(StopContext context) {
final JTAEnvironmentBean jtaBean = jtaEnvironmentBean.getValue();
synchronized (jtaBean) {
List<String> connectableResourceJNDINames = jtaBean.getCommitMarkableResourceJNDINames();
Map<String, String> connectableResourceTableNameMap = jtaBean.getCommitMarkableResourceTableNameMap();
Map<String, Boolean> performImmediateCleanupOfConnectableResourceBranchesMap = jtaBean.getPerformImmediateCleanupOfCommitMarkableResourceBranchesMap();
Map<String, Integer> connectableResourceRecordDeleteBatchSizeMap = jtaBean.getCommitMarkableResourceRecordDeleteBatchSizeMap();
connectableResourceJNDINames.remove(jndiName);
connectableResourceTableNameMap.remove(jndiName);
performImmediateCleanupOfConnectableResourceBranchesMap.remove(jndiName);
connectableResourceRecordDeleteBatchSizeMap.remove(jndiName);
jtaBean.setCommitMarkableResourceJNDINames(connectableResourceJNDINames);
jtaBean.setCommitMarkableResourceTableNameMap(connectableResourceTableNameMap);
jtaBean.setPerformImmediateCleanupOfCommitMarkableResourceBranchesMap(performImmediateCleanupOfConnectableResourceBranchesMap);
jtaBean.setCommitMarkableResourceRecordDeleteBatchSizeMap(connectableResourceRecordDeleteBatchSizeMap);
}
}
@Override
public Void getValue() throws IllegalStateException, IllegalArgumentException {
return null;
}
public Injector<JTAEnvironmentBean> getJTAEnvironmentBeanInjector() {
return this.jtaEnvironmentBean;
}
}
| 5,246
| 46.7
| 163
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/service/ExtendedJBossXATerminatorService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.service;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.tm.ExtendedJBossXATerminator;
/**
* The ExtendedJBossXATerminator service.
*
* @author <a href="mailto:gytis@redhat.com">Gytis Trikleris</a>
*/
public final class ExtendedJBossXATerminatorService implements Service<ExtendedJBossXATerminator> {
private final ExtendedJBossXATerminator value;
public ExtendedJBossXATerminatorService(ExtendedJBossXATerminator value) {
this.value = value;
}
public void start(StartContext context) throws StartException {
}
public void stop(StopContext context) {
}
public ExtendedJBossXATerminator getValue() throws IllegalStateException {
return TxnServices.notNull(value);
}
}
| 1,916
| 34.5
| 99
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/service/TransactionRemoteHTTPService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 2110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.service;
import com.arjuna.ats.jta.transaction.Transaction;
import io.undertow.server.handlers.PathHandler;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.wildfly.httpclient.transaction.HttpRemoteTransactionService;
import org.wildfly.transaction.client.LocalTransactionContext;
/**
* @author Stuart Douglas
*/
public class TransactionRemoteHTTPService implements Service<TransactionRemoteHTTPService> {
private final InjectedValue<PathHandler> pathHandlerInjectedValue = new InjectedValue<>();
private final InjectedValue<LocalTransactionContext> localTransactionContextInjectedValue = new InjectedValue<>();
@Override
public void start(StartContext context) throws StartException {
HttpRemoteTransactionService transactionService = new HttpRemoteTransactionService(localTransactionContextInjectedValue.getValue(), (transaction) -> transaction.getProviderInterface(Transaction.class).getTxId());
pathHandlerInjectedValue.getValue().addPrefixPath("/txn", transactionService.createHandler());
}
@Override
public void stop(StopContext context) {
pathHandlerInjectedValue.getValue().removePrefixPath("/txn");
}
@Override
public TransactionRemoteHTTPService getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
public InjectedValue<PathHandler> getPathHandlerInjectedValue() {
return pathHandlerInjectedValue;
}
public InjectedValue<LocalTransactionContext> getLocalTransactionContextInjectedValue() {
return localTransactionContextInjectedValue;
}
}
| 2,817
| 41.059701
| 220
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/service/LocalTransactionContextService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.service;
import static java.security.AccessController.doPrivileged;
import static org.jboss.as.txn.subsystem.TransactionSubsystemRootResourceDefinition.LOCAL_PROVIDER_CAPABILITY;
import java.security.PrivilegedAction;
import org.jboss.as.server.ServerEnvironment;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.jboss.tm.ExtendedJBossXATerminator;
import org.jboss.tm.XAResourceRecoveryRegistry;
import org.wildfly.transaction.client.LocalTransactionContext;
import org.wildfly.transaction.client.provider.jboss.JBossLocalTransactionProvider;
/**
* The service which provides the {@link LocalTransactionContext} for the server.
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
*/
public final class LocalTransactionContextService implements Service<LocalTransactionContext> {
private volatile LocalTransactionContext context;
private final InjectedValue<ExtendedJBossXATerminator> extendedJBossXATerminatorInjector = new InjectedValue<>();
private final InjectedValue<com.arjuna.ats.jbossatx.jta.TransactionManagerService> transactionManagerInjector = new InjectedValue<>();
private final InjectedValue<XAResourceRecoveryRegistry> xaResourceRecoveryRegistryInjector = new InjectedValue<>();
private final InjectedValue<ServerEnvironment> serverEnvironmentInjector = new InjectedValue<>();
private final int staleTransactionTime;
public LocalTransactionContextService(final int staleTransactionTime) {
this.staleTransactionTime = staleTransactionTime;
}
public void start(final StartContext context) throws StartException {
JBossLocalTransactionProvider.Builder builder = JBossLocalTransactionProvider.builder();
builder.setExtendedJBossXATerminator(extendedJBossXATerminatorInjector.getValue());
builder.setTransactionManager(transactionManagerInjector.getValue().getTransactionManager());
builder.setXAResourceRecoveryRegistry(xaResourceRecoveryRegistryInjector.getValue());
builder.setXARecoveryLogDirRelativeToPath(serverEnvironmentInjector.getValue().getServerDataDir().toPath());
builder.setStaleTransactionTime(staleTransactionTime);
final LocalTransactionContext transactionContext = this.context = new LocalTransactionContext(builder.build());
// TODO: replace this with per-CL settings for embedded use and to support remote UserTransaction
doPrivileged((PrivilegedAction<Void>) () -> {
LocalTransactionContext.getContextManager().setGlobalDefault(transactionContext);
return null;
});
// Install the void service required by capability org.wildfly.transactions.global-default-local-provider
// so other capabilities that require it can start their services after this capability
// has completed its work.
context.getChildTarget().addService(LOCAL_PROVIDER_CAPABILITY.getCapabilityServiceName())
.setInstance(Service.NULL)
.install();
}
public void stop(final StopContext context) {
this.context = null;
// TODO: replace this with per-CL settings for embedded use and to support remote UserTransaction
doPrivileged((PrivilegedAction<Void>) () -> {
LocalTransactionContext.getContextManager().setGlobalDefault(null);
return null;
});
}
public InjectedValue<ExtendedJBossXATerminator> getExtendedJBossXATerminatorInjector() {
return extendedJBossXATerminatorInjector;
}
public InjectedValue<com.arjuna.ats.jbossatx.jta.TransactionManagerService> getTransactionManagerInjector() {
return transactionManagerInjector;
}
public InjectedValue<XAResourceRecoveryRegistry> getXAResourceRecoveryRegistryInjector() {
return xaResourceRecoveryRegistryInjector;
}
public InjectedValue<ServerEnvironment> getServerEnvironmentInjector() {
return serverEnvironmentInjector;
}
public LocalTransactionContext getValue() throws IllegalStateException, IllegalArgumentException {
return context;
}
}
| 5,310
| 47.724771
| 138
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/service/ArjunaTransactionManagerService.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.txn.service;
import java.lang.reflect.Field;
import com.arjuna.ats.arjuna.common.CoordinatorEnvironmentBean;
import com.arjuna.ats.arjuna.common.arjPropertyManager;
import com.arjuna.ats.arjuna.coordinator.TxControl;
import com.arjuna.ats.arjuna.tools.osb.mbean.ObjStoreBrowser;
import com.arjuna.ats.jta.common.JTAEnvironmentBean;
import com.arjuna.orbportability.internal.utils.PostInitLoader;
import org.jboss.as.txn.logging.TransactionLogger;
import org.jboss.as.txn.service.internal.tsr.TransactionSynchronizationRegistryWrapper;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.jboss.tm.JBossXATerminator;
import org.jboss.tm.TransactionManagerLocator;
import org.jboss.tm.usertx.UserTransactionRegistry;
import org.omg.CORBA.ORB;
import org.wildfly.transaction.client.LocalUserTransaction;
/**
* A service for the proprietary Arjuna {@link com.arjuna.ats.jbossatx.jta.TransactionManagerService}
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
* @author Thomas.Diesler@jboss.com
* @author Scott Stark (sstark@redhat.com) (C) 2011 Red Hat Inc.
*/
public final class ArjunaTransactionManagerService implements Service<com.arjuna.ats.jbossatx.jta.TransactionManagerService> {
public static final ServiceName SERVICE_NAME = TxnServices.JBOSS_TXN_ARJUNA_TRANSACTION_MANAGER;
private final InjectedValue<JBossXATerminator> xaTerminatorInjector = new InjectedValue<JBossXATerminator>();
private final InjectedValue<ORB> orbInjector = new InjectedValue<ORB>();
private final InjectedValue<UserTransactionRegistry> userTransactionRegistry = new InjectedValue<UserTransactionRegistry>();
private final InjectedValue<JTAEnvironmentBean> jtaEnvironmentBean = new InjectedValue<>();
private com.arjuna.ats.jbossatx.jta.TransactionManagerService value;
private ObjStoreBrowser objStoreBrowser;
private boolean transactionStatusManagerEnable;
private boolean coordinatorEnableStatistics;
private int coordinatorDefaultTimeout;
private final boolean jts;
public ArjunaTransactionManagerService(final boolean coordinatorEnableStatistics, final int coordinatorDefaultTimeout,
final boolean transactionStatusManagerEnable, final boolean jts) {
this.coordinatorEnableStatistics = coordinatorEnableStatistics;
this.coordinatorDefaultTimeout = coordinatorDefaultTimeout;
this.transactionStatusManagerEnable = transactionStatusManagerEnable;
this.jts = jts;
}
@Override
public synchronized void start(final StartContext context) throws StartException {
final CoordinatorEnvironmentBean coordinatorEnvironmentBean = arjPropertyManager.getCoordinatorEnvironmentBean();
coordinatorEnvironmentBean.setEnableStatistics(coordinatorEnableStatistics);
coordinatorEnvironmentBean.setDefaultTimeout(coordinatorDefaultTimeout);
coordinatorEnvironmentBean.setTransactionStatusManagerEnable(transactionStatusManagerEnable);
TxControl.setDefaultTimeout(coordinatorDefaultTimeout);
// Object Store Browser bean
objStoreBrowser = new ObjStoreBrowser();
if (!jts) {
// No IIOP, stick with Jakarta Transactions mode.
final com.arjuna.ats.jbossatx.jta.TransactionManagerService service = new com.arjuna.ats.jbossatx.jta.TransactionManagerService();
final LocalUserTransaction userTransaction = LocalUserTransaction.getInstance();
jtaEnvironmentBean.getValue().setUserTransaction(userTransaction);
service.setJbossXATerminator(xaTerminatorInjector.getValue());
service.setTransactionSynchronizationRegistry(new TransactionSynchronizationRegistryWrapper());
try {
service.create();
} catch (Exception e) {
throw TransactionLogger.ROOT_LOGGER.managerStartFailure(e, "Transaction");
}
service.start();
value = service;
} else {
final ORB orb = orbInjector.getValue();
new PostInitLoader(PostInitLoader.generateORBPropertyName("com.arjuna.orbportability.orb"), orb);
// IIOP is enabled, so fire up JTS mode.
final com.arjuna.ats.jbossatx.jts.TransactionManagerService service = new com.arjuna.ats.jbossatx.jts.TransactionManagerService();
final LocalUserTransaction userTransaction = LocalUserTransaction.getInstance();
jtaEnvironmentBean.getValue().setUserTransaction(userTransaction);
service.setJbossXATerminator(xaTerminatorInjector.getValue());
service.setTransactionSynchronizationRegistry(new TransactionSynchronizationRegistryWrapper());
service.setPropagateFullContext(true);
// this is not great, but it's the only way presently to influence the behavior of com.arjuna.ats.internal.jbossatx.jts.InboundTransactionCurrentImple
try {
final Field field = TransactionManagerLocator.class.getDeclaredField("tm");
field.setAccessible(true);
field.set(TransactionManagerLocator.getInstance(), jtaEnvironmentBean.getValue().getTransactionManager());
} catch (IllegalAccessException e) {
throw new IllegalAccessError(e.getMessage());
} catch (NoSuchFieldException e) {
throw new NoSuchFieldError(e.getMessage());
}
try {
service.create();
} catch (Exception e) {
throw TransactionLogger.ROOT_LOGGER.createFailed(e);
}
try {
service.start(orb);
} catch (Exception e) {
throw TransactionLogger.ROOT_LOGGER.startFailure(e);
}
value = service;
}
try {
objStoreBrowser.start();
} catch (Exception e) {
throw TransactionLogger.ROOT_LOGGER.objectStoreStartFailure(e);
}
}
@Override
public synchronized void stop(final StopContext context) {
value.stop();
value.destroy();
objStoreBrowser.stop();
value = null;
}
@Override
public synchronized com.arjuna.ats.jbossatx.jta.TransactionManagerService getValue() throws IllegalStateException {
return TxnServices.notNull(value);
}
public Injector<JBossXATerminator> getXaTerminatorInjector() {
return xaTerminatorInjector;
}
public Injector<ORB> getOrbInjector() {
return orbInjector;
}
public InjectedValue<UserTransactionRegistry> getUserTransactionRegistry() {
return userTransactionRegistry;
}
public Injector<JTAEnvironmentBean> getJTAEnvironmentBeanInjector() {
return this.jtaEnvironmentBean;
}
}
| 8,108
| 43.554945
| 162
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/service/JTAEnvironmentBeanService.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.txn.service;
import com.arjuna.ats.internal.jta.recovery.arjunacore.JTANodeNameXAResourceOrphanFilter;
import com.arjuna.ats.internal.jta.recovery.arjunacore.JTATransactionLogXAResourceOrphanFilter;
import com.arjuna.ats.internal.jta.recovery.arjunacore.JTAActionStatusServiceXAResourceOrphanFilter;
import com.arjuna.ats.internal.jta.recovery.arjunacore.SubordinateJTAXAResourceOrphanFilter;
import com.arjuna.ats.internal.jta.recovery.arjunacore.SubordinationManagerXAResourceOrphanFilter;
import com.arjuna.ats.jta.common.JTAEnvironmentBean;
import com.arjuna.ats.jta.common.jtaPropertyManager;
import org.jboss.as.txn.integration.LocalUserTransactionOperationsProvider;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.tm.LastResource;
import java.util.Arrays;
import java.util.Collections;
/**
* Sets up the {@link JTAEnvironmentBean}
*
* @author Jaikiran Pai
*/
public class JTAEnvironmentBeanService implements Service<JTAEnvironmentBean> {
private final String nodeIdentifier;
private boolean useActionStatusServiceRecoveryFilter;
public JTAEnvironmentBeanService(final String nodeIdentifier) {
this.nodeIdentifier = nodeIdentifier;
this.useActionStatusServiceRecoveryFilter = Boolean.valueOf(System.getProperty("org.jboss.narayana.wildfly.useActionStatusServiceRecoveryFilter.deprecated", "true"));
}
@Override
public void start(StartContext context) throws StartException {
final JTAEnvironmentBean jtaEnvironmentBean = jtaPropertyManager.getJTAEnvironmentBean();
jtaEnvironmentBean.setLastResourceOptimisationInterfaceClassName(LastResource.class.getName());
// recovery nodes
jtaEnvironmentBean.setXaRecoveryNodes(Collections.singletonList(nodeIdentifier));
// setup the XA orphan filters
if (useActionStatusServiceRecoveryFilter) {
jtaEnvironmentBean.setXaResourceOrphanFilterClassNames(Arrays.asList(JTATransactionLogXAResourceOrphanFilter.class.getName(), JTANodeNameXAResourceOrphanFilter.class.getName(), SubordinateJTAXAResourceOrphanFilter.class.getName(), SubordinationManagerXAResourceOrphanFilter.class.getName(), JTAActionStatusServiceXAResourceOrphanFilter.class.getName()));
} else {
jtaEnvironmentBean.setXaResourceOrphanFilterClassNames(Arrays.asList(JTATransactionLogXAResourceOrphanFilter.class.getName(), JTANodeNameXAResourceOrphanFilter.class.getName(), SubordinateJTAXAResourceOrphanFilter.class.getName(), SubordinationManagerXAResourceOrphanFilter.class.getName()));
}
jtaEnvironmentBean.setXAResourceRecordWrappingPlugin(new com.arjuna.ats.internal.jbossatx.jta.XAResourceRecordWrappingPluginImpl());
jtaEnvironmentBean.setTransactionManagerJNDIContext("java:jboss/TransactionManager");
jtaEnvironmentBean.setTransactionSynchronizationRegistryJNDIContext("java:jboss/TransactionSynchronizationRegistry");
jtaEnvironmentBean.setUserTransactionOperationsProviderClassName(LocalUserTransactionOperationsProvider.class.getName());
}
@Override
public void stop(StopContext context) {
final JTAEnvironmentBean jtaEnvironmentBean = jtaPropertyManager.getJTAEnvironmentBean();
// reset the XA orphan filters
jtaEnvironmentBean.setXaResourceOrphanFilterClassNames(null);
// reset the recovery nodes
jtaEnvironmentBean.setXaRecoveryNodes(null);
// reset the record wrapper plugin
jtaEnvironmentBean.setXAResourceRecordWrappingPlugin(null);
jtaEnvironmentBean.setLastResourceOptimisationInterfaceClassName(null);
}
@Override
public JTAEnvironmentBean getValue() throws IllegalStateException, IllegalArgumentException {
return jtaPropertyManager.getJTAEnvironmentBean();
}
}
| 4,954
| 51.712766
| 366
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/service/TxnServices.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.txn.service;
import org.jboss.as.txn.logging.TransactionLogger;
import org.jboss.msc.service.ServiceName;
/**
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
* @author Thomas.Diesler@jboss.com
*/
public final class TxnServices {
public static final ServiceName JBOSS_TXN = ServiceName.JBOSS.append("txn");
public static final ServiceName JBOSS_TXN_PATHS = JBOSS_TXN.append("paths");
public static final ServiceName JBOSS_TXN_CORE_ENVIRONMENT = JBOSS_TXN.append("CoreEnvironment");
public static final ServiceName JBOSS_TXN_XA_TERMINATOR = JBOSS_TXN.append("XATerminator");
public static final ServiceName JBOSS_TXN_EXTENDED_JBOSS_XA_TERMINATOR = JBOSS_TXN.append("ExtendedJBossXATerminator");
public static final ServiceName JBOSS_TXN_ARJUNA_OBJECTSTORE_ENVIRONMENT = JBOSS_TXN.append("ArjunaObjectStoreEnvironment");
public static final ServiceName JBOSS_TXN_ARJUNA_TRANSACTION_MANAGER = JBOSS_TXN.append("ArjunaTransactionManager");
/** @deprecated Use the "org.wildfly.transactions.xa-resource-recovery-registry" capability */
@Deprecated
public static final ServiceName JBOSS_TXN_ARJUNA_RECOVERY_MANAGER = JBOSS_TXN.append("ArjunaRecoveryManager");
/** @deprecated Use the "org.wildfly.transactions.global-default-local-provider" capability to confirm existence of a local provider
* and org.wildfly.transaction.client.ContextTransactionManager to obtain a TransactionManager reference. */
@Deprecated
public static final ServiceName JBOSS_TXN_TRANSACTION_MANAGER = JBOSS_TXN.append("TransactionManager");
/** @deprecated Use the "org.wildfly.transactions.global-default-local-provider" capability to confirm existence of a local provider
* and org.wildfly.transaction.client.LocalTransactionContext to obtain a UserTransaction reference. */
@Deprecated
public static final ServiceName JBOSS_TXN_USER_TRANSACTION = JBOSS_TXN.append("UserTransaction");
public static final ServiceName JBOSS_TXN_USER_TRANSACTION_REGISTRY = JBOSS_TXN.append("UserTransactionRegistry");
/** @deprecated Use the "org.wildfly.transactions.transaction-synchronization-registry" capability */
@Deprecated
public static final ServiceName JBOSS_TXN_SYNCHRONIZATION_REGISTRY = JBOSS_TXN.append("TransactionSynchronizationRegistry");
public static final ServiceName JBOSS_TXN_JTA_ENVIRONMENT = JBOSS_TXN.append("JTAEnvironment");
public static final ServiceName JBOSS_TXN_CMR = JBOSS_TXN.append("CMR");
public static final ServiceName JBOSS_TXN_LOCAL_TRANSACTION_CONTEXT = JBOSS_TXN.append("context", "local");
public static final ServiceName JBOSS_TXN_REMOTE_TRANSACTION_SERVICE = JBOSS_TXN.append("service", "remote");
public static final ServiceName JBOSS_TXN_HTTP_REMOTE_TRANSACTION_SERVICE = JBOSS_TXN.append("service", "http-remote");
public static final ServiceName JBOSS_TXN_CONTEXT_XA_TERMINATOR = JBOSS_TXN.append("JBossContextXATerminator");
public static <T> T notNull(T value) {
if (value == null) throw TransactionLogger.ROOT_LOGGER.serviceNotStarted();
return value;
}
private TxnServices() {
}
}
| 4,252
| 46.786517
| 136
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/service/UserTransactionAccessControl.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.txn.service;
/**
* Objects which control access to User Transaction.
*
* @author Eduardo Martins
*
*/
public interface UserTransactionAccessControl {
/**
* Authorizes access of user transaction.
*/
void authorizeAccess();
}
| 1,294
| 33.078947
| 70
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/service/internal/tsr/TransactionSynchronizationRegistryWrapper.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.service.internal.tsr;
import jakarta.transaction.Synchronization;
import jakarta.transaction.SystemException;
import jakarta.transaction.TransactionSynchronizationRegistry;
import org.jboss.as.txn.logging.TransactionLogger;
import org.wildfly.transaction.client.AbstractTransaction;
import org.wildfly.transaction.client.ContextTransactionManager;
import org.wildfly.transaction.client.ContextTransactionSynchronizationRegistry;
/**
* Most of this implementation delegates down to the underlying transactions implementation to provide the services of the
* TransactionSynchronizationRegistry. The one area it modifies is the registration of the interposed Synchronizations. The
* reason this implementation needs to differ is because the Jakarta Connectors Synchronization and Jakarta Persistence Synchronizations are both specified as
* Interposed however there are defined ordering requirements between them both.
*
* The current implementation orders Jakarta Connectors relative to all other Synchronizations. For beforeCompletion, it would be possible to
* restrict this to the one case where Jakarta Connectors are ordered before Jakarta Persistence, however it is possible that other interposed Synchronizations
* would require the services of Jakarta Connectors and as such if the Jakarta Connectors are allowed to execute delistResource during beforeCompletion as
* mandated in Jakarta Connectors spec the behaviour of those subsequent interactions would be broken. For afterCompletion the Jakarta Connectors
* synchronizations are called last as that allows Jakarta Connectors to detect connection leaks from frameworks that have not closed the Jakarta Connectors
* managed resources. This is described in (for example)
* http://docs.oracle.com/javaee/5/api/javax/transaction/TransactionSynchronizationRegistry
* .html#registerInterposedSynchronization(jakarta.transaction.Synchronization) where it says that during afterCompletion
* "Resources can be closed but no transactional work can be performed with them".
*
* One implication of this approach is that if the underlying transactions implementation has special handling for various types
* of Synchronization that can also implement other interfaces (i.e. if interposedSync instanceof OtherInterface) these
* behaviours cannot take effect as the underlying implementation will never directly see the actual Synchronizations.
*/
public class TransactionSynchronizationRegistryWrapper implements TransactionSynchronizationRegistry {
private final Object key = new Object();
public TransactionSynchronizationRegistryWrapper() {
}
@Override
public void registerInterposedSynchronization(Synchronization sync)
throws IllegalStateException {
try {
AbstractTransaction tx = ContextTransactionManager.getInstance().getTransaction();
if(tx == null) {
throw TransactionLogger.ROOT_LOGGER.noActiveTransactionToRegisterSynchronization(sync);
}
JCAOrderedLastSynchronizationList jcaOrderedLastSynchronization = (JCAOrderedLastSynchronizationList) tx.getResource(key);
if (jcaOrderedLastSynchronization == null) {
final ContextTransactionSynchronizationRegistry tsr = ContextTransactionSynchronizationRegistry.getInstance();
synchronized (key) {
jcaOrderedLastSynchronization = (JCAOrderedLastSynchronizationList) tx.getResource(key);
if (jcaOrderedLastSynchronization == null) {
jcaOrderedLastSynchronization = new JCAOrderedLastSynchronizationList();
tx.putResource(key, jcaOrderedLastSynchronization);
tsr.registerInterposedSynchronization(jcaOrderedLastSynchronization);
}
}
}
jcaOrderedLastSynchronization.registerInterposedSynchronization(sync);
} catch (SystemException e) {
throw new IllegalStateException(e);
}
}
@Override
public Object getTransactionKey() {
return ContextTransactionSynchronizationRegistry.getInstance().getTransactionKey();
}
@Override
public int getTransactionStatus() {
return ContextTransactionSynchronizationRegistry.getInstance().getTransactionStatus();
}
@Override
public boolean getRollbackOnly() throws IllegalStateException {
return ContextTransactionSynchronizationRegistry.getInstance().getRollbackOnly();
}
@Override
public void setRollbackOnly() throws IllegalStateException {
ContextTransactionSynchronizationRegistry.getInstance().setRollbackOnly();
}
@Override
public Object getResource(Object key) throws IllegalStateException {
return ContextTransactionSynchronizationRegistry.getInstance().getResource(key);
}
@Override
public void putResource(Object key, Object value)
throws IllegalStateException {
ContextTransactionSynchronizationRegistry.getInstance().putResource(key, value);
}
}
| 6,140
| 51.042373
| 159
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/service/internal/tsr/JCAOrderedLastSynchronizationList.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.service.internal.tsr;
import java.util.ArrayList;
import java.util.List;
import jakarta.transaction.Status;
import jakarta.transaction.Synchronization;
import jakarta.transaction.SystemException;
import org.jboss.as.txn.logging.TransactionLogger;
import org.wildfly.transaction.client.ContextTransactionManager;
import org.wildfly.transaction.client.ContextTransactionSynchronizationRegistry;
/**
* This class was added to:
*
* 1. workaround an issue discussed in https://java.net/jira/browse/JTA_SPEC-4 whereby the Jakarta Connectors Synchronization(s) need to be
* called after the Jakarta Persistence Synchronization(s). Currently the implementation orders Jakarta Connectors relative to all interposed Synchronizations,
* if this is not desirable it would be possible to modify this class to store just the Jakarta Persistence and Jakarta Connectors syncs and the other syncs
* can simply be passed to a delegate (would need the reference to this in the constructor).
*
* 2. During afterCompletion the Jakarta Connectors synchronizations should be called last as that allows Jakarta Connectors to detect connection leaks from
* frameworks that have not closed the Jakarta Connectors managed resources. This is described in (for example)
* http://docs.oracle.com/javaee/5/api/javax/transaction/TransactionSynchronizationRegistry
* .html#registerInterposedSynchronization(jakarta.transaction.Synchronization) where it says that during afterCompletion
* "Resources can be closed but no transactional work can be performed with them"
*/
public class JCAOrderedLastSynchronizationList implements Synchronization {
private final List<Synchronization> preJcaSyncs = new ArrayList<Synchronization>();
private final List<Synchronization> jcaSyncs = new ArrayList<Synchronization>();
public JCAOrderedLastSynchronizationList() {
}
/**
* This is only allowed at various points of the transaction lifecycle.
*
* @param synchronization The synchronization to register
* @throws IllegalStateException In case the transaction was in a state that was not valid to register under
* @throws SystemException In case the transaction status was not known
*/
public void registerInterposedSynchronization(Synchronization synchronization) throws IllegalStateException, SystemException {
int status = ContextTransactionSynchronizationRegistry.getInstance().getTransactionStatus();
switch (status) {
case jakarta.transaction.Status.STATUS_ACTIVE:
case jakarta.transaction.Status.STATUS_PREPARING:
break;
case Status.STATUS_MARKED_ROLLBACK:
// do nothing; we can pretend like it was registered, but it'll never be run anyway.
return;
default:
throw TransactionLogger.ROOT_LOGGER.syncsnotallowed(status);
}
if (synchronization.getClass().getName().startsWith("org.jboss.jca")) {
if (TransactionLogger.ROOT_LOGGER.isTraceEnabled()) {
TransactionLogger.ROOT_LOGGER.trace("JCAOrderedLastSynchronizationList.jcaSyncs.add - Class: " + synchronization.getClass() + " HashCode: "
+ synchronization.hashCode() + " toString: " + synchronization);
}
jcaSyncs.add(synchronization);
} else {
if (TransactionLogger.ROOT_LOGGER.isTraceEnabled()) {
TransactionLogger.ROOT_LOGGER.trace("JCAOrderedLastSynchronizationList.preJcaSyncs.add - Class: " + synchronization.getClass() + " HashCode: "
+ synchronization.hashCode() + " toString: " + synchronization);
}
preJcaSyncs.add(synchronization);
}
}
/**
* Exceptions from Synchronizations that are registered with this TSR are not trapped for before completion. This is because
* an error in a Sync here should result in the transaction rolling back.
*
* You can see that in effect in these classes:
* https://github.com/jbosstm/narayana/blob/5.0.4.Final/ArjunaCore/arjuna/classes
* /com/arjuna/ats/arjuna/coordinator/TwoPhaseCoordinator.java#L91
* https://github.com/jbosstm/narayana/blob/5.0.4.Final/ArjunaJTA
* /jta/classes/com/arjuna/ats/internal/jta/resources/arjunacore/SynchronizationImple.java#L76
*/
@Override
public void beforeCompletion() {
// This is needed to guard against syncs being registered during the run, otherwise we could have used an iterator
int lastIndexProcessed = 0;
while ((lastIndexProcessed < preJcaSyncs.size())) {
Synchronization preJcaSync = preJcaSyncs.get(lastIndexProcessed);
if (TransactionLogger.ROOT_LOGGER.isTraceEnabled()) {
TransactionLogger.ROOT_LOGGER.trace("JCAOrderedLastSynchronizationList.preJcaSyncs.before_completion - Class: " + preJcaSync.getClass() + " HashCode: "
+ preJcaSync.hashCode()
+ " toString: "
+ preJcaSync);
}
preJcaSync.beforeCompletion();
lastIndexProcessed = lastIndexProcessed + 1;
}
// Do the same for the jca syncs
lastIndexProcessed = 0;
while ((lastIndexProcessed < jcaSyncs.size())) {
Synchronization jcaSync = jcaSyncs.get(lastIndexProcessed);
if (TransactionLogger.ROOT_LOGGER.isTraceEnabled()) {
TransactionLogger.ROOT_LOGGER.trace("JCAOrderedLastSynchronizationList.jcaSyncs.before_completion - Class: " + jcaSync.getClass() + " HashCode: "
+ jcaSync.hashCode()
+ " toString: "
+ jcaSync);
}
jcaSync.beforeCompletion();
lastIndexProcessed = lastIndexProcessed + 1;
}
}
@Override
public void afterCompletion(int status) {
// The list should be iterated in reverse order - has issues with Enterprise Beans 3 if not. See the afterCompletion method in:
// https://github.com/jbosstm/narayana/blob/main/ArjunaCore/arjuna/classes/com/arjuna/ats/arjuna/coordinator/TwoPhaseCoordinator.java
for (int i = preJcaSyncs.size() - 1; i>= 0; --i) {
Synchronization preJcaSync = preJcaSyncs.get(i);
if (TransactionLogger.ROOT_LOGGER.isTraceEnabled()) {
TransactionLogger.ROOT_LOGGER.trace("JCAOrderedLastSynchronizationList.preJcaSyncs.afterCompletion - Class: " + preJcaSync.getClass() + " HashCode: "
+ preJcaSync.hashCode()
+ " toString: " + preJcaSync);
}
try {
preJcaSync.afterCompletion(status);
} catch (Exception e) {
// Trap these exceptions so the rest of the synchronizations get the chance to complete
// https://github.com/jbosstm/narayana/blob/5.0.4.Final/ArjunaJTA/jta/classes/com/arjuna/ats/internal/jta/resources/arjunacore/SynchronizationImple.java#L102
TransactionLogger.ROOT_LOGGER.preJcaSyncAfterCompletionFailed(preJcaSync, ContextTransactionManager.getInstance().getTransaction(), e);
}
}
for (int i = jcaSyncs.size() - 1; i>= 0; --i) {
Synchronization jcaSync = jcaSyncs.get(i);
if (TransactionLogger.ROOT_LOGGER.isTraceEnabled()) {
TransactionLogger.ROOT_LOGGER.trace("JCAOrderedLastSynchronizationList.jcaSyncs.afterCompletion - Class: " + jcaSync.getClass() + " HashCode: "
+ jcaSync.hashCode()
+ " toString: "
+ jcaSync);
}
try {
jcaSync.afterCompletion(status);
} catch (Exception e) {
// Trap these exceptions so the rest of the synchronizations get the chance to complete
// https://github.com/jbosstm/narayana/blob/5.0.4.Final/ArjunaJTA/jta/classes/com/arjuna/ats/internal/jta/resources/arjunacore/SynchronizationImple.java#L102
TransactionLogger.ROOT_LOGGER.jcaSyncAfterCompletionFailed(jcaSync, ContextTransactionManager.getInstance().getTransaction(), e);
}
}
}
}
| 9,265
| 53.828402
| 173
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/logging/TransactionLogger.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.txn.logging;
import static org.jboss.logging.Logger.Level.DEBUG;
import static org.jboss.logging.Logger.Level.ERROR;
import static org.jboss.logging.Logger.Level.WARN;
import jakarta.resource.spi.work.Work;
import jakarta.resource.spi.work.WorkCompletedException;
import jakarta.transaction.Synchronization;
import jakarta.transaction.Transaction;
import javax.transaction.xa.Xid;
import javax.xml.stream.Location;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathElement;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
import org.jboss.logging.annotations.Param;
import org.jboss.msc.service.StartException;
/**
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@MessageLogger(projectCode = "WFLYTX", length = 4)
public interface TransactionLogger extends BasicLogger {
/**
* A logger with the category of the default transaction package.
*/
TransactionLogger ROOT_LOGGER = Logger.getMessageLogger(TransactionLogger.class, "org.jboss.as.txn");
/**
* If a transaction could not be rolled back
*/
@LogMessage(level = ERROR)
@Message(id = 1, value = "Unable to roll back active transaction")
void unableToRollBack(@Cause Throwable cause);
/**
* If the current transaction status could not be determined
*/
@LogMessage(level = ERROR)
@Message(id = 2, value = "Unable to get transaction state")
void unableToGetTransactionStatus(@Cause Throwable cause);
/**
* If the user left a transaction open
*/
@LogMessage(level = ERROR)
@Message(id = 3, value = "APPLICATION ERROR: transaction still active in request with status %s")
void transactionStillOpen(int status);
/**
* Creates an exception indicating a create failed.
*
* @param cause the reason the creation failed.
*
* @return a {@link StartException} initialized with the cause.
*/
@Message(id = 4, value = "Create failed")
StartException createFailed(@Cause Throwable cause);
/**
* Creates an exception indicating the start of a manager failed.
*
* @param cause the reason the start failed.
* @param managerName the name of the manager that didn't start.
*
* @return a {@link StartException} initialized with the cause and error message.
*/
@Message(id = 5, value = "%s manager create failed")
StartException managerStartFailure(@Cause Throwable cause, String managerName);
/**
* Creates an exception indicating the failure of the object store browser.
*
* @param cause the reason the start failed.
*
* @return a {@link StartException} initialized with the cause and error message.
*/
@Message(id = 6, value = "Failed to configure object store browser bean")
StartException objectStoreStartFailure(@Cause Throwable cause);
/**
* Creates an exception indicating that a service was not started.
*
* @return a {@link IllegalStateException} initialized with the cause and error message.
*/
@Message(id = 7, value = "Service not started")
IllegalStateException serviceNotStarted();
/**
* Creates an exception indicating the start failed.
*
* @param cause the reason the start failed.
*
* @return a {@link StartException} initialized with the cause.
*/
@Message(id = 8, value = "Start failed")
StartException startFailure(@Cause Throwable cause);
/**
* A message indicating the metric is unknown.
*
* @param metric the unknown metric.
*
* @return the message.
*/
@Message(id = 9, value = "Unknown metric %s")
String unknownMetric(Object metric);
@Message(id = 10, value = "MBean Server service not installed, this functionality is not available if the JMX subsystem has not been installed.")
RuntimeException jmxSubsystemNotInstalled();
// @Message(id = 11, value = "'journal-store-enable-async-io' must be true.")
// String transformJournalStoreEnableAsyncIoMustBeTrue();
@Message(id = 12, value = "Attributes %s and %s are alternatives; both cannot be set with conflicting values.")
OperationFailedException inconsistentStatisticsSettings(String attrOne, String attrTwo);
/**
* If the user has set node identifier to the default value
*/
@LogMessage(level = WARN)
@Message(id = 13, value = "The %s attribute on the %s is set to the default value. This is a danger for environments running "
+ "multiple servers. Please make sure the attribute value is unique.")
void nodeIdentifierIsSetToDefault(String attributeName, String subsystemAddress);
// /**
// * A message indicating that jndi-name is missing and it's a required attribute
// *
// * @return the message.
// */
// @Message(id = 14, value = "Jndi name is required")
// OperationFailedException jndiNameRequired();
/**
* A message indicating that jndi-name has an invalid format
*
* @return the message.
*/
@Message(id = 15, value = "Jndi names have to start with java:/ or java:jboss/")
OperationFailedException jndiNameInvalidFormat();
// @LogMessage(level = WARN)
// @Message(id = 16, value = "Transaction started in EE Concurrent invocation left open, starting rollback to prevent leak.")
// void rollbackOfTransactionStartedInEEConcurrentInvocation();
// @LogMessage(level = WARN)
// @Message(id = 17, value = "Failed to rollback transaction.")
// void failedToRollbackTransaction(@Cause Throwable cause);
// @LogMessage(level = WARN)
// @Message(id = 18, value = "Failed to suspend transaction.")
// void failedToSuspendTransaction(@Cause Throwable cause);
// @LogMessage(level = WARN)
// @Message(id = 19, value = "System error while checking for transaction leak in EE Concurrent invocation.")
// void systemErrorWhileCheckingForTransactionLeak(@Cause Throwable cause);
// @Message(id = 20, value = "EE Concurrent ContextHandle serialization must be handled by the factory.")
// IOException serializationMustBeHandledByTheFactory();
// @Message(id = 21, value = "EE Concurrent's TransactionSetupProviderService not started.")
// IllegalStateException transactionSetupProviderServiceNotStarted();
// @Message(id = 22, value = "EE Concurrent's TransactionSetupProviderService not installed.")
// IllegalStateException transactionSetupProviderServiceNotInstalled();
@Message(id = 23, value = "%s must be undefined if %s is 'true'.")
OperationFailedException mustBeUndefinedIfTrue(String attrOne, String attrTwo);
@Message(id = 24, value = "%s must be defined if %s is defined.")
OperationFailedException mustBedefinedIfDefined(String attrOne, String attrTwo);
@Message(id = 25, value = "Either %s must be 'true' or %s must be defined.")
OperationFailedException eitherTrueOrDefined(String attrOne, String attrTwo);
@LogMessage(level = WARN)
@Message(id = 26, value = "The transaction %s could not be removed from the cache during cleanup.")
void transactionNotFound(Transaction tx);
@LogMessage(level = WARN)
@Message(id = 27, value = "The pre-Jakarta Connectors synchronization %s associated with tx %s failed during after completion")
void preJcaSyncAfterCompletionFailed(Synchronization preJcaSync, Transaction tx, @Cause Exception e);
@LogMessage(level = WARN)
@Message(id = 28, value = "The Jakarta Connectors synchronization %s associated with tx %s failed during after completion")
void jcaSyncAfterCompletionFailed(Synchronization jcaSync, Transaction tx, @Cause Exception e);
@Message(id = 29, value = "Syncs are not allowed to be registered when the tx is in state %s")
IllegalStateException syncsnotallowed(int status);
@Message(id = 30, value = "Indexed child resources can only be registered if the parent resource supports ordered children. The parent of '%s' is not indexed")
IllegalStateException indexedChildResourceRegistrationNotAvailable(PathElement address);
@Message(id = 31, value = "The attribute '%s' is no longer supported")
XMLStreamException unsupportedAttribute(String attribute, @Param Location location);
@Message(id = 32, value = "%s must be defined if %s is 'true'.")
OperationFailedException mustBeDefinedIfTrue(String attrOne, String attrTwo);
@Message(id = 33, value = "Only one of %s and %s can be 'true'.")
OperationFailedException onlyOneCanBeTrue(String attrOne, String attrTwo);
@LogMessage(level = DEBUG)
@Message(id = 34, value = "relative_to property of the object-store is set to the default value with jboss.server.data.dir")
void objectStoreRelativeToIsSetToDefault();
@Message(id = 35, value = "Cannot find or import inflow transaction for xid %s and work %s")
WorkCompletedException cannotFindOrImportInflowTransaction(Xid xid, Work work, @Cause Exception e);
@Message(id = 36, value = "Imported Jakarta Connectors inflow transaction with xid %s of work %s is inactive")
WorkCompletedException importedInflowTransactionIsInactive(Xid xid, Work work, @Cause Exception e);
@Message(id = 37, value = "Unexpected error on resuming transaction %s for work %s")
WorkCompletedException cannotResumeInflowTransactionUnexpectedError(Transaction txn, Work work, @Cause Exception e);
@Message(id = 38, value = "Unexpected error on suspending transaction for work %s")
RuntimeException cannotSuspendInflowTransactionUnexpectedError(Work txn, @Cause Exception e);
@LogMessage(level = WARN)
@Message(id = 39, value = "A value of zero is not permitted for the maximum timeout, as such the timeout has been set to %s")
void timeoutValueIsSetToMaximum(int maximum_timeout);
@Message(id = 40, value = "There is no active transaction at the current context to register synchronization '%s'")
IllegalStateException noActiveTransactionToRegisterSynchronization(Synchronization sync);
}
| 11,324
| 42.895349
| 163
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/deployment/TransactionRollbackSetupAction.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.txn.deployment;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import jakarta.transaction.Status;
import jakarta.transaction.SystemException;
import jakarta.transaction.TransactionManager;
import org.jboss.as.server.deployment.SetupAction;
import org.jboss.as.txn.logging.TransactionLogger;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
/**
* Setup action that makes sure that no transactions leak from EE requests
*
* @author Stuart Douglas
*/
public class TransactionRollbackSetupAction implements SetupAction, Service<TransactionRollbackSetupAction> {
private static final ThreadLocal<Holder> depth = new ThreadLocal<Holder>();
private final InjectedValue<TransactionManager> transactionManager = new InjectedValue<TransactionManager>();
private final ServiceName serviceName;
public TransactionRollbackSetupAction(final ServiceName serviceName) {
this.serviceName = serviceName;
}
@Override
public void setup(final Map<String, Object> properties) {
changeDepth(1);
}
@Override
public void teardown(final Map<String, Object> properties) {
if (changeDepth(-1)) {
checkTransactionStatus();
}
// reset transaction timeout to the default value
final TransactionManager tm = transactionManager.getOptionalValue();
if (tm != null) {
try {
tm.setTransactionTimeout(0);
} catch (Exception ignore) {
}
}
}
@Override
public int priority() {
return 0;
}
@Override
public Set<ServiceName> dependencies() {
return Collections.singleton(serviceName);
}
@Override
public void start(final StartContext context) throws StartException {
}
@Override
public void stop(final StopContext context) {
}
@Override
public TransactionRollbackSetupAction getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
public InjectedValue<TransactionManager> getTransactionManager() {
return transactionManager;
}
private boolean changeDepth(int increment) {
Holder holder = depth.get();
if (holder == null) {
//if there is a transaction active initially we just track the depth
//and don't actually close it, because we don't 'own' the transaction
//this can happen when running async listeners outside the context of a request
holder = new Holder();
try {
final TransactionManager tm = transactionManager.getOptionalValue();
if (tm != null) {
holder.actuallyCleanUp = !isTransactionActive(tm, tm.getStatus());
}
depth.set(holder);
} catch (Exception e) {
TransactionLogger.ROOT_LOGGER.unableToGetTransactionStatus(e);
}
}
holder.depth += increment;
if (holder.depth == 0) {
depth.set(null);
return holder.actuallyCleanUp;
}
return false;
}
private void checkTransactionStatus() {
try {
final TransactionManager tm = transactionManager.getOptionalValue();
if (tm == null) {
return;
}
final int status = tm.getStatus();
final boolean active = isTransactionActive(tm, status);
if (active) {
try {
TransactionLogger.ROOT_LOGGER.transactionStillOpen(status);
tm.rollback();
} catch (Exception ex) {
TransactionLogger.ROOT_LOGGER.unableToRollBack(ex);
}
}
} catch (Exception e) {
TransactionLogger.ROOT_LOGGER.unableToGetTransactionStatus(e);
}
}
private boolean isTransactionActive(TransactionManager tm, int status) throws SystemException {
switch (status) {
case Status.STATUS_ACTIVE:
case Status.STATUS_COMMITTING:
case Status.STATUS_MARKED_ROLLBACK:
case Status.STATUS_PREPARING:
case Status.STATUS_ROLLING_BACK:
case Status.STATUS_ROLLEDBACK:
case Status.STATUS_PREPARED:
return true;
}
return false;
}
private static class Holder {
int depth;
boolean actuallyCleanUp = true;
}
}
| 5,736
| 31.596591
| 113
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/deployment/TransactionLeakRollbackProcessor.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.txn.deployment;
import jakarta.transaction.TransactionManager;
import org.jboss.as.ee.component.Attachments;
import org.jboss.as.server.deployment.AttachmentKey;
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.SetupAction;
import org.jboss.as.txn.service.TransactionManagerService;
import org.jboss.msc.service.ServiceName;
/**
* Processor that adds a {@link SetupAction} to the deployment that prevents
* transactions from leaking from web requests.
*
* @author Stuart Douglas
*/
public class TransactionLeakRollbackProcessor implements DeploymentUnitProcessor {
private static final ServiceName SERVICE_NAME = ServiceName.JBOSS.append("transaction", "ee-transaction-rollback-service");
private static final AttachmentKey<SetupAction> ATTACHMENT_KEY = AttachmentKey.create(SetupAction.class);
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final ServiceName serviceName = deploymentUnit.getServiceName().append(SERVICE_NAME);
final TransactionRollbackSetupAction service = new TransactionRollbackSetupAction(serviceName);
phaseContext.getServiceTarget().addService(serviceName, service)
.addDependency(TransactionManagerService.INTERNAL_SERVICE_NAME, TransactionManager.class, service.getTransactionManager())
.install();
deploymentUnit.addToAttachmentList(Attachments.WEB_SETUP_ACTIONS, service);
deploymentUnit.putAttachment(ATTACHMENT_KEY, service);
}
@Override
public void undeploy(DeploymentUnit deploymentUnit) {
SetupAction action = deploymentUnit.removeAttachment(ATTACHMENT_KEY);
deploymentUnit.getAttachmentList(Attachments.WEB_SETUP_ACTIONS).remove(action);
}
}
| 3,128
| 45.701493
| 138
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/deployment/TransactionDependenciesProcessor.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.txn.deployment;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.annotation.CompositeIndex;
import org.jboss.as.server.deployment.module.ModuleDependency;
import org.jboss.as.server.deployment.module.ModuleSpecification;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.DotName;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleLoader;
import jakarta.transaction.TransactionScoped;
import jakarta.transaction.Transactional;
import java.util.List;
/**
* Looks for usage of the @Transactional Jakarta Contexts and Dependency Injection interceptor (JTA 1.2) or the @TransactionScoped Jakarta Contexts and Dependency Injection context (JTA 1.2)
* and adds the org.jboss.jts module dependency if they are found.
*
* Also adds the transaction API to deployments
*
* @author Paul Robinson
*/
public class TransactionDependenciesProcessor implements DeploymentUnitProcessor {
public static final String JTS_MODULE = "org.jboss.jts";
public static final String TRANSACTION_API = "jakarta.transaction.api";
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit unit = phaseContext.getDeploymentUnit();
final ModuleLoader moduleLoader = Module.getBootModuleLoader();
final ModuleSpecification moduleSpec = unit.getAttachment(Attachments.MODULE_SPECIFICATION);
moduleSpec.addSystemDependency(new ModuleDependency(moduleLoader, TRANSACTION_API, false, false, true, false));
moduleSpec.addSystemDependency(new ModuleDependency(moduleLoader, "org.wildfly.transaction.client", false, false, true, false));
final CompositeIndex compositeIndex = unit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
if (compositeIndex == null) {
return;
}
final List<AnnotationInstance> transactionalAnnotations = compositeIndex.getAnnotations(DotName.createSimple(Transactional.class.getName()));
final List<AnnotationInstance> transactionScopedAnnotations = compositeIndex.getAnnotations(DotName.createSimple(TransactionScoped.class.getName()));
if (!transactionalAnnotations.isEmpty() || !transactionScopedAnnotations.isEmpty()) {
addJTSModuleDependencyToDeployment(unit);
}
}
private void addJTSModuleDependencyToDeployment(DeploymentUnit unit) {
final ModuleLoader moduleLoader = Module.getBootModuleLoader();
final ModuleSpecification moduleSpec = unit.getAttachment(Attachments.MODULE_SPECIFICATION);
moduleSpec.addSystemDependency(new ModuleDependency(moduleLoader, JTS_MODULE, false, false, true, false));
}
}
| 4,022
| 46.329412
| 190
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/deployment/TransactionJndiBindingProcessor.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.txn.deployment;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import jakarta.transaction.TransactionSynchronizationRegistry;
import jakarta.transaction.UserTransaction;
import org.jboss.as.ee.component.Attachments;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.ComponentNamingMode;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.ee.structure.DeploymentType;
import org.jboss.as.ee.structure.DeploymentTypeMarker;
import org.jboss.as.naming.ManagedReferenceInjector;
import org.jboss.as.naming.ServiceBasedNamingStore;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.service.BinderService;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.txn.service.TransactionSynchronizationRegistryService;
import org.jboss.as.txn.service.UserTransactionBindingService;
import org.jboss.as.txn.service.UserTransactionAccessControlService;
import org.jboss.as.txn.service.UserTransactionService;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
/**
* Processor responsible for binding transaction related resources to JNDI.
* </p>
* Unlike other resource injections this binding happens for all eligible components,
* regardless of the presence of the {@link jakarta.annotation.Resource} annotation.
*
* @author Stuart Douglas
* @author <a href="mailto:ropalka@redhat.com">Richard Opalka</a>
*/
public class TransactionJndiBindingProcessor implements DeploymentUnitProcessor {
@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;
}
final ServiceTarget serviceTarget = phaseContext.getServiceTarget();
// bind to module
final ServiceName moduleContextServiceName = ContextNames.contextServiceNameOfModule(moduleDescription.getApplicationName(),moduleDescription.getModuleName());
bindServices(deploymentUnit, serviceTarget, moduleContextServiceName);
if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) {
// bind to each component
for (ComponentDescription component : moduleDescription.getComponentDescriptions()) {
if (component.getNamingMode() == ComponentNamingMode.CREATE) {
final ServiceName compContextServiceName = ContextNames.contextServiceNameOfComponent(moduleDescription.getApplicationName(), moduleDescription.getModuleName(), component.getComponentName());
bindServices(deploymentUnit, serviceTarget, compContextServiceName);
}
}
}
}
/**
* Binds the java:comp/UserTransaction service and the java:comp/TransactionSynchronizationRegistry
*
* @param deploymentUnit The deployment unit
* @param serviceTarget The service target
* @param contextServiceName The service name of the context to bind to
*/
private void bindServices(DeploymentUnit deploymentUnit, ServiceTarget serviceTarget, ServiceName contextServiceName) {
final ServiceName userTransactionServiceName = contextServiceName.append("UserTransaction");
final UserTransactionBindingService userTransactionBindingService = new UserTransactionBindingService("UserTransaction");
serviceTarget.addService(userTransactionServiceName, userTransactionBindingService)
.addDependency(UserTransactionAccessControlService.SERVICE_NAME, UserTransactionAccessControlService.class,userTransactionBindingService.getUserTransactionAccessControlServiceInjector())
.addDependency(UserTransactionService.INTERNAL_SERVICE_NAME, UserTransaction.class,
new ManagedReferenceInjector<UserTransaction>(userTransactionBindingService.getManagedObjectInjector()))
.addDependency(contextServiceName, ServiceBasedNamingStore.class, userTransactionBindingService.getNamingStoreInjector())
.install();
final Map<ServiceName, Set<ServiceName>> jndiComponentDependencies = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.COMPONENT_JNDI_DEPENDENCIES);
Set<ServiceName> jndiDependencies = jndiComponentDependencies.get(contextServiceName);
if (jndiDependencies == null) {
jndiComponentDependencies.put(contextServiceName, jndiDependencies = new HashSet<>());
}
jndiDependencies.add(userTransactionServiceName);
final ServiceName transactionSynchronizationRegistryName = contextServiceName.append("TransactionSynchronizationRegistry");
BinderService transactionSyncBinderService = new BinderService("TransactionSynchronizationRegistry");
serviceTarget.addService(transactionSynchronizationRegistryName, transactionSyncBinderService)
.addDependency(TransactionSynchronizationRegistryService.INTERNAL_SERVICE_NAME, TransactionSynchronizationRegistry.class,
new ManagedReferenceInjector<TransactionSynchronizationRegistry>(transactionSyncBinderService.getManagedObjectInjector()))
.addDependency(contextServiceName, ServiceBasedNamingStore.class, transactionSyncBinderService.getNamingStoreInjector())
.install();
jndiDependencies.add(transactionSynchronizationRegistryName);
}
}
| 6,948
| 56.429752
| 211
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/TransactionExtension.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
import javax.management.MBeanServer;
import org.jboss.as.controller.Extension;
import org.jboss.as.controller.ExtensionContext;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SubsystemRegistration;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver;
import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler;
import org.jboss.as.controller.parsing.ExtensionParsingContext;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.services.path.ResolvePathHandler;
import org.jboss.as.txn.logging.TransactionLogger;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceRegistry;
/**
* The transaction management extension.
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
* @author Emanuel Muckenhuber
* @author Scott Stark (sstark@redhat.com) (C) 2011 Red Hat Inc.
* @author Mike Musgrove (mmusgrov@redhat.com) (C) 2012 Red Hat Inc.
*/
public class TransactionExtension implements Extension {
public static final String SUBSYSTEM_NAME = "transactions";
/**
* The operation name to resolve the object store path
*/
public static final String RESOLVE_OBJECT_STORE_PATH = "resolve-object-store-path";
private static final String RESOURCE_NAME = TransactionExtension.class.getPackage().getName() + ".LocalDescriptions";
static final ModelVersion CURRENT_MODEL_VERSION = ModelVersion.create(6, 0, 0);
private static final ServiceName MBEAN_SERVER_SERVICE_NAME = ServiceName.JBOSS.append("mbean", "server");
static final PathElement LOG_STORE_PATH = PathElement.pathElement(LogStoreConstants.LOG_STORE, LogStoreConstants.LOG_STORE);
static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, TransactionExtension.SUBSYSTEM_NAME);
static final PathElement PARTICIPANT_PATH = PathElement.pathElement(LogStoreConstants.PARTICIPANTS);
static final PathElement TRANSACTION_PATH = PathElement.pathElement(LogStoreConstants.TRANSACTIONS);
static StandardResourceDescriptionResolver getResourceDescriptionResolver(final String... keyPrefix) {
StringBuilder prefix = new StringBuilder(SUBSYSTEM_NAME);
for (String kp : keyPrefix) {
prefix.append('.').append(kp);
}
return new StandardResourceDescriptionResolver(prefix.toString(), RESOURCE_NAME, TransactionExtension.class.getClassLoader(), true, false);
}
static MBeanServer getMBeanServer(OperationContext context) {
final ServiceRegistry serviceRegistry = context.getServiceRegistry(false);
final ServiceController<?> serviceController = serviceRegistry.getService(MBEAN_SERVER_SERVICE_NAME);
if (serviceController == null) {
throw TransactionLogger.ROOT_LOGGER.jmxSubsystemNotInstalled();
}
return (MBeanServer) serviceController.getValue();
}
/**
* {@inheritDoc}
*/
@Override
public void initialize(ExtensionContext context) {
TransactionLogger.ROOT_LOGGER.debug("Initializing Transactions Extension");
final LogStoreResource resource = new LogStoreResource();
final boolean registerRuntimeOnly = context.isRuntimeOnlyRegistrationValid();
final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION);
final TransactionSubsystemRootResourceDefinition rootResourceDefinition = new TransactionSubsystemRootResourceDefinition(registerRuntimeOnly);
final ManagementResourceRegistration registration = subsystem.registerSubsystemModel(rootResourceDefinition);
registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE);
// Create the path resolver handlers
if (context.getProcessType().isServer()) {
// It's less than ideal to create a separate operation here, but this extension contains two relative-to attributes
final ResolvePathHandler objectStorePathHandler = ResolvePathHandler.Builder.of(RESOLVE_OBJECT_STORE_PATH, context.getPathManager())
.setPathAttribute(TransactionSubsystemRootResourceDefinition.OBJECT_STORE_PATH)
.setRelativeToAttribute(TransactionSubsystemRootResourceDefinition.OBJECT_STORE_RELATIVE_TO)
.build();
registration.registerOperationHandler(objectStorePathHandler.getOperationDefinition(), objectStorePathHandler);
}
ManagementResourceRegistration logStoreChild = registration.registerSubModel(new LogStoreDefinition(resource, registerRuntimeOnly));
if (registerRuntimeOnly) {
ManagementResourceRegistration transactionChild = logStoreChild.registerSubModel(new LogStoreTransactionDefinition(resource));
transactionChild.registerSubModel(new LogStoreTransactionParticipantDefinition());
}
subsystem.registerXMLElementWriter(TransactionSubsystemXMLPersister.INSTANCE);
}
/**
* {@inheritDoc}
*/
@Override
public void initializeParsers(ExtensionParsingContext context) {
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_1_0.getUriString(), TransactionSubsystem10Parser::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_1_1.getUriString(), TransactionSubsystem11Parser::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_1_2.getUriString(), TransactionSubsystem12Parser::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_1_3.getUriString(), TransactionSubsystem13Parser::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_1_4.getUriString(), TransactionSubsystem14Parser::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_1_5.getUriString(), TransactionSubsystem15Parser::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_2_0.getUriString(), TransactionSubsystem20Parser::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_3_0.getUriString(), TransactionSubsystem30Parser::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_4_0.getUriString(), TransactionSubsystem40Parser::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_5_0.getUriString(), TransactionSubsystem50Parser::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_6_0.getUriString(), TransactionSubsystem60Parser::new);
}
}
| 7,976
| 55.574468
| 150
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/LogStoreResource.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.txn.subsystem;
import java.util.Collections;
import java.util.Set;
import javax.management.ObjectName;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.registry.AbstractModelResource;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.txn.logging.TransactionLogger;
import org.jboss.dmr.ModelNode;
/**
* Resource maintaining the sub-tree for the log-store.
*
* @author Emanuel Muckenhuber
*/
class LogStoreResource implements Resource {
private volatile Resource delegate = Factory.create();
protected void update(final Resource updated) {
delegate = updated;
}
@Override
public ModelNode getModel() {
return delegate.getModel();
}
@Override
public void writeModel(ModelNode newModel) {
delegate.writeModel(newModel);
}
@Override
public boolean isModelDefined() {
return delegate.isModelDefined();
}
@Override
public boolean hasChild(PathElement element) {
return delegate.hasChild(element);
}
@Override
public Resource getChild(PathElement element) {
return delegate.getChild(element);
}
@Override
public Resource requireChild(PathElement element) {
return delegate.requireChild(element);
}
@Override
public boolean hasChildren(String childType) {
return delegate.hasChildren(childType);
}
@Override
public Resource navigate(PathAddress address) {
return delegate.navigate(address);
}
@Override
public Set<String> getChildTypes() {
return delegate.getChildTypes();
}
@Override
public Set<String> getChildrenNames(String childType) {
return delegate.getChildrenNames(childType);
}
@Override
public Set<ResourceEntry> getChildren(String childType) {
return delegate.getChildren(childType);
}
@Override
public void registerChild(PathElement address, Resource resource) {
assert resource instanceof LogStoreRuntimeResource;
delegate.registerChild(address, resource);
}
@Override
public Resource removeChild(PathElement address) {
return delegate.removeChild(address);
}
@Override
public boolean isRuntime() {
return false;
}
@Override
public boolean isProxy() {
return false;
}
@Override
public void registerChild(PathElement address, int index, Resource resource) {
throw TransactionLogger.ROOT_LOGGER.indexedChildResourceRegistrationNotAvailable(address);
}
@Override
public Set<String> getOrderedChildTypes() {
return Collections.emptySet();
}
@Override
public Resource clone() {
return this;
}
static ObjectName getObjectName(final Resource resource) {
assert resource instanceof LogStoreRuntimeResource;
return ((LogStoreRuntimeResource)resource).getObjectName();
}
static class LogStoreRuntimeResource extends AbstractModelResource {
private final ObjectName objectName;
// private volatile ModelNode model;
private volatile ModelNode model = new ModelNode();
LogStoreRuntimeResource(ObjectName objectName) {
this.objectName = objectName;
}
ObjectName getObjectName() {
return objectName;
}
@Override
public ModelNode getModel() {
return model;
}
@Override
public void writeModel(final ModelNode newModel) {
model = newModel;
}
@Override
public boolean isModelDefined() {
return model.isDefined();
}
@Override
public Resource clone() {
return this;
}
@Override
public boolean isRuntime() {
return true;
}
}
}
| 4,963
| 25.688172
| 98
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/TransactionSubsystemXMLPersister.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.txn.subsystem;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.persistence.SubsystemMarshallingContext;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.jboss.staxmapper.XMLElementWriter;
import org.jboss.staxmapper.XMLExtendedStreamWriter;
/**
* The {@link XMLElementWriter} that handles the Transaction subsystem. As we only write out the most recent version of
* a subsystem we only need to keep the latest version around.
*
* @author <a href="mailto:istudens@redhat.com">Ivo Studensky</a>
*/
class TransactionSubsystemXMLPersister implements XMLElementWriter<SubsystemMarshallingContext> {
public static final TransactionSubsystemXMLPersister INSTANCE = new TransactionSubsystemXMLPersister();
private TransactionSubsystemXMLPersister() {
}
/**
* {@inheritDoc}
*/
@Override
public void writeContent(XMLExtendedStreamWriter writer, SubsystemMarshallingContext context) throws XMLStreamException {
context.startSubsystemElement(Namespace.CURRENT.getUriString(), false);
ModelNode node = context.getModelNode();
writer.writeStartElement(Element.CORE_ENVIRONMENT.getLocalName());
TransactionSubsystemRootResourceDefinition.NODE_IDENTIFIER.marshallAsAttribute(node, writer);
writeProcessId(writer, node);
writer.writeEndElement();
if (TransactionSubsystemRootResourceDefinition.BINDING.isMarshallable(node) ||
TransactionSubsystemRootResourceDefinition.STATUS_BINDING.isMarshallable(node) ||
TransactionSubsystemRootResourceDefinition.RECOVERY_LISTENER.isMarshallable(node)) {
writer.writeStartElement(Element.RECOVERY_ENVIRONMENT.getLocalName());
TransactionSubsystemRootResourceDefinition.BINDING.marshallAsAttribute(node, writer);
TransactionSubsystemRootResourceDefinition.STATUS_BINDING.marshallAsAttribute(node, writer);
TransactionSubsystemRootResourceDefinition.RECOVERY_LISTENER.marshallAsAttribute(node, writer);
writer.writeEndElement();
}
if (TransactionSubsystemRootResourceDefinition.STATISTICS_ENABLED.isMarshallable(node)
|| TransactionSubsystemRootResourceDefinition.ENABLE_TSM_STATUS.isMarshallable(node)
|| TransactionSubsystemRootResourceDefinition.DEFAULT_TIMEOUT.isMarshallable(node)
|| TransactionSubsystemRootResourceDefinition.MAXIMUM_TIMEOUT.isMarshallable(node)) {
writer.writeStartElement(Element.COORDINATOR_ENVIRONMENT.getLocalName());
TransactionSubsystemRootResourceDefinition.STATISTICS_ENABLED.marshallAsAttribute(node, writer);
TransactionSubsystemRootResourceDefinition.ENABLE_TSM_STATUS.marshallAsAttribute(node, writer);
TransactionSubsystemRootResourceDefinition.DEFAULT_TIMEOUT.marshallAsAttribute(node, writer);
TransactionSubsystemRootResourceDefinition.MAXIMUM_TIMEOUT.marshallAsAttribute(node, writer);
writer.writeEndElement();
}
if (TransactionSubsystemRootResourceDefinition.OBJECT_STORE_RELATIVE_TO.isMarshallable(node)
|| TransactionSubsystemRootResourceDefinition.OBJECT_STORE_PATH.isMarshallable(node)) {
writer.writeStartElement(Element.OBJECT_STORE.getLocalName());
TransactionSubsystemRootResourceDefinition.OBJECT_STORE_PATH.marshallAsAttribute(node, writer);
TransactionSubsystemRootResourceDefinition.OBJECT_STORE_RELATIVE_TO.marshallAsAttribute(node, writer);
writer.writeEndElement();
}
if(node.hasDefined(CommonAttributes.JTS) && node.get(CommonAttributes.JTS).asBoolean()) {
writer.writeStartElement(Element.JTS.getLocalName());
writer.writeEndElement();
}
if(node.hasDefined(CommonAttributes.USE_JOURNAL_STORE) && node.get(CommonAttributes.USE_JOURNAL_STORE).asBoolean()) {
writer.writeStartElement(Element.USE_JOURNAL_STORE.getLocalName());
TransactionSubsystemRootResourceDefinition.JOURNAL_STORE_ENABLE_ASYNC_IO.marshallAsAttribute(node, writer);
writer.writeEndElement();
}
if (node.hasDefined(CommonAttributes.USE_JDBC_STORE) && node.get(CommonAttributes.USE_JDBC_STORE).asBoolean()) {
writer.writeStartElement(Element.JDBC_STORE.getLocalName());
TransactionSubsystemRootResourceDefinition.JDBC_STORE_DATASOURCE.marshallAsAttribute(node, writer);
if (TransactionSubsystemRootResourceDefinition.JDBC_ACTION_STORE_TABLE_PREFIX.isMarshallable(node)
|| TransactionSubsystemRootResourceDefinition.JDBC_ACTION_STORE_DROP_TABLE.isMarshallable(node)) {
writer.writeEmptyElement(Element.JDBC_ACTION_STORE.getLocalName());
TransactionSubsystemRootResourceDefinition.JDBC_ACTION_STORE_TABLE_PREFIX.marshallAsAttribute(node, writer);
TransactionSubsystemRootResourceDefinition.JDBC_ACTION_STORE_DROP_TABLE.marshallAsAttribute(node, writer);
}
if (TransactionSubsystemRootResourceDefinition.JDBC_COMMUNICATION_STORE_TABLE_PREFIX.isMarshallable(node)
|| TransactionSubsystemRootResourceDefinition.JDBC_COMMUNICATION_STORE_DROP_TABLE.isMarshallable(node)) {
writer.writeEmptyElement(Element.JDBC_COMMUNICATION_STORE.getLocalName());
TransactionSubsystemRootResourceDefinition.JDBC_COMMUNICATION_STORE_TABLE_PREFIX.marshallAsAttribute(node, writer);
TransactionSubsystemRootResourceDefinition.JDBC_COMMUNICATION_STORE_DROP_TABLE.marshallAsAttribute(node, writer);
}
if (TransactionSubsystemRootResourceDefinition.JDBC_STATE_STORE_TABLE_PREFIX.isMarshallable(node)
|| TransactionSubsystemRootResourceDefinition.JDBC_STATE_STORE_DROP_TABLE.isMarshallable(node)) {
writer.writeEmptyElement(Element.JDBC_STATE_STORE.getLocalName());
TransactionSubsystemRootResourceDefinition.JDBC_STATE_STORE_TABLE_PREFIX.marshallAsAttribute(node, writer);
TransactionSubsystemRootResourceDefinition.JDBC_STATE_STORE_DROP_TABLE.marshallAsAttribute(node, writer);
}
writer.writeEndElement();
}
if (node.hasDefined(CommonAttributes.CM_RESOURCE) && !node.get(CommonAttributes.CM_RESOURCE).asList().isEmpty()) {
writer.writeStartElement(Element.CM_RESOURCES.getLocalName());
for (Property cmr : node.get(CommonAttributes.CM_RESOURCE).asPropertyList()) {
writer.writeStartElement(CommonAttributes.CM_RESOURCE);
writer.writeAttribute(Attribute.JNDI_NAME.getLocalName(), cmr.getName());
if (cmr.getValue().hasDefined(CMResourceResourceDefinition.CM_TABLE_NAME.getName()) ||
cmr.getValue().hasDefined(CMResourceResourceDefinition.CM_TABLE_BATCH_SIZE.getName()) ||
cmr.getValue().hasDefined(CMResourceResourceDefinition.CM_TABLE_IMMEDIATE_CLEANUP.getName())) {
writer.writeStartElement(Element.CM_TABLE.getLocalName());
CMResourceResourceDefinition.CM_TABLE_NAME.marshallAsAttribute(cmr.getValue(), writer);
CMResourceResourceDefinition.CM_TABLE_BATCH_SIZE.marshallAsAttribute(cmr.getValue(), writer);
CMResourceResourceDefinition.CM_TABLE_IMMEDIATE_CLEANUP.marshallAsAttribute(cmr.getValue(), writer);
writer.writeEndElement();
}
writer.writeEndElement();
}
writer.writeEndElement();
}
if (TransactionSubsystemRootResourceDefinition.STALE_TRANSACTION_TIME.isMarshallable(node)){
writer.writeStartElement(Element.CLIENT.getLocalName());
TransactionSubsystemRootResourceDefinition.STALE_TRANSACTION_TIME.marshallAsAttribute(node, writer);
writer.writeEndElement();
}
writer.writeEndElement();
}
private void writeProcessId(final XMLExtendedStreamWriter writer, final ModelNode value) throws XMLStreamException {
writer.writeStartElement(Element.PROCESS_ID.getLocalName());
if (value.get(TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.getName()).asBoolean(false)) {
writer.writeEmptyElement(Element.UUID.getLocalName());
} else {
writer.writeStartElement(Element.SOCKET.getLocalName());
TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING.marshallAsAttribute(value, writer);
TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_MAX_PORTS.marshallAsAttribute(value, writer);
writer.writeEndElement();
}
writer.writeEndElement();
}
}
| 9,907
| 55.617143
| 131
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/TransactionSubsystem20Parser.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.txn.subsystem;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoContent;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoNamespaceAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute;
import javax.xml.stream.XMLStreamException;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* The {@link org.jboss.staxmapper.XMLElementReader} that handles the Transaction subsystem.
*
* @author <a href="mailto:istudens@redhat.com">Ivo Studensky</a>
*/
class TransactionSubsystem20Parser extends TransactionSubsystem14Parser {
TransactionSubsystem20Parser() {
super(Namespace.TRANSACTIONS_2_0);
}
TransactionSubsystem20Parser(Namespace validNamespace) {
super(validNamespace);
}
protected void parseCoordinatorEnvironmentElement(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case STATISTICS_ENABLED:
TransactionSubsystemRootResourceDefinition.STATISTICS_ENABLED.parseAndSetParameter(value, operation, reader);
break;
case ENABLE_STATISTICS:
TransactionSubsystemRootResourceDefinition.ENABLE_STATISTICS.parseAndSetParameter(value, operation, reader);
break;
case ENABLE_TSM_STATUS:
TransactionSubsystemRootResourceDefinition.ENABLE_TSM_STATUS.parseAndSetParameter(value, operation, reader);
break;
case DEFAULT_TIMEOUT:
TransactionSubsystemRootResourceDefinition.DEFAULT_TIMEOUT.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
// Handle elements
requireNoContent(reader);
}
}
| 3,305
| 41.384615
| 146
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/LogStoreDefinition.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.txn.subsystem;
import org.jboss.as.controller.AbstractRuntimeOnlyHandler;
import org.jboss.as.controller.NoopOperationStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationDefinition;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.SimpleOperationDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
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 static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE;
/**
* @author <a href="mailto:tomaz.cerar@redhat.com">Tomaz Cerar</a>
*/
public class LogStoreDefinition extends SimpleResourceDefinition {
private final boolean registerRuntimeOnly;
public LogStoreDefinition(final LogStoreResource resource, final boolean registerRuntimeOnly) {
super(new SimpleResourceDefinition.Parameters(TransactionExtension.LOG_STORE_PATH, TransactionExtension.getResourceDescriptionResolver(LogStoreConstants.LOG_STORE))
.setAddHandler(new LogStoreAddHandler(resource))
.setRemoveHandler(NoopOperationStepHandler.WITH_RESULT)
.setRemoveRestartLevel(OperationEntry.Flag.RESTART_NONE));
this.registerRuntimeOnly = registerRuntimeOnly;
}
@Override
public void registerOperations(ManagementResourceRegistration resourceRegistration) {
super.registerOperations(resourceRegistration);
final OperationDefinition probe = new SimpleOperationDefinitionBuilder(LogStoreConstants.PROBE, getResourceDescriptionResolver())
.withFlag(OperationEntry.Flag.HOST_CONTROLLER_ONLY) // TODO WFLY-8852 decide how we want to handle this in a domain
.setRuntimeOnly()
.setReadOnly()
.build();
resourceRegistration.registerOperationHandler(probe, LogStoreProbeHandler.INSTANCE);
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
super.registerAttributes(resourceRegistration);
resourceRegistration.registerReadOnlyAttribute(LogStoreConstants.LOG_STORE_TYPE, null);
if (registerRuntimeOnly) {
resourceRegistration.registerReadWriteAttribute(LogStoreConstants.EXPOSE_ALL_LOGS, null,
new ExposeAllLogsWriteAttributeHandler());
}
}
static class ExposeAllLogsWriteAttributeHandler extends AbstractRuntimeOnlyHandler {
@Override
protected void executeRuntimeStep(OperationContext context, ModelNode operation) throws OperationFailedException {
final String attributeName = operation.require(NAME).asString();
ModelNode newValue = operation.hasDefined(VALUE)
? operation.get(VALUE) : LogStoreConstants.EXPOSE_ALL_LOGS.getDefaultValue();
final Resource resource = context.readResource(PathAddress.EMPTY_ADDRESS);
final ModelNode submodel = resource.getModel();
final ModelNode syntheticOp = new ModelNode();
syntheticOp.get(attributeName).set(newValue);
LogStoreConstants.EXPOSE_ALL_LOGS.validateAndSet(syntheticOp, submodel);
// ExposeAllRecordsAsMBeans JMX attribute will be set in LogStoreProbeHandler prior to eventual probe operation execution,
// hence no need to do here anything else
context.getResult().set(new ModelNode());
context.completeStep(OperationContext.ResultHandler.NOOP_RESULT_HANDLER);
}
}
}
| 4,943
| 48.44
| 172
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/ParticipantWriteAttributeHandler.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.txn.subsystem;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.jboss.as.controller.AbstractWriteAttributeHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.PathAddress;
import org.jboss.dmr.ModelNode;
/**
* The participant is a runtime resource which is created by {@link LogStoreProbeHandler}
* and loaded with data from Narayana object store.
* There is no way in Narayana API and no reason from processing perspective
* to directly write to the participant record. The participant can be managed
* by operations like {@code :delete}, {@code :recover} but not with direct write access
* to attributes.
*
* This handler can be deleted in future.
*/
@Deprecated
public class ParticipantWriteAttributeHandler extends AbstractWriteAttributeHandler<Void> {
public ParticipantWriteAttributeHandler(final AttributeDefinition... definitions) {
super(definitions);
}
@Override
protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<Void> voidHandback) {
ModelNode subModel = context.readResource(PathAddress.EMPTY_ADDRESS).getModel();
ModelNode onAttribute = subModel.get(LogStoreConstants.JMX_ON_ATTRIBUTE);
String jmxName = onAttribute.asString();
MBeanServer mbs = TransactionExtension.getMBeanServer(context);
try {
ObjectName on = new ObjectName(jmxName);
// Invoke operation
mbs.invoke(on, "clearHeuristic", null, null);
return true;
} catch (Exception e) {
return false;
}
}
@Override
protected void revertUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode valueToRestore, ModelNode resolvedValue, Void handback) {
// no-op
}
}
| 3,043
| 39.586667
| 197
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/Element.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
import java.util.HashMap;
import java.util.Map;
/**
* Enumeration of elements used in the transactions subsystem.
*
* @author John E. Bailey
* @author Scott Stark (sstark@redhat.com) (C) 2011 Red Hat Inc.
*/
enum Element {
// must be first
UNKNOWN(null),
RECOVERY_ENVIRONMENT(CommonAttributes.RECOVERY_ENVIRONMENT),
CORE_ENVIRONMENT(CommonAttributes.CORE_ENVIRONMENT),
COORDINATOR_ENVIRONMENT(CommonAttributes.COORDINATOR_ENVIRONMENT),
OBJECT_STORE(CommonAttributes.OBJECT_STORE),
PROCESS_ID(CommonAttributes.PROCESS_ID),
SOCKET(CommonAttributes.SOCKET),
UUID(CommonAttributes.UUID),
JTS(CommonAttributes.JTS),
USE_HORNETQ_STORE(CommonAttributes.USE_HORNETQ_STORE),
USE_JOURNAL_STORE(CommonAttributes.USE_JOURNAL_STORE),
JDBC_STORE(CommonAttributes.JDBC_STORE),
JDBC_STATE_STORE(CommonAttributes.STATE_STORE),
JDBC_COMMUNICATION_STORE(CommonAttributes.COMMUNICATION_STORE),
JDBC_ACTION_STORE(CommonAttributes.ACTION_STORE),
CM_RESPOURCE(CommonAttributes.CM_RESOURCE),
CM_RESOURCES(CommonAttributes.CM_RESOURCES),
CM_TABLE(CommonAttributes.CM_LOCATION),
CLIENT(CommonAttributes.CLIENT)
;
private final String name;
Element(final String name) {
this.name = name;
}
/**
* Get the local name of this element.
*
* @return the local name
*/
public String getLocalName() {
return name;
}
private static final Map<String, Element> MAP;
static {
final Map<String, Element> map = new HashMap<String, Element>();
for (Element element : values()) {
final String name = element.getLocalName();
if (name != null) map.put(name, element);
}
MAP = map;
}
public static Element forName(String localName) {
final Element element = MAP.get(localName);
return element == null ? UNKNOWN : element;
}
}
| 2,992
| 31.89011
| 72
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/LogStoreParticipantRecoveryHandler.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.txn.subsystem;
import org.jboss.as.controller.OperationContext;
public class LogStoreParticipantRecoveryHandler extends LogStoreParticipantOperationHandler {
private LogStoreParticipantRefreshHandler refreshHandler = null;
public LogStoreParticipantRecoveryHandler(LogStoreParticipantRefreshHandler refreshHandler) {
super("clearHeuristic");
this.refreshHandler = refreshHandler;
}
// refresh the attributes of this participant (the status attribute should have changed to PREPARED
void refreshParticipant(OperationContext context) {
context.addStep(refreshHandler, OperationContext.Stage.MODEL, true);
}
}
| 1,705
| 40.609756
| 103
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/TransactionSubsystemAdd.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
import static org.jboss.as.controller.resource.AbstractSocketBindingResourceDefinition.SOCKET_BINDING_CAPABILITY_NAME;
import static org.jboss.as.txn.subsystem.CommonAttributes.CM_RESOURCE;
import static org.jboss.as.txn.subsystem.CommonAttributes.JDBC_STORE_DATASOURCE;
import static org.jboss.as.txn.subsystem.CommonAttributes.JTS;
import static org.jboss.as.txn.subsystem.CommonAttributes.USE_JOURNAL_STORE;
import static org.jboss.as.txn.subsystem.CommonAttributes.USE_JDBC_STORE;
import static org.jboss.as.txn.subsystem.TransactionSubsystemRootResourceDefinition.REMOTE_TRANSACTION_SERVICE_CAPABILITY;
import static org.jboss.as.txn.subsystem.TransactionSubsystemRootResourceDefinition.TRANSACTION_CAPABILITY;
import static org.jboss.as.txn.subsystem.TransactionSubsystemRootResourceDefinition.XA_RESOURCE_RECOVERY_REGISTRY_CAPABILITY;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;
import com.arjuna.ats.jbossatx.jta.RecoveryManagerService;
import jakarta.transaction.TransactionSynchronizationRegistry;
import jakarta.transaction.UserTransaction;
import io.undertow.server.handlers.PathHandler;
import org.jboss.as.controller.AbstractBoottimeAddStepHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.CapabilityServiceBuilder;
import org.jboss.as.controller.CapabilityServiceTarget;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.ProcessStateNotifier;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.controller.services.path.PathManager;
import org.jboss.as.controller.services.path.PathManagerService;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.naming.ManagedReferenceInjector;
import org.jboss.as.naming.ServiceBasedNamingStore;
import org.jboss.as.naming.ValueManagedReferenceFactory;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.service.BinderService;
import org.jboss.as.network.SocketBinding;
import org.jboss.as.network.SocketBindingManager;
import org.jboss.as.server.AbstractDeploymentChainStep;
import org.jboss.as.server.DeploymentProcessorTarget;
import org.jboss.as.server.ServerEnvironment;
import org.jboss.as.server.ServerEnvironmentService;
import org.jboss.as.server.deployment.Phase;
import org.jboss.as.server.suspend.SuspendController;
import org.jboss.as.txn.deployment.TransactionDependenciesProcessor;
import org.jboss.as.txn.deployment.TransactionJndiBindingProcessor;
import org.jboss.as.txn.deployment.TransactionLeakRollbackProcessor;
import org.jboss.as.txn.logging.TransactionLogger;
import org.jboss.as.txn.service.ArjunaObjectStoreEnvironmentService;
import org.jboss.as.txn.service.ArjunaRecoveryManagerService;
import org.jboss.as.txn.service.ArjunaTransactionManagerService;
import org.jboss.as.txn.service.JBossContextXATerminatorService;
import org.jboss.as.txn.service.CoreEnvironmentService;
import org.jboss.as.txn.service.ExtendedJBossXATerminatorService;
import org.jboss.as.txn.service.JTAEnvironmentBeanService;
import org.jboss.as.txn.service.LocalTransactionContextService;
import org.jboss.as.txn.service.RemotingTransactionServiceService;
import org.jboss.as.txn.service.TransactionManagerService;
import org.jboss.as.txn.service.TransactionRemoteHTTPService;
import org.jboss.as.txn.service.TransactionSynchronizationRegistryService;
import org.jboss.as.txn.service.TxnServices;
import org.jboss.as.txn.service.UserTransactionAccessControlService;
import org.jboss.as.txn.service.UserTransactionBindingService;
import org.jboss.as.txn.service.UserTransactionRegistryService;
import org.jboss.as.txn.service.UserTransactionService;
import org.jboss.as.txn.service.XATerminatorService;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.inject.InjectionException;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController.Mode;
import org.jboss.msc.service.ServiceName;
import org.jboss.remoting3.Endpoint;
import org.jboss.tm.ExtendedJBossXATerminator;
import org.jboss.tm.JBossXATerminator;
import org.jboss.tm.XAResourceRecoveryRegistry;
import org.jboss.tm.usertx.UserTransactionRegistry;
import org.omg.CORBA.ORB;
import org.wildfly.common.function.Functions;
import org.wildfly.iiop.openjdk.service.CorbaNamingService;
import com.arjuna.ats.internal.arjuna.utils.UuidProcessId;
import com.arjuna.ats.jta.common.JTAEnvironmentBean;
import com.arjuna.ats.jts.common.jtsPropertyManager;
import org.wildfly.transaction.client.ContextTransactionManager;
import org.wildfly.transaction.client.LocalTransactionContext;
/**
* Adds the transaction management subsystem.
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
* @author Emanuel Muckenhuber
* @author Scott Stark (sstark@redhat.com) (C) 2011 Red Hat Inc.
* @author <a href="mailto:ropalka@redhat.com">Richard Opalka</a>
*/
class TransactionSubsystemAdd extends AbstractBoottimeAddStepHandler {
static final TransactionSubsystemAdd INSTANCE = new TransactionSubsystemAdd();
private static final String UNDERTOW_HTTP_INVOKER_CAPABILITY_NAME = "org.wildfly.undertow.http-invoker";
private static final String REMOTING_ENDPOINT_CAPABILITY_NAME = "org.wildfly.remoting.endpoint";
private TransactionSubsystemAdd() {
}
@Override
protected void populateModel(ModelNode operation, ModelNode model) throws OperationFailedException {
populateModelWithRecoveryEnvConfig(operation, model);
populateModelWithCoreEnvConfig(operation, model);
populateModelWithCoordinatorEnvConfig(operation, model);
populateModelWithObjectStoreConfig(operation, model);
TransactionSubsystemRootResourceDefinition.JTS.validateAndSet(operation, model);
validateStoreConfig(operation, model);
TransactionSubsystemRootResourceDefinition.USE_JOURNAL_STORE.validateAndSet(operation, model);
for (AttributeDefinition ad : TransactionSubsystemRootResourceDefinition.attributes_1_2) {
ad.validateAndSet(operation, model);
}
TransactionSubsystemRootResourceDefinition.JOURNAL_STORE_ENABLE_ASYNC_IO.validateAndSet(operation, model);
TransactionSubsystemRootResourceDefinition.STALE_TRANSACTION_TIME.validateAndSet(operation, model);
}
private void populateModelWithObjectStoreConfig(ModelNode operation, ModelNode objectStoreModel) throws OperationFailedException {
TransactionSubsystemRootResourceDefinition.OBJECT_STORE_RELATIVE_TO.validateAndSet(operation, objectStoreModel);
TransactionSubsystemRootResourceDefinition.OBJECT_STORE_PATH.validateAndSet(operation, objectStoreModel);
ModelNode relativeVal = objectStoreModel.get(TransactionSubsystemRootResourceDefinition.OBJECT_STORE_RELATIVE_TO.getName());
ModelNode pathVal = objectStoreModel.get(TransactionSubsystemRootResourceDefinition.OBJECT_STORE_PATH.getName());
if (!relativeVal.isDefined() &&
(!pathVal.isDefined() || pathVal.asString().equals(TransactionSubsystemRootResourceDefinition.OBJECT_STORE_PATH.getDefaultValue().asString()))) {
relativeVal.set(new ModelNode().set("jboss.server.data.dir"));
TransactionLogger.ROOT_LOGGER.objectStoreRelativeToIsSetToDefault();
}
}
private void populateModelWithCoordinatorEnvConfig(ModelNode operation, ModelNode coordEnvModel) throws OperationFailedException {
TransactionSubsystemRootResourceDefinition.STATISTICS_ENABLED.validateAndSet(operation, coordEnvModel);
TransactionSubsystemRootResourceDefinition.ENABLE_STATISTICS.validateAndSet(operation, coordEnvModel);
TransactionSubsystemRootResourceDefinition.ENABLE_TSM_STATUS.validateAndSet(operation, coordEnvModel);
TransactionSubsystemRootResourceDefinition.DEFAULT_TIMEOUT.validateAndSet(operation, coordEnvModel);
TransactionSubsystemRootResourceDefinition.MAXIMUM_TIMEOUT.validateAndSet(operation, coordEnvModel);
ModelNode mceVal = coordEnvModel.get(TransactionSubsystemRootResourceDefinition.ENABLE_STATISTICS.getName());
if (mceVal.isDefined()) {
ModelNode seVal = coordEnvModel.get(TransactionSubsystemRootResourceDefinition.STATISTICS_ENABLED.getName());
if (seVal.isDefined() && !seVal.equals(mceVal)) {
throw TransactionLogger.ROOT_LOGGER.inconsistentStatisticsSettings(TransactionSubsystemRootResourceDefinition.STATISTICS_ENABLED.getName(),
TransactionSubsystemRootResourceDefinition.ENABLE_STATISTICS.getName());
}
seVal.set(mceVal);
mceVal.set(new ModelNode());
}
}
private void populateModelWithCoreEnvConfig(ModelNode operation, ModelNode model) throws OperationFailedException {
//core environment
TransactionSubsystemRootResourceDefinition.NODE_IDENTIFIER.validateAndSet(operation, model);
// We have some complex logic for the 'process-id' stuff because of the alternatives
if (operation.hasDefined(TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.getName()) && operation.get(TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.getName()).asBoolean()) {
TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.validateAndSet(operation, model);
if (operation.hasDefined(TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING.getName())) {
throw new OperationFailedException(String.format("%s must be undefined if %s is 'true'.",
TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING.getName(), TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.getName()));
} else if (operation.hasDefined(TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_MAX_PORTS.getName())) {
throw new OperationFailedException(String.format("%s must be undefined if %s is 'true'.",
TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_MAX_PORTS.getName(), TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.getName()));
}
//model.get(TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING.getName());
//model.get(TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_MAX_PORTS.getName());
} else if (operation.hasDefined(TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING.getName())) {
TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING.validateAndSet(operation, model);
TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_MAX_PORTS.validateAndSet(operation, model);
} else if (operation.hasDefined(TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_MAX_PORTS.getName())) {
throw new OperationFailedException(String.format("%s must be defined if %s is defined.",
TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING.getName(), TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_MAX_PORTS.getName()));
} else {
// not uuid and also not sockets!
throw new OperationFailedException(String.format("Either %s must be 'true' or %s must be defined.",
TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.getName(), TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING.getName()));
}
}
private void populateModelWithRecoveryEnvConfig(ModelNode operation, ModelNode model) throws OperationFailedException {
//recovery environment
TransactionSubsystemRootResourceDefinition.BINDING.validateAndSet(operation, model);
TransactionSubsystemRootResourceDefinition.STATUS_BINDING.validateAndSet(operation, model);
TransactionSubsystemRootResourceDefinition.RECOVERY_LISTENER.validateAndSet(operation, model);
}
private void validateStoreConfig(ModelNode operation, ModelNode model) throws OperationFailedException {
if (operation.hasDefined(USE_JDBC_STORE) && operation.get(USE_JDBC_STORE).asBoolean()
&& operation.hasDefined(USE_JOURNAL_STORE) && operation.get(USE_JOURNAL_STORE).asBoolean()) {
throw TransactionLogger.ROOT_LOGGER.onlyOneCanBeTrue(USE_JDBC_STORE, USE_JOURNAL_STORE);
}
if (operation.hasDefined(USE_JDBC_STORE) && operation.get(USE_JDBC_STORE).asBoolean()
&& !operation.hasDefined(JDBC_STORE_DATASOURCE)) {
throw TransactionLogger.ROOT_LOGGER.mustBeDefinedIfTrue(JDBC_STORE_DATASOURCE, USE_JDBC_STORE);
}
}
@Override
protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
checkIfNodeIdentifierIsDefault(context, model);
boolean jts = model.hasDefined(JTS) && model.get(JTS).asBoolean();
final Resource subsystemResource = context.readResourceFromRoot(PathAddress.pathAddress(TransactionExtension.SUBSYSTEM_PATH), false);
final List<ServiceName> deps = new LinkedList<>();
for (String name : subsystemResource.getChildrenNames(CM_RESOURCE)) {
deps.add(TxnServices.JBOSS_TXN_CMR.append(name));
}
//recovery environment
performRecoveryEnvBoottime(context, model, jts, deps);
//core environment
performCoreEnvironmentBootTime(context, model);
//coordinator environment
performCoordinatorEnvBoottime(context, model, jts);
//object store
performObjectStoreBoottime(context, model);
//always propagate the transaction context
//TODO: need a better way to do this, but this value gets cached in a static
//so we need to make sure we set it before anything tries to read it
jtsPropertyManager.getJTSEnvironmentBean().setAlwaysPropagateContext(true);
context.addStep(new AbstractDeploymentChainStep() {
protected void execute(final DeploymentProcessorTarget processorTarget) {
processorTarget.addDeploymentProcessor(TransactionExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_TRANSACTION_ROLLBACK_ACTION, new TransactionLeakRollbackProcessor());
processorTarget.addDeploymentProcessor(TransactionExtension.SUBSYSTEM_NAME, Phase.INSTALL, Phase.INSTALL_TRANSACTION_BINDINGS, new TransactionJndiBindingProcessor());
processorTarget.addDeploymentProcessor(TransactionExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_TRANSACTIONS, new TransactionDependenciesProcessor());
}
}, OperationContext.Stage.RUNTIME);
//bind the TransactionManger and the TSR into JNDI
final BinderService tmBinderService = new BinderService("TransactionManager");
final ServiceBuilder<ManagedReferenceFactory> tmBuilder = context.getServiceTarget().addService(ContextNames.JBOSS_CONTEXT_SERVICE_NAME.append("TransactionManager"), tmBinderService);
tmBuilder.addDependency(ContextNames.JBOSS_CONTEXT_SERVICE_NAME, ServiceBasedNamingStore.class, tmBinderService.getNamingStoreInjector());
tmBuilder.addDependency(TransactionManagerService.INTERNAL_SERVICE_NAME, jakarta.transaction.TransactionManager.class, new Injector<jakarta.transaction.TransactionManager>() {
@Override
public void inject(final jakarta.transaction.TransactionManager value) throws InjectionException {
tmBinderService.getManagedObjectInjector().inject(new ValueManagedReferenceFactory(value));
}
@Override
public void uninject() {
tmBinderService.getManagedObjectInjector().uninject();
}
});
tmBuilder.install();
final BinderService tmLegacyBinderService = new BinderService("TransactionManager");
final ServiceBuilder<ManagedReferenceFactory> tmLegacyBuilder = context.getServiceTarget().addService(ContextNames.JAVA_CONTEXT_SERVICE_NAME.append("TransactionManager"), tmLegacyBinderService);
tmLegacyBuilder.addDependency(ContextNames.JAVA_CONTEXT_SERVICE_NAME, ServiceBasedNamingStore.class, tmLegacyBinderService.getNamingStoreInjector());
tmLegacyBuilder.addDependency(TransactionManagerService.INTERNAL_SERVICE_NAME, jakarta.transaction.TransactionManager.class, new Injector<jakarta.transaction.TransactionManager>() {
@Override
public void inject(final jakarta.transaction.TransactionManager value) throws InjectionException {
tmLegacyBinderService.getManagedObjectInjector().inject(new ValueManagedReferenceFactory(value));
}
@Override
public void uninject() {
tmLegacyBinderService.getManagedObjectInjector().uninject();
}
});
tmLegacyBuilder.install();
final BinderService tsrBinderService = new BinderService("TransactionSynchronizationRegistry");
final ServiceBuilder<ManagedReferenceFactory> tsrBuilder = context.getServiceTarget().addService(ContextNames.JBOSS_CONTEXT_SERVICE_NAME.append("TransactionSynchronizationRegistry"), tsrBinderService);
tsrBuilder.addDependency(ContextNames.JBOSS_CONTEXT_SERVICE_NAME, ServiceBasedNamingStore.class, tsrBinderService.getNamingStoreInjector());
tsrBuilder.addDependency(TransactionSynchronizationRegistryService.INTERNAL_SERVICE_NAME, TransactionSynchronizationRegistry.class, new Injector<TransactionSynchronizationRegistry>() {
@Override
public void inject(final TransactionSynchronizationRegistry value) throws InjectionException {
tsrBinderService.getManagedObjectInjector().inject(new ValueManagedReferenceFactory(value));
}
@Override
public void uninject() {
tsrBinderService.getManagedObjectInjector().uninject();
}
});
tsrBuilder.install();
// Install the UserTransactionAccessControlService
final UserTransactionAccessControlService lookupControlService = new UserTransactionAccessControlService();
context.getServiceTarget().addService(UserTransactionAccessControlService.SERVICE_NAME, lookupControlService).install();
// Bind the UserTransaction into JNDI
final UserTransactionBindingService userTransactionBindingService = new UserTransactionBindingService("UserTransaction");
final ServiceBuilder<ManagedReferenceFactory> utBuilder = context.getServiceTarget().addService(ContextNames.JBOSS_CONTEXT_SERVICE_NAME.append("UserTransaction"), userTransactionBindingService);
utBuilder.addDependency(ContextNames.JBOSS_CONTEXT_SERVICE_NAME, ServiceBasedNamingStore.class, userTransactionBindingService.getNamingStoreInjector())
.addDependency(UserTransactionAccessControlService.SERVICE_NAME, UserTransactionAccessControlService.class, userTransactionBindingService.getUserTransactionAccessControlServiceInjector())
.addDependency(UserTransactionService.INTERNAL_SERVICE_NAME, UserTransaction.class,
new ManagedReferenceInjector<UserTransaction>(userTransactionBindingService.getManagedObjectInjector()));
utBuilder.install();
}
private void performObjectStoreBoottime(OperationContext context, ModelNode model) throws OperationFailedException {
boolean useJournalStore = model.hasDefined(USE_JOURNAL_STORE) && model.get(USE_JOURNAL_STORE).asBoolean();
final boolean enableAsyncIO = TransactionSubsystemRootResourceDefinition.JOURNAL_STORE_ENABLE_ASYNC_IO.resolveModelAttribute(context, model).asBoolean();
final String objectStorePathRef = TransactionSubsystemRootResourceDefinition.OBJECT_STORE_RELATIVE_TO.resolveModelAttribute(context, model).isDefined() ?
TransactionSubsystemRootResourceDefinition.OBJECT_STORE_RELATIVE_TO.resolveModelAttribute(context, model).asString(): null;
final String objectStorePath = TransactionSubsystemRootResourceDefinition.OBJECT_STORE_PATH.resolveModelAttribute(context, model).asString();
final boolean useJdbcStore = model.hasDefined(USE_JDBC_STORE) && model.get(USE_JDBC_STORE).asBoolean();
final String dataSourceJndiName = TransactionSubsystemRootResourceDefinition.JDBC_STORE_DATASOURCE.resolveModelAttribute(context, model).asString();
ArjunaObjectStoreEnvironmentService.JdbcStoreConfigBulder confiBuilder = new ArjunaObjectStoreEnvironmentService.JdbcStoreConfigBulder();
confiBuilder.setActionDropTable(TransactionSubsystemRootResourceDefinition.JDBC_ACTION_STORE_DROP_TABLE.resolveModelAttribute(context, model).asBoolean())
.setStateDropTable(TransactionSubsystemRootResourceDefinition.JDBC_STATE_STORE_DROP_TABLE.resolveModelAttribute(context, model).asBoolean())
.setCommunicationDropTable(TransactionSubsystemRootResourceDefinition.JDBC_COMMUNICATION_STORE_DROP_TABLE.resolveModelAttribute(context, model).asBoolean());
if (model.hasDefined(TransactionSubsystemRootResourceDefinition.JDBC_ACTION_STORE_TABLE_PREFIX.getName()))
confiBuilder.setActionTablePrefix(TransactionSubsystemRootResourceDefinition.JDBC_ACTION_STORE_TABLE_PREFIX.resolveModelAttribute(context, model).asString());
if (model.hasDefined(TransactionSubsystemRootResourceDefinition.JDBC_STATE_STORE_TABLE_PREFIX.getName()))
confiBuilder.setStateTablePrefix(TransactionSubsystemRootResourceDefinition.JDBC_STATE_STORE_TABLE_PREFIX.resolveModelAttribute(context, model).asString());
if (model.hasDefined(TransactionSubsystemRootResourceDefinition.JDBC_COMMUNICATION_STORE_TABLE_PREFIX.getName()))
confiBuilder.setCommunicationTablePrefix(TransactionSubsystemRootResourceDefinition.JDBC_COMMUNICATION_STORE_TABLE_PREFIX.resolveModelAttribute(context, model).asString());
TransactionLogger.ROOT_LOGGER.debugf("objectStorePathRef=%s, objectStorePath=%s%n", objectStorePathRef, objectStorePath);
CapabilityServiceTarget target = context.getCapabilityServiceTarget();
// Configure the ObjectStoreEnvironmentBeans
final ArjunaObjectStoreEnvironmentService objStoreEnvironmentService = new ArjunaObjectStoreEnvironmentService(useJournalStore, enableAsyncIO, objectStorePath, objectStorePathRef, useJdbcStore, dataSourceJndiName, confiBuilder.build());
ServiceBuilder<Void> builder = target.addService(TxnServices.JBOSS_TXN_ARJUNA_OBJECTSTORE_ENVIRONMENT, objStoreEnvironmentService);
builder.addDependency(PathManagerService.SERVICE_NAME, PathManager.class, objStoreEnvironmentService.getPathManagerInjector());
builder.requires(TxnServices.JBOSS_TXN_CORE_ENVIRONMENT);
if (useJdbcStore) {
final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(dataSourceJndiName);
builder.requires(bindInfo.getBinderServiceName());
}
builder.setInitialMode(Mode.ACTIVE).install();
TransactionManagerService.addService(target);
UserTransactionService.addService(target);
target.addService(TxnServices.JBOSS_TXN_USER_TRANSACTION_REGISTRY, new UserTransactionRegistryService())
.setInitialMode(Mode.ACTIVE).install();
TransactionSynchronizationRegistryService.addService(target);
}
private void performCoreEnvironmentBootTime(OperationContext context, ModelNode coreEnvModel) throws OperationFailedException {
// Configure the core configuration.
final String nodeIdentifier = TransactionSubsystemRootResourceDefinition.NODE_IDENTIFIER.resolveModelAttribute(context, coreEnvModel).asString();
TransactionLogger.ROOT_LOGGER.debugf("nodeIdentifier=%s%n", nodeIdentifier);
final CapabilityServiceBuilder<?> builder = context.getCapabilityServiceTarget().addCapability(TRANSACTION_CAPABILITY);
Supplier<SocketBinding> socketBindingSupplier = Functions.constantSupplier(null);
String socketBindingName = null;
if (!TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.resolveModelAttribute(context, coreEnvModel).asBoolean(false)) {
socketBindingName = TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING.resolveModelAttribute(context, coreEnvModel).asString();
socketBindingSupplier = builder.requiresCapability(SOCKET_BINDING_CAPABILITY_NAME, SocketBinding.class, socketBindingName);
}
final CoreEnvironmentService coreEnvironmentService = new CoreEnvironmentService(nodeIdentifier, socketBindingSupplier);
if (TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.resolveModelAttribute(context, coreEnvModel).asBoolean(false)) {
// Use the UUID based id
UuidProcessId id = new UuidProcessId();
coreEnvironmentService.setProcessImplementation(id);
} else {
// Use the socket process id
coreEnvironmentService.setProcessImplementationClassName(ProcessIdType.SOCKET.getClazz());
int ports = TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_MAX_PORTS.resolveModelAttribute(context, coreEnvModel).asInt();
coreEnvironmentService.setSocketProcessIdMaxPorts(ports);
}
builder.setInstance(coreEnvironmentService).addAliases(TxnServices.JBOSS_TXN_CORE_ENVIRONMENT).setInitialMode(Mode.ACTIVE).install();
}
private void performRecoveryEnvBoottime(OperationContext context, ModelNode model, final boolean jts, List<ServiceName> deps) throws OperationFailedException {
CapabilityServiceTarget serviceTarget = context.getCapabilityServiceTarget();
//recovery environment
final String recoveryBindingName = TransactionSubsystemRootResourceDefinition.BINDING.resolveModelAttribute(context, model).asString();
final String recoveryStatusBindingName = TransactionSubsystemRootResourceDefinition.STATUS_BINDING.resolveModelAttribute(context, model).asString();
final boolean recoveryListener = TransactionSubsystemRootResourceDefinition.RECOVERY_LISTENER.resolveModelAttribute(context, model).asBoolean();
final CapabilityServiceBuilder<?> recoveryManagerServiceServiceBuilder = serviceTarget.addCapability(XA_RESOURCE_RECOVERY_REGISTRY_CAPABILITY);
final Consumer<RecoveryManagerService> consumer = recoveryManagerServiceServiceBuilder.provides(XA_RESOURCE_RECOVERY_REGISTRY_CAPABILITY);
final Supplier<SocketBinding> recoveryBindingSupplier = recoveryManagerServiceServiceBuilder.requiresCapability("org.wildfly.network.socket-binding", SocketBinding.class, recoveryBindingName);
final Supplier<SocketBinding> statusBindingSupplier = recoveryManagerServiceServiceBuilder.requiresCapability("org.wildfly.network.socket-binding", SocketBinding.class, recoveryStatusBindingName);
final Supplier<SocketBindingManager> bindingManagerSupplier = recoveryManagerServiceServiceBuilder.requiresCapability("org.wildfly.management.socket-binding-manager", SocketBindingManager.class);
final Supplier<SuspendController> suspendControllerSupplier = recoveryManagerServiceServiceBuilder.requiresCapability("org.wildfly.server.suspend-controller", SuspendController.class);
final Supplier<ProcessStateNotifier> processStateSupplier = recoveryManagerServiceServiceBuilder.requiresCapability("org.wildfly.management.process-state-notifier", ProcessStateNotifier.class);
recoveryManagerServiceServiceBuilder.requires(TxnServices.JBOSS_TXN_CORE_ENVIRONMENT);
recoveryManagerServiceServiceBuilder.requires(TxnServices.JBOSS_TXN_ARJUNA_OBJECTSTORE_ENVIRONMENT);
recoveryManagerServiceServiceBuilder.addAliases(TxnServices.JBOSS_TXN_ARJUNA_RECOVERY_MANAGER);
// add dependency on Jakarta Transactions environment bean
for (final ServiceName dep : deps) {
recoveryManagerServiceServiceBuilder.requires(dep);
}
// Register WildFly transaction services - TODO: this should eventually be separated from the Narayana subsystem
final int staleTransactionTime = TransactionSubsystemRootResourceDefinition.STALE_TRANSACTION_TIME.resolveModelAttribute(context, model).asInt();
final LocalTransactionContextService localTransactionContextService = new LocalTransactionContextService(staleTransactionTime);
serviceTarget.addService(TxnServices.JBOSS_TXN_LOCAL_TRANSACTION_CONTEXT, localTransactionContextService)
.addDependency(TxnServices.JBOSS_TXN_EXTENDED_JBOSS_XA_TERMINATOR, ExtendedJBossXATerminator.class, localTransactionContextService.getExtendedJBossXATerminatorInjector())
.addDependency(TxnServices.JBOSS_TXN_ARJUNA_TRANSACTION_MANAGER, com.arjuna.ats.jbossatx.jta.TransactionManagerService.class, localTransactionContextService.getTransactionManagerInjector())
.addDependency(XA_RESOURCE_RECOVERY_REGISTRY_CAPABILITY.getCapabilityServiceName(), XAResourceRecoveryRegistry.class, localTransactionContextService.getXAResourceRecoveryRegistryInjector())
.addDependency(ServerEnvironmentService.SERVICE_NAME, ServerEnvironment.class, localTransactionContextService.getServerEnvironmentInjector())
.setInitialMode(Mode.ACTIVE)
.install();
if (context.hasOptionalCapability(REMOTING_ENDPOINT_CAPABILITY_NAME, TRANSACTION_CAPABILITY.getName(),null)) {
final RemotingTransactionServiceService remoteTransactionServiceService = new RemotingTransactionServiceService();
serviceTarget.addCapability(REMOTE_TRANSACTION_SERVICE_CAPABILITY)
.setInstance(remoteTransactionServiceService)
.addDependency(TxnServices.JBOSS_TXN_LOCAL_TRANSACTION_CONTEXT, LocalTransactionContext.class, remoteTransactionServiceService.getLocalTransactionContextInjector())
.addDependency(context.getCapabilityServiceName(REMOTING_ENDPOINT_CAPABILITY_NAME, Endpoint.class), Endpoint.class, remoteTransactionServiceService.getEndpointInjector())
.setInitialMode(Mode.ACTIVE)
.install();
}
if(context.hasOptionalCapability(UNDERTOW_HTTP_INVOKER_CAPABILITY_NAME, TRANSACTION_CAPABILITY.getName(), null)) {
final TransactionRemoteHTTPService remoteHTTPService = new TransactionRemoteHTTPService();
serviceTarget.addService(TxnServices.JBOSS_TXN_HTTP_REMOTE_TRANSACTION_SERVICE, remoteHTTPService)
.addDependency(TxnServices.JBOSS_TXN_LOCAL_TRANSACTION_CONTEXT, LocalTransactionContext.class, remoteHTTPService.getLocalTransactionContextInjectedValue())
.addDependency(context.getCapabilityServiceName(UNDERTOW_HTTP_INVOKER_CAPABILITY_NAME, PathHandler.class), PathHandler.class, remoteHTTPService.getPathHandlerInjectedValue())
.install();
}
final String nodeIdentifier = TransactionSubsystemRootResourceDefinition.NODE_IDENTIFIER.resolveModelAttribute(context, model).asString();
// install Jakarta Transactions environment bean service
final JTAEnvironmentBeanService jtaEnvironmentBeanService = new JTAEnvironmentBeanService(nodeIdentifier);
serviceTarget.addService(TxnServices.JBOSS_TXN_JTA_ENVIRONMENT, jtaEnvironmentBeanService)
.setInitialMode(Mode.ACTIVE)
.install();
final XATerminatorService xaTerminatorService;
final ExtendedJBossXATerminatorService extendedJBossXATerminatorService;
Supplier<ORB> orbSupplier = null;
if (jts) {
jtaEnvironmentBeanService.getValue()
.setTransactionManagerClassName(com.arjuna.ats.jbossatx.jts.TransactionManagerDelegate.class.getName());
orbSupplier = recoveryManagerServiceServiceBuilder.requires(ServiceName.JBOSS.append("iiop-openjdk", "orb-service"));
com.arjuna.ats.internal.jbossatx.jts.jca.XATerminator terminator = new com.arjuna.ats.internal.jbossatx.jts.jca.XATerminator();
xaTerminatorService = new XATerminatorService(terminator);
extendedJBossXATerminatorService = new ExtendedJBossXATerminatorService(terminator);
} else {
jtaEnvironmentBeanService.getValue()
.setTransactionManagerClassName(com.arjuna.ats.jbossatx.jta.TransactionManagerDelegate.class.getName());
com.arjuna.ats.internal.jbossatx.jta.jca.XATerminator terminator = new com.arjuna.ats.internal.jbossatx.jta.jca.XATerminator();
xaTerminatorService = new XATerminatorService(terminator);
extendedJBossXATerminatorService = new ExtendedJBossXATerminatorService(terminator);
}
serviceTarget.addService(TxnServices.JBOSS_TXN_XA_TERMINATOR, xaTerminatorService)
.setInitialMode(Mode.ACTIVE).install();
serviceTarget
.addService(TxnServices.JBOSS_TXN_EXTENDED_JBOSS_XA_TERMINATOR, extendedJBossXATerminatorService)
.setInitialMode(Mode.ACTIVE).install();
final JBossContextXATerminatorService contextXATerminatorService = new JBossContextXATerminatorService();
serviceTarget
.addService(TxnServices.JBOSS_TXN_CONTEXT_XA_TERMINATOR, contextXATerminatorService)
.addDependency(TxnServices.JBOSS_TXN_XA_TERMINATOR, JBossXATerminator.class, contextXATerminatorService.getJBossXATerminatorInjector())
.addDependency(TxnServices.JBOSS_TXN_LOCAL_TRANSACTION_CONTEXT, LocalTransactionContext.class, contextXATerminatorService.getLocalTransactionContextInjector())
.setInitialMode(Mode.ACTIVE).install();
final ArjunaRecoveryManagerService recoveryManagerService = new ArjunaRecoveryManagerService(consumer, recoveryBindingSupplier, statusBindingSupplier, bindingManagerSupplier, suspendControllerSupplier, processStateSupplier, orbSupplier, recoveryListener, jts);
recoveryManagerServiceServiceBuilder.setInstance(recoveryManagerService);
recoveryManagerServiceServiceBuilder.install();
}
private void performCoordinatorEnvBoottime(OperationContext context, ModelNode coordEnvModel, final boolean jts) throws OperationFailedException {
final boolean coordinatorEnableStatistics = TransactionSubsystemRootResourceDefinition.STATISTICS_ENABLED.resolveModelAttribute(context, coordEnvModel).asBoolean();
final boolean transactionStatusManagerEnable = TransactionSubsystemRootResourceDefinition.ENABLE_TSM_STATUS.resolveModelAttribute(context, coordEnvModel).asBoolean();
final int coordinatorDefaultTimeout = TransactionSubsystemRootResourceDefinition.DEFAULT_TIMEOUT.resolveModelAttribute(context, coordEnvModel).asInt();
final int maximumTimeout = TransactionSubsystemRootResourceDefinition.MAXIMUM_TIMEOUT.resolveModelAttribute(context, coordEnvModel).asInt();
// WFLY-9955 Allow the timeout set to "0" while translating into the maximum timeout
if (coordinatorDefaultTimeout == 0) {
ContextTransactionManager.setGlobalDefaultTransactionTimeout(maximumTimeout);
TransactionLogger.ROOT_LOGGER.timeoutValueIsSetToMaximum(maximumTimeout);
} else {
ContextTransactionManager.setGlobalDefaultTransactionTimeout(coordinatorDefaultTimeout);
}
final ArjunaTransactionManagerService transactionManagerService = new ArjunaTransactionManagerService(coordinatorEnableStatistics, coordinatorDefaultTimeout, transactionStatusManagerEnable, jts);
final ServiceBuilder<com.arjuna.ats.jbossatx.jta.TransactionManagerService> transactionManagerServiceServiceBuilder = context.getServiceTarget().addService(TxnServices.JBOSS_TXN_ARJUNA_TRANSACTION_MANAGER, transactionManagerService);
// add dependency on Jakarta Transactions environment bean service
transactionManagerServiceServiceBuilder.addDependency(TxnServices.JBOSS_TXN_JTA_ENVIRONMENT, JTAEnvironmentBean.class, transactionManagerService.getJTAEnvironmentBeanInjector());
//if jts is enabled we need the ORB
if (jts) {
transactionManagerServiceServiceBuilder.addDependency(ServiceName.JBOSS.append("iiop-openjdk", "orb-service"), ORB.class, transactionManagerService.getOrbInjector());
transactionManagerServiceServiceBuilder.requires(CorbaNamingService.SERVICE_NAME);
}
transactionManagerServiceServiceBuilder.addDependency(TxnServices.JBOSS_TXN_XA_TERMINATOR, JBossXATerminator.class, transactionManagerService.getXaTerminatorInjector());
transactionManagerServiceServiceBuilder.addDependency(TxnServices.JBOSS_TXN_USER_TRANSACTION_REGISTRY, UserTransactionRegistry.class, transactionManagerService.getUserTransactionRegistry());
transactionManagerServiceServiceBuilder.requires(TxnServices.JBOSS_TXN_CORE_ENVIRONMENT);
transactionManagerServiceServiceBuilder.requires(TxnServices.JBOSS_TXN_ARJUNA_OBJECTSTORE_ENVIRONMENT);
transactionManagerServiceServiceBuilder.requires(XA_RESOURCE_RECOVERY_REGISTRY_CAPABILITY.getCapabilityServiceName());
transactionManagerServiceServiceBuilder.setInitialMode(Mode.ACTIVE);
transactionManagerServiceServiceBuilder.install();
}
private void checkIfNodeIdentifierIsDefault(final OperationContext context, final ModelNode model) throws OperationFailedException {
final String nodeIdentifier = TransactionSubsystemRootResourceDefinition.NODE_IDENTIFIER.resolveModelAttribute(context, model).asString();
final String defaultNodeIdentifier = TransactionSubsystemRootResourceDefinition.NODE_IDENTIFIER.getDefaultValue().asString();
if (defaultNodeIdentifier.equals(nodeIdentifier)) {
TransactionLogger.ROOT_LOGGER.nodeIdentifierIsSetToDefault(CommonAttributes.NODE_IDENTIFIER, context.getCurrentAddress().toCLIStyleString());
}
}
}
| 39,259
| 69.358423
| 268
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/TransactionSubsystemRootResourceDefinition.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import jakarta.transaction.TransactionSynchronizationRegistry;
import org.jboss.as.controller.AbstractWriteAttributeHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.ModelVersion;
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.ReloadRequiredWriteAttributeHandler;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleOperationDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.client.helpers.MeasurementUnit;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.validation.IntRangeValidator;
import org.jboss.as.controller.operations.validation.StringBytesLengthValidator;
import org.jboss.as.controller.operations.validation.StringLengthValidator;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ImmutableManagementResourceRegistration;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.OperationEntry;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.txn.logging.TransactionLogger;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.tm.XAResourceRecoveryRegistry;
import org.wildfly.transaction.client.ContextTransactionManager;
import com.arjuna.ats.arjuna.common.CoordinatorEnvironmentBean;
import com.arjuna.ats.arjuna.common.arjPropertyManager;
import com.arjuna.ats.arjuna.coordinator.TxControl;
import org.wildfly.transaction.client.provider.remoting.RemotingTransactionService;
/**
* {@link org.jboss.as.controller.ResourceDefinition} for the root resource of the transaction subsystem.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class TransactionSubsystemRootResourceDefinition extends SimpleResourceDefinition {
static final RuntimeCapability<Void> TRANSACTION_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.transactions", Void.class)
.build();
/** Capability that indicates a local TransactionManager provider is present. */
public static final RuntimeCapability<Void> LOCAL_PROVIDER_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.transactions.global-default-local-provider", Void.class)
.build();
/**
* Provides access to the special TransactionSynchronizationRegistry impl that ensures proper ordering between
* Jakarta Connectors and other synchronizations.
*/
public static final RuntimeCapability<Void> TRANSACTION_SYNCHRONIZATION_REGISTRY_CAPABILITY =
RuntimeCapability.Builder.of("org.wildfly.transactions.transaction-synchronization-registry", TransactionSynchronizationRegistry.class)
.build();
public static final RuntimeCapability<Void> REMOTE_TRANSACTION_SERVICE_CAPABILITY =
RuntimeCapability.Builder.of("org.wildfly.transactions.remote-transaction-service", RemotingTransactionService.class)
.build();
static final RuntimeCapability<Void> XA_RESOURCE_RECOVERY_REGISTRY_CAPABILITY =
RuntimeCapability.Builder.of("org.wildfly.transactions.xa-resource-recovery-registry", XAResourceRecoveryRegistry.class)
.build();
//recovery environment
public static final SimpleAttributeDefinition BINDING = new SimpleAttributeDefinitionBuilder(CommonAttributes.BINDING, ModelType.STRING, false)
.setValidator(new StringLengthValidator(1))
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.setXmlName(Attribute.BINDING.getLocalName())
.setAllowExpression(true)
.addAccessConstraint(SensitiveTargetAccessConstraintDefinition.SOCKET_BINDING_REF)
.build();
public static final SimpleAttributeDefinition STATUS_BINDING = new SimpleAttributeDefinitionBuilder(CommonAttributes.STATUS_BINDING, ModelType.STRING, false)
.setValidator(new StringLengthValidator(1))
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.setXmlName(Attribute.STATUS_BINDING.getLocalName())
.setAllowExpression(true)
.addAccessConstraint(SensitiveTargetAccessConstraintDefinition.SOCKET_BINDING_REF)
.build();
public static final SimpleAttributeDefinition RECOVERY_LISTENER = new SimpleAttributeDefinitionBuilder(CommonAttributes.RECOVERY_LISTENER, ModelType.BOOLEAN, true)
.setDefaultValue(ModelNode.FALSE)
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.setXmlName(Attribute.RECOVERY_LISTENER.getLocalName())
.setAllowExpression(true).build();
//core environment
public static final SimpleAttributeDefinition NODE_IDENTIFIER = new SimpleAttributeDefinitionBuilder(CommonAttributes.NODE_IDENTIFIER, ModelType.STRING, true)
.setDefaultValue(new ModelNode().set("1"))
.setFlags(AttributeAccess.Flag.RESTART_JVM)
.setAllowExpression(true)
.setValidator(new StringBytesLengthValidator(0,23,true,true))
.build();
public static final SimpleAttributeDefinition PROCESS_ID_UUID = new SimpleAttributeDefinitionBuilder("process-id-uuid", ModelType.BOOLEAN, true)
.setDefaultValue(ModelNode.FALSE)
.setAlternatives("process-id-socket-binding")
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.build();
public static final SimpleAttributeDefinition PROCESS_ID_SOCKET_BINDING = new SimpleAttributeDefinitionBuilder("process-id-socket-binding", ModelType.STRING)
.setRequired(true)
.setValidator(new StringLengthValidator(1, true))
.setAlternatives("process-id-uuid")
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.setXmlName(Attribute.BINDING.getLocalName())
.setAllowExpression(true)
.addAccessConstraint(SensitiveTargetAccessConstraintDefinition.SOCKET_BINDING_REF)
.build();
public static final SimpleAttributeDefinition PROCESS_ID_SOCKET_MAX_PORTS = new SimpleAttributeDefinitionBuilder("process-id-socket-max-ports", ModelType.INT, true)
.setValidator(new IntRangeValidator(1, true))
.setDefaultValue(new ModelNode().set(10))
.setRequires("process-id-socket-binding")
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.setXmlName(Attribute.SOCKET_PROCESS_ID_MAX_PORTS.getLocalName())
.setAllowExpression(true)
.addAccessConstraint(SensitiveTargetAccessConstraintDefinition.SOCKET_CONFIG)
.build();
//coordinator environment
public static final SimpleAttributeDefinition STATISTICS_ENABLED = new SimpleAttributeDefinitionBuilder(CommonAttributes.STATISTICS_ENABLED, ModelType.BOOLEAN, true)
.setDefaultValue(ModelNode.FALSE)
.setFlags(AttributeAccess.Flag.RESTART_NONE)
.setAllowExpression(true).build();
public static final SimpleAttributeDefinition ENABLE_STATISTICS = new SimpleAttributeDefinitionBuilder(CommonAttributes.ENABLE_STATISTICS, ModelType.BOOLEAN, true)
.setDefaultValue(ModelNode.FALSE)
.setFlags(AttributeAccess.Flag.RESTART_NONE)
.setXmlName(Attribute.ENABLE_STATISTICS.getLocalName())
.setDeprecated(ModelVersion.create(2))
.setAllowExpression(true).build();
public static final SimpleAttributeDefinition ENABLE_TSM_STATUS = new SimpleAttributeDefinitionBuilder(CommonAttributes.ENABLE_TSM_STATUS, ModelType.BOOLEAN, true)
.setDefaultValue(ModelNode.FALSE)
.setFlags(AttributeAccess.Flag.RESTART_JVM)
.setXmlName(Attribute.ENABLE_TSM_STATUS.getLocalName())
.setAllowExpression(true).build();
public static final SimpleAttributeDefinition DEFAULT_TIMEOUT = new SimpleAttributeDefinitionBuilder(CommonAttributes.DEFAULT_TIMEOUT, ModelType.INT, true)
.setValidator(new IntRangeValidator(0))
.setMeasurementUnit(MeasurementUnit.SECONDS)
.setDefaultValue(new ModelNode().set(300))
.setFlags(AttributeAccess.Flag.RESTART_NONE)
.setXmlName(Attribute.DEFAULT_TIMEOUT.getLocalName())
.setAllowExpression(true).build();
public static final SimpleAttributeDefinition MAXIMUM_TIMEOUT = new SimpleAttributeDefinitionBuilder(CommonAttributes.MAXIMUM_TIMEOUT, ModelType.INT, true)
.setValidator(new IntRangeValidator(300))
.setMeasurementUnit(MeasurementUnit.SECONDS)
.setDefaultValue(new ModelNode().set(31536000))
.setFlags(AttributeAccess.Flag.RESTART_NONE)
.setAllowExpression(true).build();
//object store
public static final SimpleAttributeDefinition OBJECT_STORE_RELATIVE_TO = new SimpleAttributeDefinitionBuilder(CommonAttributes.OBJECT_STORE_RELATIVE_TO, ModelType.STRING, true)
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.setXmlName(Attribute.RELATIVE_TO.getLocalName())
.setAllowExpression(true).build();
public static final SimpleAttributeDefinition OBJECT_STORE_PATH = new SimpleAttributeDefinitionBuilder(CommonAttributes.OBJECT_STORE_PATH, ModelType.STRING, true)
.setDefaultValue(new ModelNode().set("tx-object-store"))
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.setXmlName(Attribute.PATH.getLocalName())
.setAllowExpression(true).build();
public static final SimpleAttributeDefinition JTS = new SimpleAttributeDefinitionBuilder(CommonAttributes.JTS, ModelType.BOOLEAN, true)
.setDefaultValue(ModelNode.FALSE)
.setFlags(AttributeAccess.Flag.RESTART_JVM) //I think the use of statics in arjunta will require a JVM restart
.setAllowExpression(false).build();
public static final SimpleAttributeDefinition USE_HORNETQ_STORE = new SimpleAttributeDefinitionBuilder(CommonAttributes.USE_HORNETQ_STORE, ModelType.BOOLEAN, true)
.setDefaultValue(ModelNode.FALSE)
.addAlternatives(CommonAttributes.USE_JDBC_STORE)
.setFlags(AttributeAccess.Flag.RESTART_JVM)
.setAllowExpression(false)
.setDeprecated(ModelVersion.create(3)).build();
// Use a separate AD for the :add op to advertise that use-hornetq-store and use-journal-store together is not optimal
static final SimpleAttributeDefinition USE_HORNETQ_STORE_PARAM = new SimpleAttributeDefinitionBuilder(USE_HORNETQ_STORE)
.addAlternatives(CommonAttributes.USE_JOURNAL_STORE).build();
public static final SimpleAttributeDefinition HORNETQ_STORE_ENABLE_ASYNC_IO = new SimpleAttributeDefinitionBuilder(CommonAttributes.HORNETQ_STORE_ENABLE_ASYNC_IO, ModelType.BOOLEAN, true)
.setDefaultValue(ModelNode.FALSE)
.setFlags(AttributeAccess.Flag.RESTART_JVM)
.setXmlName(Attribute.ENABLE_ASYNC_IO.getLocalName())
.setAllowExpression(true)
.setRequires(CommonAttributes.USE_HORNETQ_STORE)
.setDeprecated(ModelVersion.create(3)).build();
public static final SimpleAttributeDefinition USE_JOURNAL_STORE = new SimpleAttributeDefinitionBuilder(CommonAttributes.USE_JOURNAL_STORE, ModelType.BOOLEAN, true)
.setDefaultValue(ModelNode.FALSE)
.addAlternatives(CommonAttributes.USE_JDBC_STORE)
.setFlags(AttributeAccess.Flag.RESTART_JVM)
.setAllowExpression(false).build();
// Use a separate AD for the :add op to advertise that use-hornetq-store and use-journal-store together is not optimal
static final SimpleAttributeDefinition USE_JOURNAL_STORE_PARAM = new SimpleAttributeDefinitionBuilder(USE_JOURNAL_STORE)
.addAlternatives(CommonAttributes.USE_HORNETQ_STORE).build();
public static final SimpleAttributeDefinition JOURNAL_STORE_ENABLE_ASYNC_IO = new SimpleAttributeDefinitionBuilder(CommonAttributes.JOURNAL_STORE_ENABLE_ASYNC_IO, ModelType.BOOLEAN, true)
.setDefaultValue(ModelNode.FALSE)
.setFlags(AttributeAccess.Flag.RESTART_JVM)
.setXmlName(Attribute.ENABLE_ASYNC_IO.getLocalName())
.setAllowExpression(true)
.setRequires(CommonAttributes.USE_JOURNAL_STORE).build();
public static final SimpleAttributeDefinition USE_JDBC_STORE = new SimpleAttributeDefinitionBuilder(CommonAttributes.USE_JDBC_STORE, ModelType.BOOLEAN, true)
.setDefaultValue(ModelNode.FALSE)
.addAlternatives(CommonAttributes.USE_JOURNAL_STORE)
.addAlternatives(CommonAttributes.USE_HORNETQ_STORE)
.setRequires(CommonAttributes.JDBC_STORE_DATASOURCE)
.setFlags(AttributeAccess.Flag.RESTART_JVM)
.setAllowExpression(false).build();
public static final SimpleAttributeDefinition JDBC_STORE_DATASOURCE = new SimpleAttributeDefinitionBuilder(CommonAttributes.JDBC_STORE_DATASOURCE, ModelType.STRING, true)
.setFlags(AttributeAccess.Flag.RESTART_JVM)
.setXmlName(Attribute.DATASOURCE_JNDI_NAME.getLocalName())
.setAllowExpression(true).build();
public static final SimpleAttributeDefinition JDBC_ACTION_STORE_TABLE_PREFIX =
new SimpleAttributeDefinitionBuilder(CommonAttributes.JDBC_ACTION_STORE_TABLE_PREFIX, ModelType.STRING, true)
.setFlags(AttributeAccess.Flag.RESTART_JVM)
.setXmlName(Attribute.TABLE_PREFIX.getLocalName())
.setAllowExpression(true)
.setRequires(CommonAttributes.USE_JDBC_STORE).build();
public static final SimpleAttributeDefinition JDBC_ACTION_STORE_DROP_TABLE = new SimpleAttributeDefinitionBuilder(CommonAttributes.JDBC_ACTION_STORE_DROP_TABLE, ModelType.BOOLEAN, true)
.setDefaultValue(ModelNode.FALSE)
.setFlags(AttributeAccess.Flag.RESTART_JVM)
.setXmlName(Attribute.DROP_TABLE.getLocalName())
.setAllowExpression(true)
.setRequires(CommonAttributes.USE_JDBC_STORE).build();
public static final SimpleAttributeDefinition JDBC_COMMUNICATION_STORE_TABLE_PREFIX = new SimpleAttributeDefinitionBuilder(CommonAttributes.JDBC_COMMUNICATION_STORE_TABLE_PREFIX, ModelType.STRING, true)
.setFlags(AttributeAccess.Flag.RESTART_JVM)
.setXmlName(Attribute.TABLE_PREFIX.getLocalName())
.setAllowExpression(true)
.setRequires(CommonAttributes.USE_JDBC_STORE).build();
public static final SimpleAttributeDefinition JDBC_COMMUNICATION_STORE_DROP_TABLE = new SimpleAttributeDefinitionBuilder(CommonAttributes.JDBC_COMMUNICATION_STORE_DROP_TABLE, ModelType.BOOLEAN, true)
.setDefaultValue(ModelNode.FALSE)
.setFlags(AttributeAccess.Flag.RESTART_JVM)
.setXmlName(Attribute.DROP_TABLE.getLocalName())
.setAllowExpression(true)
.setRequires(CommonAttributes.USE_JDBC_STORE).build();
public static final SimpleAttributeDefinition JDBC_STATE_STORE_TABLE_PREFIX = new SimpleAttributeDefinitionBuilder(CommonAttributes.JDBC_STATE_STORE_TABLE_PREFIX, ModelType.STRING, true)
.setFlags(AttributeAccess.Flag.RESTART_JVM)
.setXmlName(Attribute.TABLE_PREFIX.getLocalName())
.setAllowExpression(true)
.setRequires(CommonAttributes.USE_JDBC_STORE).build();
public static final SimpleAttributeDefinition JDBC_STATE_STORE_DROP_TABLE = new SimpleAttributeDefinitionBuilder(CommonAttributes.JDBC_STATE_STORE_DROP_TABLE, ModelType.BOOLEAN, true)
.setDefaultValue(ModelNode.FALSE)
.setFlags(AttributeAccess.Flag.RESTART_JVM)
.setXmlName(Attribute.DROP_TABLE.getLocalName())
.setAllowExpression(true)
.setRequires(CommonAttributes.USE_JDBC_STORE).build();
public static final SimpleAttributeDefinition STALE_TRANSACTION_TIME = new SimpleAttributeDefinitionBuilder(CommonAttributes.STALE_TRANSACTION_TIME, ModelType.INT, true)
.setValidator(new IntRangeValidator(0))
.setMeasurementUnit(MeasurementUnit.SECONDS)
.setDefaultValue(new ModelNode().set(600))
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.setAllowExpression(true).build();
private final boolean registerRuntimeOnly;
TransactionSubsystemRootResourceDefinition(boolean registerRuntimeOnly) {
super(new Parameters(TransactionExtension.SUBSYSTEM_PATH,
TransactionExtension.getResourceDescriptionResolver())
.setAddHandler(TransactionSubsystemAdd.INSTANCE)
.setRemoveHandler(TransactionSubsystemRemove.INSTANCE)
.setCapabilities(TRANSACTION_CAPABILITY, LOCAL_PROVIDER_CAPABILITY,
TRANSACTION_SYNCHRONIZATION_REGISTRY_CAPABILITY,
XA_RESOURCE_RECOVERY_REGISTRY_CAPABILITY)
// Configuring these is not required as these are defaulted based on our add/remove handler types
//OperationEntry.Flag.RESTART_ALL_SERVICES, OperationEntry.Flag.RESTART_ALL_SERVICES
);
this.registerRuntimeOnly = registerRuntimeOnly;
}
// all attributes
static final AttributeDefinition[] add_attributes = new AttributeDefinition[] {
BINDING, STATUS_BINDING, RECOVERY_LISTENER, NODE_IDENTIFIER, PROCESS_ID_UUID, PROCESS_ID_SOCKET_BINDING,
PROCESS_ID_SOCKET_MAX_PORTS, STATISTICS_ENABLED, ENABLE_TSM_STATUS, DEFAULT_TIMEOUT, MAXIMUM_TIMEOUT,
OBJECT_STORE_RELATIVE_TO, OBJECT_STORE_PATH, JTS, USE_HORNETQ_STORE_PARAM, USE_JOURNAL_STORE_PARAM, USE_JDBC_STORE, JDBC_STORE_DATASOURCE,
JDBC_ACTION_STORE_DROP_TABLE, JDBC_ACTION_STORE_TABLE_PREFIX, JDBC_COMMUNICATION_STORE_DROP_TABLE,
JDBC_COMMUNICATION_STORE_TABLE_PREFIX, JDBC_STATE_STORE_DROP_TABLE, JDBC_STATE_STORE_TABLE_PREFIX,
JOURNAL_STORE_ENABLE_ASYNC_IO, ENABLE_STATISTICS, HORNETQ_STORE_ENABLE_ASYNC_IO, STALE_TRANSACTION_TIME
};
static final AttributeDefinition[] attributes_1_2 = new AttributeDefinition[] {USE_JDBC_STORE, JDBC_STORE_DATASOURCE,
JDBC_ACTION_STORE_DROP_TABLE, JDBC_ACTION_STORE_TABLE_PREFIX,
JDBC_COMMUNICATION_STORE_DROP_TABLE, JDBC_COMMUNICATION_STORE_TABLE_PREFIX,
JDBC_STATE_STORE_DROP_TABLE, JDBC_STATE_STORE_TABLE_PREFIX
};
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
// Register all attributes except of the mutual ones
Set<AttributeDefinition> attributesWithoutMutuals = new HashSet<>(Arrays.asList(add_attributes));
attributesWithoutMutuals.remove(USE_HORNETQ_STORE_PARAM);
attributesWithoutMutuals.remove(USE_JOURNAL_STORE_PARAM);
attributesWithoutMutuals.remove(USE_JDBC_STORE);
attributesWithoutMutuals.remove(STATISTICS_ENABLED);
attributesWithoutMutuals.remove(DEFAULT_TIMEOUT);
attributesWithoutMutuals.remove(MAXIMUM_TIMEOUT);
attributesWithoutMutuals.remove(JDBC_STORE_DATASOURCE); // Remove these as it also needs special write handler
attributesWithoutMutuals.remove(PROCESS_ID_UUID);
attributesWithoutMutuals.remove(PROCESS_ID_SOCKET_BINDING);
attributesWithoutMutuals.remove(PROCESS_ID_SOCKET_MAX_PORTS);
attributesWithoutMutuals.remove(ENABLE_STATISTICS);
attributesWithoutMutuals.remove(HORNETQ_STORE_ENABLE_ASYNC_IO);
OperationStepHandler writeHandler = new ReloadRequiredWriteAttributeHandler(attributesWithoutMutuals);
for(final AttributeDefinition def : attributesWithoutMutuals) {
resourceRegistration.registerReadWriteAttribute(def, null, writeHandler);
}
// Register mutual object store attributes
OperationStepHandler mutualWriteHandler = new ObjectStoreMutualWriteHandler(USE_JOURNAL_STORE, USE_JDBC_STORE);
resourceRegistration.registerReadWriteAttribute(USE_JOURNAL_STORE, null, mutualWriteHandler);
resourceRegistration.registerReadWriteAttribute(USE_JDBC_STORE, null, mutualWriteHandler);
//Register default-timeout attribute
resourceRegistration.registerReadWriteAttribute(DEFAULT_TIMEOUT, null, new DefaultTimeoutHandler(DEFAULT_TIMEOUT));
resourceRegistration.registerReadWriteAttribute(MAXIMUM_TIMEOUT, null, new MaximumTimeoutHandler(MAXIMUM_TIMEOUT));
// Register jdbc-store-datasource attribute
resourceRegistration.registerReadWriteAttribute(JDBC_STORE_DATASOURCE, null, new JdbcStoreDatasourceWriteHandler(JDBC_STORE_DATASOURCE));
// Register mutual object store attributes
OperationStepHandler mutualProcessIdWriteHandler = new ProcessIdWriteHandler(PROCESS_ID_UUID, PROCESS_ID_SOCKET_BINDING, PROCESS_ID_SOCKET_MAX_PORTS);
resourceRegistration.registerReadWriteAttribute(PROCESS_ID_UUID, null, mutualProcessIdWriteHandler);
resourceRegistration.registerReadWriteAttribute(PROCESS_ID_SOCKET_BINDING, null, mutualProcessIdWriteHandler);
resourceRegistration.registerReadWriteAttribute(PROCESS_ID_SOCKET_MAX_PORTS, null, mutualProcessIdWriteHandler);
//Register statistics-enabled attribute
resourceRegistration.registerReadWriteAttribute(STATISTICS_ENABLED, null, new StatisticsEnabledHandler(STATISTICS_ENABLED));
AliasedHandler esh = new AliasedHandler(STATISTICS_ENABLED.getName());
resourceRegistration.registerReadWriteAttribute(ENABLE_STATISTICS, esh, esh);
AliasedHandler hsh = new AliasedHandler(USE_JOURNAL_STORE.getName());
resourceRegistration.registerReadWriteAttribute(USE_HORNETQ_STORE, hsh, hsh);
AliasedHandler hseh = new AliasedHandler(JOURNAL_STORE_ENABLE_ASYNC_IO.getName());
resourceRegistration.registerReadWriteAttribute(HORNETQ_STORE_ENABLE_ASYNC_IO, hseh, hseh);
if (registerRuntimeOnly) {
TxStatsHandler.INSTANCE.registerMetrics(resourceRegistration);
}
}
@SuppressWarnings("deprecation")
@Override
protected void registerAddOperation(ManagementResourceRegistration registration, OperationStepHandler handler, OperationEntry.Flag... flags) {
// Sort the add params alphabetically to match what DefaultResourceAddDescriptionProvider does
SortedSet<AttributeDefinition> sorted = new TreeSet<>(Comparator.comparing(AttributeDefinition::getName));
for (AttributeDefinition ad : add_attributes) {
if (!ad.getFlags().contains(AttributeAccess.Flag.STORAGE_RUNTIME)) {
sorted.add(ad);
}
}
registration.registerOperationHandler(new SimpleOperationDefinitionBuilder(ModelDescriptionConstants.ADD, getResourceDescriptionResolver())
.withFlags(flags)
.setParameters(sorted.toArray(new AttributeDefinition[add_attributes.length]))
.setEntryType(OperationEntry.EntryType.PUBLIC)
.build()
, handler);
}
private static class AliasedHandler implements OperationStepHandler {
private final String aliasedName;
public AliasedHandler(String aliasedName) {
this.aliasedName = aliasedName;
}
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
ModelNode aliased = getAliasedOperation(operation);
context.addStep(aliased, getHandlerForOperation(context, operation), OperationContext.Stage.MODEL, true);
}
private ModelNode getAliasedOperation(ModelNode operation) {
ModelNode aliased = operation.clone();
aliased.get(ModelDescriptionConstants.NAME).set(aliasedName);
return aliased;
}
private static OperationStepHandler getHandlerForOperation(OperationContext context, ModelNode operation) {
ImmutableManagementResourceRegistration imrr = context.getResourceRegistration();
return imrr.getOperationHandler(PathAddress.EMPTY_ADDRESS, operation.get(OP).asString());
}
}
private static class ObjectStoreMutualWriteHandler extends ReloadRequiredWriteAttributeHandler {
public ObjectStoreMutualWriteHandler(final AttributeDefinition... definitions) {
super(definitions);
}
@Override
protected void finishModelStage(final OperationContext context, final ModelNode operation, String attributeName,
ModelNode newValue, ModelNode oldValue, final Resource model) throws OperationFailedException {
super.finishModelStage(context, operation, attributeName, newValue, oldValue, model);
assert !USE_JOURNAL_STORE.isAllowExpression() && !USE_JDBC_STORE.isAllowExpression() : "rework this before enabling expression";
if (attributeName.equals(USE_JOURNAL_STORE.getName()) || attributeName.equals(USE_JDBC_STORE.getName())) {
if (newValue.isDefined() && newValue.asBoolean()) {
// check the value of the mutual attribute and disable it if it is set to true
final String mutualAttributeName = attributeName.equals(USE_JDBC_STORE.getName())
? USE_JOURNAL_STORE.getName()
: USE_JDBC_STORE.getName();
ModelNode resourceModel = model.getModel();
if (resourceModel.hasDefined(mutualAttributeName) && resourceModel.get(mutualAttributeName).asBoolean()) {
resourceModel.get(mutualAttributeName).set(ModelNode.FALSE);
}
}
}
context.addStep(JdbcStoreValidationStep.INSTANCE, OperationContext.Stage.MODEL);
}
}
private static class JdbcStoreDatasourceWriteHandler extends ReloadRequiredWriteAttributeHandler {
public JdbcStoreDatasourceWriteHandler(AttributeDefinition... definitions) {
super(definitions);
}
@Override
protected void validateUpdatedModel(OperationContext context, Resource model) throws OperationFailedException {
super.validateUpdatedModel(context, model);
context.addStep(JdbcStoreValidationStep.INSTANCE, OperationContext.Stage.MODEL);
}
}
/**
* Validates that if use-jdbc-store is set, jdbc-store-datasource must be also set.
*
* Must be added to both use-jdbc-store and jdbc-store-datasource fields.
*/
private static class JdbcStoreValidationStep implements OperationStepHandler {
private static final JdbcStoreValidationStep INSTANCE = new JdbcStoreValidationStep();
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
ModelNode modelNode = context.readResource(PathAddress.EMPTY_ADDRESS).getModel();
if (modelNode.hasDefined(USE_JDBC_STORE.getName()) && modelNode.get(USE_JDBC_STORE.getName()).asBoolean()
&& !modelNode.hasDefined(JDBC_STORE_DATASOURCE.getName())) {
throw TransactionLogger.ROOT_LOGGER.mustBeDefinedIfTrue(JDBC_STORE_DATASOURCE.getName(), USE_JDBC_STORE.getName());
}
}
}
private static class ProcessIdWriteHandler extends ReloadRequiredWriteAttributeHandler {
public ProcessIdWriteHandler(final AttributeDefinition... definitions) {
super(definitions);
}
@Override
protected void validateUpdatedModel(final OperationContext context, final Resource model) {
context.addStep(new OperationStepHandler() {
@Override
public void execute(OperationContext operationContext, ModelNode operation) throws OperationFailedException {
ModelNode node = context.readResource(PathAddress.EMPTY_ADDRESS).getModel();
if (node.hasDefined(TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.getName())
&& node.get(TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.getName()).asBoolean()) {
if (node.hasDefined(TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING.getName())) {
throw TransactionLogger.ROOT_LOGGER.mustBeUndefinedIfTrue(TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING.getName(), TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.getName());
} else if (node.hasDefined(TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_MAX_PORTS.getName())) {
throw TransactionLogger.ROOT_LOGGER.mustBeUndefinedIfTrue(TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_MAX_PORTS.getName(), TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.getName());
}
} else if (node.hasDefined(TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING.getName())) {
//it's fine do nothing
} else if (node.hasDefined(TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_MAX_PORTS.getName())) {
throw TransactionLogger.ROOT_LOGGER.mustBedefinedIfDefined(TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING.getName(), TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_MAX_PORTS.getName());
} else {
// not uuid and also not sockets!
throw TransactionLogger.ROOT_LOGGER.eitherTrueOrDefined(TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.getName(), TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING.getName());
}
}
}, OperationContext.Stage.MODEL);
}
@Override
protected void finishModelStage(final OperationContext context, final ModelNode operation, String attributeName,
ModelNode newValue, ModelNode oldValue, final Resource model) {
if (attributeName.equals(PROCESS_ID_SOCKET_BINDING.getName())
&& newValue.isDefined()) {
ModelNode resourceModel = model.getModel();
if (resourceModel.hasDefined(PROCESS_ID_UUID.getName())
&& resourceModel.get(PROCESS_ID_UUID.getName()).asBoolean()) {
resourceModel.get(PROCESS_ID_UUID.getName()).set(ModelNode.FALSE);
}
}
if (attributeName.equals(PROCESS_ID_UUID.getName())
&& newValue.asBoolean(false)) {
ModelNode resourceModel = model.getModel();
resourceModel.get(PROCESS_ID_SOCKET_BINDING.getName()).clear();
resourceModel.get(PROCESS_ID_SOCKET_MAX_PORTS.getName()).clear();
}
validateUpdatedModel(context, model);
}
}
@Override
public void registerChildren(ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerSubModel(new CMResourceResourceDefinition());
}
private static class DefaultTimeoutHandler extends AbstractWriteAttributeHandler<Void> {
public DefaultTimeoutHandler(final AttributeDefinition... definitions) {
super(definitions);
}
@Override
protected boolean applyUpdateToRuntime(final OperationContext context, final ModelNode operation,
final String attributeName, final ModelNode resolvedValue,
final ModelNode currentValue, final HandbackHolder<Void> handbackHolder)
throws OperationFailedException {
int timeout = resolvedValue.asInt();
// TxControl allow timeout to be set to 0 with meaning of no timeout at all
arjPropertyManager.getCoordinatorEnvironmentBean().setDefaultTimeout(timeout);
TxControl.setDefaultTimeout(timeout);
if (timeout == 0) {
ModelNode model = context.readResource(PathAddress.EMPTY_ADDRESS).getModel();
timeout = MAXIMUM_TIMEOUT.resolveModelAttribute(context, model).asInt();
TransactionLogger.ROOT_LOGGER.timeoutValueIsSetToMaximum(timeout);
}
ContextTransactionManager.setGlobalDefaultTransactionTimeout(timeout);
return false;
}
@Override
protected void revertUpdateToRuntime(final OperationContext context, final ModelNode operation,
final String attributeName, final ModelNode valueToRestore,
final ModelNode valueToRevert, final Void handback)
throws OperationFailedException {
arjPropertyManager.getCoordinatorEnvironmentBean().setDefaultTimeout(valueToRestore.asInt());
TxControl.setDefaultTimeout(valueToRestore.asInt());
ContextTransactionManager.setGlobalDefaultTransactionTimeout(valueToRestore.asInt());
}
}
private static class MaximumTimeoutHandler extends AbstractWriteAttributeHandler<Void> {
public MaximumTimeoutHandler(final AttributeDefinition... definitions) {
super(definitions);
}
@Override
protected boolean applyUpdateToRuntime(final OperationContext context, final ModelNode operation,
final String attributeName, final ModelNode resolvedValue,
final ModelNode currentValue, final HandbackHolder<Void> handbackHolder)
throws OperationFailedException {
int maximum_timeout = resolvedValue.asInt();
if (TxControl.getDefaultTimeout() == 0) {
TransactionLogger.ROOT_LOGGER.timeoutValueIsSetToMaximum(maximum_timeout);
ContextTransactionManager.setGlobalDefaultTransactionTimeout(maximum_timeout);
}
return false;
}
@Override
protected void revertUpdateToRuntime(OperationContext operationContext, ModelNode modelNode, String s, ModelNode modelNode1, ModelNode modelNode2, Void aVoid) throws OperationFailedException {
}
}
private static class StatisticsEnabledHandler extends AbstractWriteAttributeHandler<Void> {
private volatile CoordinatorEnvironmentBean coordinatorEnvironmentBean;
public StatisticsEnabledHandler(final AttributeDefinition... definitions) {
super(definitions);
}
@Override
protected boolean applyUpdateToRuntime(final OperationContext context, final ModelNode operation,
final String attributeName, final ModelNode resolvedValue,
final ModelNode currentValue, final HandbackHolder<Void> handbackHolder)
throws OperationFailedException {
if (this.coordinatorEnvironmentBean == null) {
this.coordinatorEnvironmentBean = arjPropertyManager.getCoordinatorEnvironmentBean();
}
coordinatorEnvironmentBean.setEnableStatistics(resolvedValue.asBoolean());
return false;
}
@Override
protected void revertUpdateToRuntime(final OperationContext context, final ModelNode operation,
final String attributeName, final ModelNode valueToRestore,
final ModelNode valueToRevert, final Void handback)
throws OperationFailedException {
if (this.coordinatorEnvironmentBean == null) {
this.coordinatorEnvironmentBean = arjPropertyManager.getCoordinatorEnvironmentBean();
}
coordinatorEnvironmentBean.setEnableStatistics(valueToRestore.asBoolean());
}
}
}
| 37,895
| 57.211982
| 245
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/LogStoreParticipantRefreshHandler.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.txn.subsystem;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
import javax.management.AttributeList;
import javax.management.MBeanServer;
import javax.management.ObjectName;
public class LogStoreParticipantRefreshHandler implements OperationStepHandler {
static final LogStoreParticipantRefreshHandler INSTANCE = new LogStoreParticipantRefreshHandler();
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
MBeanServer mbs = TransactionExtension.getMBeanServer(context);
final Resource resource = context.readResource(PathAddress.EMPTY_ADDRESS);
try {
final ObjectName on = LogStoreResource.getObjectName(resource);
final ModelNode model = resource.getModel().clone();
AttributeList attributes = mbs.getAttributes(on, LogStoreConstants.PARTICIPANT_JMX_NAMES);
for (javax.management.Attribute attribute : attributes.asList()) {
String modelName = LogStoreConstants.jmxNameToModelName(LogStoreConstants.MODEL_TO_JMX_PARTICIPANT_NAMES, attribute.getName());
if (modelName != null) {
ModelNode aNode = model.get(modelName);
Object value = attribute.getValue();
if (aNode != null)
aNode.set(value == null ? "" : value.toString());
}
}
// Replace the model
resource.writeModel(model);
} catch (Exception e) {
throw new OperationFailedException("JMX error: " + e.getMessage());
}
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
}
| 2,985
| 41.657143
| 143
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/LogStoreTransactionDeleteHandler.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.txn.subsystem;
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.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
/**
* Operation handler for removing transaction logs from the TM and from the subsystem model
*/
public class LogStoreTransactionDeleteHandler implements OperationStepHandler {
// Generic failure reason if we cannot determine a more specific cause
static final String LOG_DELETE_FAILURE_MESSAGE = "Unable to remove transaction log";
private LogStoreResource logStoreResource = null;
LogStoreTransactionDeleteHandler(LogStoreResource resource) {
this.logStoreResource = resource;
}
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
MBeanServer mbs = TransactionExtension.getMBeanServer(context);
final Resource resource = context.readResourceForUpdate(PathAddress.EMPTY_ADDRESS);
try {
final ObjectName on = LogStoreResource.getObjectName(resource);
// Invoke operation
Object res = mbs.invoke(on, "remove", null, null);
try {
// validate that the MBean was removed:
mbs.getObjectInstance(on);
String reason = res != null ? res.toString() : LOG_DELETE_FAILURE_MESSAGE;
throw new OperationFailedException(reason);
} catch (InstanceNotFoundException e) {
// success, the MBean was deleted
final PathAddress address = PathAddress.pathAddress(operation.require(ModelDescriptionConstants.OP_ADDR));
final PathElement element = address.getLastElement();
logStoreResource.removeChild(element);
}
} catch (OperationFailedException e) {
throw e;
} catch (Exception e) {
throw new OperationFailedException(e.getMessage());
}
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
}
| 3,465
| 39.776471
| 122
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/TransactionSubsystem12Parser.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.txn.subsystem;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.parsing.ParseUtils.duplicateNamedElement;
import static org.jboss.as.controller.parsing.ParseUtils.missingOneOf;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequired;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequiredElement;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoContent;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoNamespaceAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.txn.logging.TransactionLogger;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
*/
class TransactionSubsystem12Parser implements XMLStreamConstants, XMLElementReader<List<ModelNode>> {
TransactionSubsystem12Parser() {
}
/**
* {@inheritDoc}
*/
@Override
public void readElement(XMLExtendedStreamReader reader, List<ModelNode> list) throws XMLStreamException {
// no attributes
if (reader.getAttributeCount() > 0) {
throw unexpectedAttribute(reader, 0);
}
final ModelNode address = new ModelNode();
address.add(ModelDescriptionConstants.SUBSYSTEM, TransactionExtension.SUBSYSTEM_NAME);
address.protect();
final ModelNode subsystem = new ModelNode();
subsystem.get(OP).set(ADD);
subsystem.get(OP_ADDR).set(address);
list.add(subsystem);
final ModelNode logStoreAddress = address.clone();
final ModelNode logStoreOperation = new ModelNode();
logStoreOperation.get(OP).set(ADD);
logStoreAddress.add(LogStoreConstants.LOG_STORE, LogStoreConstants.LOG_STORE);
logStoreAddress.protect();
logStoreOperation.get(OP_ADDR).set(logStoreAddress);
list.add(logStoreOperation);
// elements
final EnumSet<Element> required = EnumSet.of(Element.RECOVERY_ENVIRONMENT, Element.CORE_ENVIRONMENT);
final EnumSet<Element> encountered = EnumSet.noneOf(Element.class);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
switch (Namespace.forUri(reader.getNamespaceURI())) {
case TRANSACTIONS_1_2: {
final Element element = Element.forName(reader.getLocalName());
required.remove(element);
if (!encountered.add(element)) {
throw unexpectedElement(reader);
}
switch (element) {
case RECOVERY_ENVIRONMENT: {
parseRecoveryEnvironmentElement(reader, subsystem);
break;
}
case CORE_ENVIRONMENT: {
parseCoreEnvironmentElement(reader, subsystem);
break;
}
case COORDINATOR_ENVIRONMENT: {
parseCoordinatorEnvironmentElement(reader, subsystem);
break;
}
case OBJECT_STORE: {
parseObjectStoreEnvironmentElementAndEnrichOperation(reader, subsystem);
break;
}
case JTS: {
parseJts(reader, subsystem);
break;
}
case USE_HORNETQ_STORE: {
parseUseJournalstore(reader, logStoreOperation);
subsystem.get(CommonAttributes.USE_JOURNAL_STORE).set(true);
break;
}
default: {
throw unexpectedElement(reader);
}
}
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
if (!required.isEmpty()) {
throw missingRequiredElement(reader, required);
}
}
private void parseJts(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
// no attributes
if (reader.getAttributeCount() > 0) {
throw unexpectedAttribute(reader, 0);
}
operation.get(CommonAttributes.JTS).set(true);
requireNoContent(reader);
}
private void parseUseJournalstore(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
operation.get(LogStoreConstants.LOG_STORE_TYPE.getName()).set("journal");
requireNoContent(reader);
}
static void parseObjectStoreEnvironmentElementAndEnrichOperation(final XMLExtendedStreamReader reader, ModelNode operation) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case RELATIVE_TO:
TransactionSubsystemRootResourceDefinition.OBJECT_STORE_RELATIVE_TO.parseAndSetParameter(value, operation, reader);
break;
case PATH:
TransactionSubsystemRootResourceDefinition.OBJECT_STORE_PATH.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
// Handle elements
requireNoContent(reader);
}
static void parseCoordinatorEnvironmentElement(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case ENABLE_STATISTICS:
TransactionSubsystemRootResourceDefinition.ENABLE_STATISTICS.parseAndSetParameter(value, operation, reader);
break;
case ENABLE_TSM_STATUS:
TransactionSubsystemRootResourceDefinition.ENABLE_TSM_STATUS.parseAndSetParameter(value, operation, reader);
break;
case DEFAULT_TIMEOUT:
TransactionSubsystemRootResourceDefinition.DEFAULT_TIMEOUT.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
// Handle elements
requireNoContent(reader);
}
/**
* Handle the core-environment element and children
*
* @param reader the stream reader
* @param operation ModelNode for the core-environment add operation
* @throws XMLStreamException
*
*/
static void parseCoreEnvironmentElement(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NODE_IDENTIFIER:
TransactionSubsystemRootResourceDefinition.NODE_IDENTIFIER.parseAndSetParameter(value, operation, reader);
break;
case PATH:
case RELATIVE_TO:
throw TransactionLogger.ROOT_LOGGER.unsupportedAttribute(attribute.getLocalName(), reader.getLocation());
default:
throw unexpectedAttribute(reader, i);
}
}
// elements
final EnumSet<Element> required = EnumSet.of(Element.PROCESS_ID);
final EnumSet<Element> encountered = EnumSet.noneOf(Element.class);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
required.remove(element);
switch (element) {
case PROCESS_ID: {
if (!encountered.add(element)) {
throw duplicateNamedElement(reader, reader.getLocalName());
}
parseProcessIdEnvironmentElement(reader, operation);
break;
}
default:
throw unexpectedElement(reader);
}
}
if (!required.isEmpty()) {
throw missingRequiredElement(reader, required);
}
}
/**
* Handle the process-id child elements
*
* @param reader the stream reader
* @param coreEnvironmentAdd the add operation
*
* @throws XMLStreamException
*
*/
static void parseProcessIdEnvironmentElement(XMLExtendedStreamReader reader, ModelNode coreEnvironmentAdd) throws XMLStreamException {
// no attributes
if (reader.getAttributeCount() > 0) {
throw unexpectedAttribute(reader, 0);
}
// elements
boolean encountered = false;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case UUID:
if (encountered) {
throw unexpectedElement(reader);
}
encountered = true;
if (reader.getAttributeCount() > 0) {
throw unexpectedAttribute(reader, 0);
}
coreEnvironmentAdd.get(TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.getName()).set(true);
requireNoContent(reader);
break;
case SOCKET: {
if (encountered) {
throw unexpectedElement(reader);
}
encountered = true;
parseSocketProcessIdElement(reader, coreEnvironmentAdd);
break;
}
default:
throw unexpectedElement(reader);
}
}
if (!encountered) {
throw missingOneOf(reader, EnumSet.of(Element.UUID, Element.SOCKET));
}
}
static void parseSocketProcessIdElement(XMLExtendedStreamReader reader, ModelNode coreEnvironmentAdd) throws XMLStreamException {
final int count = reader.getAttributeCount();
final EnumSet<Attribute> required = EnumSet.of(Attribute.BINDING);
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case BINDING:
TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING.parseAndSetParameter(value, coreEnvironmentAdd, reader);
break;
case SOCKET_PROCESS_ID_MAX_PORTS:
TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_MAX_PORTS.parseAndSetParameter(value, coreEnvironmentAdd, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
// Handle elements
requireNoContent(reader);
}
static void parseRecoveryEnvironmentElement(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
Set<Attribute> required = EnumSet.of(Attribute.BINDING, Attribute.STATUS_BINDING);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case BINDING:
TransactionSubsystemRootResourceDefinition.BINDING.parseAndSetParameter(value, operation, reader);
break;
case STATUS_BINDING:
TransactionSubsystemRootResourceDefinition.STATUS_BINDING.parseAndSetParameter(value, operation, reader);
break;
case RECOVERY_LISTENER:
TransactionSubsystemRootResourceDefinition.RECOVERY_LISTENER.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
// Handle elements
requireNoContent(reader);
}
}
| 15,342
| 41.738162
| 155
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/LogStoreParticipantOperationHandler.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.txn.subsystem;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
import javax.management.MBeanServer;
import javax.management.ObjectName;
abstract class LogStoreParticipantOperationHandler implements OperationStepHandler {
private String operationName;
public LogStoreParticipantOperationHandler(String operationName) {
this.operationName = operationName;
}
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
MBeanServer mbs = TransactionExtension.getMBeanServer(context);
final Resource resource = context.readResource(PathAddress.EMPTY_ADDRESS);
try {
// Get the internal object name
final ObjectName on = LogStoreResource.getObjectName(resource);
// Invoke the MBean operation
mbs.invoke(on, operationName, null, null);
} catch (Exception e) {
throw new OperationFailedException("JMX error: " + e.getMessage());
}
// refresh the attributes of this participant (the status attribute should have changed to PREPARED
refreshParticipant(context);
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
abstract void refreshParticipant(OperationContext context);
}
| 2,588
| 37.641791
| 107
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.