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/sar/src/test/_java/org/jboss/as/service/LegacyServiceMBean.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.service;
/**
* @author John Bailey
*/
public interface LegacyServiceMBean {
}
| 1,126 | 36.566667 | 70 |
java
|
null |
wildfly-main/sar/src/test/java/org/jboss/as/service/ReflectionUtilsTest.java
|
/*
Copyright 2016 Red Hat, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.jboss.as.service;
import org.junit.Test;
import java.lang.reflect.Method;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
public class ReflectionUtilsTest {
public static class Foo {
public int getA() {
return 0;
}
public boolean isB() {
return false;
}
public int getC(int c) {
return c;
}
}
@Test
public void findNonBooleanGetter() throws Exception {
final Method getter = ReflectionUtils.getGetter(Foo.class, "a");
assertNotNull(getter);
assertEquals("getA", getter.getName());
}
@Test
public void findBooleanGetter() throws Exception {
final Method getter = ReflectionUtils.getGetter(Foo.class, "b");
assertNotNull(getter);
assertEquals("isB", getter.getName());
}
@Test(expected = IllegalStateException.class)
public void doNotFindGetterWithArgument() throws Exception {
ReflectionUtils.getGetter(Foo.class, "c");
fail("Should have thrown exception - getC is not a getter");
}
}
| 1,738 | 26.603175 | 72 |
java
|
null |
wildfly-main/sar/src/test/java/org/jboss/as/service/SarSubsystemTestCase.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.service;
import java.io.IOException;
import java.util.EnumSet;
import java.util.Locale;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
* @author <a href="[email protected]">Kabir Khan</a>
*/
@RunWith(Parameterized.class)
public class SarSubsystemTestCase extends AbstractSubsystemBaseTest {
@Parameters
public static Iterable<SarSubsystemSchema> parameters() {
return EnumSet.allOf(SarSubsystemSchema.class);
}
private static final AdditionalInitialization ADDITIONAL_INITIALIZATION = AdditionalInitialization.withCapabilities("org.wildfly.management.jmx");
private final SarSubsystemSchema schema;
public SarSubsystemTestCase(SarSubsystemSchema schema) {
super(SarExtension.SUBSYSTEM_NAME, new SarExtension());
this.schema = schema;
}
@Override
protected AdditionalInitialization createAdditionalInitialization() {
return ADDITIONAL_INITIALIZATION;
}
@Override
protected String getSubsystemXml() throws IOException {
return String.format(Locale.ROOT, "<subsystem xmlns=\"%s\"/>", this.schema.getNamespace());
}
@Override
protected String getSubsystemXsdPath() throws Exception {
return String.format(Locale.ROOT, "schema/jboss-as-sar_%d_%d.xsd", this.schema.getVersion().major(), this.schema.getVersion().minor());
}
}
| 2,582 | 37.552239 | 150 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/SarStructureProcessor.java
|
package org.jboss.as.service;
import java.io.Closeable;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Map;
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.MountedDeploymentOverlay;
import org.jboss.as.server.deployment.module.ModuleRootMarker;
import org.jboss.as.server.deployment.module.MountHandle;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.as.server.deployment.module.TempFileProviderService;
import org.jboss.as.service.logging.SarLogger;
import org.jboss.vfs.VFS;
import org.jboss.vfs.VFSUtils;
import org.jboss.vfs.VirtualFile;
import org.jboss.vfs.VisitorAttributes;
import org.jboss.vfs.util.SuffixMatchFilter;
/**
* @author Tomasz Adamski
*/
public class SarStructureProcessor implements DeploymentUnitProcessor {
private static final String SAR_EXTENSION = ".sar";
private static final String JAR_EXTENSION = ".jar";
private static final SuffixMatchFilter CHILD_ARCHIVE_FILTER = new SuffixMatchFilter(JAR_EXTENSION,
VisitorAttributes.RECURSE_LEAVES_ONLY);
private static Closeable NO_OP_CLOSEABLE = new Closeable() {
public void close() throws IOException {
// NO-OP
}
};
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final ResourceRoot resourceRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
if (resourceRoot == null) {
return;
}
final VirtualFile deploymentRoot = resourceRoot.getRoot();
if (deploymentRoot == null || !deploymentRoot.exists()) {
return;
}
final String deploymentRootName = deploymentRoot.getName().toLowerCase(Locale.ENGLISH);
if (!deploymentRootName.endsWith(SAR_EXTENSION)) {
return;
}
ModuleRootMarker.mark(resourceRoot, true);
Map<String, MountedDeploymentOverlay> overlays = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_OVERLAY_LOCATIONS);
try {
final List<VirtualFile> childArchives = deploymentRoot.getChildren(CHILD_ARCHIVE_FILTER);
for (final VirtualFile child : childArchives) {
String relativeName = child.getPathNameRelativeTo(deploymentRoot);
MountedDeploymentOverlay overlay = overlays.get(relativeName);
Closeable closable = NO_OP_CLOSEABLE;
if(overlay != null) {
overlay.remountAsZip(false);
} else if(child.isFile()) {
closable = VFS.mountZip(child, child, TempFileProviderService.provider());
}
final MountHandle mountHandle = MountHandle.create(closable);
final ResourceRoot childResource = new ResourceRoot(child, mountHandle);
ModuleRootMarker.mark(childResource);
deploymentUnit.addToAttachmentList(Attachments.RESOURCE_ROOTS, childResource);
resourceRoot.addToAttachmentList(Attachments.INDEX_IGNORE_PATHS, child.getPathNameRelativeTo(deploymentRoot));
}
} catch (IOException e) {
throw SarLogger.ROOT_LOGGER.failedToProcessSarChild(e, deploymentRoot);
}
}
@Override
public void undeploy(DeploymentUnit context) {
final List<ResourceRoot> childRoots = context.removeAttachment(Attachments.RESOURCE_ROOTS);
if (childRoots != null) {
for (ResourceRoot childRoot : childRoots) {
VFSUtils.safeClose(childRoot.getMountHandle());
}
}
}
}
| 4,004 | 39.454545 | 128 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/SarExtension.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.service;
import java.util.EnumSet;
import java.util.List;
import org.jboss.as.controller.Extension;
import org.jboss.as.controller.ExtensionContext;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.PersistentResourceXMLDescription;
import org.jboss.as.controller.PersistentResourceXMLDescriptionReader;
import org.jboss.as.controller.PersistentResourceXMLDescriptionWriter;
import org.jboss.as.controller.ReloadRequiredRemoveStepHandler;
import org.jboss.as.controller.ResourceDefinition;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.SubsystemRegistration;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.descriptions.ParentResourceDescriptionResolver;
import org.jboss.as.controller.descriptions.SubsystemResourceDescriptionResolver;
import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler;
import org.jboss.as.controller.parsing.ExtensionParsingContext;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
/**
* Extension used to enable SAR deployments.
*
* @author John Bailey
* @author Emanuel Muckenhuber
*/
public class SarExtension implements Extension {
public static final String NAMESPACE = "urn:jboss:domain:sar:1.0";
public static final String SUBSYSTEM_NAME = "sar";
private static final ParentResourceDescriptionResolver RESOLVER = new SubsystemResourceDescriptionResolver(SUBSYSTEM_NAME, SarExtension.class);
static final PathElement PATH = PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, SarExtension.SUBSYSTEM_NAME);
static final String JMX_CAPABILITY = "org.wildfly.management.jmx";
static final RuntimeCapability<Void> SAR_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.sar-deployment")
.addRequirements(JMX_CAPABILITY)
.build();
private static final ModelVersion CURRENT_MODEL_VERSION = ModelVersion.create(1, 0, 0);
private final PersistentResourceXMLDescription currentDescription = SarSubsystemSchema.CURRENT.getXMLDescription();
@Override
public void initialize(ExtensionContext context) {
final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION);
ResourceDefinition definition = new SimpleResourceDefinition(new SimpleResourceDefinition.Parameters(PATH, RESOLVER)
.setAddHandler(SarSubsystemAdd.INSTANCE)
.setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE)
.setCapabilities(SAR_CAPABILITY));
final ManagementResourceRegistration registration = subsystem.registerSubsystemModel(definition);
registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE);
subsystem.registerXMLElementWriter(new PersistentResourceXMLDescriptionWriter(this.currentDescription));
}
/** {@inheritDoc} */
@Override
public void initializeParsers(ExtensionParsingContext context) {
for (SarSubsystemSchema schema : EnumSet.allOf(SarSubsystemSchema.class)) {
XMLElementReader<List<ModelNode>> reader = (schema == SarSubsystemSchema.CURRENT) ? new PersistentResourceXMLDescriptionReader(this.currentDescription) : schema;
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, schema.getNamespace().getUri(), reader);
}
}
}
| 4,664 | 49.16129 | 173 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/MBeanRegistrationService.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.service;
import static org.jboss.as.service.logging.SarLogger.ROOT_LOGGER;
import java.lang.management.ManagementFactory;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
import java.util.function.Supplier;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.jboss.as.server.deployment.SetupAction;
import org.jboss.msc.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;
/**
* Service used to register and unregister an mbean with an mbean server.
*
* @author John Bailey
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
final class MBeanRegistrationService implements Service {
/** @deprecated Use {@link ServiceNameFactory#newRegisterUnregister(String)} -- only kept for a while in case user code looks for this */
@Deprecated
static final ServiceName SERVICE_NAME = ServiceName.JBOSS.append("mbean", "registration");
private final Supplier<MBeanServer> mBeanServerSupplier;
private final Supplier<Object> objectSupplier;
private final String name;
private ObjectName objectName;
private final List<SetupAction> setupActions;
public MBeanRegistrationService(final String name, final List<SetupAction> setupActions,
final Supplier<MBeanServer> mBeanServerSupplier,
final Supplier<Object> objectSupplier) {
this.name = name;
this.setupActions = setupActions;
this.mBeanServerSupplier = mBeanServerSupplier;
this.objectSupplier = objectSupplier;
}
public synchronized void start(final StartContext context) throws StartException {
final MBeanServer mBeanServer = getMBeanServer();
final Object value = objectSupplier.get();
try {
objectName = new ObjectName(name);
} catch (MalformedObjectNameException e) {
throw ROOT_LOGGER.mbeanRegistrationFailed(e, name);
}
try {
for (SetupAction action : setupActions) {
action.setup(Collections.<String, Object>emptyMap());
}
try {
ROOT_LOGGER.debugf("Registering [%s] with name [%s]", value, objectName);
mBeanServer.registerMBean(value, objectName);
} catch (Exception e) {
throw ROOT_LOGGER.mbeanRegistrationFailed(e, name);
}
} finally {
ListIterator<SetupAction> it = setupActions.listIterator(setupActions.size());
while (it.hasPrevious()) {
SetupAction action = it.previous();
action.teardown(Collections.<String, Object>emptyMap());
}
}
}
public synchronized void stop(final StopContext context) {
if (objectName == null) {
ROOT_LOGGER.cannotUnregisterObject();
}
final MBeanServer mBeanServer = getMBeanServer();
try {
for (SetupAction action : setupActions) {
action.setup(Collections.<String, Object>emptyMap());
}
try {
mBeanServer.unregisterMBean(objectName);
} catch (Exception e) {
ROOT_LOGGER.unregistrationFailure(e, objectName);
}
} finally {
ListIterator<SetupAction> it = setupActions.listIterator(setupActions.size());
while (it.hasPrevious()) {
SetupAction action = it.previous();
action.teardown(Collections.<String, Object>emptyMap());
}
}
}
private MBeanServer getMBeanServer() {
MBeanServer mBeanServer = mBeanServerSupplier.get();
if (mBeanServer == null) {
mBeanServer = ManagementFactory.getPlatformMBeanServer();
}
return mBeanServer;
}
}
| 5,065 | 38.889764 | 141 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/DelegatingSupplier.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.service;
import java.util.function.Supplier;
/**
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
abstract class DelegatingSupplier implements Supplier<Object> {
protected volatile Supplier<Object> objectSupplier;
void setObjectSupplier(final Supplier<Object> objectSupplier) {
this.objectSupplier = objectSupplier;
}
}
| 1,411 | 35.205128 | 70 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/ServiceDeploymentParsingProcessor.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.service;
import java.io.InputStream;
import java.util.Locale;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import org.jboss.as.ee.structure.JBossDescriptorPropertyReplacement;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.service.descriptor.JBossServiceXmlDescriptor;
import org.jboss.as.service.descriptor.JBossServiceXmlDescriptorParser;
import org.jboss.as.service.descriptor.ParseResult;
import org.jboss.as.service.logging.SarLogger;
import org.jboss.staxmapper.XMLMapper;
import org.jboss.vfs.VFSUtils;
import org.jboss.vfs.VirtualFile;
/**
* DeploymentUnitProcessor responsible for parsing a jboss-service.xml descriptor and attaching the corresponding JBossServiceXmlDescriptor.
*
* @author John E. Bailey
*/
public class ServiceDeploymentParsingProcessor implements DeploymentUnitProcessor {
static final String SERVICE_DESCRIPTOR_PATH = "META-INF/jboss-service.xml";
static final String SERVICE_DESCRIPTOR_SUFFIX = "-service.xml";
private final XMLInputFactory inputFactory = XMLInputFactory.newInstance();
/**
* Construct a new instance.
*/
public ServiceDeploymentParsingProcessor() {
}
/**
* Process a deployment for jboss-service.xml files. Will parse the xml file and attach a configuration discovered
* during processing.
*
* @param phaseContext the deployment unit context
* @throws DeploymentUnitProcessingException
*/
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final VirtualFile deploymentRoot = phaseContext.getDeploymentUnit().getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot();
if(deploymentRoot == null || !deploymentRoot.exists())
return;
VirtualFile serviceXmlFile = null;
if(deploymentRoot.isDirectory()) {
serviceXmlFile = deploymentRoot.getChild(SERVICE_DESCRIPTOR_PATH);
} else if(deploymentRoot.getName().toLowerCase(Locale.ENGLISH).endsWith(SERVICE_DESCRIPTOR_SUFFIX)) {
serviceXmlFile = deploymentRoot;
}
if(serviceXmlFile == null || !serviceXmlFile.exists())
return;
final XMLMapper xmlMapper = XMLMapper.Factory.create();
final JBossServiceXmlDescriptorParser jBossServiceXmlDescriptorParser = new JBossServiceXmlDescriptorParser(JBossDescriptorPropertyReplacement.propertyReplacer(phaseContext.getDeploymentUnit()));
xmlMapper.registerRootElement(new QName("urn:jboss:service:7.0", "server"), jBossServiceXmlDescriptorParser);
xmlMapper.registerRootElement(new QName(null, "server"), jBossServiceXmlDescriptorParser);
InputStream xmlStream = null;
try {
xmlStream = serviceXmlFile.openStream();
final XMLStreamReader reader = inputFactory.createXMLStreamReader(xmlStream);
final ParseResult<JBossServiceXmlDescriptor> result = new ParseResult<JBossServiceXmlDescriptor>();
xmlMapper.parseDocument(result, reader);
final JBossServiceXmlDescriptor xmlDescriptor = result.getResult();
if(xmlDescriptor != null)
phaseContext.getDeploymentUnit().putAttachment(JBossServiceXmlDescriptor.ATTACHMENT_KEY, xmlDescriptor);
else
throw SarLogger.ROOT_LOGGER.failedXmlParsing(serviceXmlFile);
} catch(Exception e) {
throw SarLogger.ROOT_LOGGER.failedXmlParsing(e, serviceXmlFile);
} finally {
VFSUtils.safeClose(xmlStream);
}
}
}
| 4,857 | 43.981481 | 203 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/AbstractService.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.service;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.ExecutorService;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.jboss.as.server.deployment.SetupAction;
import org.jboss.msc.service.LifecycleContext;
import org.jboss.msc.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Abstract service class.
*
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
abstract class AbstractService implements Service {
protected final Object mBeanInstance;
private final List<SetupAction> setupActions;
private final ClassLoader mbeanContextClassLoader;
private final Consumer<Object> mBeanInstanceConsumer;
protected final Supplier<ExecutorService> executorSupplier;
/**
* @param mBeanInstance
* @param setupActions actions to setup the thread local context
*/
protected AbstractService(final Object mBeanInstance, final List<SetupAction> setupActions, final ClassLoader mbeanContextClassLoader, final Consumer<Object> mBeanInstanceConsumer, final Supplier<ExecutorService> executorSupplier) {
this.mBeanInstance = mBeanInstance;
this.setupActions = setupActions;
this.mbeanContextClassLoader = mbeanContextClassLoader;
this.mBeanInstanceConsumer = mBeanInstanceConsumer;
this.executorSupplier = executorSupplier;
}
@Override
public void start(final StartContext context) {
mBeanInstanceConsumer.accept(mBeanInstance);
}
@Override
public void stop(final StopContext context) {
mBeanInstanceConsumer.accept(null);
}
protected void invokeLifecycleMethod(final Method method, final LifecycleContext context) throws InvocationTargetException, IllegalAccessException {
if (method != null) {
try {
for (SetupAction action : setupActions) {
action.setup(Collections.<String, Object>emptyMap());
}
final ClassLoader old = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(this.mbeanContextClassLoader);
try {
method.invoke(mBeanInstance);
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(old);
}
} finally {
ListIterator<SetupAction> it = setupActions.listIterator(setupActions.size());
while (it.hasPrevious()) {
SetupAction action = it.previous();
action.teardown(Collections.<String, Object>emptyMap());
}
}
}
}
}
| 3,938 | 38.787879 | 236 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/SarSubsystemSchema.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.service;
import static org.jboss.as.controller.PersistentResourceXMLDescription.builder;
import org.jboss.as.controller.PersistentResourceXMLDescription;
import org.jboss.as.controller.PersistentSubsystemSchema;
import org.jboss.as.controller.SubsystemSchema;
import org.jboss.as.controller.xml.VersionedNamespace;
import org.jboss.staxmapper.IntVersion;
/**
* Enumerates the supported namespaces of the SAR subsystem.
* @author Paul Ferraro
*/
public enum SarSubsystemSchema implements PersistentSubsystemSchema<SarSubsystemSchema> {
VERSION_1_0(1),
;
static final SarSubsystemSchema CURRENT = VERSION_1_0;
private final VersionedNamespace<IntVersion, SarSubsystemSchema> namespace;
SarSubsystemSchema(int major) {
this.namespace = SubsystemSchema.createLegacySubsystemURN(SarExtension.SUBSYSTEM_NAME, new IntVersion(major));
}
@Override
public VersionedNamespace<IntVersion, SarSubsystemSchema> getNamespace() {
return this.namespace;
}
@Override
public PersistentResourceXMLDescription getXMLDescription() {
return builder(SarExtension.PATH, this.namespace).build();
}
}
| 2,202 | 36.338983 | 118 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/StartStopService.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.service;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.function.Supplier;
import java.util.function.Consumer;
import org.jboss.as.server.deployment.SetupAction;
import org.jboss.as.service.logging.SarLogger;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* Service wrapper for legacy JBoss services that controls the service start and stop lifecycle.
*
* @author John E. Bailey
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
final class StartStopService extends AbstractService {
private final Method startMethod;
private final Method stopMethod;
StartStopService(final Object mBeanInstance, final Method startMethod, final Method stopMethod, final List<SetupAction> setupActions, final ClassLoader mbeanContextClassLoader, final Consumer<Object> mBeanInstanceConsumer, final Supplier<ExecutorService> executorSupplier) {
super(mBeanInstance, setupActions, mbeanContextClassLoader, mBeanInstanceConsumer, executorSupplier);
this.startMethod = startMethod;
this.stopMethod = stopMethod;
}
/** {@inheritDoc} */
public void start(final StartContext context) {
super.start(context);
if (SarLogger.ROOT_LOGGER.isTraceEnabled()) {
SarLogger.ROOT_LOGGER.tracef("Starting Service: %s", context.getController().getName());
}
final Runnable task = new Runnable() {
@Override
public void run() {
try {
invokeLifecycleMethod(startMethod, context);
context.complete();
} catch (Throwable e) {
context.failed(new StartException(SarLogger.ROOT_LOGGER.failedExecutingLegacyMethod("start()"), e));
}
}
};
try {
executorSupplier.get().submit(task);
} catch (RejectedExecutionException e) {
task.run();
} finally {
context.asynchronous();
}
}
/** {@inheritDoc} */
public void stop(final StopContext context) {
super.stop(context);
if (SarLogger.ROOT_LOGGER.isTraceEnabled()) {
SarLogger.ROOT_LOGGER.tracef("Stopping Service: %s", context.getController().getName());
}
final Runnable task = new Runnable() {
@Override
public void run() {
try {
invokeLifecycleMethod(stopMethod, context);
} catch (Exception e) {
SarLogger.ROOT_LOGGER.error(SarLogger.ROOT_LOGGER.failedExecutingLegacyMethod("stop()"), e);
} finally {
context.complete();
}
}
};
try {
executorSupplier.get().submit(task);
} catch (RejectedExecutionException e) {
task.run();
} finally {
context.asynchronous();
}
}
}
| 4,140 | 36.990826 | 278 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/ParsedServiceDeploymentProcessor.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.service;
import java.beans.PropertyEditor;
import java.util.Collections;
import java.util.LinkedList;
import java.util.function.Supplier;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.management.MalformedObjectNameException;
import javax.management.NotificationBroadcasterSupport;
import javax.management.ObjectName;
import javax.management.StandardMBean;
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.reflect.ClassReflectionIndex;
import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex;
import org.jboss.as.service.component.ServiceComponentInstantiator;
import org.jboss.as.service.descriptor.JBossServiceAttributeConfig;
import org.jboss.as.service.descriptor.JBossServiceAttributeConfig.Inject;
import org.jboss.as.service.descriptor.JBossServiceAttributeConfig.ValueFactory;
import org.jboss.as.service.descriptor.JBossServiceAttributeConfig.ValueFactoryParameter;
import org.jboss.as.service.descriptor.JBossServiceConfig;
import org.jboss.as.service.descriptor.JBossServiceConstructorConfig;
import org.jboss.as.service.descriptor.JBossServiceConstructorConfig.Argument;
import org.jboss.as.service.descriptor.JBossServiceDependencyConfig;
import org.jboss.as.service.descriptor.JBossServiceDependencyListConfig;
import org.jboss.as.service.descriptor.JBossServiceXmlDescriptor;
import org.jboss.as.service.logging.SarLogger;
import org.jboss.common.beans.property.finder.PropertyEditorFinder;
import org.jboss.modules.Module;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* DeploymentUnit processor responsible for taking JBossServiceXmlDescriptor configuration and creating the
* corresponding services.
*
* @author John E. Bailey
* @author <a href="mailto:[email protected]">Richard Opalka</a>
* @author Eduardo Martins
*/
public class ParsedServiceDeploymentProcessor implements DeploymentUnitProcessor {
private final ServiceName mbeanServerServiceName;
ParsedServiceDeploymentProcessor(ServiceName mbeanServerServiceName) {
this.mbeanServerServiceName = mbeanServerServiceName;
}
/**
* Process a deployment for JbossService configuration. Will install a {@code JBossService} for each configured service.
*
* @param phaseContext the deployment unit context
* @throws DeploymentUnitProcessingException
*/
@Override
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final JBossServiceXmlDescriptor serviceXmlDescriptor = deploymentUnit.getAttachment(JBossServiceXmlDescriptor.ATTACHMENT_KEY);
if (serviceXmlDescriptor == null) {
// Skip deployments without a service xml descriptor
return;
}
// assert module
final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
if (module == null)
throw SarLogger.ROOT_LOGGER.failedToGetAttachment("module", deploymentUnit);
// assert reflection index
final DeploymentReflectionIndex reflectionIndex = deploymentUnit.getAttachment(Attachments.REFLECTION_INDEX);
if (reflectionIndex == null)
throw SarLogger.ROOT_LOGGER.failedToGetAttachment("reflection index", deploymentUnit);
// install services
final ClassLoader classLoader = module.getClassLoader();
final List<JBossServiceConfig> serviceConfigs = serviceXmlDescriptor.getServiceConfigs();
final ServiceTarget target = phaseContext.getServiceTarget();
final Map<String,ServiceComponentInstantiator> serviceComponents = deploymentUnit.getAttachment(ServiceAttachments.SERVICE_COMPONENT_INSTANTIATORS);
for (final JBossServiceConfig serviceConfig : serviceConfigs) {
addServices(target, serviceConfig, classLoader, reflectionIndex, serviceComponents != null ? serviceComponents.get(serviceConfig.getName()) : null, phaseContext);
}
}
private void addServices(final ServiceTarget target, final JBossServiceConfig mBeanConfig, final ClassLoader classLoader, final DeploymentReflectionIndex index, ServiceComponentInstantiator componentInstantiator, final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final String mBeanClassName = mBeanConfig.getCode();
final List<ClassReflectionIndex> mBeanClassHierarchy = getClassHierarchy(mBeanClassName, index, classLoader);
final Object mBeanInstance = newInstance(mBeanConfig, mBeanClassHierarchy, classLoader);
final String mBeanName = mBeanConfig.getName();
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final MBeanServices mBeanServices = new MBeanServices(mBeanName, mBeanInstance, mBeanClassHierarchy, target, componentInstantiator, deploymentUnit.getAttachmentList(org.jboss.as.ee.component.Attachments.WEB_SETUP_ACTIONS), classLoader, mbeanServerServiceName);
final JBossServiceDependencyConfig[] dependencyConfigs = mBeanConfig.getDependencyConfigs();
addDependencies(dependencyConfigs, mBeanClassHierarchy, mBeanServices, mBeanInstance);
final JBossServiceDependencyListConfig[] dependencyListConfigs = mBeanConfig.getDependencyConfigLists();
addDependencyLists(dependencyListConfigs, mBeanClassHierarchy, mBeanServices, mBeanInstance);
final JBossServiceAttributeConfig[] attributeConfigs = mBeanConfig.getAttributeConfigs();
addAttributes(attributeConfigs, mBeanClassHierarchy, mBeanServices, classLoader, mBeanInstance);
// register all mBean related services
mBeanServices.install();
}
private void addDependencies(final JBossServiceDependencyConfig[] dependencyConfigs, final List<ClassReflectionIndex> mBeanClassHierarchy, final MBeanServices mBeanServices, final Object mBeanInstance) throws DeploymentUnitProcessingException {
if (dependencyConfigs != null) {
for (final JBossServiceDependencyConfig dependencyConfig : dependencyConfigs) {
final String optionalAttributeName = dependencyConfig.getOptionalAttributeName();
if(optionalAttributeName != null){
final Method setter = ReflectionUtils.getSetter(mBeanClassHierarchy, optionalAttributeName);
final ObjectName dependencyObjectName = createDependencyObjectName(dependencyConfig.getDependencyName());
final Supplier<Object> objectSupplier = new ObjectSupplier(dependencyObjectName);
mBeanServices.addValue(setter, objectSupplier);
}
mBeanServices.addDependency(dependencyConfig.getDependencyName());
}
}
}
private void addDependencyLists(final JBossServiceDependencyListConfig[] dependencyListConfigs, final List<ClassReflectionIndex> mBeanClassHierarchy, final MBeanServices mBeanServices, final Object mBeanInstance) throws DeploymentUnitProcessingException {
if(dependencyListConfigs != null){
for(final JBossServiceDependencyListConfig dependencyListConfig: dependencyListConfigs) {
final List<ObjectName> dependencyObjectNames = new ArrayList<ObjectName>(dependencyListConfig.getDependencyConfigs().length);
for(final JBossServiceDependencyConfig dependencyConfig: dependencyListConfig.getDependencyConfigs()){
final String dependencyName = dependencyConfig.getDependencyName();
mBeanServices.addDependency(dependencyName);
final ObjectName dependencyObjectName = createDependencyObjectName(dependencyName);
dependencyObjectNames.add(dependencyObjectName);
}
final String optionalAttributeName = dependencyListConfig.getOptionalAttributeName();
if(optionalAttributeName != null){
final Method setter = ReflectionUtils.getSetter(mBeanClassHierarchy, optionalAttributeName);
final ObjectSupplier objectSupplier = new ObjectSupplier(dependencyObjectNames);
mBeanServices.addValue(setter, objectSupplier);
}
}
}
}
private void addAttributes(final JBossServiceAttributeConfig[] attributeConfigs, final List<ClassReflectionIndex> mBeanClassHierarchy, final MBeanServices mBeanServices, final ClassLoader classLoader, final Object mBeanInstance) throws DeploymentUnitProcessingException {
if (attributeConfigs != null) {
for (final JBossServiceAttributeConfig attributeConfig : attributeConfigs) {
final String propertyName = attributeConfig.getName();
final Inject injectConfig = attributeConfig.getInject();
final ValueFactory valueFactoryConfig = attributeConfig.getValueFactory();
final Method setter = ReflectionUtils.getSetter(mBeanClassHierarchy, propertyName);
if (injectConfig != null) {
final DelegatingSupplier propertySupplier = getObjectSupplier(injectConfig);
mBeanServices.addAttribute(injectConfig.getBeanName(), setter, propertySupplier);
} else if (valueFactoryConfig != null) {
final DelegatingSupplier valueFactorySupplier = getObjectSupplier(valueFactoryConfig, classLoader);
mBeanServices.addAttribute(valueFactoryConfig.getBeanName(), setter, valueFactorySupplier);
} else {
final Supplier<Object> value = getObjectSupplier(attributeConfig, mBeanClassHierarchy);
mBeanServices.addValue(setter, value);
}
}
}
}
private ObjectName createDependencyObjectName(final String dependencyName) throws DeploymentUnitProcessingException {
try {
return new ObjectName(dependencyName);
} catch(MalformedObjectNameException exception){
throw SarLogger.ROOT_LOGGER.malformedDependencyName(exception, dependencyName);
}
}
private static DelegatingSupplier getObjectSupplier(final Inject injectConfig) {
return new PropertySupplier(injectConfig.getPropertyName());
}
private static DelegatingSupplier getObjectSupplier(final ValueFactory valueFactory, final ClassLoader classLoader) {
final String methodName = valueFactory.getMethodName();
final ValueFactoryParameter[] parameters = valueFactory.getParameters();
final Class<?>[] paramTypes = new Class<?>[parameters.length];
final Object[] args = new Object[parameters.length];
int index = 0;
for (ValueFactoryParameter parameter : parameters) {
final Class<?> attributeType = ReflectionUtils.getClass(parameter.getType(), classLoader);
paramTypes[index] = attributeType;
args[index] = newValue(attributeType, parameter.getValue());
index++;
}
return new ValueFactorySupplier(methodName, paramTypes, args);
}
private static Supplier<Object> getObjectSupplier(final JBossServiceAttributeConfig attributeConfig, final List<ClassReflectionIndex> mBeanClassHierarchy) {
final String attributeName = attributeConfig.getName();
final Method setterMethod = ReflectionUtils.getSetter(mBeanClassHierarchy, attributeName);
final Class<?> setterType = setterMethod.getParameterTypes()[0];
return new ObjectSupplier(newValue(setterType, attributeConfig.getValue()));
}
private static Object newInstance(final JBossServiceConfig serviceConfig, final List<ClassReflectionIndex> mBeanClassHierarchy, final ClassLoader deploymentClassLoader) throws DeploymentUnitProcessingException {
// set TCCL so that the MBean instantiation happens in the deployment's classloader
final ClassLoader oldTCCL = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(deploymentClassLoader);
try {
final JBossServiceConstructorConfig constructorConfig = serviceConfig.getConstructorConfig();
final int paramCount = constructorConfig != null ? constructorConfig.getArguments().length : 0;
final Class<?>[] types = new Class<?>[paramCount];
final Object[] params = new Object[paramCount];
if (constructorConfig != null) {
final Argument[] arguments = constructorConfig.getArguments();
for (int i = 0; i < paramCount; i++) {
final Argument argument = arguments[i];
types[i] = ReflectionUtils.getClass(argument.getType(), deploymentClassLoader);
params[i] = newValue(ReflectionUtils.getClass(argument.getType(), deploymentClassLoader), argument.getValue());
}
}
final Constructor<?> constructor = mBeanClassHierarchy.get(0).getConstructor(types);
if(constructor == null){
throw SarLogger.ROOT_LOGGER.defaultConstructorNotFound(mBeanClassHierarchy.get(0).getIndexedClass());
}
final Object mBeanInstance = ReflectionUtils.newInstance(constructor, params);
return mBeanInstance;
} finally {
// switch back the TCCL
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTCCL);
}
}
private static Object newValue(final Class<?> type, final String value) {
final PropertyEditor editor = PropertyEditorFinder.getInstance().find(type);
if (editor == null) {
SarLogger.ROOT_LOGGER.propertyNotFound(type);
return null;
}
editor.setAsText(value);
return editor.getValue();
}
/**
* Uses the provided DeploymentReflectionIndex to provide an reflection index for the class hierarchy for
* the class with the given name. Superclass data will not be provided for java.lang.Object or for
* javax.management.NotificationBroadcasterSupport or javax.management.StandardMBean as those classes do not
* provide methods relevant to our use of superclass information from the reflection index. Not providing an
* index for those classes avoids the need to include otherwise unneeded --add-opens calls when lauching the server.
*
* @param className the name of the initial class in the hierarchy
* @param index DeploymentReflectionIndex to use for creating the ClassReflectionIndex elements
* @param classLoader classloader to use to load {@code className}
* @return reflection indices for the class hierarchy. The first element in the returned list will be for the
* provided className; later elements will be for superclasses.
*/
private static List<ClassReflectionIndex> getClassHierarchy(final String className, final DeploymentReflectionIndex index, final ClassLoader classLoader) {
final List<ClassReflectionIndex> retVal = new LinkedList<ClassReflectionIndex>();
Class<?> initialClazz = ReflectionUtils.getClass(className, classLoader);
Class<?> temp = initialClazz;
while (temp != null
&& (temp == initialClazz
|| (temp != Object.class && temp != NotificationBroadcasterSupport.class && temp != StandardMBean.class))) {
retVal.add(index.getClassIndex(temp));
temp = temp.getSuperclass();
}
return Collections.unmodifiableList(retVal);
}
}
| 17,072 | 55.72093 | 302 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/SarSubsystemAdd.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.service;
import javax.management.MBeanServer;
import org.jboss.as.controller.AbstractBoottimeAddStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.server.AbstractDeploymentChainStep;
import org.jboss.as.server.DeploymentProcessorTarget;
import org.jboss.as.server.deployment.Phase;
import org.jboss.as.service.component.ServiceComponentProcessor;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceName;
/**
* @author Emanuel Muckenhuber
*/
public class SarSubsystemAdd extends AbstractBoottimeAddStepHandler {
static final SarSubsystemAdd INSTANCE = new SarSubsystemAdd();
private SarSubsystemAdd() {
}
protected void populateModel(ModelNode operation, ModelNode model) {
model.setEmptyObject();
}
protected void performBoottime(final OperationContext context, ModelNode operation, ModelNode model) {
context.addStep(new AbstractDeploymentChainStep() {
public void execute(DeploymentProcessorTarget processorTarget) {
ServiceName jmxCapability = context.getCapabilityServiceName(SarExtension.JMX_CAPABILITY, MBeanServer.class);
processorTarget.addDeploymentProcessor(SarExtension.SUBSYSTEM_NAME, Phase.STRUCTURE, Phase.STRUCTURE_SAR_SUB_DEPLOY_CHECK, new SarSubDeploymentProcessor());
processorTarget.addDeploymentProcessor(SarExtension.SUBSYSTEM_NAME, Phase.STRUCTURE, Phase.STRUCTURE_SAR, new SarStructureProcessor());
processorTarget.addDeploymentProcessor(SarExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_SAR_MODULE, new SarModuleDependencyProcessor());
processorTarget.addDeploymentProcessor(SarExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_SERVICE_DEPLOYMENT, new ServiceDeploymentParsingProcessor());
processorTarget.addDeploymentProcessor(SarExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_SAR_SERVICE_COMPONENT, new ServiceComponentProcessor());
processorTarget.addDeploymentProcessor(SarExtension.SUBSYSTEM_NAME, Phase.INSTALL, Phase.INSTALL_SERVICE_DEPLOYMENT, new ParsedServiceDeploymentProcessor(jmxCapability));
}
}, OperationContext.Stage.RUNTIME);
}
}
| 3,302 | 47.573529 | 186 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/CreateDestroyService.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.service;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.server.deployment.SetupAction;
import org.jboss.as.service.component.ServiceComponentInstantiator;
import org.jboss.as.service.logging.SarLogger;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* Service wrapper for legacy JBoss services that controls the service create and destroy lifecycle.
*
* @author John E. Bailey
* @author <a href="mailto:[email protected]">Richard Opalka</a>
* @author Eduardo Martins
*/
final class CreateDestroyService extends AbstractService {
private final Method createMethod;
private final Method destroyMethod;
private final ServiceComponentInstantiator componentInstantiator;
private final Map<Method, Supplier<Object>> injections = new HashMap<>();
private ManagedReference managedReference;
CreateDestroyService(final Object mBeanInstance, final Method createMethod, final Method destroyMethod, ServiceComponentInstantiator componentInstantiator,
List<SetupAction> setupActions, final ClassLoader mbeanContextClassLoader, final Consumer<Object> mBeanInstanceConsumer, final Supplier<ExecutorService> executorSupplier) {
super(mBeanInstance, setupActions, mbeanContextClassLoader, mBeanInstanceConsumer, executorSupplier);
this.createMethod = createMethod;
this.destroyMethod = destroyMethod;
this.componentInstantiator = componentInstantiator;
}
/** {@inheritDoc} */
public void start(final StartContext context) {
super.start(context);
if (SarLogger.ROOT_LOGGER.isTraceEnabled()) {
SarLogger.ROOT_LOGGER.tracef("Creating Service: %s", context.getController().getName());
}
final Runnable task = new Runnable() {
@Override
public void run() {
try {
injectDependencies();
invokeLifecycleMethod(createMethod, context);
if (componentInstantiator != null) {
managedReference = componentInstantiator.initializeInstance(mBeanInstance);
}
context.complete();
} catch (Throwable e) {
uninjectDependencies();
context.failed(new StartException(SarLogger.ROOT_LOGGER.failedExecutingLegacyMethod("create()"), e));
}
}
};
try {
executorSupplier.get().submit(task);
} catch (RejectedExecutionException e) {
task.run();
} finally {
context.asynchronous();
}
}
/** {@inheritDoc} */
public void stop(final StopContext context) {
super.stop(context);
if (SarLogger.ROOT_LOGGER.isTraceEnabled()) {
SarLogger.ROOT_LOGGER.tracef("Destroying Service: %s", context.getController().getName());
}
final Runnable task = new Runnable() {
@Override
public void run() {
try {
if(managedReference != null) {
managedReference.release();
}
invokeLifecycleMethod(destroyMethod, context);
} catch (Exception e) {
SarLogger.ROOT_LOGGER.error(SarLogger.ROOT_LOGGER.failedExecutingLegacyMethod("destroy()"), e);
} finally {
uninjectDependencies();
context.complete();
}
}
};
try {
executorSupplier.get().submit(task);
} catch (RejectedExecutionException e) {
task.run();
} finally {
context.asynchronous();
}
}
void inject(final Method setter, final Supplier<Object> injectionSupplier) {
injections.put(setter, injectionSupplier);
}
private void injectDependencies() throws IllegalAccessException, InvocationTargetException {
Method setter;
Object arg;
for (final Entry<Method, Supplier<Object>> injection : injections.entrySet()) {
setter = injection.getKey();
arg = injection.getValue().get();
setter.invoke(mBeanInstance, arg);
}
}
private void uninjectDependencies() {
Method setter;
for (final Entry<Method, Supplier<Object>> injection : injections.entrySet()) {
try {
setter = injection.getKey();
setter.invoke(mBeanInstance, (Object[]) null);
} catch (final Throwable ignored) {}
}
}
}
| 6,094 | 38.322581 | 197 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/SarModuleDependencyProcessor.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.service;
import javax.management.MBeanTrustPermission;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.module.ModuleDependency;
import org.jboss.as.server.deployment.module.ModuleSpecification;
import org.jboss.as.service.descriptor.JBossServiceXmlDescriptor;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.security.ImmediatePermissionFactory;
/**
*
* @author <a href="[email protected]">Kabir Khan</a>
* @version $Revision: 1.1 $
*/
public class SarModuleDependencyProcessor implements DeploymentUnitProcessor {
private static final ModuleIdentifier JBOSS_MODULES_ID = ModuleIdentifier.create("org.jboss.modules");
private static final ModuleIdentifier JBOSS_AS_SYSTEM_JMX_ID = ModuleIdentifier.create("org.jboss.as.system-jmx");
private static final ModuleIdentifier PROPERTIES_EDITOR_MODULE_ID = ModuleIdentifier.create("org.jboss.common-beans");
private static final ImmediatePermissionFactory REGISTER_PERMISSION_FACTORY = new ImmediatePermissionFactory(new MBeanTrustPermission("register"));
/**
* Add dependencies for modules required for manged bean deployments, if managed bean configurations are attached
* to the deployment.
*
* @param phaseContext the deployment unit context
* @throws DeploymentUnitProcessingException
*/
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);
final JBossServiceXmlDescriptor serviceXmlDescriptor = deploymentUnit.getAttachment(JBossServiceXmlDescriptor.ATTACHMENT_KEY);
if(serviceXmlDescriptor == null) {
return; // Skip deployments with out a service xml descriptor
}
moduleSpecification.addSystemDependency(new ModuleDependency(Module.getBootModuleLoader(), JBOSS_MODULES_ID, false, false, false, false));
moduleSpecification.addSystemDependency(new ModuleDependency(Module.getBootModuleLoader(), JBOSS_AS_SYSTEM_JMX_ID, true, false, false, false));
// depend on Properties editor module which uses ServiceLoader approach to load the appropriate org.jboss.common.beans.property.finder.PropertyEditorFinder
moduleSpecification.addSystemDependency(new ModuleDependency(Module.getBootModuleLoader(), PROPERTIES_EDITOR_MODULE_ID, false, false, true, false));
// All SARs require the ability to register MBeans.
moduleSpecification.addPermissionFactory(REGISTER_PERMISSION_FACTORY);
}
}
| 4,024 | 51.960526 | 163 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/MBeanServices.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.service;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.function.Consumer;
import java.util.function.Supplier;
import javax.management.MBeanServer;
import org.jboss.as.controller.AbstractControllerService;
import org.jboss.as.server.deployment.SetupAction;
import org.jboss.as.server.deployment.reflect.ClassReflectionIndex;
import org.jboss.as.service.component.ServiceComponentInstantiator;
import org.jboss.as.service.logging.SarLogger;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
/**
* Services associated with MBean responsible for dependencies & injection management.
*
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
final class MBeanServices {
private static final String CREATE_METHOD_NAME = "create";
private static final String DESTROY_METHOD_NAME = "destroy";
private static final String START_METHOD_NAME = "start";
private static final String STOP_METHOD_NAME = "stop";
private final CreateDestroyService createDestroyService;
private final ServiceBuilder<?> createDestroyServiceBuilder;
private final ServiceBuilder<?> startStopServiceBuilder;
private final ServiceBuilder<?> registerUnregisterServiceBuilder;
private boolean installed;
MBeanServices(final String mBeanName, final Object mBeanInstance, final List<ClassReflectionIndex> mBeanClassHierarchy,
final ServiceTarget target, final ServiceComponentInstantiator componentInstantiator,
final List<SetupAction> setupActions, final ClassLoader mbeanContextClassLoader, final ServiceName mbeanServerServiceName) {
if (mBeanClassHierarchy == null) {
throw SarLogger.ROOT_LOGGER.nullVar("mBeanClassHierarchy");
}
if (mBeanInstance == null) {
throw SarLogger.ROOT_LOGGER.nullVar("mBeanInstance");
}
if (target == null) {
throw SarLogger.ROOT_LOGGER.nullVar("target");
}
if (mbeanServerServiceName == null) {
throw SarLogger.ROOT_LOGGER.nullVar("mbeanServerServiceName");
}
final Method createMethod = ReflectionUtils.getNoArgMethod(mBeanClassHierarchy, CREATE_METHOD_NAME);
final Method destroyMethod = ReflectionUtils.getNoArgMethod(mBeanClassHierarchy, DESTROY_METHOD_NAME);
ServiceName createDestroyServiceName = ServiceNameFactory.newCreateDestroy(mBeanName);
createDestroyServiceBuilder = target.addService(createDestroyServiceName);
Consumer<Object> mBeanInstanceConsumer = createDestroyServiceBuilder.provides(createDestroyServiceName);
Supplier<ExecutorService> executorSupplier = createDestroyServiceBuilder.requires(AbstractControllerService.EXECUTOR_CAPABILITY.getCapabilityServiceName());
createDestroyService = new CreateDestroyService(mBeanInstance, createMethod, destroyMethod, componentInstantiator, setupActions, mbeanContextClassLoader, mBeanInstanceConsumer, executorSupplier);
createDestroyServiceBuilder.setInstance(createDestroyService);
if(componentInstantiator != null) {
// the service that starts the EE component needs to start first
createDestroyServiceBuilder.requires(componentInstantiator.getComponentStartServiceName());
}
final Method startMethod = ReflectionUtils.getNoArgMethod(mBeanClassHierarchy, START_METHOD_NAME);
final Method stopMethod = ReflectionUtils.getNoArgMethod(mBeanClassHierarchy, STOP_METHOD_NAME);
ServiceName startStopServiceName = ServiceNameFactory.newStartStop(mBeanName);
startStopServiceBuilder = target.addService(startStopServiceName);
mBeanInstanceConsumer = startStopServiceBuilder.provides(startStopServiceName);
executorSupplier = startStopServiceBuilder.requires(AbstractControllerService.EXECUTOR_CAPABILITY.getCapabilityServiceName());
StartStopService startStopService = new StartStopService(mBeanInstance, startMethod, stopMethod, setupActions, mbeanContextClassLoader, mBeanInstanceConsumer, executorSupplier);
startStopServiceBuilder.setInstance(startStopService);
startStopServiceBuilder.requires(createDestroyServiceName);
ServiceName registerUnregisterServiceName = ServiceNameFactory.newRegisterUnregister(mBeanName);
registerUnregisterServiceBuilder = target.addService(registerUnregisterServiceName);
// register with the legacy alias as well
registerUnregisterServiceBuilder.provides(registerUnregisterServiceName, MBeanRegistrationService.SERVICE_NAME.append(mBeanName));
final Supplier<MBeanServer> mBeanServerSupplier = registerUnregisterServiceBuilder.requires(mbeanServerServiceName);
final Supplier<Object> objectSupplier = registerUnregisterServiceBuilder.requires(startStopServiceName);
registerUnregisterServiceBuilder.setInstance(new MBeanRegistrationService(mBeanName, setupActions, mBeanServerSupplier, objectSupplier));
for (SetupAction action : setupActions) {
for (ServiceName dependency : action.dependencies()) {
startStopServiceBuilder.requires(dependency);
createDestroyServiceBuilder.requires(dependency);
}
}
}
void addDependency(final String dependencyMBeanName) {
assertState();
final ServiceName injectedMBeanCreateDestroyServiceName = ServiceNameFactory.newCreateDestroy(dependencyMBeanName);
createDestroyServiceBuilder.requires(injectedMBeanCreateDestroyServiceName);
final ServiceName injectedMBeanStartStopServiceName = ServiceNameFactory.newStartStop(dependencyMBeanName);
startStopServiceBuilder.requires(injectedMBeanStartStopServiceName);
final ServiceName injectedMBeanRegisterUnregisterServiceName = ServiceNameFactory.newRegisterUnregister(dependencyMBeanName);
registerUnregisterServiceBuilder.requires(injectedMBeanRegisterUnregisterServiceName);
}
void addAttribute(final String attributeMBeanName, final Method setter, final DelegatingSupplier propertySupplier) {
assertState();
final ServiceName injectedMBeanCreateDestroyServiceName = ServiceNameFactory.newCreateDestroy(attributeMBeanName);
final Supplier<Object> injectedMBeanSupplier = createDestroyServiceBuilder.requires(injectedMBeanCreateDestroyServiceName);
propertySupplier.setObjectSupplier(injectedMBeanSupplier);
createDestroyService.inject(setter, propertySupplier);
final ServiceName injectedMBeanStartStopServiceName = ServiceNameFactory.newStartStop(attributeMBeanName);
startStopServiceBuilder.requires(injectedMBeanStartStopServiceName);
}
void addValue(final Method setter, final Supplier<Object> objectSupplier) {
assertState();
createDestroyService.inject(setter, objectSupplier);
}
void install() {
assertState();
createDestroyServiceBuilder.install();
startStopServiceBuilder.install();
registerUnregisterServiceBuilder.install();
installed = true;
}
private void assertState() {
if (installed) {
throw new IllegalStateException();
}
}
}
| 8,376 | 52.698718 | 203 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/ObjectSupplier.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.service;
import java.util.function.Supplier;
/**
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
final class ObjectSupplier implements Supplier<Object> {
private final Object object;
ObjectSupplier(final Object object) {
this.object = object;
}
@Override
public Object get() {
return object;
}
}
| 1,409 | 31.045455 | 70 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/PropertySupplier.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.service;
import java.lang.reflect.InvocationTargetException;
import java.util.function.Supplier;
/**
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
final class PropertySupplier extends DelegatingSupplier {
private final String propertyName;
PropertySupplier(final String propertyName) {
this.propertyName = propertyName;
}
@Override
public Object get() {
final Supplier<Object> objectSupplier = this.objectSupplier;
if (objectSupplier == null) {
throw new IllegalStateException("Object supplier not available");
}
final Object o = objectSupplier.get();
if (o == null) {
throw new IllegalStateException("Object not available");
}
if (propertyName != null) {
try {
return ReflectionUtils.getGetter(o.getClass(), propertyName).invoke(o, (Object[]) null);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Method is not accessible", e);
} catch (InvocationTargetException e) {
throw new IllegalStateException("Failed to invoke method", e);
}
} else {
return o;
}
}
}
| 2,294 | 34.859375 | 104 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/ServiceAttachments.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.service;
import java.util.Map;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.service.component.ServiceComponentInstantiator;
/**
* @author Eduardo Martins
*/
public class ServiceAttachments {
public static final AttachmentKey<Map<String, ServiceComponentInstantiator>> SERVICE_COMPONENT_INSTANTIATORS = AttachmentKey
.<Map<String, ServiceComponentInstantiator>> create(Map.class);
private ServiceAttachments() {
}
}
| 1,512 | 35.902439 | 128 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/SarSubDeploymentProcessor.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.service;
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.SubDeploymentMarker;
import org.jboss.as.server.deployment.module.ModuleRootMarker;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.vfs.VirtualFile;
import java.util.List;
/**
* Deployment processor used to determine if a possible sub-deployment contains a service descriptor.
*
* @author John Bailey
*/
public class SarSubDeploymentProcessor implements DeploymentUnitProcessor {
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (deploymentUnit.getParent() != null) {
return;
}
final List<ResourceRoot> resourceRoots = deploymentUnit.getAttachmentList(Attachments.RESOURCE_ROOTS);
for (ResourceRoot resourceRoot : resourceRoots) {
final VirtualFile rootFile = resourceRoot.getRoot();
if (!SubDeploymentMarker.isSubDeployment(resourceRoot)) {
final VirtualFile sarDescriptor = rootFile
.getChild(ServiceDeploymentParsingProcessor.SERVICE_DESCRIPTOR_PATH);
if (sarDescriptor.exists()) {
SubDeploymentMarker.mark(resourceRoot);
ModuleRootMarker.mark(resourceRoot);
}
}
}
}
}
| 2,750 | 42.666667 | 110 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/ReflectionUtils.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.service;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.jboss.as.server.deployment.reflect.ClassReflectionIndex;
import org.jboss.as.service.logging.SarLogger;
/**
* Reflection utility methods.
*
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
final class ReflectionUtils {
private static final Class<?>[] NO_ARGS = new Class<?>[0];
private ReflectionUtils() {
// forbidden instantiation
}
static Method getGetter(final Class<?> clazz, final String propertyName) {
final String getterName = "get" + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1);
final String iserName = "is" + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1);
try {
return clazz.getMethod(getterName, NO_ARGS);
} catch (NoSuchMethodException e) {
// ignore for now - might be a boolean property
}
try {
return clazz.getMethod(iserName, NO_ARGS);
} catch (NoSuchMethodException e) {
final String className = clazz.getName();
throw SarLogger.ROOT_LOGGER.propertyMethodNotFound("Get", propertyName, className);
}
}
static Method getSetter(final List<ClassReflectionIndex> classHierarchy, final String propertyName) {
final String setterName = "set" + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1);
for (final ClassReflectionIndex classIndex : classHierarchy) {
final Iterator<Method> methods = classIndex.getMethods().iterator();
Method method;
while (methods.hasNext()) {
method = methods.next();
if (setterName.equals(method.getName()) && method.getParameterCount() == 1) {
return method;
}
}
}
final String className = classHierarchy.get(0).getIndexedClass().getName();
throw SarLogger.ROOT_LOGGER.propertyMethodNotFound("Set", propertyName, className);
}
public static Method getMethod(Class<?> clazz, String methodName, Class<?>[] argumentList) {
try {
return clazz.getMethod(methodName, argumentList);
} catch (NoSuchMethodException e) {
throw SarLogger.ROOT_LOGGER.methodNotFound(methodName, parameterList(argumentList), clazz.getName());
}
}
static Method getNoArgMethod(final List<ClassReflectionIndex> classHierarchy, final String methodName) {
for (final ClassReflectionIndex classIndex : classHierarchy) {
final Collection<Method> methods = classIndex.getMethods(methodName, NO_ARGS);
if (methods.size() == 1) {
return methods.iterator().next();
}
}
return null;
}
static Object newInstance(final Constructor<?> constructor, final Object[] args) {
try {
return constructor.newInstance(args);
} catch (Exception e) {
throw SarLogger.ROOT_LOGGER.classNotInstantiated(e);
}
}
static Class<?> getClass(final String className, final ClassLoader classLoader) {
try {
return Class.forName(className, false, classLoader);
} catch (final ClassNotFoundException e) {
throw SarLogger.ROOT_LOGGER.classNotFound(e);
}
}
private static String parameterList(final Class<?>[] parameterTypes) {
final StringBuilder result = new StringBuilder();
if (parameterTypes != null && parameterTypes.length > 0) {
result.append(parameterTypes[0]);
for (int i = 1; i < parameterTypes.length; i++) {
result.append(", ").append(parameterTypes[i]);
}
}
return result.toString();
}
}
| 4,969 | 37.527132 | 116 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/ValueFactorySupplier.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.service;
import java.lang.reflect.InvocationTargetException;
import java.util.function.Supplier;
/**
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
final class ValueFactorySupplier extends DelegatingSupplier {
private final String methodName;
private final Class<?>[] paramTypes;
private final Object[] args;
ValueFactorySupplier(final String methodName, final Class<?>[] paramTypes, final Object[] args) {
this.methodName = methodName;
this.paramTypes = paramTypes;
this.args = args;
}
@Override
public Object get() {
final Supplier<Object> objectSupplier = this.objectSupplier;
if (objectSupplier == null) {
throw new IllegalStateException("Object supplier not available");
}
final Object o = objectSupplier.get();
if (o == null) {
throw new IllegalStateException("Object not available");
}
try {
return ReflectionUtils.getMethod(o.getClass(), methodName, paramTypes).invoke(o, args);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Method is not accessible", e);
} catch (InvocationTargetException e) {
throw new IllegalStateException("Failed to invoke method", e);
}
}
}
| 2,367 | 36.587302 | 101 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/ServiceNameFactory.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.service;
import org.jboss.as.service.logging.SarLogger;
import org.jboss.msc.service.ServiceName;
/**
* Utility class for creating mBean service names.
*
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
final class ServiceNameFactory {
private static final ServiceName MBEAN_SERVICE_NAME_BASE = ServiceName.JBOSS.append("mbean","service");
private static final String CREATE_SUFFIX = "create";
private static final String START_SUFFIX = "start";
private static final String REGISTRATION_SUFFIX = "registration";
private ServiceNameFactory() {
// forbidden instantiation
}
static ServiceName newCreateDestroy(final String mBeanName) {
return newServiceName(mBeanName).append(CREATE_SUFFIX);
}
static ServiceName newStartStop(final String mBeanName) {
return newServiceName(mBeanName).append(START_SUFFIX);
}
static ServiceName newRegisterUnregister(final String mBeanName) {
return newServiceName(mBeanName).append(REGISTRATION_SUFFIX);
}
private static ServiceName newServiceName(final String name) {
if(name == null) {
throw SarLogger.ROOT_LOGGER.nullVar("name");
}
return MBEAN_SERVICE_NAME_BASE.append(name);
}
}
| 2,316 | 35.777778 | 107 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/logging/SarLogger.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.service.logging;
import static org.jboss.logging.Logger.Level.ERROR;
import static org.jboss.logging.Logger.Level.WARN;
import javax.xml.namespace.QName;
import javax.management.ObjectName;
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.vfs.VirtualFile;
import org.jboss.msc.service.StartException;
/**
* @author <a href="mailto:[email protected]">James R. Perkins</a>
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
@MessageLogger(projectCode = "WFLYSAR", length = 4)
public interface SarLogger extends BasicLogger {
/**
* A logger with a category of the package name.
*/
SarLogger ROOT_LOGGER = Logger.getMessageLogger(SarLogger.class, "org.jboss.as.service");
/**
* A message indicating a failure to execute a legacy service method, represented by the {@code methodName}
* parameter.
*
* @param methodName the name of the method that failed to execute.
*
* @return the message
*/
@Message(id = 1, value = "Failed to execute legacy service %s method")
String failedExecutingLegacyMethod(String methodName);
/**
* Logs a warning message indicating the inability to find a {@link java.beans.PropertyEditor} for the type.
*
* @param type the type.
*/
@LogMessage(level = WARN)
@Message(id = 2, value = "Unable to find PropertyEditor for type %s")
void propertyNotFound(Class<?> type);
/**
* Creates an exception indicating the class could not be found.
*
* @param cause the cause of the error.
*
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 3, value = "Class not found")
IllegalArgumentException classNotFound(@Cause Throwable cause);
/**
* Creates an exception indicating the class was not instantiated.
*
* @param cause the cause of the error.
*
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 4, value = "Class not instantiated")
IllegalArgumentException classNotInstantiated(@Cause Throwable cause);
/**
* Creates an exception indicating a failure to get an attachment.
*
* @param attachmentType the type/name of the attachment.
* @param deploymentUnit the deployment unit.
*
* @return a {@link org.jboss.as.server.deployment.DeploymentUnitProcessingException} for the error.
*/
@Message(id = 5, value = "Failed to get %s attachment for %s")
DeploymentUnitProcessingException failedToGetAttachment(String attachmentType, DeploymentUnit deploymentUnit);
/**
* Creates an exception indicating a failure to parse the service XML file.
*
* @param xmlFile the XML file that failed to parse.
*
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 6, value = "Failed to parse service xml [%s]")
DeploymentUnitProcessingException failedXmlParsing(VirtualFile xmlFile);
/**
* Creates an exception indicating a failure to parse the service XML file.
*
* @param cause the cause of the error.
* @param xmlFile the XML file that failed to parse.
*
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
DeploymentUnitProcessingException failedXmlParsing(@Cause Throwable cause, VirtualFile xmlFile);
/**
* Creates an exception indicating the method could not be found.
*
* @param methodName the name of the method.
* @param methodParams the method parameters.
* @param className the name of the class.
*
* @return an {@link IllegalStateException} for the error.
*/
@Message(id = 7, value = "Method '%s(%s)' not found for: %s")
IllegalStateException methodNotFound(String methodName, String methodParams, String className);
/**
* A message indicating one or more required attributes are missing.
*
* @return the message.
*/
@Message(id = 8, value = "Missing one or more required attributes:")
String missingRequiredAttributes();
/**
* Creates an exception indicating the variable, represented by the {@code name} parameter, is {@code null}.
*
* @param name the name of the variable.
*
* @return an {@link IllegalArgumentException} for the error.
*/
@Message(id = 9, value = "%s is null")
IllegalArgumentException nullVar(String name);
/**
* Creates an exception indicating the method for the property is not found.
*
* @param methodPrefix the prefix for the method, e.g. {@code get} or {@code set}.
* @param propertyName the name of the property.
* @param className the class the property was being queried on.
*
* @return an {@link IllegalStateException} for the error.
*/
@Message(id = 10, value = "%s method for property '%s' not found for: %s")
IllegalStateException propertyMethodNotFound(String methodPrefix, String propertyName, String className);
/**
* A message indicating unexpected content was found.
*
* @param kind the kind of content.
* @param name the name of the attribute.
* @param text the value text of the attribute.
*
* @return the message.
*/
@Message(id = 11, value = "Unexpected content of type '%s' named '%s', text is: %s")
String unexpectedContent(String kind, QName name, String text);
/**
* Creates an exception indicating a failure to process the resource adapter child archives for the deployment root
* represented by the {@code deploymentRoot} parameter.
*
* @param cause the cause of the error.
* @param deploymentRoot the deployment root.
*
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 12, value = "Failed to process SAR child archives for [%s]")
DeploymentUnitProcessingException failedToProcessSarChild(@Cause Throwable cause, VirtualFile deploymentRoot);
/**
* Creates an exception indicating that dependency of mbean was malformed in service descriptor.
*
* @param cause MalformedObjectNameException.
* @param dependencyName the name of malformed dependency.
*
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 13, value = "Malformed dependency name %s")
DeploymentUnitProcessingException malformedDependencyName(@Cause Throwable cause, String dependencyName);
/**
* Creates an exception indicating the default constructor for the class, represented by the {@code clazz} parameter, could
* not be found.
*
* @param clazz the class.
*
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 14, value = "Could not find default constructor for %s")
DeploymentUnitProcessingException defaultConstructorNotFound(Class<?> clazz);
/**
* Creates an exception indicating a failure to register the MBean.
*
* @param cause the cause of the error.
* @param name the name of the MBean.
*
* @return a {@link StartException} for the error.
*/
@Message(id = 15, value = "Failed to register mbean [%s]")
StartException mbeanRegistrationFailed(@Cause Throwable cause, String name);
/**
* Logs a warning message indicating no {@link javax.management.ObjectName} is available to unregister.
*/
@LogMessage(level = WARN)
@Message(id = 16, value = "No ObjectName available to unregister")
void cannotUnregisterObject();
/**
* Logs an error message indicating a failure to unregister the object name.
*
* @param cause the cause of the error.
* @param name the name of the object name.
*/
@LogMessage(level = ERROR)
@Message(id = 17, value = "Failed to unregister [%s]")
void unregistrationFailure(@Cause Throwable cause, ObjectName name);
}
| 9,349 | 37.636364 | 127 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/descriptor/JBossServiceDependencyListConfig.java
|
package org.jboss.as.service.descriptor;
import java.io.Serializable;
public class JBossServiceDependencyListConfig implements Serializable {
private static final long serialVersionUID = 634835167098065568L;
private String optionalAttributeName;
private JBossServiceDependencyConfig[] dependencyConfigs;
public String getOptionalAttributeName() {
return optionalAttributeName;
}
public void setOptionalAttributeName(String optionalAttributeName) {
this.optionalAttributeName = optionalAttributeName;
}
public JBossServiceDependencyConfig[] getDependencyConfigs() {
return dependencyConfigs;
}
public void setDependencyConfigs(JBossServiceDependencyConfig[] dependencyConfigs) {
this.dependencyConfigs = dependencyConfigs;
}
}
| 807 | 31.32 | 88 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/descriptor/JBossServiceAttributeConfig.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.service.descriptor;
import java.io.Serializable;
/**
* Configuration for a service attribute.
*
* @author John E. Bailey
*/
public class JBossServiceAttributeConfig implements Serializable {
private static final long serialVersionUID = 7859894445434159600L;
private String name;
private boolean replace;
private boolean trim;
private String value;
private ValueFactory valueFactory;
private Inject inject;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public boolean isReplace() {
return replace;
}
public void setReplace(boolean replace) {
this.replace = replace;
}
public boolean isTrim() {
return trim;
}
public void setTrim(boolean trim) {
this.trim = trim;
}
public ValueFactory getValueFactory() {
return valueFactory;
}
public void setValueFactory(ValueFactory valueFactory) {
this.valueFactory = valueFactory;
}
public Inject getInject() {
return inject;
}
public void setInject(Inject inject) {
this.inject = inject;
}
public static class ValueFactory implements Serializable {
private static final long serialVersionUID = 2524264651820839136L;
private String beanName;
private String methodName;
private ValueFactoryParameter[] parameters;
public String getBeanName() {
return beanName;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public ValueFactoryParameter[] getParameters() {
return parameters;
}
public void setParameters(ValueFactoryParameter[] parameters) {
this.parameters = parameters;
}
}
public static class ValueFactoryParameter implements Serializable {
private static final long serialVersionUID = -1980437946334603841L;
private String type;
private String value;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public static class Inject implements Serializable {
private static final long serialVersionUID = 7644229980407045584L;
private String beanName;
private String propertyName;
public String getBeanName() {
return beanName;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public String getPropertyName() {
return propertyName;
}
public void setPropertyName(String propertyName) {
this.propertyName = propertyName;
}
}
}
| 4,342 | 25.005988 | 75 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/descriptor/ParseResult.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.service.descriptor;
/**
* The result of a parsing operation.
*
* @param <T> the parse result type
*
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
public final class ParseResult<T> {
private T result;
/**
* Set the result.
*
* @param result the parsing result
*/
public void setResult(T result) {
this.result = result;
}
/**
* Get the result.
*
* @return the parsing result
*/
public T getResult() {
return result;
}
}
| 1,583 | 28.333333 | 70 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/descriptor/JBossServiceConstructorConfig.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.service.descriptor;
import java.io.Serializable;
/**
* Configuration object for a JBoss service constructor.
*
* @author John E. Bailey
*/
public class JBossServiceConstructorConfig implements Serializable {
private static final long serialVersionUID = -4307592928958905408L;
public static final Argument[] EMPTY_ARGS = {};
private Argument[] arguments = EMPTY_ARGS;
public Argument[] getArguments() {
return arguments;
}
public void setArguments(Argument[] arguments) {
this.arguments = arguments;
}
public static class Argument implements Serializable {
private static final long serialVersionUID = 7644229980407045584L;
private final String value;
private final String type;
public Argument(final String type, final String value) {
this.value = value;
this.type = type;
}
public String getType() {
return type;
}
public String getValue() {
return value;
}
}
}
| 2,095 | 30.757576 | 74 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/descriptor/JBossServiceDependencyConfig.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.service.descriptor;
import java.io.Serializable;
/**
* Configuration for a service dependency.
*
* @author John E. Bailey
*/
public class JBossServiceDependencyConfig implements Serializable {
private static final long serialVersionUID = 7058092116435789802L;
private String dependencyName;
private JBossServiceConfig serviceConfig;
private String proxyType;
private String optionalAttributeName;
public String getDependencyName() {
return dependencyName;
}
public void setDependencyName(String dependencyName) {
this.dependencyName = dependencyName;
}
public JBossServiceConfig getServiceConfig() {
return serviceConfig;
}
public void setServiceConfig(JBossServiceConfig serviceConfig) {
this.serviceConfig = serviceConfig;
}
public String getProxyType() {
return proxyType;
}
public void setProxyType(String proxyType) {
this.proxyType = proxyType;
}
public String getOptionalAttributeName() {
return optionalAttributeName;
}
public void setOptionalAttributeName(String optionalAttributeName) {
this.optionalAttributeName = optionalAttributeName;
}
}
| 2,261 | 30.416667 | 72 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/descriptor/JBossServiceXmlDescriptorParser.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.service.descriptor;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.stream.Location;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.jboss.as.service.logging.SarLogger;
import org.jboss.metadata.property.PropertyReplacer;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* @author John Bailey
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
* @author Tomasz Adamski
*/
public final class JBossServiceXmlDescriptorParser implements XMLElementReader<ParseResult<JBossServiceXmlDescriptor>>, XMLStreamConstants {
private enum Namespace {
UNKNOWN(null),
NONE(""),
SERVICE_7_0("urn:jboss:service:7.0"),
;
private final String namespace;
private static final Map<String, Namespace> NS_MAP = new HashMap<String, Namespace>();
static {
for (Namespace namespace : Namespace.values()) {
NS_MAP.put(namespace.namespace, namespace);
}
}
private Namespace(String namespace) {
this.namespace = namespace;
}
public static Namespace of(final String uri) {
if (uri == null) return NONE;
final Namespace namespace = NS_MAP.get(uri);
return namespace == null ? UNKNOWN : namespace;
}
}
public static final String NAMESPACE = "urn:jboss:service:7.0";
private enum Element {
UNKNOWN(null),
MBEAN("mbean"),
CONSTRUCTOR("constructor"),
ARG("arg"),
ATTRIBUTE("attribute"),
INJECT("inject"),
VALUE_FACTORY("value-factory"),
PARAMETER("parameter"),
DEPENDS("depends"),
DEPENDS_LIST("depends-list"),
DEPENDS_LIST_ELEMENT("depends-list-element"),
ALIAS("alias"),
ANNOTATION("annotation"),
;
private final String localName;
private static final Map<String, Element> NAME_MAP = new HashMap<String, Element>();
static {
for (Element element : Element.values()) {
NAME_MAP.put(element.localName, element);
}
}
private Element(final String localName) {
this.localName = localName;
}
static Element of(final String localName) {
final Element element = NAME_MAP.get(localName);
return element == null ? UNKNOWN : element;
}
}
private enum Attribute {
MODE(new QName("mode")),
NAME(new QName("name")),
CODE(new QName("code")),
TYPE(new QName("type")),
VALUE(new QName("value")),
TRIM(new QName("trim")),
REPLACE(new QName("replace")),
BEAN(new QName("bean")),
PROPERTY(new QName("property")),
CLASS(new QName("class")),
METHOD(new QName("method")),
OPTIONAL_ATTRIBUTE_NAME(new QName("optional-attribute-name")),
PROXY_TYPE(new QName("proxy-type")),
UNKNOWN(null);
private final QName qName;
private static final Map<QName, Attribute> QNAME_MAP = new HashMap<QName, Attribute>();
static {
for(Attribute attribute : Attribute.values()) {
QNAME_MAP.put(attribute.qName, attribute);
}
}
private Attribute(final QName qName) {
this.qName = qName;
}
static Attribute of(QName qName) {
final Attribute attribute = QNAME_MAP.get(qName);
return attribute == null ? UNKNOWN : attribute;
}
}
private final PropertyReplacer propertyReplacer;
public JBossServiceXmlDescriptorParser(final PropertyReplacer propertyReplacer) {
this.propertyReplacer = propertyReplacer;
}
@Override
public void readElement(final XMLExtendedStreamReader reader, final ParseResult<JBossServiceXmlDescriptor> value) throws XMLStreamException {
final JBossServiceXmlDescriptor serviceXmlDescriptor = new JBossServiceXmlDescriptor();
final List<JBossServiceConfig> serviceConfigs = new ArrayList<JBossServiceConfig>();
serviceXmlDescriptor.setServiceConfigs(serviceConfigs);
value.setResult(serviceXmlDescriptor);
final int count = reader.getAttributeCount();
for(int i = 0; i < count; i++) {
final QName attributeName = reader.getAttributeName(i);
final Attribute attribute = Attribute.of(attributeName);
final String attributeValue = reader.getAttributeValue(i);
switch(attribute) {
case MODE:
serviceXmlDescriptor.setControllerMode(JBossServiceXmlDescriptor.ControllerMode.of(attributeValue));
break;
}
}
while (reader.hasNext()) {
switch (reader.nextTag()) {
case COMMENT:
break;
case END_ELEMENT:
return;
case START_ELEMENT:
switch (Namespace.of(reader.getNamespaceURI())) {
case NONE:
case SERVICE_7_0: {
break;
}
default: throw unexpectedContent(reader);
}
switch (Element.of(reader.getLocalName())) {
case MBEAN:
serviceConfigs.add(parseMBean(reader));
break;
default:
throw unexpectedContent(reader);
}
break;
}
}
}
private JBossServiceConfig parseMBean(final XMLExtendedStreamReader reader) throws XMLStreamException {
// Handle Attributes
final JBossServiceConfig serviceConfig = new JBossServiceConfig();
final int count = reader.getAttributeCount();
final Set<Attribute> required = EnumSet.of(Attribute.NAME, Attribute.CODE);
for(int i = 0; i < count; i++) {
final Attribute attribute = Attribute.of(reader.getAttributeName(i));
required.remove(attribute);
final String attributeValue = reader.getAttributeValue(i);
switch(attribute) {
case NAME:
serviceConfig.setName(attributeValue);
break;
case CODE:
serviceConfig.setCode(attributeValue);
break;
default:
throw unexpectedContent(reader);
}
}
if(!required.isEmpty()) {
throw missingAttributes(reader.getLocation(), required);
}
final List<JBossServiceDependencyConfig> dependencyConfigs = new ArrayList<JBossServiceDependencyConfig>();
final List<JBossServiceDependencyListConfig> dependencyListConfigs = new ArrayList<JBossServiceDependencyListConfig>();
final List<JBossServiceAttributeConfig> attributes = new ArrayList<JBossServiceAttributeConfig>();
final List<String> aliases = new ArrayList<String>();
final List<String> annotations = new ArrayList<String>();
while (reader.hasNext()) {
switch (reader.nextTag()) {
case END_ELEMENT:
serviceConfig.setDependencyConfigs(dependencyConfigs.toArray(new JBossServiceDependencyConfig[dependencyConfigs.size()]));
serviceConfig.setDependencyConfigLists(dependencyListConfigs.toArray(new JBossServiceDependencyListConfig[dependencyListConfigs.size()]));
serviceConfig.setAliases(aliases.toArray(new String[aliases.size()]));
serviceConfig.setAnnotations(annotations.toArray(new String[annotations.size()]));
serviceConfig.setAttributeConfigs(attributes.toArray(new JBossServiceAttributeConfig[attributes.size()]));
return serviceConfig;
case START_ELEMENT:
switch (Namespace.of(reader.getNamespaceURI())) {
case NONE:
case SERVICE_7_0: {
break;
}
default: throw unexpectedContent(reader);
}
switch(Element.of(reader.getLocalName())) {
case CONSTRUCTOR:
serviceConfig.setConstructorConfig(parseConstructor(reader));
break;
case DEPENDS:
dependencyConfigs.add(parseDepends(reader));
break;
case DEPENDS_LIST:
dependencyListConfigs.add(parseDependsList(reader));
break;
case ALIAS:
aliases.add(parseTextElement(reader));
break;
case ANNOTATION:
annotations.add(parseTextElement(reader));
break;
case ATTRIBUTE:
attributes.add(parseAttribute(reader));
break;
default:
throw unexpectedContent(reader);
}
break;
}
}
throw unexpectedContent(reader);
}
private JBossServiceConstructorConfig parseConstructor(final XMLExtendedStreamReader reader) throws XMLStreamException {
final JBossServiceConstructorConfig constructorConfig = new JBossServiceConstructorConfig();
final List<JBossServiceConstructorConfig.Argument> arguments = new ArrayList<JBossServiceConstructorConfig.Argument>();
while (reader.hasNext()) {
switch (reader.nextTag()) {
case END_ELEMENT:
constructorConfig.setArguments(arguments.toArray(new JBossServiceConstructorConfig.Argument[arguments.size()]));
return constructorConfig;
case START_ELEMENT:
switch (Namespace.of(reader.getNamespaceURI())) {
case NONE:
case SERVICE_7_0: {
break;
}
default: throw unexpectedContent(reader);
}
switch(Element.of(reader.getLocalName())) {
case ARG:
arguments.add(parseArgument(reader));
break;
default:
throw unexpectedContent(reader);
}
break;
}
}
throw unexpectedContent(reader);
}
private JBossServiceConstructorConfig.Argument parseArgument(XMLExtendedStreamReader reader) throws XMLStreamException {
String type = null;
String value = null;
final int count = reader.getAttributeCount();
final Set<Attribute> required = EnumSet.of(Attribute.TYPE, Attribute.VALUE);
for(int i = 0; i < count; i++) {
final Attribute attribute = Attribute.of(reader.getAttributeName(i));
required.remove(attribute);
final String attributeValue = reader.getAttributeValue(i);
switch(attribute) {
case TYPE:
type = attributeValue;
break;
case VALUE:
value = attributeValue;
break;
default:
throw unexpectedContent(reader);
}
}
if(!required.isEmpty()) {
throw missingAttributes(reader.getLocation(), required);
}
reader.discardRemainder();
return new JBossServiceConstructorConfig.Argument(type, value);
}
private JBossServiceAttributeConfig parseAttribute(XMLExtendedStreamReader reader) throws XMLStreamException {
final JBossServiceAttributeConfig attributeConfig = new JBossServiceAttributeConfig();
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.getAttributeName(i));
required.remove(attribute);
final String attributeValue = reader.getAttributeValue(i);
switch(attribute) {
case NAME:
attributeConfig.setName(attributeValue);
break;
case TRIM:
attributeConfig.setTrim(Boolean.parseBoolean(attributeValue));
break;
case REPLACE:
attributeConfig.setReplace(Boolean.parseBoolean(attributeValue));
break;
default:
throw unexpectedContent(reader);
}
}
if(!required.isEmpty()) {
throw missingAttributes(reader.getLocation(), required);
}
final StringBuilder valueBuilder = new StringBuilder();
while (reader.hasNext()) {
switch (reader.next()) {
case END_ELEMENT:
attributeConfig.setValue(propertyReplacer.replaceProperties(valueBuilder.toString().trim()));
return attributeConfig;
case START_ELEMENT:
switch (Namespace.of(reader.getNamespaceURI())) {
case NONE:
case SERVICE_7_0: {
break;
}
default: throw unexpectedContent(reader);
}
switch(Element.of(reader.getLocalName())) {
case INJECT:
attributeConfig.setInject(parseInject(reader));
break;
case VALUE_FACTORY:
attributeConfig.setValueFactory(parseValueFactory(reader));
break;
default:
throw unexpectedContent(reader);
}
break;
case CHARACTERS:
valueBuilder.append(reader.getText());
}
}
throw unexpectedContent(reader);
}
private JBossServiceAttributeConfig.Inject parseInject(XMLExtendedStreamReader reader) throws XMLStreamException {
final JBossServiceAttributeConfig.Inject injectConfig = new JBossServiceAttributeConfig.Inject();
final int count = reader.getAttributeCount();
final Set<Attribute> required = EnumSet.of(Attribute.BEAN);
for(int i = 0; i < count; i++) {
final Attribute attribute = Attribute.of(reader.getAttributeName(i));
required.remove(attribute);
final String attributeValue = reader.getAttributeValue(i);
switch(attribute) {
case BEAN:
injectConfig.setBeanName(attributeValue);
break;
case PROPERTY:
injectConfig.setPropertyName(attributeValue);
break;
default:
throw unexpectedContent(reader);
}
}
if(!required.isEmpty()) {
throw missingAttributes(reader.getLocation(), required);
}
reader.discardRemainder();
return injectConfig;
}
private JBossServiceAttributeConfig.ValueFactory parseValueFactory(XMLExtendedStreamReader reader) throws XMLStreamException {
final JBossServiceAttributeConfig.ValueFactory valueFactory = new JBossServiceAttributeConfig.ValueFactory();
final int count = reader.getAttributeCount();
final Set<Attribute> required = EnumSet.of(Attribute.BEAN, Attribute.METHOD);
for(int i = 0; i < count; i++) {
final Attribute attribute = Attribute.of(reader.getAttributeName(i));
required.remove(attribute);
final String attributeValue = reader.getAttributeValue(i);
switch(attribute) {
case BEAN:
valueFactory.setBeanName(attributeValue);
break;
case METHOD:
valueFactory.setMethodName(attributeValue);
break;
default:
throw unexpectedContent(reader);
}
}
if(!required.isEmpty()) {
throw missingAttributes(reader.getLocation(), required);
}
final List<JBossServiceAttributeConfig.ValueFactoryParameter> parameters = new ArrayList<JBossServiceAttributeConfig.ValueFactoryParameter>();
while (reader.hasNext()) {
switch (reader.next()) {
case END_ELEMENT:
valueFactory.setParameters(parameters.toArray(new JBossServiceAttributeConfig.ValueFactoryParameter[parameters.size()]));
return valueFactory;
case START_ELEMENT:
switch (Namespace.of(reader.getNamespaceURI())) {
case NONE:
case SERVICE_7_0: {
break;
}
default: throw unexpectedContent(reader);
}
switch(Element.of(reader.getLocalName())) {
case PARAMETER:
parameters.add(parseValueFactoryParameter(reader));
break;
default:
throw unexpectedContent(reader);
}
break;
}
}
throw unexpectedContent(reader);
}
private JBossServiceAttributeConfig.ValueFactoryParameter parseValueFactoryParameter(XMLExtendedStreamReader reader) throws XMLStreamException {
final JBossServiceAttributeConfig.ValueFactoryParameter parameterConfig = new JBossServiceAttributeConfig.ValueFactoryParameter();
final int count = reader.getAttributeCount();
final Set<Attribute> required = EnumSet.of(Attribute.CLASS);
for(int i = 0; i < count; i++) {
final Attribute attribute = Attribute.of(reader.getAttributeName(i));
required.remove(attribute);
final String attributeValue = reader.getAttributeValue(i);
switch(attribute) {
case CLASS:
parameterConfig.setType(attributeValue);
break;
default:
throw unexpectedContent(reader);
}
}
if(!required.isEmpty()) {
throw missingAttributes(reader.getLocation(), required);
}
while (reader.hasNext()) {
switch (reader.next()) {
case END_ELEMENT:
return parameterConfig;
case CHARACTERS:
parameterConfig.setValue(reader.getText());
break;
}
}
throw unexpectedContent(reader);
}
private JBossServiceDependencyConfig parseDepends(final XMLExtendedStreamReader reader) throws XMLStreamException {
final JBossServiceDependencyConfig dependencyConfig = new JBossServiceDependencyConfig();
final int count = reader.getAttributeCount();
for(int i = 0; i < count; i++) {
final Attribute attribute = Attribute.of(reader.getAttributeName(i));
final String attributeValue = reader.getAttributeValue(i);
switch(attribute) {
case OPTIONAL_ATTRIBUTE_NAME:
dependencyConfig.setOptionalAttributeName(attributeValue);
break;
case PROXY_TYPE:
dependencyConfig.setProxyType(attributeValue);
break;
default:
throw unexpectedContent(reader);
}
}
parseDependency(reader, dependencyConfig);
return dependencyConfig;
}
private JBossServiceDependencyListConfig parseDependsList(final XMLExtendedStreamReader reader) throws XMLStreamException {
final JBossServiceDependencyListConfig dependencyListConfig = new JBossServiceDependencyListConfig();
final List<JBossServiceDependencyConfig> dependencyConfigs = new ArrayList<JBossServiceDependencyConfig>();
String optionalAttributeName = null;
final int count = reader.getAttributeCount();
for(int i = 0; i < count; i++) {
final Attribute attribute = Attribute.of(reader.getAttributeName(i));
final String attributeValue = reader.getAttributeValue(i);
switch(attribute) {
case OPTIONAL_ATTRIBUTE_NAME:
optionalAttributeName = attributeValue;
break;
default:
throw unexpectedContent(reader);
}
}
while (reader.hasNext()) {
switch (reader.next()) {
case END_ELEMENT:
dependencyListConfig.setOptionalAttributeName(optionalAttributeName);
dependencyListConfig.setDependencyConfigs(dependencyConfigs.toArray(new JBossServiceDependencyConfig[dependencyConfigs.size()]));
return dependencyListConfig;
case START_ELEMENT:
switch (Namespace.of(reader.getNamespaceURI())) {
case NONE:
case SERVICE_7_0: {
break;
}
default: throw unexpectedContent(reader);
}
switch(Element.of(reader.getLocalName())) {
case DEPENDS_LIST_ELEMENT:
final JBossServiceDependencyConfig dependencyConfig = new JBossServiceDependencyConfig();
parseDependency(reader, dependencyConfig);
dependencyConfigs.add(dependencyConfig);
break;
default:
throw unexpectedContent(reader);
}
break;
}
}
throw unexpectedContent(reader);
}
private void parseDependency(final XMLExtendedStreamReader reader, final JBossServiceDependencyConfig dependencyConfig) throws XMLStreamException {
final StringBuilder nameBuilder = new StringBuilder();
while (reader.hasNext()) {
switch (reader.next()) {
case END_ELEMENT:
dependencyConfig.setDependencyName(nameBuilder.toString().trim());
return;
case START_ELEMENT:
switch (Namespace.of(reader.getNamespaceURI())) {
case NONE:
case SERVICE_7_0: {
break;
}
default: throw unexpectedContent(reader);
}
switch(Element.of(reader.getLocalName())) {
case MBEAN:
dependencyConfig.setServiceConfig(parseMBean(reader));
break;
default:
throw unexpectedContent(reader);
}
break;
case CHARACTERS:
nameBuilder.append(reader.getText());
break;
}
}
}
private String parseTextElement(final XMLExtendedStreamReader reader) throws XMLStreamException {
final StringBuilder valueBuilder = new StringBuilder();
while (reader.hasNext()) {
switch(reader.next()) {
case END_ELEMENT:
return valueBuilder.toString().trim();
case CHARACTERS:
valueBuilder.append(reader.getText());
break;
}
}
throw unexpectedContent(reader);
}
private static XMLStreamException unexpectedContent(final XMLStreamReader reader) {
final String kind;
switch (reader.getEventType()) {
case XMLStreamConstants.ATTRIBUTE: kind = "attribute"; break;
case XMLStreamConstants.CDATA: kind = "cdata"; break;
case XMLStreamConstants.CHARACTERS: kind = "characters"; break;
case XMLStreamConstants.COMMENT: kind = "comment"; break;
case XMLStreamConstants.DTD: kind = "dtd"; break;
case XMLStreamConstants.END_DOCUMENT: kind = "document end"; break;
case XMLStreamConstants.END_ELEMENT: kind = "element end"; break;
case XMLStreamConstants.ENTITY_DECLARATION: kind = "entity decl"; break;
case XMLStreamConstants.ENTITY_REFERENCE: kind = "entity ref"; break;
case XMLStreamConstants.NAMESPACE: kind = "namespace"; break;
case XMLStreamConstants.NOTATION_DECLARATION: kind = "notation decl"; break;
case XMLStreamConstants.PROCESSING_INSTRUCTION: kind = "processing instruction"; break;
case XMLStreamConstants.SPACE: kind = "whitespace"; break;
case XMLStreamConstants.START_DOCUMENT: kind = "document start"; break;
case XMLStreamConstants.START_ELEMENT: kind = "element start"; break;
default: kind = "unknown"; break;
}
return new XMLStreamException(SarLogger.ROOT_LOGGER.unexpectedContent(kind, reader.getName(), reader.getText()), reader.getLocation());
}
private static XMLStreamException missingAttributes(final Location location, final Set<Attribute> required) {
final StringBuilder b = new StringBuilder(SarLogger.ROOT_LOGGER.missingRequiredAttributes());
for (Attribute attribute : required) {
b.append(' ').append(attribute);
}
return new XMLStreamException(b.toString(), location);
}
}
| 27,616 | 41.553159 | 158 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/descriptor/JBossServiceXmlDescriptor.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.service.descriptor;
import org.jboss.as.server.deployment.AttachmentKey;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The object representation of a legacy "jboss-service.xml" descriptor file.
*
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
public final class JBossServiceXmlDescriptor implements Serializable {
private static final long serialVersionUID = 3148478338698997486L;
public static final AttachmentKey<JBossServiceXmlDescriptor> ATTACHMENT_KEY = AttachmentKey.create(JBossServiceXmlDescriptor.class);
private ControllerMode controllerMode = ControllerMode.PASSIVE;
private List<JBossServiceConfig> serviceConfigs;
public List<JBossServiceConfig> getServiceConfigs() {
return serviceConfigs;
}
public void setServiceConfigs(List<JBossServiceConfig> serviceConfigs) {
this.serviceConfigs = serviceConfigs;
}
public ControllerMode getControllerMode() {
return controllerMode;
}
public void setControllerMode(ControllerMode controllerMode) {
this.controllerMode = controllerMode;
}
public static enum ControllerMode {
ACTIVE("active"), PASSIVE("passive"), ON_DEMAND("on demand"), NEVER("never");
private static final Map<String, ControllerMode> MAP = new HashMap<String, ControllerMode>();
static {
for(ControllerMode mode : ControllerMode.values()) {
MAP.put(mode.value, mode);
}
}
private final String value;
private ControllerMode(final String value) {
this.value = value;
}
static ControllerMode of(String value) {
final ControllerMode controllerMode = MAP.get(value);
return controllerMode == null ? PASSIVE : controllerMode;
}
}
}
| 2,933 | 33.517647 | 136 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/descriptor/JBossServiceConfig.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.service.descriptor;
import java.io.Serializable;
/**
* Configuration for a service coming from a JBoss service XML definition.
*
* @author John E. Bailey
*/
public class JBossServiceConfig implements Serializable {
private static final long serialVersionUID = -1118010052087288568L;
private String name;
private String code;
private String[] aliases;
private String[] annotations;
private JBossServiceDependencyConfig[] dependencyConfigs;
private JBossServiceDependencyListConfig[] dependencyConfigLists;
private JBossServiceAttributeConfig[] attributeConfigs;
private JBossServiceConstructorConfig constructorConfig;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public JBossServiceConstructorConfig getConstructorConfig() {
return constructorConfig;
}
public void setConstructorConfig(JBossServiceConstructorConfig constructorConfig) {
this.constructorConfig = constructorConfig;
}
public String[] getAliases() {
return aliases;
}
public void setAliases(String[] aliases) {
this.aliases = aliases;
}
public String[] getAnnotations() {
return annotations;
}
public void setAnnotations(String[] annotations) {
this.annotations = annotations;
}
public JBossServiceDependencyConfig[] getDependencyConfigs() {
return dependencyConfigs;
}
public void setDependencyConfigs(JBossServiceDependencyConfig[] dependencyConfigs) {
this.dependencyConfigs = dependencyConfigs;
}
public JBossServiceAttributeConfig[] getAttributeConfigs() {
return attributeConfigs;
}
public void setAttributeConfigs(JBossServiceAttributeConfig[] attributeConfigs) {
this.attributeConfigs = attributeConfigs;
}
public JBossServiceDependencyListConfig[] getDependencyConfigLists() {
return dependencyConfigLists;
}
public void setDependencyConfigLists(JBossServiceDependencyListConfig[] dependencyConfigLists) {
this.dependencyConfigLists = dependencyConfigLists;
}
}
| 3,341 | 30.233645 | 100 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/component/ServiceComponentProcessor.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.service.component;
import java.util.HashMap;
import java.util.Map;
import org.jboss.as.ee.component.EEApplicationClasses;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.service.ServiceAttachments;
import org.jboss.as.service.descriptor.JBossServiceConfig;
import org.jboss.as.service.descriptor.JBossServiceXmlDescriptor;
/**
* Creates EE component descriptions for mbeans, to support {@link javax.annotation.Resource} injection.
*
* @author Eduardo Martins
*
*/
public class ServiceComponentProcessor implements DeploymentUnitProcessor {
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final JBossServiceXmlDescriptor serviceXmlDescriptor = deploymentUnit
.getAttachment(JBossServiceXmlDescriptor.ATTACHMENT_KEY);
if (serviceXmlDescriptor == null) {
// Skip deployments without a service xml descriptor
return;
}
final EEModuleDescription moduleDescription = deploymentUnit
.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION);
if (moduleDescription == null) {
return; // not an EE deployment
}
final EEApplicationClasses applicationClassesDescription = deploymentUnit
.getAttachment(org.jboss.as.ee.component.Attachments.EE_APPLICATION_CLASSES_DESCRIPTION);
final Map<String, ServiceComponentInstantiator> serviceComponents = new HashMap<String, ServiceComponentInstantiator>();
for (final JBossServiceConfig serviceConfig : serviceXmlDescriptor.getServiceConfigs()) {
ServiceComponentDescription componentDescription = new ServiceComponentDescription(serviceConfig.getName(),
serviceConfig.getCode(), moduleDescription, deploymentUnit.getServiceName(), applicationClassesDescription);
moduleDescription.addComponent(componentDescription);
serviceComponents.put(serviceConfig.getName(), new ServiceComponentInstantiator(deploymentUnit,
componentDescription));
}
deploymentUnit.putAttachment(ServiceAttachments.SERVICE_COMPONENT_INSTANTIATORS, serviceComponents);
}
}
| 3,625 | 49.361111 | 128 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/component/ServiceComponentInstantiator.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.service.component;
import org.jboss.as.ee.component.BasicComponent;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceRegistry;
/**
* Instantiator for MBean's EE components
*
* @author Eduardo Martins
*/
public class ServiceComponentInstantiator {
private volatile BasicComponent component;
private final ServiceRegistry serviceRegistry;
private final ServiceName componentStartServiceName;
public ServiceComponentInstantiator(DeploymentUnit deploymentUnit, ComponentDescription componentDescription) {
componentStartServiceName = componentDescription.getStartServiceName();
this.serviceRegistry = deploymentUnit.getServiceRegistry();
}
public ServiceName getComponentStartServiceName() {
return componentStartServiceName;
}
@SuppressWarnings("unchecked")
private synchronized void setupComponent() {
if (component == null) {
component = ((ServiceController<BasicComponent>) serviceRegistry.getRequiredService(componentStartServiceName))
.getValue();
}
}
public ManagedReference initializeInstance(final Object instance) {
setupComponent();
return new ManagedReference() {
private final ComponentInstance componentInstance = component.createInstance(instance);
private boolean destroyed;
@Override
public synchronized void release() {
if (!destroyed) {
componentInstance.destroy();
destroyed = true;
}
}
@Override
public Object getInstance() {
return componentInstance.getInstance();
}
};
}
}
| 3,055 | 35.380952 | 123 |
java
|
null |
wildfly-main/sar/src/main/java/org/jboss/as/service/component/ServiceComponentDescription.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.service.component;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.ComponentFactory;
import org.jboss.as.ee.component.EEApplicationClasses;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.server.deployment.reflect.ClassReflectionIndex;
import org.jboss.invocation.InterceptorContext;
import org.jboss.modules.ModuleLoader;
import org.jboss.msc.service.ServiceName;
/**
* @author Eduardo Martins
*/
public final class ServiceComponentDescription extends ComponentDescription {
public ServiceComponentDescription(final String componentName, final String componentClassName,
final EEModuleDescription moduleDescription, final ServiceName deploymentUnitServiceName,
final EEApplicationClasses applicationClassesDescription) {
super(componentName, componentClassName, moduleDescription, deploymentUnitServiceName);
setExcludeDefaultInterceptors(true);
}
public boolean isIntercepted() {
return false;
}
@Override
public ComponentConfiguration createConfiguration(final ClassReflectionIndex classIndex, final ClassLoader moduleClassLoader,
final ModuleLoader moduleLoader) {
final ComponentConfiguration configuration = super.createConfiguration(classIndex, moduleClassLoader, moduleLoader);
// will not be used, but if instance factory is not set then components must have default constructor, which is not a
// requirement for MBeans
configuration.setInstanceFactory(new ComponentFactory() {
@Override
public ManagedReference create(final InterceptorContext context) {
return new ManagedReference() {
@Override
public void release() {
}
@Override
public Object getInstance() {
return null;
}
};
}
});
return configuration;
}
}
| 3,298 | 41.294872 | 129 |
java
|
null |
wildfly-main/dist/src/test/java/org/wildfly/dist/subsystem/xml/XSDValidationUnitTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.dist.subsystem.xml;
import org.junit.Test;
import org.wildfly.test.distribution.validation.AbstractValidationUnitTest;
/**
* A XSDValidationUnitTestCase.
*
* @author <a href="[email protected]">Alexey Loubyansky</a>
* @author <a href="mailto:[email protected]">James R. Perkins</a>
*/
public class XSDValidationUnitTestCase extends AbstractValidationUnitTest {
@Test
public void testJBossXsds() throws Exception {
jbossXsdsTest();
}
}
| 1,505 | 36.65 | 75 |
java
|
null |
wildfly-main/dist/src/test/java/org/wildfly/dist/subsystem/xml/StandardConfigsXMLValidationUnitTestCase.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.wildfly.dist.subsystem.xml;
import org.junit.Test;
import org.wildfly.test.distribution.validation.AbstractValidationUnitTest;
/**
* Performs validation against their xsd of the server configuration files in the distribution.
*
* @author Brian Stansberry
*/
public class StandardConfigsXMLValidationUnitTestCase extends AbstractValidationUnitTest {
@Test
public void testHost() throws Exception {
parseXml("domain/configuration/host.xml");
}
@Test
public void testHostSecondary() throws Exception {
parseXml("domain/configuration/host-secondary.xml");
}
@Test
public void testHostPrimary() throws Exception {
parseXml("domain/configuration/host-primary.xml");
}
@Test
public void testDomain() throws Exception {
parseXml("domain/configuration/domain.xml");
}
@Test
public void testStandalone() throws Exception {
parseXml("standalone/configuration/standalone.xml");
}
@Test
public void testStandaloneHA() throws Exception {
parseXml("standalone/configuration/standalone-ha.xml");
}
@Test
public void testStandaloneFull() throws Exception {
parseXml("standalone/configuration/standalone-full.xml");
}
@Test
public void testStandaloneMicroProfile() throws Exception {
parseXml("standalone/configuration/standalone-microprofile.xml");
}
@Test
public void testStandaloneMicroProfileHA() throws Exception {
parseXml("standalone/configuration/standalone-microprofile-ha.xml");
}
//TODO Leave commented out until domain-jts.xml is definitely removed from the configuration
// @Test
// public void testDomainJTS() throws Exception {
// parseXml("docs/examples/configs/domain-jts.xml");
// }
//
@Test
public void testStandaloneEC2HA() throws Exception {
parseXml("docs/examples/configs/standalone-ec2-ha.xml");
}
@Test
public void testStandaloneEC2FullHA() throws Exception {
parseXml("docs/examples/configs/standalone-ec2-full-ha.xml");
}
@Test
public void testStandaloneGossipHA() throws Exception {
parseXml("docs/examples/configs/standalone-gossip-ha.xml");
}
@Test
public void testStandaloneGossipFullHA() throws Exception {
parseXml("docs/examples/configs/standalone-gossip-full-ha.xml");
}
@Test
public void testStandaloneJTS() throws Exception {
parseXml("docs/examples/configs/standalone-jts.xml");
}
@Test
public void testStandaloneMinimalistic() throws Exception {
parseXml("docs/examples/configs/standalone-minimalistic.xml");
}
@Test
public void testStandaloneXTS() throws Exception {
parseXml("docs/examples/configs/standalone-xts.xml");
}
@Test
public void testStandaloneRTS() throws Exception {
parseXml("docs/examples/configs/standalone-rts.xml");
}
@Test
public void testStandaloneGenericJMS() throws Exception {
parseXml("docs/examples/configs/standalone-genericjms.xml");
}
}
| 4,136 | 30.580153 | 96 |
java
|
null |
wildfly-main/web-common/src/test/java/org/jboss/as/web/session/SimpleSessionIdentifierCodecTestCase.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.web.session;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
import java.util.AbstractMap.SimpleImmutableEntry;
import org.junit.Test;
/**
* Unit test for {@link SimpleSessionIdentifierCodec}.
* @author Paul Ferraro
*/
public class SimpleSessionIdentifierCodecTestCase {
@Test
public void encode() {
RoutingSupport routing = mock(RoutingSupport.class);
SessionIdentifierCodec codec = new SimpleSessionIdentifierCodec(routing, null);
String sessionId = "session";
CharSequence result = codec.encode(sessionId);
assertNull(sessionId, null);
String route = "route";
codec = new SimpleSessionIdentifierCodec(routing, route);
result = codec.encode(null);
assertNull(result);
String encodedSessionId = "session.route";
when(routing.format(sessionId, route)).thenReturn(encodedSessionId);
result = codec.encode(sessionId);
assertSame(encodedSessionId, result);
}
@Test
public void decode() {
RoutingSupport routing = mock(RoutingSupport.class);
String route = "route";
SessionIdentifierCodec codec = new SimpleSessionIdentifierCodec(routing, route);
CharSequence result = codec.decode(null);
assertNull(result);
String sessionId = "session";
when(routing.parse(sessionId)).thenReturn(new SimpleImmutableEntry<>(sessionId, null));
result = codec.decode(sessionId);
assertSame(sessionId, result);
String encodedSessionId = "session.route";
when(routing.parse(encodedSessionId)).thenReturn(new SimpleImmutableEntry<>(sessionId, route));
result = codec.decode(encodedSessionId);
assertSame(sessionId, result);
}
}
| 2,830 | 30.455556 | 103 |
java
|
null |
wildfly-main/web-common/src/test/java/org/jboss/as/web/session/SimpleRoutingSupportTestCase.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.web.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.nio.CharBuffer;
import java.util.Map;
import org.junit.Test;
/**
* Unit test for {@link SimpleRoutingSupport}.
* @author Paul Ferraro
*/
public class SimpleRoutingSupportTestCase {
private final RoutingSupport routing = new SimpleRoutingSupport();
@Test
public void parse() {
Map.Entry<CharSequence, CharSequence> result = this.routing.parse("session1.route1");
assertEquals("session1", result.getKey().toString());
assertEquals("route1", result.getValue().toString());
result = this.routing.parse("session2");
assertEquals("session2", result.getKey().toString());
assertNull(result.getValue());
result = this.routing.parse(null);
assertNull(result.getKey());
assertNull(result.getValue());
result = this.routing.parse(CharBuffer.wrap("session1.route1"));
assertEquals("session1", result.getKey().toString());
assertEquals("route1", result.getValue().toString());
result = this.routing.parse(new StringBuilder("session1.route1"));
assertEquals("session1", result.getKey().toString());
assertEquals("route1", result.getValue().toString());
}
@Test
public void format() {
assertEquals("session1.route1", this.routing.format("session1", "route1").toString());
assertEquals("session2", this.routing.format("session2", "").toString());
assertEquals("session3", this.routing.format("session3", null).toString());
assertEquals("session1.route1", this.routing.format(CharBuffer.wrap("session1"), CharBuffer.wrap("route1")).toString());
assertEquals("session1.route1", this.routing.format(new StringBuilder("session1"), new StringBuilder("route1")).toString());
assertNull(this.routing.format(null, null));
}
}
| 2,969 | 39.684932 | 132 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/common/CachingWebInjectionContainer.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.web.common;
import java.lang.reflect.InvocationTargetException;
import java.util.EnumSet;
import java.util.Map;
import org.jboss.as.ee.component.ComponentRegistry;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ManagedReferenceFactory;
/**
* A {@link WebInjectionContainer} that caches {@link ManagedReference} instances between {@link #newInstance(Object)} and {@link #destroyInstance(Object)}.
* @author Emanuel Muckenhuber
* @author Paul Ferraro
*/
public class CachingWebInjectionContainer extends AbstractWebInjectionContainer {
private final Map<Object, ManagedReference> references;
public CachingWebInjectionContainer(ClassLoader loader, ComponentRegistry componentRegistry) {
super(loader, componentRegistry);
this.references = new ConcurrentReferenceHashMap<>(256, ConcurrentReferenceHashMap.DEFAULT_LOAD_FACTOR,
Runtime.getRuntime().availableProcessors(), ConcurrentReferenceHashMap.ReferenceType.STRONG,
ConcurrentReferenceHashMap.ReferenceType.STRONG, EnumSet.of(ConcurrentReferenceHashMap.Option.IDENTITY_COMPARISONS));
}
@Override
public void destroyInstance(Object instance) {
final ManagedReference reference = this.references.remove(instance);
if (reference != null) {
reference.release();
}
}
@Override
public Object newInstance(Class<?> clazz) throws IllegalAccessException, InvocationTargetException, InstantiationException {
final ManagedReferenceFactory factory = this.getComponentRegistry().createInstanceFactory(clazz);
ManagedReference reference = factory.getReference();
if (reference != null) {
this.references.put(reference.getInstance(), reference);
return reference.getInstance();
}
return clazz.newInstance();
}
@Override
public void newInstance(Object instance) {
final ManagedReference reference = this.getComponentRegistry().createInstance(instance);
if (reference != null) {
this.references.put(instance, reference);
}
}
}
| 3,173 | 40.763158 | 156 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/common/WebInjectionContainer.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.web.common;
import java.lang.reflect.InvocationTargetException;
import org.jboss.as.ee.component.ComponentRegistry;
/**
* The web injection container.
*
* @author Emanuel Muckenhuber
* @author Paul Ferraro
*/
public interface WebInjectionContainer {
void destroyInstance(Object instance);
Object newInstance(String className) throws IllegalAccessException, InvocationTargetException, InstantiationException, ClassNotFoundException;
Object newInstance(Class<?> clazz) throws IllegalAccessException, InvocationTargetException, InstantiationException;
void newInstance(Object arg0);
default Object newInstance(String className, ClassLoader loader) throws IllegalAccessException, InvocationTargetException, InstantiationException, ClassNotFoundException {
return this.newInstance(loader.loadClass(className));
}
ComponentRegistry getComponentRegistry();
}
| 1,939 | 37.8 | 175 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/common/AbstractWebInjectionContainer.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.web.common;
import java.lang.reflect.InvocationTargetException;
import org.jboss.as.ee.component.ComponentRegistry;
/**
* @author Paul Ferraro
*/
public abstract class AbstractWebInjectionContainer implements WebInjectionContainer {
private final ClassLoader loader;
private final ComponentRegistry registry;
public AbstractWebInjectionContainer(ClassLoader loader, ComponentRegistry registry) {
this.loader = loader;
this.registry = registry;
}
@Override
public Object newInstance(String className) throws IllegalAccessException, InvocationTargetException, InstantiationException, ClassNotFoundException {
return this.newInstance(className, this.loader);
}
@Override
public ComponentRegistry getComponentRegistry() {
return this.registry;
}
}
| 1,870 | 34.980769 | 154 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/common/SimpleWebInjectionContainer.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.web.common;
import java.lang.reflect.InvocationTargetException;
import org.jboss.as.ee.component.ComponentRegistry;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ManagedReferenceFactory;
/**
* A {@link WebInjectionContainer} implementation for use with distributable web applications that does not cache {@link ManagedReference} instances.
* @author Paul Ferraro
*/
public class SimpleWebInjectionContainer extends AbstractWebInjectionContainer {
public SimpleWebInjectionContainer(ClassLoader loader, ComponentRegistry componentRegistry) {
super(loader, componentRegistry);
}
@Override
public void destroyInstance(Object instance) {
ManagedReference reference = this.getComponentRegistry().getInstance(instance);
if (reference != null) {
reference.release();
}
}
@Override
public Object newInstance(Class<?> clazz) throws IllegalAccessException, InvocationTargetException, InstantiationException {
final ManagedReferenceFactory factory = this.getComponentRegistry().createInstanceFactory(clazz);
ManagedReference reference = factory.getReference();
if (reference != null) {
return reference.getInstance();
}
return clazz.newInstance();
}
@Override
public void newInstance(Object instance) {
this.getComponentRegistry().createInstance(instance);
}
}
| 2,479 | 37.75 | 149 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/common/SharedTldsMetaDataBuilder.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.web.common;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.dmr.ModelNode;
import org.jboss.metadata.parser.jsp.TldMetaDataParser;
import org.jboss.metadata.parser.util.NoopXMLResolver;
import org.jboss.metadata.web.spec.TldMetaData;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleClassLoader;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoadException;
/**
* Internal helper creating a shared TLD metadata list based on the domain configuration.
*
* @author Emanuel Muckenhuber
* @author Stan Silvert
*/
public class SharedTldsMetaDataBuilder {
public static final AttachmentKey<List<TldMetaData>> ATTACHMENT_KEY = AttachmentKey.create(List.class);
private static final String[] JSTL_TAGLIBS = { "c-1_0-rt.tld", "c-1_0.tld", "c.tld", "fmt-1_0-rt.tld", "fmt-1_0.tld", "fmt.tld", "fn.tld", "permittedTaglibs.tld", "scriptfree.tld", "sql-1_0-rt.tld", "sql-1_0.tld", "sql.tld", "x-1_0-rt.tld", "x-1_0.tld", "x.tld" };
// Not used right now due to hardcoding
/** The common container config. */
private final ModelNode containerConfig;
public SharedTldsMetaDataBuilder(final ModelNode containerConfig) {
this.containerConfig = containerConfig;
}
public List<TldMetaData> getSharedTlds(DeploymentUnit deploymentUnit) {
final List<TldMetaData> metadata = new ArrayList<TldMetaData>();
try {
ModuleClassLoader jstl = Module.getModuleFromCallerModuleLoader(ModuleIdentifier.create("javax.servlet.jstl.api")).getClassLoader();
for (String tld : JSTL_TAGLIBS) {
InputStream is = jstl.getResourceAsStream("META-INF/" + tld);
if (is != null) {
TldMetaData tldMetaData = parseTLD(is);
metadata.add(tldMetaData);
}
}
} catch (ModuleLoadException e) {
// Ignore
} catch (Exception e) {
// Ignore
}
List<TldMetaData> additionalSharedTlds = deploymentUnit.getAttachment(ATTACHMENT_KEY);
if (additionalSharedTlds != null) {
metadata.addAll(additionalSharedTlds);
}
return metadata;
}
private TldMetaData parseTLD(InputStream is)
throws Exception {
try {
final XMLInputFactory inputFactory = XMLInputFactory.newInstance();
inputFactory.setXMLResolver(NoopXMLResolver.create());
XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(is);
return TldMetaDataParser.parse(xmlReader );
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
// Ignore
}
}
}
}
| 4,100 | 36.623853 | 268 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/common/WebComponentDescription.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.web.common;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.EEApplicationClasses;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.server.deployment.AttachmentList;
import org.jboss.msc.service.ServiceName;
/**
* @author Stuart Douglas
*/
public final class WebComponentDescription extends ComponentDescription {
public static final AttachmentKey<AttachmentList<ServiceName>> WEB_COMPONENTS = AttachmentKey.createList(ServiceName.class);
public WebComponentDescription(final String componentName, final String componentClassName, final EEModuleDescription moduleDescription, final ServiceName deploymentUnitServiceName, final EEApplicationClasses applicationClassesDescription) {
super(componentName, componentClassName, moduleDescription, deploymentUnitServiceName);
setExcludeDefaultInterceptors(true);
}
public boolean isIntercepted() {
return false;
}
/**
* Web components are optional. If they are actually required we leave it up to the web subsystem to error out.
* @return <code>true</code>
*/
@Override
public boolean isOptional() {
return true;
}
}
| 2,315 | 38.254237 | 245 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/common/ServletContextAttribute.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.web.common;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.server.deployment.AttachmentList;
/**
* Configuration object used to store a {@link jakarta.servlet.ServletContext} attribute name and value.
*
* @author John Bailey
*/
public class ServletContextAttribute {
public static final AttachmentKey<AttachmentList<ServletContextAttribute>> ATTACHMENT_KEY = AttachmentKey.createList(ServletContextAttribute.class);
private final String name;
private final Object value;
/**
* Create a new instance.
*
* @param name The attribute name
* @param value The attribute valule
*/
public ServletContextAttribute(final String name, final Object value) {
this.name = name;
this.value = value;
}
/**
* Get the attribute name.
*
* @return the attribute name
*/
public String getName() {
return name;
}
/**
* Get the attribute value.
*
* @return the attribute value
*/
public Object getValue() {
return value;
}
}
| 2,129 | 30.323529 | 152 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/common/VirtualHttpServerMechanismFactoryMarkerUtility.java
|
/*
* Copyright 2021 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.web.common;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.msc.service.ServiceName;
/**
* Utility class to mark a {@link DeploymentUnit} or {@code OperationContext} as requiring a virtual HttpServerAuthenticationMechanismFactory.
*
* @author <a href="mailto:[email protected]">Farah Juma</a>
*/
public class VirtualHttpServerMechanismFactoryMarkerUtility {
private static final AttachmentKey<Boolean> REQUIRED = AttachmentKey.create(Boolean.class);
private static final ServiceName MECHANISM_FACTORY_SUFFIX = ServiceName.of("http-server-mechanism-factory", "virtual");
public static void virtualMechanismFactoryRequired(final DeploymentUnit deploymentUnit) {
DeploymentUnit rootUnit = toRoot(deploymentUnit);
rootUnit.putAttachment(REQUIRED, Boolean.TRUE);
}
public static boolean isVirtualMechanismFactoryRequired(final DeploymentUnit deploymentUnit) {
DeploymentUnit rootUnit = toRoot(deploymentUnit);
Boolean required = rootUnit.getAttachment(REQUIRED);
return required == null ? false : required.booleanValue();
}
public static ServiceName virtualMechanismFactoryName(final DeploymentUnit deploymentUnit) {
DeploymentUnit rootUnit = toRoot(deploymentUnit);
return rootUnit.getServiceName().append(MECHANISM_FACTORY_SUFFIX);
}
public static ServiceName virtualMechanismFactoryName(final OperationContext operationContext) {
return ServiceName.of(operationContext.getCurrentAddressValue()).append(MECHANISM_FACTORY_SUFFIX);
}
private static DeploymentUnit toRoot(final DeploymentUnit deploymentUnit) {
DeploymentUnit result = deploymentUnit;
DeploymentUnit parent = result.getParent();
while (parent != null) {
result = parent;
parent = result.getParent();
}
return result;
}
}
| 2,614 | 37.455882 | 142 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/common/ExpressionFactoryWrapper.java
|
package org.jboss.as.web.common;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.server.deployment.AttachmentList;
import jakarta.el.ExpressionFactory;
import jakarta.servlet.ServletContext;
/**
* @author Stuart Douglas
*/
public interface ExpressionFactoryWrapper {
AttachmentKey<AttachmentList<ExpressionFactoryWrapper>> ATTACHMENT_KEY = AttachmentKey.createList(ExpressionFactoryWrapper.class);
ExpressionFactory wrap(ExpressionFactory expressionFactory, ServletContext servletContext);
}
| 533 | 27.105263 | 134 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/common/ConcurrentReferenceHashMap.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.
*/
/*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
package org.jboss.as.web.common;
import static org.wildfly.common.Assert.checkNotNullParamWithNullPointerException;
import java.io.IOException;
import java.io.Serializable;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;
/**
* An advanced hash table supporting configurable garbage collection semantics
* of keys and values, optional referential-equality, full concurrency of
* retrievals, and adjustable expected concurrency for updates.
*
* This table is designed around specific advanced use-cases. If there is any
* doubt whether this table is for you, you most likely should be using
* {@link java.util.concurrent.ConcurrentHashMap} instead.
*
* This table supports strong, weak, and soft keys and values. By default keys
* are weak, and values are strong. Such a configuration offers similar behavior
* to {@link java.util.WeakHashMap}, entries of this table are periodically
* removed once their corresponding keys are no longer referenced outside of
* this table. In other words, this table will not prevent a key from being
* discarded by the garbage collector. Once a key has been discarded by the
* collector, the corresponding entry is no longer visible to this table;
* however, the entry may occupy space until a future table operation decides to
* reclaim it. For this reason, summary functions such as <tt>size</tt> and
* <tt>isEmpty</tt> might return a value greater than the observed number of
* entries. In order to support a high level of concurrency, stale entries are
* only reclaimed during blocking (usually mutating) operations.
*
* Enabling soft keys allows entries in this table to remain until their space
* is absolutely needed by the garbage collector. This is unlike weak keys which
* can be reclaimed as soon as they are no longer referenced by a normal strong
* reference. The primary use case for soft keys is a cache, which ideally
* occupies memory that is not in use for as long as possible.
*
* By default, values are held using a normal strong reference. This provides
* the commonly desired guarantee that a value will always have at least the
* same life-span as it's key. For this reason, care should be taken to ensure
* that a value never refers, either directly or indirectly, to its key, thereby
* preventing reclamation. If this is unavoidable, then it is recommended to use
* the same reference type in use for the key. However, it should be noted that
* non-strong values may disappear before their corresponding key.
*
* While this table does allow the use of both strong keys and values, it is
* recommended to use {@link java.util.concurrent.ConcurrentHashMap} for such a
* configuration, since it is optimized for that case.
*
* Just like {@link java.util.concurrent.ConcurrentHashMap}, this class obeys
* the same functional specification as {@link java.util.Hashtable}, and
* includes versions of methods corresponding to each method of
* <tt>Hashtable</tt>. However, even though all operations are thread-safe,
* retrieval operations do <em>not</em> entail locking, and there is
* <em>not</em> any support for locking the entire table in a way that
* prevents all access. This class is fully interoperable with
* <tt>Hashtable</tt> in programs that rely on its thread safety but not on
* its synchronization details.
*
* <p>
* Retrieval operations (including <tt>get</tt>) generally do not block, so
* may overlap with update operations (including <tt>put</tt> and
* <tt>remove</tt>). Retrievals reflect the results of the most recently
* <em>completed</em> update operations holding upon their onset. For
* aggregate operations such as <tt>putAll</tt> and <tt>clear</tt>,
* concurrent retrievals may reflect insertion or removal of only some entries.
* Similarly, Iterators and Enumerations return elements reflecting the state of
* the hash table at some point at or since the creation of the
* iterator/enumeration. They do <em>not</em> throw
* {@link java.util.ConcurrentModificationException}. However, iterators are designed to
* be used by only one thread at a time.
*
* <p>
* The allowed concurrency among update operations is guided by the optional
* <tt>concurrencyLevel</tt> constructor argument (default <tt>16</tt>),
* which is used as a hint for internal sizing. The table is internally
* partitioned to try to permit the indicated number of concurrent updates
* without contention. Because placement in hash tables is essentially random,
* the actual concurrency will vary. Ideally, you should choose a value to
* accommodate as many threads as will ever concurrently modify the table. Using
* a significantly higher value than you need can waste space and time, and a
* significantly lower value can lead to thread contention. But overestimates
* and underestimates within an order of magnitude do not usually have much
* noticeable impact. A value of one is appropriate when it is known that only
* one thread will modify and all others will only read. Also, resizing this or
* any other kind of hash table is a relatively slow operation, so, when
* possible, it is a good idea to provide estimates of expected table sizes in
* constructors.
*
* <p>
* This class and its views and iterators implement all of the <em>optional</em>
* methods of the {@link Map} and {@link Iterator} interfaces.
*
* <p>
* Like {@link java.util.Hashtable} but unlike {@link java.util.HashMap}, this class does
* <em>not</em> allow <tt>null</tt> to be used as a key or value.
*
* <p>
* This class is a member of the <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* @author Doug Lea
* @author Jason T. Greene
* @param <K> the type of keys maintained by this map
* @param <V> the type of mapped values
*/
final class ConcurrentReferenceHashMap<K, V> extends AbstractMap<K, V>
implements java.util.concurrent.ConcurrentMap<K, V>, Serializable {
private static final long serialVersionUID = 7249069246763182397L;
/*
* The basic strategy is to subdivide the table among Segments,
* each of which itself is a concurrently readable hash table.
*/
/**
* An option specifying which Java reference type should be used to refer
* to a key and/or value.
*/
public static enum ReferenceType {
/** Indicates a normal Java strong reference should be used */
STRONG,
/** Indicates a {@link WeakReference} should be used */
WEAK,
/** Indicates a {@link SoftReference} should be used */
SOFT
}
public static enum Option {
/** Indicates that referential-equality (== instead of .equals()) should
* be used when locating keys. This offers similar behavior to {@link java.util.IdentityHashMap} */
IDENTITY_COMPARISONS
}
/* ---------------- Constants -------------- */
static final ReferenceType DEFAULT_KEY_TYPE = ReferenceType.WEAK;
static final ReferenceType DEFAULT_VALUE_TYPE = ReferenceType.STRONG;
/**
* The default initial capacity for this table,
* used when not otherwise specified in a constructor.
*/
static final int DEFAULT_INITIAL_CAPACITY = 16;
/**
* The default load factor for this table, used when not
* otherwise specified in a constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* The default concurrency level for this table, used when not
* otherwise specified in a constructor.
*/
static final int DEFAULT_CONCURRENCY_LEVEL = 16;
/**
* The maximum capacity, used if a higher value is implicitly
* specified by either of the constructors with arguments. MUST
* be a power of two <= 1<<30 to ensure that entries are indexable
* using ints.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The maximum number of segments to allow; used to bound
* constructor arguments.
*/
static final int MAX_SEGMENTS = 1 << 16; // slightly conservative
/**
* Number of unsynchronized retries in size and containsValue
* methods before resorting to locking. This is used to avoid
* unbounded retries if tables undergo continuous modification
* which would make it impossible to obtain an accurate result.
*/
static final int RETRIES_BEFORE_LOCK = 2;
/* ---------------- Fields -------------- */
/**
* Mask value for indexing into segments. The upper bits of a
* key's hash code are used to choose the segment.
*/
final int segmentMask;
/**
* Shift value for indexing within segments.
*/
final int segmentShift;
/**
* The segments, each of which is a specialized hash table
*/
final Segment<K,V>[] segments;
boolean identityComparisons;
transient Set<K> keySet;
transient Set<Map.Entry<K,V>> entrySet;
transient Collection<V> values;
/* ---------------- Small Utilities -------------- */
/**
* Applies a supplemental hash function to a given hashCode, which
* defends against poor quality hash functions. This is critical
* because ConcurrentReferenceHashMap uses power-of-two length hash tables,
* that otherwise encounter collisions for hashCodes that do not
* differ in lower or upper bits.
*/
private static int hash(int h) {
// Spread bits to regularize both segment and index locations,
// using variant of single-word Wang/Jenkins hash.
h += (h << 15) ^ 0xffffcd7d;
h ^= (h >>> 10);
h += (h << 3);
h ^= (h >>> 6);
h += (h << 2) + (h << 14);
return h ^ (h >>> 16);
}
/**
* Returns the segment that should be used for key with given hash
* @param hash the hash code for the key
* @return the segment
*/
Segment<K,V> segmentFor(int hash) {
return segments[(hash >>> segmentShift) & segmentMask];
}
private int hashOf(Object key) {
return hash(identityComparisons ?
System.identityHashCode(key) : key.hashCode());
}
/* ---------------- Inner Classes -------------- */
interface KeyReference {
int keyHash();
Object keyRef();
}
/**
* A weak-key reference which stores the key hash needed for reclamation.
*/
static final class WeakKeyReference<K> extends WeakReference<K> implements KeyReference {
final int hash;
WeakKeyReference(K key, int hash, ReferenceQueue<Object> refQueue) {
super(key, refQueue);
this.hash = hash;
}
public int keyHash() {
return hash;
}
public Object keyRef() {
return this;
}
}
/**
* A soft-key reference which stores the key hash needed for reclamation.
*/
static final class SoftKeyReference<K> extends SoftReference<K> implements KeyReference {
final int hash;
SoftKeyReference(K key, int hash, ReferenceQueue<Object> refQueue) {
super(key, refQueue);
this.hash = hash;
}
public int keyHash() {
return hash;
}
public Object keyRef() {
return this;
}
}
static final class WeakValueReference<V> extends WeakReference<V> implements KeyReference {
final Object keyRef;
final int hash;
WeakValueReference(V value, Object keyRef, int hash, ReferenceQueue<Object> refQueue) {
super(value, refQueue);
this.keyRef = keyRef;
this.hash = hash;
}
public int keyHash() {
return hash;
}
public Object keyRef() {
return keyRef;
}
}
static final class SoftValueReference<V> extends SoftReference<V> implements KeyReference {
final Object keyRef;
final int hash;
SoftValueReference(V value, Object keyRef, int hash, ReferenceQueue<Object> refQueue) {
super(value, refQueue);
this.keyRef = keyRef;
this.hash = hash;
}
public int keyHash() {
return hash;
}
public Object keyRef() {
return keyRef;
}
}
/**
* ConcurrentReferenceHashMap list entry. Note that this is never exported
* out as a user-visible Map.Entry.
*
* Because the value field is volatile, not final, it is legal wrt
* the Java Memory Model for an unsynchronized reader to see null
* instead of initial value when read via a data race. Although a
* reordering leading to this is not likely to ever actually
* occur, the Segment.readValueUnderLock method is used as a
* backup in case a null (pre-initialized) value is ever seen in
* an unsynchronized access method.
*/
static final class HashEntry<K,V> {
final Object keyRef;
final int hash;
volatile Object valueRef;
final HashEntry<K,V> next;
HashEntry(K key, int hash, HashEntry<K,V> next, V value,
ReferenceType keyType, ReferenceType valueType,
ReferenceQueue<Object> refQueue) {
this.hash = hash;
this.next = next;
this.keyRef = newKeyReference(key, keyType, refQueue);
this.valueRef = newValueReference(value, valueType, refQueue);
}
Object newKeyReference(K key, ReferenceType keyType,
ReferenceQueue<Object> refQueue) {
if (keyType == ReferenceType.WEAK)
return new WeakKeyReference<K>(key, hash, refQueue);
if (keyType == ReferenceType.SOFT)
return new SoftKeyReference<K>(key, hash, refQueue);
return key;
}
Object newValueReference(V value, ReferenceType valueType,
ReferenceQueue<Object> refQueue) {
if (valueType == ReferenceType.WEAK)
return new WeakValueReference<V>(value, keyRef, hash, refQueue);
if (valueType == ReferenceType.SOFT)
return new SoftValueReference<V>(value, keyRef, hash, refQueue);
return value;
}
@SuppressWarnings("unchecked")
K key() {
if (keyRef instanceof KeyReference)
return ((Reference<K>)keyRef).get();
return (K) keyRef;
}
V value() {
return dereferenceValue(valueRef);
}
@SuppressWarnings("unchecked")
V dereferenceValue(Object value) {
if (value instanceof KeyReference)
return ((Reference<V>)value).get();
return (V) value;
}
void setValue(V value, ReferenceType valueType, ReferenceQueue<Object> refQueue) {
this.valueRef = newValueReference(value, valueType, refQueue);
}
@SuppressWarnings("unchecked")
static <K,V> HashEntry<K,V>[] newArray(int i) {
return new HashEntry[i];
}
}
/**
* Segments are specialized versions of hash tables. This
* subclasses from ReentrantLock opportunistically, just to
* simplify some locking and avoid separate construction.
*/
static final class Segment<K,V> extends ReentrantLock implements Serializable {
/*
* Segments maintain a table of entry lists that are ALWAYS
* kept in a consistent state, so can be read without locking.
* Next fields of nodes are immutable (final). All list
* additions are performed at the front of each bin. This
* makes it easy to check changes, and also fast to traverse.
* When nodes would otherwise be changed, new nodes are
* created to replace them. This works well for hash tables
* since the bin lists tend to be short. (The average length
* is less than two for the default load factor threshold.)
*
* Read operations can thus proceed without locking, but rely
* on selected uses of volatiles to ensure that completed
* write operations performed by other threads are
* noticed. For most purposes, the "count" field, tracking the
* number of elements, serves as that volatile variable
* ensuring visibility. This is convenient because this field
* needs to be read in many read operations anyway:
*
* - All (unsynchronized) read operations must first read the
* "count" field, and should not look at table entries if
* it is 0.
*
* - All (synchronized) write operations should write to
* the "count" field after structurally changing any bin.
* The operations must not take any action that could even
* momentarily cause a concurrent read operation to see
* inconsistent data. This is made easier by the nature of
* the read operations in Map. For example, no operation
* can reveal that the table has grown but the threshold
* has not yet been updated, so there are no atomicity
* requirements for this with respect to reads.
*
* As a guide, all critical volatile reads and writes to the
* count field are marked in code comments.
*/
private static final long serialVersionUID = 2249069246763182397L;
/**
* The number of elements in this segment's region.
*/
transient volatile int count;
/**
* Number of updates that alter the size of the table. This is
* used during bulk-read methods to make sure they see a
* consistent snapshot: If modCounts change during a traversal
* of segments computing size or checking containsValue, then
* we might have an inconsistent view of state so (usually)
* must retry.
*/
transient int modCount;
/**
* The table is rehashed when its size exceeds this threshold.
* (The value of this field is always <tt>(int)(capacity *
* loadFactor)</tt>.)
*/
transient int threshold;
/**
* The per-segment table.
*/
transient volatile HashEntry<K,V>[] table;
/**
* The load factor for the hash table. Even though this value
* is same for all segments, it is replicated to avoid needing
* links to outer object.
* @serial
*/
final float loadFactor;
/**
* The collected weak-key reference queue for this segment.
* This should be (re)initialized whenever table is assigned,
*/
transient volatile ReferenceQueue<Object> refQueue;
final ReferenceType keyType;
final ReferenceType valueType;
final boolean identityComparisons;
Segment(int initialCapacity, float lf, ReferenceType keyType,
ReferenceType valueType, boolean identityComparisons) {
loadFactor = lf;
this.keyType = keyType;
this.valueType = valueType;
this.identityComparisons = identityComparisons;
setTable(HashEntry.<K,V>newArray(initialCapacity));
}
@SuppressWarnings("unchecked")
static <K,V> Segment<K,V>[] newArray(int i) {
return new Segment[i];
}
private boolean keyEq(Object src, Object dest) {
return identityComparisons ? src == dest : src.equals(dest);
}
/**
* Sets table to new HashEntry array.
* Call only while holding lock or in constructor.
*/
void setTable(HashEntry<K,V>[] newTable) {
threshold = (int)(newTable.length * loadFactor);
table = newTable;
refQueue = new ReferenceQueue<Object>();
}
/**
* Returns properly casted first entry of bin for given hash.
*/
HashEntry<K,V> getFirst(int hash) {
HashEntry<K,V>[] tab = table;
return tab[hash & (tab.length - 1)];
}
HashEntry<K,V> newHashEntry(K key, int hash, HashEntry<K, V> next, V value) {
return new HashEntry<K,V>(key, hash, next, value, keyType, valueType, refQueue);
}
/**
* Reads value field of an entry under lock. Called if value
* field ever appears to be null. This is possible only if a
* compiler happens to reorder a HashEntry initialization with
* its table assignment, which is legal under memory model
* but is not known to ever occur.
*/
V readValueUnderLock(HashEntry<K,V> e) {
lock();
try {
removeStale();
return e.value();
} finally {
unlock();
}
}
/* Specialized implementations of map methods */
V get(Object key, int hash) {
if (count != 0) { // read-volatile
HashEntry<K,V> e = getFirst(hash);
while (e != null) {
if (e.hash == hash && keyEq(key, e.key())) {
Object opaque = e.valueRef;
if (opaque != null)
return e.dereferenceValue(opaque);
return readValueUnderLock(e); // recheck
}
e = e.next;
}
}
return null;
}
boolean containsKey(Object key, int hash) {
if (count != 0) { // read-volatile
HashEntry<K,V> e = getFirst(hash);
while (e != null) {
if (e.hash == hash && keyEq(key, e.key()))
return true;
e = e.next;
}
}
return false;
}
boolean containsValue(Object value) {
if (count != 0) { // read-volatile
HashEntry<K,V>[] tab = table;
int len = tab.length;
for (int i = 0 ; i < len; i++) {
for (HashEntry<K,V> e = tab[i]; e != null; e = e.next) {
Object opaque = e.valueRef;
V v;
if (opaque == null)
v = readValueUnderLock(e); // recheck
else
v = e.dereferenceValue(opaque);
if (value.equals(v))
return true;
}
}
}
return false;
}
boolean replace(K key, int hash, V oldValue, V newValue) {
lock();
try {
removeStale();
HashEntry<K,V> e = getFirst(hash);
while (e != null && (e.hash != hash || !keyEq(key, e.key())))
e = e.next;
boolean replaced = false;
if (e != null && oldValue.equals(e.value())) {
replaced = true;
e.setValue(newValue, valueType, refQueue);
}
return replaced;
} finally {
unlock();
}
}
V replace(K key, int hash, V newValue) {
lock();
try {
removeStale();
HashEntry<K,V> e = getFirst(hash);
while (e != null && (e.hash != hash || !keyEq(key, e.key())))
e = e.next;
V oldValue = null;
if (e != null) {
oldValue = e.value();
e.setValue(newValue, valueType, refQueue);
}
return oldValue;
} finally {
unlock();
}
}
V put(K key, int hash, V value, boolean onlyIfAbsent) {
lock();
try {
removeStale();
int c = count;
if (c++ > threshold) {// ensure capacity
int reduced = rehash();
if (reduced > 0) // adjust from possible weak cleanups
count = (c -= reduced) - 1; // write-volatile
}
HashEntry<K,V>[] tab = table;
int index = hash & (tab.length - 1);
HashEntry<K,V> first = tab[index];
HashEntry<K,V> e = first;
while (e != null && (e.hash != hash || !keyEq(key, e.key())))
e = e.next;
V oldValue;
if (e != null) {
oldValue = e.value();
if (!onlyIfAbsent || oldValue == null) // null = gc AFTER stale removal
e.setValue(value, valueType, refQueue);
}
else {
oldValue = null;
++modCount;
tab[index] = newHashEntry(key, hash, first, value);
count = c; // write-volatile
}
return oldValue;
} finally {
unlock();
}
}
int rehash() {
HashEntry<K,V>[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity >= MAXIMUM_CAPACITY)
return 0;
/*
* Reclassify nodes in each list to new Map. Because we are
* using power-of-two expansion, the elements from each bin
* must either stay at same index, or move with a power of two
* offset. We eliminate unnecessary node creation by catching
* cases where old nodes can be reused because their next
* fields won't change. Statistically, at the default
* threshold, only about one-sixth of them need cloning when
* a table doubles. The nodes they replace will be garbage
* collectable as soon as they are no longer referenced by any
* reader thread that may be in the midst of traversing table
* right now.
*/
HashEntry<K,V>[] newTable = HashEntry.newArray(oldCapacity<<1);
threshold = (int)(newTable.length * loadFactor);
int sizeMask = newTable.length - 1;
int reduce = 0;
for (int i = 0; i < oldCapacity ; i++) {
// We need to guarantee that any existing reads of old Map can
// proceed. So we cannot yet null out each bin.
HashEntry<K,V> e = oldTable[i];
if (e != null) {
HashEntry<K,V> next = e.next;
int idx = e.hash & sizeMask;
// Single node on list
if (next == null)
newTable[idx] = e;
else {
// Reuse trailing consecutive sequence at same slot
HashEntry<K,V> lastRun = e;
int lastIdx = idx;
for (HashEntry<K,V> last = next;
last != null;
last = last.next) {
int k = last.hash & sizeMask;
if (k != lastIdx) {
lastIdx = k;
lastRun = last;
}
}
newTable[lastIdx] = lastRun;
// Clone all remaining nodes
for (HashEntry<K,V> p = e; p != lastRun; p = p.next) {
// Skip GC'd weak refs
K key = p.key();
if (key == null) {
reduce++;
continue;
}
int k = p.hash & sizeMask;
HashEntry<K,V> n = newTable[k];
newTable[k] = newHashEntry(key, p.hash, n, p.value());
}
}
}
}
table = newTable;
return reduce;
}
/**
* Remove; match on key only if value null, else match both.
*/
V remove(Object key, int hash, Object value, boolean refRemove) {
lock();
try {
if (!refRemove)
removeStale();
int c = count - 1;
HashEntry<K,V>[] tab = table;
int index = hash & (tab.length - 1);
HashEntry<K,V> first = tab[index];
HashEntry<K,V> e = first;
// a ref remove operation compares the Reference instance
while (e != null && key != e.keyRef
&& (refRemove || hash != e.hash || !keyEq(key, e.key())))
e = e.next;
V oldValue = null;
if (e != null) {
V v = e.value();
if (value == null || value.equals(v)) {
oldValue = v;
// All entries following removed node can stay
// in list, but all preceding ones need to be
// cloned.
++modCount;
HashEntry<K,V> newFirst = e.next;
for (HashEntry<K,V> p = first; p != e; p = p.next) {
K pKey = p.key();
if (pKey == null) { // Skip GC'd keys
c--;
continue;
}
newFirst = newHashEntry(pKey, p.hash, newFirst, p.value());
}
tab[index] = newFirst;
count = c; // write-volatile
}
}
return oldValue;
} finally {
unlock();
}
}
void removeStale() {
KeyReference ref;
while ((ref = (KeyReference) refQueue.poll()) != null) {
remove(ref.keyRef(), ref.keyHash(), null, true);
}
}
void clear() {
if (count != 0) {
lock();
try {
HashEntry<K,V>[] tab = table;
for (int i = 0; i < tab.length ; i++)
tab[i] = null;
++modCount;
// replace the reference queue to avoid unnecessary stale cleanups
refQueue = new ReferenceQueue<Object>();
count = 0; // write-volatile
} finally {
unlock();
}
}
}
}
/* ---------------- Public operations -------------- */
/**
* Creates a new, empty map with the specified initial
* capacity, reference types, load factor and concurrency level.
*
* Behavioral changing options such as {@link Option#IDENTITY_COMPARISONS}
* can also be specified.
*
* @param initialCapacity the initial capacity. The implementation
* performs internal sizing to accommodate this many elements.
* @param loadFactor the load factor threshold, used to control resizing.
* Resizing may be performed when the average number of elements per
* bin exceeds this threshold.
* @param concurrencyLevel the estimated number of concurrently
* updating threads. The implementation performs internal sizing
* to try to accommodate this many threads.
* @param keyType the reference type to use for keys
* @param valueType the reference type to use for values
* @param options the behavioral options
* @throws IllegalArgumentException if the initial capacity is
* negative or the load factor or concurrencyLevel are
* nonpositive.
*/
public ConcurrentReferenceHashMap(int initialCapacity,
float loadFactor, int concurrencyLevel,
ReferenceType keyType, ReferenceType valueType,
EnumSet<Option> options) {
if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0)
throw new IllegalArgumentException();
if (concurrencyLevel > MAX_SEGMENTS)
concurrencyLevel = MAX_SEGMENTS;
// Find power-of-two sizes best matching arguments
int sshift = 0;
int ssize = 1;
while (ssize < concurrencyLevel) {
++sshift;
ssize <<= 1;
}
segmentShift = 32 - sshift;
segmentMask = ssize - 1;
this.segments = Segment.newArray(ssize);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
int c = initialCapacity / ssize;
if (c * ssize < initialCapacity)
++c;
int cap = 1;
while (cap < c)
cap <<= 1;
identityComparisons = options != null && options.contains(Option.IDENTITY_COMPARISONS);
for (int i = 0; i < this.segments.length; ++i)
this.segments[i] = new Segment<K,V>(cap, loadFactor,
keyType, valueType, identityComparisons);
}
/**
* Creates a new, empty map with the specified initial
* capacity, load factor and concurrency level.
*
* @param initialCapacity the initial capacity. The implementation
* performs internal sizing to accommodate this many elements.
* @param loadFactor the load factor threshold, used to control resizing.
* Resizing may be performed when the average number of elements per
* bin exceeds this threshold.
* @param concurrencyLevel the estimated number of concurrently
* updating threads. The implementation performs internal sizing
* to try to accommodate this many threads.
* @throws IllegalArgumentException if the initial capacity is
* negative or the load factor or concurrencyLevel are
* nonpositive.
*/
public ConcurrentReferenceHashMap(int initialCapacity,
float loadFactor, int concurrencyLevel) {
this(initialCapacity, loadFactor, concurrencyLevel,
DEFAULT_KEY_TYPE, DEFAULT_VALUE_TYPE, null);
}
/**
* Creates a new, empty map with the specified initial capacity
* and load factor and with the default reference types (weak keys,
* strong values), and concurrencyLevel (16).
*
* @param initialCapacity The implementation performs internal
* sizing to accommodate this many elements.
* @param loadFactor the load factor threshold, used to control resizing.
* Resizing may be performed when the average number of elements per
* bin exceeds this threshold.
* @throws IllegalArgumentException if the initial capacity of
* elements is negative or the load factor is nonpositive
*
* @since 1.6
*/
public ConcurrentReferenceHashMap(int initialCapacity, float loadFactor) {
this(initialCapacity, loadFactor, DEFAULT_CONCURRENCY_LEVEL);
}
/**
* Creates a new, empty map with the specified initial capacity,
* reference types and with default load factor (0.75) and concurrencyLevel (16).
*
* @param initialCapacity the initial capacity. The implementation
* performs internal sizing to accommodate this many elements.
* @param keyType the reference type to use for keys
* @param valueType the reference type to use for values
* @throws IllegalArgumentException if the initial capacity of
* elements is negative.
*/
public ConcurrentReferenceHashMap(int initialCapacity,
ReferenceType keyType, ReferenceType valueType) {
this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL,
keyType, valueType, null);
}
/**
* Creates a new, empty map with the specified initial capacity,
* and with default reference types (weak keys, strong values),
* load factor (0.75) and concurrencyLevel (16).
*
* @param initialCapacity the initial capacity. The implementation
* performs internal sizing to accommodate this many elements.
* @throws IllegalArgumentException if the initial capacity of
* elements is negative.
*/
public ConcurrentReferenceHashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
}
/**
* Creates a new, empty map with a default initial capacity (16),
* reference types (weak keys, strong values), default
* load factor (0.75) and concurrencyLevel (16).
*/
public ConcurrentReferenceHashMap() {
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
}
/**
* Creates a new map with the same mappings as the given map.
* The map is created with a capacity of 1.5 times the number
* of mappings in the given map or 16 (whichever is greater),
* and a default load factor (0.75) and concurrencyLevel (16).
*
* @param m the map
*/
public ConcurrentReferenceHashMap(Map<? extends K, ? extends V> m) {
this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
DEFAULT_INITIAL_CAPACITY),
DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
putAll(m);
}
/**
* Returns <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> if this map contains no key-value mappings
*/
public boolean isEmpty() {
final Segment<K,V>[] segments = this.segments;
/*
* We keep track of per-segment modCounts to avoid ABA
* problems in which an element in one segment was added and
* in another removed during traversal, in which case the
* table was never actually empty at any point. Note the
* similar use of modCounts in the size() and containsValue()
* methods, which are the only other methods also susceptible
* to ABA problems.
*/
int[] mc = new int[segments.length];
int mcsum = 0;
for (int i = 0; i < segments.length; ++i) {
if (segments[i].count != 0)
return false;
else
mcsum += mc[i] = segments[i].modCount;
}
// If mcsum happens to be zero, then we know we got a snapshot
// before any modifications at all were made. This is
// probably common enough to bother tracking.
if (mcsum != 0) {
for (int i = 0; i < segments.length; ++i) {
if (segments[i].count != 0 ||
mc[i] != segments[i].modCount)
return false;
}
}
return true;
}
/**
* Returns the number of key-value mappings in this map. If the
* map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of key-value mappings in this map
*/
public int size() {
final Segment<K,V>[] segments = this.segments;
long sum = 0;
long check = 0;
int[] mc = new int[segments.length];
// Try a few times to get accurate count. On failure due to
// continuous async changes in table, resort to locking.
for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) {
check = 0;
sum = 0;
int mcsum = 0;
for (int i = 0; i < segments.length; ++i) {
sum += segments[i].count;
mcsum += mc[i] = segments[i].modCount;
}
if (mcsum != 0) {
for (int i = 0; i < segments.length; ++i) {
check += segments[i].count;
if (mc[i] != segments[i].modCount) {
check = -1; // force retry
break;
}
}
}
if (check == sum)
break;
}
if (check != sum) { // Resort to locking all segments
sum = 0;
for (int i = 0; i < segments.length; ++i)
segments[i].lock();
for (int i = 0; i < segments.length; ++i)
sum += segments[i].count;
for (int i = 0; i < segments.length; ++i)
segments[i].unlock();
}
if (sum > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
else
return (int)sum;
}
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code key.equals(k)},
* then this method returns {@code v}; otherwise it returns
* {@code null}. (There can be at most one such mapping.)
*
* @throws NullPointerException if the specified key is null
*/
public V get(Object key) {
int hash = hashOf(key);
return segmentFor(hash).get(key, hash);
}
/**
* Tests if the specified object is a key in this table.
*
* @param key possible key
* @return <tt>true</tt> if and only if the specified object
* is a key in this table, as determined by the
* <tt>equals</tt> method; <tt>false</tt> otherwise.
* @throws NullPointerException if the specified key is null
*/
public boolean containsKey(Object key) {
int hash = hashOf(key);
return segmentFor(hash).containsKey(key, hash);
}
/**
* Returns <tt>true</tt> if this map maps one or more keys to the
* specified value. Note: This method requires a full internal
* traversal of the hash table, and so is much slower than
* method <tt>containsKey</tt>.
*
* @param value value whose presence in this map is to be tested
* @return <tt>true</tt> if this map maps one or more keys to the
* specified value
* @throws NullPointerException if the specified value is null
*/
public boolean containsValue(Object value) {
checkNotNullParamWithNullPointerException("value", value);
// See explanation of modCount use above
final Segment<K,V>[] segments = this.segments;
int[] mc = new int[segments.length];
// Try a few times without locking
for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) {
int mcsum = 0;
for (int i = 0; i < segments.length; ++i) {
mcsum += mc[i] = segments[i].modCount;
if (segments[i].containsValue(value))
return true;
}
boolean cleanSweep = true;
if (mcsum != 0) {
for (int i = 0; i < segments.length; ++i) {
if (mc[i] != segments[i].modCount) {
cleanSweep = false;
break;
}
}
}
if (cleanSweep)
return false;
}
// Resort to locking all segments
for (int i = 0; i < segments.length; ++i)
segments[i].lock();
boolean found = false;
try {
for (int i = 0; i < segments.length; ++i) {
if (segments[i].containsValue(value)) {
found = true;
break;
}
}
} finally {
for (int i = 0; i < segments.length; ++i)
segments[i].unlock();
}
return found;
}
/**
* Legacy method testing if some key maps into the specified value
* in this table. This method is identical in functionality to
* {@link #containsValue}, and exists solely to ensure
* full compatibility with class {@link java.util.Hashtable},
* which supported this method prior to introduction of the
* Java Collections framework.
* @param value a value to search for
* @return <tt>true</tt> if and only if some key maps to the
* <tt>value</tt> argument in this table as
* determined by the <tt>equals</tt> method;
* <tt>false</tt> otherwise
* @throws NullPointerException if the specified value is null
*/
public boolean contains(Object value) {
return containsValue(value);
}
/**
* Maps the specified key to the specified value in this table.
* Neither the key nor the value can be null.
*
* <p> The value can be retrieved by calling the <tt>get</tt> method
* with a key that is equal to the original key.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>
* @throws NullPointerException if the specified key or value is null
*/
public V put(K key, V value) {
checkNotNullParamWithNullPointerException("value", value);
int hash = hashOf(key);
return segmentFor(hash).put(key, hash, value, false);
}
/**
* {@inheritDoc}
*
* @return the previous value associated with the specified key,
* or <tt>null</tt> if there was no mapping for the key
* @throws NullPointerException if the specified key or value is null
*/
public V putIfAbsent(K key, V value) {
checkNotNullParamWithNullPointerException("value", value);
int hash = hashOf(key);
return segmentFor(hash).put(key, hash, value, true);
}
/**
* Copies all of the mappings from the specified map to this one.
* These mappings replace any mappings that this map had for any of the
* keys currently in the specified map.
*
* @param m mappings to be stored in this map
*/
public void putAll(Map<? extends K, ? extends V> m) {
for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
put(e.getKey(), e.getValue());
}
/**
* Removes the key (and its corresponding value) from this map.
* This method does nothing if the key is not in the map.
*
* @param key the key that needs to be removed
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>
* @throws NullPointerException if the specified key is null
*/
public V remove(Object key) {
int hash = hashOf(key);
return segmentFor(hash).remove(key, hash, null, false);
}
/**
* {@inheritDoc}
*
* @throws NullPointerException if the specified key is null
*/
public boolean remove(Object key, Object value) {
int hash = hashOf(key);
if (value == null)
return false;
return segmentFor(hash).remove(key, hash, value, false) != null;
}
/**
* {@inheritDoc}
*
* @throws NullPointerException if any of the arguments are null
*/
public boolean replace(K key, V oldValue, V newValue) {
checkNotNullParamWithNullPointerException("oldValue", oldValue);
checkNotNullParamWithNullPointerException("newValue", newValue);
int hash = hashOf(key);
return segmentFor(hash).replace(key, hash, oldValue, newValue);
}
/**
* {@inheritDoc}
*
* @return the previous value associated with the specified key,
* or <tt>null</tt> if there was no mapping for the key
* @throws NullPointerException if the specified key or value is null
*/
public V replace(K key, V value) {
checkNotNullParamWithNullPointerException("value", value);
int hash = hashOf(key);
return segmentFor(hash).replace(key, hash, value);
}
/**
* Removes all of the mappings from this map.
*/
public void clear() {
for (int i = 0; i < segments.length; ++i)
segments[i].clear();
}
/**
* Removes any stale entries whose keys have been finalized. Use of this
* method is normally not necessary since stale entries are automatically
* removed lazily, when blocking operations are required. However, there
* are some cases where this operation should be performed eagerly, such
* as cleaning up old references to a ClassLoader in a multi-classloader
* environment.
*
* Note: this method will acquire locks, one at a time, across all segments
* of this table, so if it is to be used, it should be used sparingly.
*/
public void purgeStaleEntries() {
for (int i = 0; i < segments.length; ++i)
segments[i].removeStale();
}
/**
* Returns a {@link Set} view of the keys contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. The set supports element
* removal, which removes the corresponding mapping from this map,
* via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
* <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
* operations. It does not support the <tt>add</tt> or
* <tt>addAll</tt> operations.
*
* <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
* that will never throw {@link java.util.ConcurrentModificationException},
* and guarantees to traverse elements as they existed upon
* construction of the iterator, and may (but is not guaranteed to)
* reflect any modifications subsequent to construction.
*/
public Set<K> keySet() {
Set<K> ks = keySet;
return (ks != null) ? ks : (keySet = new KeySet());
}
/**
* Returns a {@link Collection} view of the values contained in this map.
* The collection is backed by the map, so changes to the map are
* reflected in the collection, and vice-versa. The collection
* supports element removal, which removes the corresponding
* mapping from this map, via the <tt>Iterator.remove</tt>,
* <tt>Collection.remove</tt>, <tt>removeAll</tt>,
* <tt>retainAll</tt>, and <tt>clear</tt> operations. It does not
* support the <tt>add</tt> or <tt>addAll</tt> operations.
*
* <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
* that will never throw {@link java.util.ConcurrentModificationException},
* and guarantees to traverse elements as they existed upon
* construction of the iterator, and may (but is not guaranteed to)
* reflect any modifications subsequent to construction.
*/
public Collection<V> values() {
Collection<V> vs = values;
return (vs != null) ? vs : (values = new Values());
}
/**
* Returns a {@link Set} view of the mappings contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. The set supports element
* removal, which removes the corresponding mapping from the map,
* via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
* <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
* operations. It does not support the <tt>add</tt> or
* <tt>addAll</tt> operations.
*
* <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
* that will never throw {@link java.util.ConcurrentModificationException},
* and guarantees to traverse elements as they existed upon
* construction of the iterator, and may (but is not guaranteed to)
* reflect any modifications subsequent to construction.
*/
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es = entrySet;
return (es != null) ? es : (entrySet = new EntrySet());
}
/**
* Returns an enumeration of the keys in this table.
*
* @return an enumeration of the keys in this table
* @see #keySet()
*/
public Enumeration<K> keys() {
return new KeyIterator();
}
/**
* Returns an enumeration of the values in this table.
*
* @return an enumeration of the values in this table
* @see #values()
*/
public Enumeration<V> elements() {
return new ValueIterator();
}
/* ---------------- Iterator Support -------------- */
abstract class HashIterator {
int nextSegmentIndex;
int nextTableIndex;
HashEntry<K,V>[] currentTable;
HashEntry<K, V> nextEntry;
HashEntry<K, V> lastReturned;
K currentKey; // Strong reference to weak key (prevents gc)
HashIterator() {
nextSegmentIndex = segments.length - 1;
nextTableIndex = -1;
advance();
}
public boolean hasMoreElements() {
return hasNext();
}
final void advance() {
if (nextEntry != null && (nextEntry = nextEntry.next) != null)
return;
while (nextTableIndex >= 0) {
if ( (nextEntry = currentTable[nextTableIndex--]) != null)
return;
}
while (nextSegmentIndex >= 0) {
Segment<K,V> seg = segments[nextSegmentIndex--];
if (seg.count != 0) {
currentTable = seg.table;
for (int j = currentTable.length - 1; j >= 0; --j) {
if ( (nextEntry = currentTable[j]) != null) {
nextTableIndex = j - 1;
return;
}
}
}
}
}
public boolean hasNext() {
while (nextEntry != null) {
if (nextEntry.key() != null)
return true;
advance();
}
return false;
}
HashEntry<K,V> nextEntry() {
do {
if (nextEntry == null)
throw new NoSuchElementException();
lastReturned = nextEntry;
currentKey = lastReturned.key();
advance();
} while (currentKey == null); // Skip GC'd keys
return lastReturned;
}
public void remove() {
if (lastReturned == null)
throw new IllegalStateException();
ConcurrentReferenceHashMap.this.remove(currentKey);
lastReturned = null;
}
}
final class KeyIterator
extends HashIterator
implements Iterator<K>, Enumeration<K> {
public K next() {
return super.nextEntry().key();
}
public K nextElement() {
return super.nextEntry().key();
}
}
final class ValueIterator
extends HashIterator
implements Iterator<V>, Enumeration<V> {
public V next() {
return super.nextEntry().value();
}
public V nextElement() {
return super.nextEntry().value();
}
}
/*
* This class is needed for JDK5 compatibility.
*/
static class SimpleEntry<K, V> implements Entry<K, V>,
java.io.Serializable {
private static final long serialVersionUID = -8499721149061103585L;
private final K key;
private V value;
public SimpleEntry(K key, V value) {
this.key = key;
this.value = value;
}
public SimpleEntry(Entry<? extends K, ? extends V> entry) {
this.key = entry.getKey();
this.value = entry.getValue();
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public V setValue(V value) {
V oldValue = this.value;
this.value = value;
return oldValue;
}
public boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> e = (Map.Entry<?,?>) o;
return eq(key, e.getKey()) && eq(value, e.getValue());
}
public int hashCode() {
return (key == null ? 0 : key.hashCode())
^ (value == null ? 0 : value.hashCode());
}
public String toString() {
return key + "=" + value;
}
private static boolean eq(Object o1, Object o2) {
return o1 == null ? o2 == null : o1.equals(o2);
}
}
/**
* Custom Entry class used by EntryIterator.next(), that relays setValue
* changes to the underlying map.
*/
final class WriteThroughEntry extends SimpleEntry<K,V> {
private static final long serialVersionUID = -7900634345345313646L;
WriteThroughEntry(K k, V v) {
super(k,v);
}
/**
* Set our entry's value and write through to the map. The
* value to return is somewhat arbitrary here. Since a
* WriteThroughEntry does not necessarily track asynchronous
* changes, the most recent "previous" value could be
* different from what we return (or could even have been
* removed in which case the put will re-establish). We do not
* and cannot guarantee more.
*/
public V setValue(V value) {
checkNotNullParamWithNullPointerException("value", value);
V v = super.setValue(value);
ConcurrentReferenceHashMap.this.put(getKey(), value);
return v;
}
}
final class EntryIterator
extends HashIterator
implements Iterator<Entry<K,V>> {
public Map.Entry<K,V> next() {
HashEntry<K,V> e = super.nextEntry();
return new WriteThroughEntry(e.key(), e.value());
}
}
final class KeySet extends AbstractSet<K> {
public Iterator<K> iterator() {
return new KeyIterator();
}
public int size() {
return ConcurrentReferenceHashMap.this.size();
}
public boolean isEmpty() {
return ConcurrentReferenceHashMap.this.isEmpty();
}
public boolean contains(Object o) {
return ConcurrentReferenceHashMap.this.containsKey(o);
}
public boolean remove(Object o) {
return ConcurrentReferenceHashMap.this.remove(o) != null;
}
public void clear() {
ConcurrentReferenceHashMap.this.clear();
}
}
final class Values extends AbstractCollection<V> {
public Iterator<V> iterator() {
return new ValueIterator();
}
public int size() {
return ConcurrentReferenceHashMap.this.size();
}
public boolean isEmpty() {
return ConcurrentReferenceHashMap.this.isEmpty();
}
public boolean contains(Object o) {
return ConcurrentReferenceHashMap.this.containsValue(o);
}
public void clear() {
ConcurrentReferenceHashMap.this.clear();
}
}
final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
public Iterator<Map.Entry<K,V>> iterator() {
return new EntryIterator();
}
public boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
V v = ConcurrentReferenceHashMap.this.get(e.getKey());
return v != null && v.equals(e.getValue());
}
public boolean remove(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
return ConcurrentReferenceHashMap.this.remove(e.getKey(), e.getValue());
}
public int size() {
return ConcurrentReferenceHashMap.this.size();
}
public boolean isEmpty() {
return ConcurrentReferenceHashMap.this.isEmpty();
}
public void clear() {
ConcurrentReferenceHashMap.this.clear();
}
}
/* ---------------- Serialization Support -------------- */
/**
* Save the state of the <tt>ConcurrentReferenceHashMap</tt> instance to a
* stream (i.e., serialize it).
* @param s the stream
* @serialData
* the key (Object) and value (Object)
* for each key-value mapping, followed by a null pair.
* The key-value mappings are emitted in no particular order.
*/
private void writeObject(java.io.ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
for (int k = 0; k < segments.length; ++k) {
Segment<K,V> seg = segments[k];
seg.lock();
try {
HashEntry<K,V>[] tab = seg.table;
for (int i = 0; i < tab.length; ++i) {
for (HashEntry<K,V> e = tab[i]; e != null; e = e.next) {
K key = e.key();
if (key == null) // Skip GC'd keys
continue;
s.writeObject(key);
s.writeObject(e.value());
}
}
} finally {
seg.unlock();
}
}
s.writeObject(null);
s.writeObject(null);
}
/**
* Reconstitute the <tt>ConcurrentReferenceHashMap</tt> instance from a
* stream (i.e., deserialize it).
* @param s the stream
*/
@SuppressWarnings("unchecked")
private void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
// Initialize each segment to be minimally sized, and let grow.
for (int i = 0; i < segments.length; ++i) {
segments[i].setTable(new HashEntry[1]);
}
// Read the keys and values, and put the mappings in the table
for (;;) {
K key = (K) s.readObject();
V value = (V) s.readObject();
if (key == null)
break;
put(key, value);
}
}
}
| 64,355 | 36.221515 | 107 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/common/StartupContext.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.web.common;
/**
*
* Contains context information that is exposed on startup via a thread local
*
* @author Stuart Douglas
*/
public class StartupContext {
private static final ThreadLocal<WebInjectionContainer> INJECTION_CONTAINER = new ThreadLocal<WebInjectionContainer>();
public static void setInjectionContainer(final WebInjectionContainer injectionContainer) {
INJECTION_CONTAINER.set(injectionContainer);
}
public static WebInjectionContainer getInjectionContainer() {
return INJECTION_CONTAINER.get();
}
public static void removeInjectionContainer() {
INJECTION_CONTAINER.remove();
}
}
| 1,702 | 33.755102 | 123 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/common/WarMetaData.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.web.common;
import java.io.File;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.metadata.web.jboss.JBossWebMetaData;
import org.jboss.metadata.web.spec.WebFragmentMetaData;
import org.jboss.metadata.web.spec.WebMetaData;
import org.jboss.msc.service.ServiceName;
import org.jboss.vfs.VirtualFile;
/**
* @author Remy Maucherat
*/
public class WarMetaData {
public static final AttachmentKey<WarMetaData> ATTACHMENT_KEY = AttachmentKey.create(WarMetaData.class);
/**
* jboss-web.xml metadata.
*/
private volatile JBossWebMetaData jbossWebMetaData;
/**
* Main web.xml metadata.
*/
private volatile WebMetaData webMetaData;
/**
* Web fragments metadata.
*/
private volatile Map<String, WebFragmentMetaData> webFragmentsMetaData;
/**
* Annotations metadata.
*/
private volatile Map<String, WebMetaData> annotationsMetaData;
/**
* additional module annotations metadata.
*/
private volatile List<WebMetaData> additionalModuleAnnotationsMetadata;
/**
* Order.
*/
private volatile List<String> order;
/**
* No order flag.
*/
private volatile boolean noOrder = false;
/**
* Overlays.
*/
private volatile Set<VirtualFile> overlays;
/**
* SCIs.
*/
private volatile Map<String, VirtualFile> scis;
/**
* Final merged metadata.
*/
private volatile JBossWebMetaData mergedJBossWebMetaData;
private File tempDir;
private final Set<ServiceName> additionalDependencies = new HashSet<ServiceName>();
public JBossWebMetaData getJBossWebMetaData() {
return jbossWebMetaData;
}
public void setJBossWebMetaData(JBossWebMetaData jbossWebMetaData) {
this.jbossWebMetaData = jbossWebMetaData;
}
public WebMetaData getWebMetaData() {
return webMetaData;
}
public void setWebMetaData(WebMetaData webMetaData) {
this.webMetaData = webMetaData;
}
public Map<String, WebFragmentMetaData> getWebFragmentsMetaData() {
return webFragmentsMetaData;
}
public void setWebFragmentsMetaData(Map<String, WebFragmentMetaData> webFragmentsMetaData) {
this.webFragmentsMetaData = webFragmentsMetaData;
}
public Map<String, WebMetaData> getAnnotationsMetaData() {
return annotationsMetaData;
}
public void setAnnotationsMetaData(Map<String, WebMetaData> annotationsMetaData) {
this.annotationsMetaData = annotationsMetaData;
}
public List<String> getOrder() {
return order;
}
public void setOrder(List<String> order) {
this.order = order;
}
public boolean isNoOrder() {
return noOrder;
}
public void setNoOrder(boolean noOrder) {
this.noOrder = noOrder;
}
public Set<VirtualFile> getOverlays() {
return overlays;
}
public void setOverlays(Set<VirtualFile> overlays) {
this.overlays = overlays;
}
public Map<String, VirtualFile> getScis() {
return scis;
}
public void setScis(Map<String, VirtualFile> scis) {
this.scis = scis;
}
public JBossWebMetaData getMergedJBossWebMetaData() {
return mergedJBossWebMetaData;
}
public void setMergedJBossWebMetaData(JBossWebMetaData mergedJBossWebMetaData) {
this.mergedJBossWebMetaData = mergedJBossWebMetaData;
}
public List<WebMetaData> getAdditionalModuleAnnotationsMetadata() {
return additionalModuleAnnotationsMetadata;
}
public void setAdditionalModuleAnnotationsMetadata(List<WebMetaData> additionalModuleAnnotationsMetadata) {
this.additionalModuleAnnotationsMetadata = additionalModuleAnnotationsMetadata;
}
public void addAdditionalDependency(final ServiceName serviceName) {
this.additionalDependencies.add(serviceName);
}
public Set<ServiceName> getAdditionalDependencies() {
return Collections.unmodifiableSet(additionalDependencies);
}
public File getTempDir() {
return tempDir;
}
public void setTempDir(File tempDir) {
this.tempDir = tempDir;
}
}
| 5,358 | 26.482051 | 111 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/host/CommonWebServer.java
|
package org.jboss.as.web.host;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.msc.service.ServiceName;
/**
* @author Stuart Douglas
*/
public interface CommonWebServer {
@Deprecated
ServiceName SERVICE_NAME = ServiceName.JBOSS.append("web", "common", "server");
String CAPABILITY_NAME = "org.wildfly.web.common.server";
RuntimeCapability<Void> CAPABILITY = RuntimeCapability.Builder.of(CAPABILITY_NAME, false, CommonWebServer.class)
.setAllowMultipleRegistrations(true)
.build();
int getPort(String protocol, boolean secure);
}
| 612 | 25.652174 | 116 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/host/WebDeploymentController.java
|
package org.jboss.as.web.host;
/**
* @author Stuart Douglas
*/
public interface WebDeploymentController {
void create() throws Exception;
void start() throws Exception;
void stop() throws Exception;
void destroy() throws Exception;
}
| 258 | 14.235294 | 42 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/host/WebDeploymentBuilder.java
|
package org.jboss.as.web.host;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import io.undertow.predicate.Predicate;
/**
* @author Stuart Douglas
*/
public class WebDeploymentBuilder {
private ClassLoader classLoader;
private String contextRoot;
private File documentRoot;
private final List<ServletBuilder> servlets = new ArrayList<>();
public final List<Predicate> allowRequestPredicates = new ArrayList<>();
public ClassLoader getClassLoader() {
return classLoader;
}
public WebDeploymentBuilder setClassLoader(final ClassLoader classLoader) {
this.classLoader = classLoader;
return this;
}
public void addServlet(final ServletBuilder servlet) {
servlets.add(servlet);
}
public List<ServletBuilder> getServlets() {
return Collections.unmodifiableList(servlets);
}
public String getContextRoot() {
return contextRoot;
}
public WebDeploymentBuilder setContextRoot(final String contextRoot) {
this.contextRoot = contextRoot;
return this;
}
public File getDocumentRoot() {
return documentRoot;
}
public WebDeploymentBuilder setDocumentRoot(final File documentRoot) {
this.documentRoot = documentRoot;
return this;
}
public WebDeploymentBuilder addAllowedRequestPredicate(Predicate predicate) {
allowRequestPredicates.add(predicate);
return this;
}
public List<Predicate> getAllowRequestPredicates() {
return Collections.unmodifiableList(allowRequestPredicates);
}
}
| 1,649 | 24.384615 | 81 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/host/WebHost.java
|
package org.jboss.as.web.host;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.msc.service.ServiceName;
/**
* @author Stuart Douglas
*/
public interface WebHost {
@Deprecated
ServiceName SERVICE_NAME = ServiceName.JBOSS.append("web", "common", "host");
String CAPABILITY_NAME = "org.wildfly.web.common.host";
RuntimeCapability<Void> CAPABILITY = RuntimeCapability.Builder.of(CAPABILITY_NAME, true, WebHost.class)
.addRequirements(CommonWebServer.CAPABILITY_NAME)
.setAllowMultipleRegistrations(true)
.build();
WebDeploymentController addWebDeployment(WebDeploymentBuilder webDeploymentBuilder) throws Exception;
}
| 707 | 31.181818 | 107 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/host/ServletBuilder.java
|
package org.jboss.as.web.host;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import jakarta.servlet.Servlet;
/**
* @author Stuart Douglas
*/
public class ServletBuilder {
private Class<?> servletClass;
private Servlet servlet;
private String servletName;
private boolean forceInit;
private final List<String> urlMappings = new ArrayList<>();
private final Map<String, String> initParams = new LinkedHashMap<>();
public Class<?> getServletClass() {
return servletClass;
}
public void setServletClass(final Class<?> servletClass) {
this.servletClass = servletClass;
}
public Servlet getServlet() {
return servlet;
}
public void setServlet(final Servlet servlet) {
this.servlet = servlet;
}
public String getServletName() {
return servletName;
}
public void setServletName(final String servletName) {
this.servletName = servletName;
}
public ServletBuilder addUrlMapping(final String mapping) {
this.urlMappings.add(mapping);
return this;
}
public ServletBuilder addUrlMappings(final String... mappings) {
this.urlMappings.addAll(Arrays.asList(mappings));
return this;
}
public ServletBuilder addUrlMappings(final Collection<String> mappings) {
this.urlMappings.addAll(mappings);
return this;
}
public List<String> getUrlMappings() {
return Collections.unmodifiableList(urlMappings);
}
public ServletBuilder addInitParam(final String name, final String value) {
initParams.put(name, value);
return this;
}
public Map<String, String> getInitParams() {
return Collections.unmodifiableMap(initParams);
}
public boolean isForceInit() {
return forceInit;
}
public void setForceInit(boolean forceInit) {
this.forceInit = forceInit;
}
}
| 2,079 | 23.761905 | 79 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/session/RoutingSupport.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.web.session;
import java.util.Map;
/**
* Exposes the mechanism for parsing and formation routing information from/into a requested session identifier.
* @author Paul Ferraro
*/
public interface RoutingSupport {
/**
* Parses the routing information from the specified session identifier.
* @param requestedSessionId the requested session identifier.
* @return a map entry containing the session ID and routing information as the key and value, respectively.
*/
Map.Entry<CharSequence, CharSequence> parse(CharSequence requestedSessionId);
/**
* Formats the specified session identifier and route identifier into a single identifier.
* @param sessionId a session identifier
* @param route a route identifier.
* @return a single identifier containing the specified session identifier and routing identifier.
*/
CharSequence format(CharSequence sessionId, CharSequence route);
}
| 1,986 | 42.195652 | 112 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/session/SharedSessionManagerConfig.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.web.session;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.metadata.web.jboss.ReplicationConfig;
import org.jboss.metadata.web.spec.SessionConfigMetaData;
import org.jboss.msc.service.ServiceName;
/**
* @author Stuart Douglas
*/
public class SharedSessionManagerConfig {
public static final AttachmentKey<SharedSessionManagerConfig> ATTACHMENT_KEY = AttachmentKey.create(SharedSessionManagerConfig.class);
public static final ServiceName SHARED_SESSION_MANAGER_SERVICE_NAME = ServiceName.of("web", "shared-session-manager");
public static final ServiceName SHARED_SESSION_AFFINITY_SERVICE_NAME = SHARED_SESSION_MANAGER_SERVICE_NAME.append("affinity");
private boolean distributable = false;
private Integer maxActiveSessions;
private ReplicationConfig replicationConfig;
private SessionConfigMetaData sessionConfig;
public boolean isDistributable() {
return this.distributable;
}
public void setDistributable(boolean distributable) {
this.distributable = distributable;
}
public Integer getMaxActiveSessions() {
return maxActiveSessions;
}
public void setMaxActiveSessions(Integer maxActiveSessions) {
this.maxActiveSessions = maxActiveSessions;
}
@Deprecated
public ReplicationConfig getReplicationConfig() {
return replicationConfig;
}
@Deprecated
public void setReplicationConfig(ReplicationConfig replicationConfig) {
this.replicationConfig = replicationConfig;
}
public SessionConfigMetaData getSessionConfig() {
return sessionConfig;
}
public void setSessionConfig(SessionConfigMetaData sessionConfig) {
this.sessionConfig = sessionConfig;
}
}
| 2,797 | 34.871795 | 138 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/session/SimpleRoutingSupport.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.web.session;
import java.nio.CharBuffer;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.Map;
import org.wildfly.common.string.CompositeCharSequence;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Implements logic for parsing/appending routing information from/to a session identifier.
*
* @author Paul Ferraro
*/
public class SimpleRoutingSupport implements RoutingSupport {
private static final String DELIMITER = WildFlySecurityManager.getPropertyPrivileged("jboss.session.route.delimiter", ".");
@Override
public Map.Entry<CharSequence, CharSequence> parse(CharSequence id) {
if (id != null) {
int length = id.length();
int delimiterLength = DELIMITER.length();
for (int i = 0; i <= length - delimiterLength; ++i) {
int routeStart = i + delimiterLength;
if (DELIMITER.contentEquals(id.subSequence(i, routeStart))) {
return new SimpleImmutableEntry<>(CharBuffer.wrap(id, 0, i), CharBuffer.wrap(id, routeStart, length));
}
}
}
return new SimpleImmutableEntry<>(id, null);
}
@Override
public CharSequence format(CharSequence sessionId, CharSequence routeId) {
if ((routeId == null) || (routeId.length() == 0)) return sessionId;
return new CompositeCharSequence(sessionId, DELIMITER, routeId);
}
}
| 2,476 | 38.951613 | 127 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/session/SimpleAffinityLocator.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.web.session;
/**
* Simple affinity locator implementation using static affinity.
*
* @author Radoslav Husar
*/
public class SimpleAffinityLocator implements AffinityLocator {
private final String route;
public SimpleAffinityLocator(String route) {
this.route = route;
}
@Override
public String locate(String sessionID) {
return route;
}
}
| 1,432 | 32.325581 | 70 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/session/AffinityLocator.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.web.session;
/**
* Locates the affinity most appropriate for a provided session identifier.
*
* @author Radoslav Husar
*/
public interface AffinityLocator {
/**
* Locates the affinity most appropriate for a provided session identifier.
*
* @param sessionID a unique session identifier to be located
* @return affinity of the corresponding instance
*/
String locate(String sessionID);
}
| 1,471 | 34.902439 | 79 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/session/SessionIdentifierCodec.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.web.session;
/**
* Encapsulates logic to encode/decode additional information in/from a session identifier.
* Both the {@link #encode(CharSequence)} and {@link #decode(CharSequence)} methods should be idempotent.
* The codec methods should also be symmetrical. i.e. the result of
* <code>decode(encode(x))</code> should yield <code>x</code>, just as the result of
* <code>encode(decode(y))</code> should yield <code>y</code>.
* @author Paul Ferraro
*/
public interface SessionIdentifierCodec {
/**
* Encodes the specified session identifier
* @param sessionId a session identifier
* @return an encoded session identifier
*/
CharSequence encode(CharSequence sessionId);
/**
* Decodes the specified session identifier encoded via {@link #encode(CharSequence)}.
* @param encodedSessionId an encoded session identifier
* @return the decoded session identifier
*/
CharSequence decode(CharSequence encodedSessionId);
}
| 1,707 | 38.72093 | 105 |
java
|
null |
wildfly-main/web-common/src/main/java/org/jboss/as/web/session/SimpleSessionIdentifierCodec.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.web.session;
/**
* Simple codec implementation that uses a static route source.
* @author Paul Ferraro
*/
public class SimpleSessionIdentifierCodec implements SessionIdentifierCodec {
private final RoutingSupport routing;
private final String route;
public SimpleSessionIdentifierCodec(RoutingSupport routing, String route) {
this.routing = routing;
this.route = route;
}
@Override
public CharSequence encode(CharSequence sessionId) {
return (this.route != null) ? this.routing.format(sessionId, this.route) : sessionId;
}
@Override
public CharSequence decode(CharSequence encodedSessionId) {
return (encodedSessionId != null) ? this.routing.parse(encodedSessionId).getKey() : null;
}
}
| 1,811 | 36.75 | 97 |
java
|
null |
wildfly-main/appclient/src/main/java/org/jboss/as/appclient/service/ApplicationClientDeploymentService.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.appclient.service;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ARCHIVE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.COMPOSITE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CONTENT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEPLOYMENT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PATH;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS;
import java.io.File;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.jboss.as.controller.LocalModelControllerClient;
import org.jboss.as.controller.ModelControllerClientFactory;
import org.jboss.as.controller.client.Operation;
import org.jboss.as.controller.client.OperationBuilder;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.server.deployment.DeploymentAddHandler;
import org.jboss.as.server.deployment.DeploymentDeployHandler;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
/**
* Service responsible for deploying the application client that was specified on the command line
*
* @author Stuart Douglas
*/
public class ApplicationClientDeploymentService implements Service {
private final File path;
private final Consumer<ApplicationClientDeploymentService> consumer;
private final Supplier<ModelControllerClientFactory> clientFactorySupplier;
private final Supplier<ExecutorService> executorServiceSupplier;
private final CountDownLatch deploymentCompleteLatch = new CountDownLatch(1);
public ApplicationClientDeploymentService(final Consumer<ApplicationClientDeploymentService> consumer,
final File path,
final Supplier<ModelControllerClientFactory> clientFactorySupplier,
final Supplier<ExecutorService> executorServiceSupplier) {
this.consumer = consumer;
this.path = path;
this.clientFactorySupplier = clientFactorySupplier;
this.executorServiceSupplier = executorServiceSupplier;
}
@Override
public synchronized void start(final StartContext context) {
final DeployTask task = new DeployTask();
// TODO use executorServiceSupplier
Thread thread = new Thread(new DeploymentTask(new OperationBuilder(task.getUpdate()).build()));
thread.start();
consumer.accept(this);
}
@Override
public synchronized void stop(final StopContext context) {
//TODO: undeploy
consumer.accept(null);
}
private final class DeployTask {
ModelNode getUpdate() {
final ModelNode address = new ModelNode().add(DEPLOYMENT, path.getName());
final ModelNode addOp = Util.getEmptyOperation(DeploymentAddHandler.OPERATION_NAME, address);
addOp.get(CONTENT).set(createContent());
final ModelNode deployOp = Util.getEmptyOperation(DeploymentDeployHandler.OPERATION_NAME, address);
return getCompositeUpdate(addOp, deployOp);
}
ModelNode createContent() {
final ModelNode content = new ModelNode();
final ModelNode contentItem = content.get(0);
contentItem.get(PATH).set(path.getAbsolutePath());
contentItem.get(ARCHIVE).set(!path.isDirectory());
return content;
}
private ModelNode getCompositeUpdate(final ModelNode... updates) {
final ModelNode op = Util.getEmptyOperation(COMPOSITE, new ModelNode());
final ModelNode steps = op.get(STEPS);
for (ModelNode update : updates) {
steps.add(update);
}
return op;
}
}
private class DeploymentTask implements Runnable {
private final Operation deploymentOp;
private DeploymentTask(final Operation deploymentOp) {
this.deploymentOp = deploymentOp;
}
@Override
public void run() {
try (LocalModelControllerClient controllerClient = clientFactorySupplier.get().createSuperUserClient(executorServiceSupplier.get())) {
ModelNode result = controllerClient.execute(deploymentOp);
if (!SUCCESS.equals(result.get(OUTCOME).asString())) {
System.exit(1);
}
deploymentCompleteLatch.countDown();
}
}
}
public CountDownLatch getDeploymentCompleteLatch() {
return deploymentCompleteLatch;
}
}
| 6,052 | 40.458904 | 146 |
java
|
null |
wildfly-main/appclient/src/main/java/org/jboss/as/appclient/service/ApplicationClientStartService.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.appclient.service;
import static org.jboss.as.appclient.logging.AppClientLogger.ROOT_LOGGER;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
import java.util.function.Supplier;
import org.jboss.as.ee.component.Component;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.as.ee.naming.InjectedEENamespaceContextSelector;
import org.jboss.as.naming.context.NamespaceContextSelector;
import org.jboss.as.server.deployment.SetupAction;
import org.jboss.msc.Service;
import org.jboss.msc.service.ServiceContainer;
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.wildfly.security.manager.WildFlySecurityManager;
/**
* Service that is responsible for running an application clients main method, and shutting down the server once it
* completes
*
* @author Stuart Douglas
*/
public class ApplicationClientStartService implements Service {
public static final ServiceName SERVICE_NAME = ServiceName.of("appClientStart");
private final Supplier<ApplicationClientDeploymentService> applicationClientDeploymentServiceSupplier;
private final Supplier<Component> applicationClientComponentSupplier;
private final InjectedEENamespaceContextSelector namespaceContextSelectorInjectedValue;
private final List<SetupAction> setupActions;
private final Method mainMethod;
private final String[] parameters;
private final ClassLoader classLoader;
private Thread thread;
private ComponentInstance instance;
public ApplicationClientStartService(final Method mainMethod, final String[] parameters,
final InjectedEENamespaceContextSelector namespaceContextSelectorInjectedValue,
final ClassLoader classLoader, final List<SetupAction> setupActions,
final Supplier<ApplicationClientDeploymentService> applicationClientDeploymentServiceSupplier,
final Supplier<Component> applicationClientComponentSupplier) {
this.mainMethod = mainMethod;
this.parameters = parameters;
this.namespaceContextSelectorInjectedValue = namespaceContextSelectorInjectedValue;
this.classLoader = classLoader;
this.setupActions = setupActions;
this.applicationClientComponentSupplier = applicationClientComponentSupplier;
this.applicationClientDeploymentServiceSupplier = applicationClientDeploymentServiceSupplier;
}
@Override
public synchronized void start(final StartContext context) throws StartException {
final ServiceContainer serviceContainer = context.getController().getServiceContainer();
thread = new Thread(new Runnable() {
@Override
public void run() {
final ClassLoader oldTccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
Throwable originalException = null;
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader);
applicationClientDeploymentServiceSupplier.get().getDeploymentCompleteLatch().await();
NamespaceContextSelector.setDefault(namespaceContextSelectorInjectedValue);
try {
//perform any additional setup that may be needed
for (SetupAction action : setupActions) {
action.setup(Collections.<String, Object>emptyMap());
}
//do static injection etc
instance = applicationClientComponentSupplier.get().createInstance();
mainMethod.invoke(null, new Object[]{parameters});
} catch (Throwable ex) {
if (ex instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
originalException = ex;
} finally {
final ListIterator<SetupAction> iterator = setupActions.listIterator(setupActions.size());
Throwable suppressed = originalException;
while (iterator.hasPrevious()) {
SetupAction action = iterator.previous();
try {
action.teardown(Collections.<String, Object>emptyMap());
} catch (Throwable e) {
if (suppressed != null) {
suppressed.addSuppressed(e);
} else {
suppressed = e;
}
}
}
if (suppressed != null) {
if (suppressed instanceof RuntimeException) {
throw (RuntimeException) suppressed;
}
if (suppressed instanceof Error) {
throw (Error) suppressed;
}
throw new RuntimeException(suppressed);
}
}
} catch (Exception e) {
ROOT_LOGGER.exceptionRunningAppClient(e, e.getClass().getSimpleName());
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);
}
} finally {
serviceContainer.shutdown();
}
}
});
thread.start();
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
if(serviceContainer != null) {
serviceContainer.shutdown();
}
}
}));
}
@Override
public synchronized void stop(final StopContext context) {
if (instance != null) {
instance.destroy();
}
thread.interrupt();
thread = null;
}
}
| 7,856 | 45.217647 | 135 |
java
|
null |
wildfly-main/appclient/src/main/java/org/jboss/as/appclient/logging/AppClientLogger.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.appclient.logging;
import static org.jboss.logging.Logger.Level.ERROR;
import java.io.File;
import java.net.URL;
import javax.xml.stream.Location;
import javax.xml.stream.XMLStreamException;
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.logging.annotations.Param;
import org.jboss.vfs.VirtualFile;
/**
* @author <a href="mailto:[email protected]">James R. Perkins</a>
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
@MessageLogger(projectCode = "WFLYAC", length = 4)
public interface AppClientLogger extends BasicLogger {
/**
* The root logger.
*/
AppClientLogger ROOT_LOGGER = Logger.getMessageLogger(AppClientLogger.class, "org.jboss.as.appclient");
// /**
// * Logs a generic error message using the {@link Throwable#toString() t.toString()} for the error message.
// *
// * @param cause the cause of the error.
// * @param t the cause to use for the log message.
// */
// @LogMessage(level = ERROR)
// @Message(id = 1, value = "%s")
// void caughtException(@Cause Throwable cause, Throwable t);
/**
* Logs an error message indicating there was an error running the app client.
*
* @param cause the cause of the error.
* @param exceptionName the exception name thrown.
*/
@LogMessage(level = ERROR)
@Message(id = 2, value = "%s running app client main")
void exceptionRunningAppClient(@Cause Throwable cause, String exceptionName);
// /**
// *
// * @param cause the cause of the error.
// */
// @LogMessage(level = ERROR)
// @Message(id = 3, value = "Error closing connection")
// void exceptionClosingConnection(@Cause Throwable cause);
@Message(id = Message.NONE, value = "Name of the app client configuration file to use (default is \"appclient.xml\")")
String argAppClientConfig();
/**
* Instructions for the {@link org.jboss.as.process.CommandLineConstants#HELP} command line arguments.
*
* @return the instructions.
*/
@Message(id = Message.NONE, value = "Display this message and exit")
String argHelp();
/**
* Instructions for the {@link org.jboss.as.process.CommandLineConstants#HOST} command line arguments.
*
* @return the instructions.
*/
@Message(id = Message.NONE, value = "Set the url of the application server instance to connect to")
String argHost();
/**
* Instructions for the {@link org.jboss.as.process.CommandLineConstants#CONNECTION_PROPERTIES} command line
* arguments.
*
* @return the instructions.
*/
@Message(id = Message.NONE, value = "Load ejb-client.properties file from the given url")
String argConnectionProperties();
/**
* Instructions for the {@link org.jboss.as.process.CommandLineConstants#PROPERTIES} command line
* arguments.
*
* @return the instructions.
*/
@Message(id = Message.NONE, value = "Load system properties from the given url")
String argProperties();
/**
* Instructions for {@link org.jboss.as.process.CommandLineConstants#SYS_PROP} command line argument.
*
* @return the instructions.
*/
@Message(id = Message.NONE, value = "Set a system property")
String argSystemProperty();
// /**
// * Instructions for the usage of the command line arguments instructions.
// *
// * @return the instructions.
// */
// @Message(id = Message.NONE, value = "Usage: ./appclient.sh [args...] myear.ear#appClient.jar [client args...]%n%nwhere args include:%n")
// String argUsage();
/**
* Instructions for {@link org.jboss.as.process.CommandLineConstants#VERSION} command line argument.
*
* @return the instructions.
*/
@Message(id = Message.NONE, value = "Print version and exit")
String argVersion();
/**
* Instructions for {@link org.jboss.as.process.CommandLineConstants#VERSION} command line argument.
*
* @return the instructions.
*/
@Message(id = Message.NONE, value = "Runs the container with the security manager enabled.")
String argSecMgr();
/**
* A general description of the appclient usage.
*
* @return a {@link String} for the message.
*/
@Message(id = Message.NONE, value = "The appclient script starts an application client which can be used to test and access the deployed Jakarta Enterprise Beans.")
String usageDescription();
/**
* A message indicating that you must specify an application client to execute.
*
* @return the message.
*/
@Message(id = 4, value = "You must specify the application client to execute")
String appClientNotSpecified();
/**
* A message indicating the argument, represented by the {@code arg} parameter, expected an additional argument.
*
* @param arg the argument that expects an additional argument.
*
* @return the message.
*/
@Message(id = 5, value = "Argument expected for option %s")
String argumentExpected(String arg);
/**
* Creates an exception indicating the application client could not be found to start.
*
* @return an {@link RuntimeException} for the error.
*/
@Message(id = 6, value = "Could not find application client jar in deployment")
RuntimeException cannotFindAppClient();
/**
* Creates an exception indicating that the application client, represented by the {@code deploymentName}, could
* not be found.
*
* @param deploymentName the name of the deployment.
*
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 7, value = "Could not find application client %s")
DeploymentUnitProcessingException cannotFindAppClient(String deploymentName);
/**
* Creates an exception indicating that the application client could not load the main class.
*
* @param cause the cause of the error.
*
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 8, value = "Could not load application client main class")
RuntimeException cannotLoadAppClientMainClass(@Cause Throwable cause);
// /**
// * Creates an exception indicating the component class could not be loaded.
// *
// * @param cause the cause of the error.
// *
// * @return a {@link DeploymentUnitProcessingException} for the error.
// */
// @Message(id = 9, value = "Could not load component class")
// DeploymentUnitProcessingException cannotLoadComponentClass(@Cause Throwable cause);
/**
* A message indicating the properties could not be loaded from the URL.
*
* @param url the url to the properties.
*
* @return the message.
*/
@Message(id = 10, value = "Unable to load properties from URL %s")
String cannotLoadProperties(URL url);
/**
* Creates an exception indicating the app client could not start due to no main class being found.
*
* @param deploymentName the deployment name.
*
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 11, value = "Could not start app client %s as no main class was found")
RuntimeException cannotStartAppClient(String deploymentName);
/**
* Creates an exception indicating the app client could not start due to the main method missing on the main class.
*
* @param deploymentName the deployment name.
* @param mainClass the main class defined.
*
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 12, value = "Could not start app client %s as no main method was found on main class %s")
RuntimeException cannotStartAppClient(String deploymentName, Class<?> mainClass);
/**
* Creates an exception indicating the subsystem declaration has been duplicated.
*
* @param location the location of the error for the constructor of th exception.
*
* @return a {@link XMLStreamException} for the error.
*/
@Message(id = 13, value = "Duplicate subsystem declaration")
XMLStreamException duplicateSubsystemDeclaration(@Param Location location);
// /**
// * Creates an exception indicating the element, represented by the {@code elementName} parameter, has already been
// * declared.
// *
// * @param elementName the element name.
// * @param value the value.
// * @param location the location used in the constructor of the exception.
// *
// * @return a {@link XMLStreamException} for the error.
// */
// @Message(id = 14, value = "%s %s already declared")
// XMLStreamException elementAlreadyDeclared(String elementName, Object value, @Param Location location);
/**
* Creates an exception indicating a failure to parse the xml file represented by the {@code appXml} parameter.
*
* @param cause the cause of the error.
* @param appXml the file that failed to be parsed.
*
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 15, value = "Failed to parse %s")
DeploymentUnitProcessingException failedToParseXml(@Cause Throwable cause, VirtualFile appXml);
/**
* Creates an exception indicating a failure to parse the xml file represented by the {@code appXml} parameter.
*
* @param appXml the file that failed to be parsed.
* @param lineNumber the line the failure occurred on.
* @param columnNumber the column the failure occurred on.
*
* @return a {@link DeploymentUnitProcessingException} for the error.
*/
@Message(id = 16, value = "Failed to parse %s at [%d,%d]")
DeploymentUnitProcessingException failedToParseXml(@Cause Throwable cause, VirtualFile appXml, int lineNumber, int columnNumber);
/**
* A message indicating the URL in the argument was malformed.
*
* @param arg the invalid argument.
*
* @return the message.
*/
@Message(id = 17, value = "Malformed URL provided for option %s")
String malformedUrl(String arg);
/**
* Creates an exception indicating that more than one application client was found and not app client name was
* specified.
*
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 18, value = "More than one application client found and no app client name specified")
RuntimeException multipleAppClientsFound();
// /**
// * Creates an exception indicating the model contains multiple nodes represented by the {@code nodeName} parameter.
// *
// * @param nodeName the name of the node.
// *
// * @return an {@link IllegalStateException} for the error.
// */
// @Message(id = 19, value = "Model contains multiple %s nodes")
// IllegalStateException multipleNodesFound(String nodeName);
/**
* A message indicating a known option.
*
* @param option the unknown option.
*
* @return the message.
*/
@Message(id = 20, value = "Unknown option %s")
String unknownOption(String option);
/**
* A message indicating the callback handler could not be loaded
*
*/
@Message(id = 21, value = "Could not load callback-handler class %s")
DeploymentUnitProcessingException couldNotLoadCallbackClass(String clazz);
/**
* A message indicating the callback handler could not be instantiated
*
*/
@Message(id = 22, value = "Could not create instance of callback-handler class %s")
DeploymentUnitProcessingException couldNotCreateCallbackHandler(String clazz);
/**
* Creates an exception indicating that the application client, represented by the {@code deploymentName}, could
* not be found.
*
* @param deploymentName the name of the deployment.
*
* @return a {@link RuntimeException} for the error.
*/
@Message(id = 23, value = "Could not find application client %s")
RuntimeException cannotFindAppClientFile(File deploymentName);
@Message(id = 24, value = "Cannot specify both a host to connect to and an ejb-client.properties file. ")
RuntimeException cannotSpecifyBothHostAndPropertiesFile();
// /**
// * The ejb-client.properties could not be loaded
// */
// @Message(id = 25, value = "Unable to load ejb-client.properties URL: %s ")
// DeploymentUnitProcessingException exceptionLoadingEjbClientPropertiesURL(final String file, @Cause Throwable cause);
}
| 13,884 | 36.730978 | 168 |
java
|
null |
wildfly-main/appclient/src/main/java/org/jboss/as/appclient/deployment/ApplicationClientStartProcessor.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.appclient.deployment;
import static org.jboss.as.appclient.subsystem.AppClientSubsystemResourceDefinition.APPCLIENT_CAPABILITY;
import java.lang.reflect.Method;
import java.util.List;
import java.util.function.Supplier;
import org.jboss.as.appclient.component.ApplicationClientComponentDescription;
import org.jboss.as.appclient.logging.AppClientLogger;
import org.jboss.as.appclient.service.ApplicationClientDeploymentService;
import org.jboss.as.appclient.service.ApplicationClientStartService;
import org.jboss.as.ee.component.Component;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.SetupAction;
import org.jboss.as.server.deployment.reflect.ClassReflectionIndex;
import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex;
import org.jboss.metadata.appclient.spec.ApplicationClientMetaData;
import org.jboss.modules.Module;
import org.jboss.msc.service.ServiceBuilder;
/**
* Processor that starts an application client deployment
*
* @author Stuart Douglas
*/
public class ApplicationClientStartProcessor implements DeploymentUnitProcessor {
private final String[] parameters;
public ApplicationClientStartProcessor(final String[] parameters) {
this.parameters = parameters;
}
@Override
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final EEModuleDescription moduleDescription = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION);
final ApplicationClientMetaData appClientData = deploymentUnit.getAttachment(AppClientAttachments.APPLICATION_CLIENT_META_DATA);
final DeploymentReflectionIndex deploymentReflectionIndex = deploymentUnit.getAttachment(Attachments.REFLECTION_INDEX);
final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
Boolean activate = deploymentUnit.getAttachment(AppClientAttachments.START_APP_CLIENT);
if (activate == null || !activate) {
return;
}
final Class<?> mainClass = deploymentUnit.getAttachment(AppClientAttachments.MAIN_CLASS);
if (mainClass == null) {
throw AppClientLogger.ROOT_LOGGER.cannotStartAppClient(deploymentUnit.getName());
}
final ApplicationClientComponentDescription component = deploymentUnit.getAttachment(AppClientAttachments.APPLICATION_CLIENT_COMPONENT);
Method mainMethod = null;
Class<?> klass = mainClass;
while (klass != Object.class) {
final ClassReflectionIndex index = deploymentReflectionIndex.getClassIndex(klass);
mainMethod = index.getMethod(void.class, "main", String[].class);
if (mainMethod != null) {
break;
}
klass = klass.getSuperclass();
}
if (mainMethod == null) {
throw AppClientLogger.ROOT_LOGGER.cannotStartAppClient(deploymentUnit.getName(), mainClass);
}
final List<SetupAction> setupActions = deploymentUnit.getAttachmentList(org.jboss.as.ee.component.Attachments.OTHER_EE_SETUP_ACTIONS);
ServiceBuilder<?> builder = phaseContext.getServiceTarget()
.addService(deploymentUnit.getServiceName().append(ApplicationClientStartService.SERVICE_NAME));
Supplier<ApplicationClientDeploymentService> acdsSupplier = builder.requires(APPCLIENT_CAPABILITY.getCapabilityServiceName());
Supplier<Component> componentSupplier = builder.requires(component.getCreateServiceName());
final ApplicationClientStartService startService = new ApplicationClientStartService(mainMethod, parameters, moduleDescription.getNamespaceContextSelector(),
module.getClassLoader(), setupActions, acdsSupplier, componentSupplier);
builder.setInstance(startService).install();
}
}
| 5,309 | 49.09434 | 165 |
java
|
null |
wildfly-main/appclient/src/main/java/org/jboss/as/appclient/deployment/ApplicationClientManifestProcessor.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.appclient.deployment;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import org.jboss.as.appclient.component.ApplicationClientComponentDescription;
import org.jboss.as.appclient.logging.AppClientLogger;
import org.jboss.as.ee.component.DeploymentDescriptorEnvironment;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.ee.component.deployers.DescriptorEnvironmentLifecycleMethodProcessor;
import org.jboss.as.ee.structure.DeploymentType;
import org.jboss.as.ee.structure.DeploymentTypeMarker;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.modules.Module;
/**
* DUP that processes the manifest to get the main class
*
* @author Stuart Douglas
*/
public class ApplicationClientManifestProcessor implements DeploymentUnitProcessor {
@Override
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (!DeploymentTypeMarker.isType(DeploymentType.APPLICATION_CLIENT, deploymentUnit)) {
return;
}
final ResourceRoot root = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
final EEModuleDescription moduleDescription = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION);
final Manifest manifest = root.getAttachment(Attachments.MANIFEST);
if (manifest != null) {
Attributes main = manifest.getMainAttributes();
if (main != null) {
String mainClass = main.getValue("Main-Class");
if (mainClass != null && !mainClass.isEmpty()) {
try {
final Class<?> clazz = module.getClassLoader().loadClass(mainClass);
deploymentUnit.putAttachment(AppClientAttachments.MAIN_CLASS, clazz);
final ApplicationClientComponentDescription description = new ApplicationClientComponentDescription(clazz.getName(), moduleDescription, deploymentUnit.getServiceName());
moduleDescription.addComponent(description);
deploymentUnit.putAttachment(AppClientAttachments.APPLICATION_CLIENT_COMPONENT, description);
final DeploymentDescriptorEnvironment environment = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.MODULE_DEPLOYMENT_DESCRIPTOR_ENVIRONMENT);
if (environment != null) {
DescriptorEnvironmentLifecycleMethodProcessor.handleMethods(environment, moduleDescription, mainClass);
}
} catch (ClassNotFoundException e) {
throw AppClientLogger.ROOT_LOGGER.cannotLoadAppClientMainClass(e);
}
}
}
}
}
}
| 4,336 | 50.023529 | 193 |
java
|
null |
wildfly-main/appclient/src/main/java/org/jboss/as/appclient/deployment/ApplicationClientParsingDeploymentProcessor.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.appclient.deployment;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.jboss.as.appclient.logging.AppClientLogger;
import org.jboss.as.ee.component.DeploymentDescriptorEnvironment;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.ee.metadata.MetadataCompleteMarker;
import org.jboss.as.ee.structure.DeploymentType;
import org.jboss.as.ee.structure.DeploymentTypeMarker;
import org.jboss.as.ee.structure.JBossDescriptorPropertyReplacement;
import org.jboss.as.ee.structure.SpecDescriptorPropertyReplacement;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.metadata.appclient.jboss.JBossClientMetaData;
import org.jboss.metadata.appclient.parser.jboss.JBossClientMetaDataParser;
import org.jboss.metadata.appclient.parser.spec.ApplicationClientMetaDataParser;
import org.jboss.metadata.appclient.spec.AppClientEnvironmentRefsGroupMetaData;
import org.jboss.metadata.appclient.spec.ApplicationClientMetaData;
import org.jboss.metadata.parser.util.NoopXMLResolver;
import org.jboss.metadata.property.PropertyReplacer;
import org.jboss.vfs.VirtualFile;
/**
* @author Stuart Douglas
*/
public class ApplicationClientParsingDeploymentProcessor implements DeploymentUnitProcessor {
private static final String APP_XML = "META-INF/application-client.xml";
private static final String JBOSS_CLIENT_XML = "META-INF/jboss-client.xml";
@Override
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (!DeploymentTypeMarker.isType(DeploymentType.APPLICATION_CLIENT, deploymentUnit)) {
return;
}
final ApplicationClientMetaData appClientMD = parseAppClient(deploymentUnit, SpecDescriptorPropertyReplacement.propertyReplacer(deploymentUnit));
final JBossClientMetaData jbossClientMD = parseJBossClient(deploymentUnit, JBossDescriptorPropertyReplacement.propertyReplacer(deploymentUnit));
final JBossClientMetaData merged;
if (appClientMD == null && jbossClientMD == null) {
return;
} else if (appClientMD == null) {
merged = jbossClientMD;
} else {
merged = new JBossClientMetaData();
merged.setEnvironmentRefsGroupMetaData(new AppClientEnvironmentRefsGroupMetaData());
merged.merge(jbossClientMD, appClientMD);
}
if(merged.isMetadataComplete()) {
MetadataCompleteMarker.setMetadataComplete(deploymentUnit, true);
}
deploymentUnit.putAttachment(AppClientAttachments.APPLICATION_CLIENT_META_DATA, merged);
final DeploymentDescriptorEnvironment environment = new DeploymentDescriptorEnvironment("java:module/env/", merged.getEnvironmentRefsGroupMetaData());
deploymentUnit.putAttachment(org.jboss.as.ee.component.Attachments.MODULE_DEPLOYMENT_DESCRIPTOR_ENVIRONMENT, environment);
//override module name if applicable
if(merged.getModuleName() != null && !merged.getModuleName().isEmpty()) {
final EEModuleDescription description = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION);
description.setModuleName(merged.getModuleName());
}
}
private ApplicationClientMetaData parseAppClient(DeploymentUnit deploymentUnit, final PropertyReplacer propertyReplacer) throws DeploymentUnitProcessingException {
final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
final VirtualFile alternateDescriptor = deploymentRoot.getAttachment(org.jboss.as.ee.structure.Attachments.ALTERNATE_CLIENT_DEPLOYMENT_DESCRIPTOR);
// Locate the descriptor
final VirtualFile descriptor;
if (alternateDescriptor != null) {
descriptor = alternateDescriptor;
} else {
descriptor = deploymentRoot.getRoot().getChild(APP_XML);
}
if (descriptor.exists()) {
InputStream is = null;
try {
is = descriptor.openStream();
ApplicationClientMetaData data = new ApplicationClientMetaDataParser().parse(getXMLStreamReader(is), propertyReplacer);
return data;
} catch (XMLStreamException e) {
throw AppClientLogger.ROOT_LOGGER.failedToParseXml(e, descriptor, e.getLocation().getLineNumber(), e.getLocation().getColumnNumber());
} catch (IOException e) {
throw new DeploymentUnitProcessingException("Failed to parse " + descriptor, e);
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
// Ignore
}
}
} else {
return null;
}
}
private JBossClientMetaData parseJBossClient(DeploymentUnit deploymentUnit, final PropertyReplacer propertyReplacer) throws DeploymentUnitProcessingException {
final VirtualFile deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot();
final VirtualFile appXml = deploymentRoot.getChild(JBOSS_CLIENT_XML);
if (appXml.exists()) {
InputStream is = null;
try {
is = appXml.openStream();
JBossClientMetaData data = new JBossClientMetaDataParser().parse(getXMLStreamReader(is), propertyReplacer);
return data;
} catch (XMLStreamException e) {
throw AppClientLogger.ROOT_LOGGER.failedToParseXml(e, appXml, e.getLocation().getLineNumber(), e.getLocation().getColumnNumber());
} catch (IOException e) {
throw AppClientLogger.ROOT_LOGGER.failedToParseXml(e, appXml);
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
// Ignore
}
}
} else {
//we may already have this info from jboss-all.xml
return deploymentUnit.getAttachment(AppClientJBossAllParser.ATTACHMENT_KEY);
}
}
private XMLStreamReader getXMLStreamReader(InputStream is) throws XMLStreamException {
final XMLInputFactory inputFactory = XMLInputFactory.newInstance();
inputFactory.setXMLResolver(NoopXMLResolver.create());
XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(is);
return xmlReader;
}
}
| 8,141 | 47.754491 | 167 |
java
|
null |
wildfly-main/appclient/src/main/java/org/jboss/as/appclient/deployment/AppClientAttachments.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.appclient.deployment;
import org.jboss.as.appclient.component.ApplicationClientComponentDescription;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.metadata.appclient.spec.ApplicationClientMetaData;
/**
* @author Stuart Douglas
*/
public class AppClientAttachments {
public static final AttachmentKey<Class<?>> MAIN_CLASS = AttachmentKey.create(Class.class);
public static final AttachmentKey<Boolean> START_APP_CLIENT = AttachmentKey.create(Boolean.class);
public static final AttachmentKey<ApplicationClientMetaData> APPLICATION_CLIENT_META_DATA = AttachmentKey.create(ApplicationClientMetaData.class);
public static final AttachmentKey<ApplicationClientComponentDescription> APPLICATION_CLIENT_COMPONENT = AttachmentKey.create(ApplicationClientComponentDescription.class);
private AppClientAttachments() {
}
}
| 1,906 | 42.340909 | 174 |
java
|
null |
wildfly-main/appclient/src/main/java/org/jboss/as/appclient/deployment/ActiveApplicationClientProcessor.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.appclient.deployment;
import org.jboss.as.appclient.logging.AppClientLogger;
import org.jboss.as.ee.structure.DeploymentType;
import org.jboss.as.ee.structure.DeploymentTypeMarker;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import java.util.ArrayList;
import java.util.List;
/**
* Processor that determines which application client should be started. This may be specified on the command line,
* or alternatively if there is only one app client in the deployment it will be used.
*
* @author Stuart Douglas
*/
public class ActiveApplicationClientProcessor implements DeploymentUnitProcessor {
/**
* The deployment name passed in at startup. May be null.
*/
private final String deploymentName;
public ActiveApplicationClientProcessor(final String deploymentName) {
this.deploymentName = deploymentName;
}
@Override
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (!DeploymentTypeMarker.isType(DeploymentType.EAR, deploymentUnit)) {
if(deploymentUnit.getParent() == null ) {
deploymentUnit.putAttachment(AppClientAttachments.START_APP_CLIENT, true);
}
return;
}
final List<DeploymentUnit> appClients = new ArrayList<DeploymentUnit>();
for (DeploymentUnit subDeployment : deploymentUnit.getAttachmentList(org.jboss.as.server.deployment.Attachments.SUB_DEPLOYMENTS)) {
if (DeploymentTypeMarker.isType(DeploymentType.APPLICATION_CLIENT, subDeployment)) {
if (deploymentName != null && deploymentName.equals(subDeployment.getName())) {
subDeployment.putAttachment(AppClientAttachments.START_APP_CLIENT, true);
return;
}
appClients.add(subDeployment);
}
}
if(deploymentName != null && ! deploymentName.isEmpty()) {
throw AppClientLogger.ROOT_LOGGER.cannotFindAppClient(deploymentName);
}
if (appClients.size() == 1) {
appClients.get(0).putAttachment(AppClientAttachments.START_APP_CLIENT, true);
} else if (appClients.isEmpty()) {
throw AppClientLogger.ROOT_LOGGER.cannotFindAppClient();
} else {
throw AppClientLogger.ROOT_LOGGER.multipleAppClientsFound();
}
}
}
| 3,705 | 41.597701 | 139 |
java
|
null |
wildfly-main/appclient/src/main/java/org/jboss/as/appclient/deployment/ApplicationClientDependencyProcessor.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.appclient.deployment;
import java.util.HashSet;
import java.util.ListIterator;
import java.util.Set;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.module.ModuleDependency;
import org.jboss.as.server.deployment.module.ModuleSpecification;
import org.jboss.as.server.moduleservice.ExtensionIndexService;
import org.jboss.as.server.moduleservice.ServiceModuleLoader;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoader;
/**
* DUP that handles app client dependencies.
*
* This DUP is quite unusual, as it will also remove dependencies if they refer to
* dependencies that are not accessible to the application client. This allows a server
* side deployment to reference another module, while still allowing the app client to
* function when that additional deployment is not present.
*
* @author Stuart Douglas
*/
public class ApplicationClientDependencyProcessor implements DeploymentUnitProcessor {
public static final ModuleIdentifier CORBA_ID = ModuleIdentifier.create("org.omg.api");
public static final ModuleIdentifier XNIO = ModuleIdentifier.create("org.jboss.xnio");
public ApplicationClientDependencyProcessor() {
}
@Override
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);
final ModuleLoader loader = deploymentUnit.getAttachment(Attachments.SERVICE_MODULE_LOADER);
moduleSpecification.addSystemDependency(new ModuleDependency(loader, CORBA_ID, false, true, true, false));
moduleSpecification.addSystemDependency(new ModuleDependency(loader, XNIO, false, true, true, false));
final Set<ModuleIdentifier> moduleIdentifiers = new HashSet<ModuleIdentifier>();
final DeploymentUnit top = deploymentUnit.getParent() == null ? deploymentUnit : deploymentUnit.getParent();
moduleIdentifiers.add(top.getAttachment(Attachments.MODULE_IDENTIFIER));
for(final DeploymentUnit module : top.getAttachmentList(Attachments.SUB_DEPLOYMENTS)) {
moduleIdentifiers.add(module.getAttachment(Attachments.MODULE_IDENTIFIER));
}
final ListIterator<ModuleDependency> iterator = moduleSpecification.getMutableUserDependencies().listIterator();
while (iterator.hasNext()) {
final ModuleDependency dep = iterator.next();
final ModuleIdentifier identifier = dep.getIdentifier();
if (identifier.getName().startsWith(ServiceModuleLoader.MODULE_PREFIX)
&& !identifier.getName().startsWith(ExtensionIndexService.MODULE_PREFIX)
&& !moduleIdentifiers.contains(identifier)) {
iterator.remove();
}
}
}
}
| 4,248 | 45.692308 | 120 |
java
|
null |
wildfly-main/appclient/src/main/java/org/jboss/as/appclient/deployment/AppClientJBossAllParser.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.appclient.deployment;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.ee.structure.JBossDescriptorPropertyReplacement;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.jbossallxml.JBossAllXMLParser;
import org.jboss.metadata.appclient.jboss.JBossClientMetaData;
import org.jboss.metadata.appclient.parser.jboss.JBossClientMetaDataParser;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* The app client handler for jboss-all.xml
*
* @author Stuart Douglas
*/
public class AppClientJBossAllParser implements JBossAllXMLParser<JBossClientMetaData> {
public static final AttachmentKey<JBossClientMetaData> ATTACHMENT_KEY = AttachmentKey.create(JBossClientMetaData.class);
public static final QName ROOT_ELEMENT = new QName("http://www.jboss.com/xml/ns/javaee", "jboss-client");
@Override
public JBossClientMetaData parse(final XMLExtendedStreamReader reader, final DeploymentUnit deploymentUnit) throws XMLStreamException {
return new JBossClientMetaDataParser().parse(reader, JBossDescriptorPropertyReplacement.propertyReplacer(deploymentUnit));
}
}
| 2,286 | 42.980769 | 139 |
java
|
null |
wildfly-main/appclient/src/main/java/org/jboss/as/appclient/deployment/ApplicationClientStructureProcessor.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.appclient.deployment;
import java.io.Closeable;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.jboss.as.appclient.logging.AppClientLogger;
import org.jboss.as.ee.structure.DeploymentType;
import org.jboss.as.ee.structure.DeploymentTypeMarker;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.SubDeploymentMarker;
import org.jboss.as.server.deployment.module.ModuleRootMarker;
import org.jboss.as.server.deployment.module.MountHandle;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.as.server.deployment.module.TempFileProviderService;
import org.jboss.vfs.VFS;
import org.jboss.vfs.VirtualFile;
/**
* Processor that marks a sub-deployment as an application client based on the parameters passed on the command line
*
* @author Stuart Douglas
*/
public class ApplicationClientStructureProcessor implements DeploymentUnitProcessor {
private final String deployment;
public ApplicationClientStructureProcessor(final String deployment) {
this.deployment = deployment;
}
@Override
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
String deploymentUnitName = deploymentUnit.getName().toLowerCase(Locale.ENGLISH);
if (deploymentUnitName.endsWith(".ear")) {
final Map<VirtualFile, ResourceRoot> existing = new HashMap<VirtualFile, ResourceRoot>();
for (final ResourceRoot additional : deploymentUnit.getAttachmentList(Attachments.RESOURCE_ROOTS)) {
existing.put(additional.getRoot(), additional);
}
final ResourceRoot root = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
final VirtualFile appClientRoot = root.getRoot().getChild(deployment);
if (appClientRoot.exists()) {
if (existing.containsKey(appClientRoot)) {
final ResourceRoot existingRoot = existing.get(appClientRoot);
SubDeploymentMarker.mark(existingRoot);
ModuleRootMarker.mark(existingRoot);
} else {
final Closeable closable = appClientRoot.isFile() ? mount(appClientRoot, false) : null;
final MountHandle mountHandle = MountHandle.create(closable);
final ResourceRoot childResource = new ResourceRoot(appClientRoot, mountHandle);
ModuleRootMarker.mark(childResource);
SubDeploymentMarker.mark(childResource);
deploymentUnit.addToAttachmentList(Attachments.RESOURCE_ROOTS, childResource);
}
} else {
throw AppClientLogger.ROOT_LOGGER.cannotFindAppClient(deployment);
}
} else if (deploymentUnit.getParent() != null && deploymentUnitName.endsWith(".jar")) {
final ResourceRoot parentRoot = deploymentUnit.getParent().getAttachment(Attachments.DEPLOYMENT_ROOT);
final VirtualFile appClientRoot = parentRoot.getRoot().getChild(deployment);
final ResourceRoot root = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
if (appClientRoot.equals(root.getRoot())) {
DeploymentTypeMarker.setType(DeploymentType.APPLICATION_CLIENT, deploymentUnit);
}
}
}
private static Closeable mount(VirtualFile moduleFile, boolean explode) throws DeploymentUnitProcessingException {
try {
return explode ? VFS.mountZipExpanded(moduleFile, moduleFile, TempFileProviderService.provider())
: VFS.mountZip(moduleFile, moduleFile, TempFileProviderService.provider());
} catch (IOException e) {
throw new DeploymentUnitProcessingException(e);
}
}
}
| 5,241 | 47.537037 | 118 |
java
|
null |
wildfly-main/appclient/src/main/java/org/jboss/as/appclient/subsystem/Constants.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.appclient.subsystem;
/**
* @author Stuart Douglas
*/
class Constants {
public static final String SUBSYSTEM_NAME = "appclient";
public static final String HOST_URL ="host-url";
public static final String CONNECTION_PROPERTIES_URL ="connection-properties-url";
public static final String FILE = "file";
public static final String DEPLOYMENT = "deployment";
public static final String PARAMETERS = "parameters";
}
| 1,480 | 36.974359 | 86 |
java
|
null |
wildfly-main/appclient/src/main/java/org/jboss/as/appclient/subsystem/Main.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.appclient.subsystem;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import javax.xml.namespace.QName;
import org.jboss.as.appclient.logging.AppClientLogger;
import org.jboss.as.appclient.subsystem.parsing.AppClientXml;
import org.jboss.as.controller.extension.ExtensionRegistry;
import org.jboss.as.controller.parsing.Namespace;
import org.jboss.as.controller.persistence.ConfigurationExtensionFactory;
import org.jboss.as.controller.persistence.ExtensibleConfigurationPersister;
import org.jboss.as.process.CommandLineConstants;
import org.jboss.as.server.Bootstrap;
import org.jboss.as.server.ServerEnvironment;
import org.jboss.as.server.SystemExiter;
import org.jboss.as.version.ProductConfig;
import org.jboss.modules.Module;
import org.jboss.stdio.LoggingOutputStream;
import org.jboss.stdio.NullInputStream;
import org.jboss.stdio.SimpleStdioContextSelector;
import org.jboss.stdio.StdioContext;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* The application client entry point
*
* @author Stuart Douglas
*/
public final class Main {
// Capture System.out and System.err before they are redirected by STDIO
private static final PrintStream STDOUT = System.out;
private static final PrintStream STDERR = System.err;
private static void usage() {
CommandLineArgumentUsageImpl.printUsage(STDOUT);
}
private Main() {
}
/**
* The main method.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
if (java.util.logging.LogManager.getLogManager().getClass().getName().equals("org.jboss.logmanager.LogManager")) {
// Make sure our original stdio is properly captured.
try {
Class.forName(org.jboss.logmanager.handlers.ConsoleHandler.class.getName(), true, org.jboss.logmanager.handlers.ConsoleHandler.class.getClassLoader());
} catch (Throwable ignored) {
}
// Install JBoss Stdio to avoid any nasty crosstalk, after command line arguments are processed.
StdioContext.install();
final StdioContext context = StdioContext.create(
new NullInputStream(),
new LoggingOutputStream(org.jboss.logmanager.Logger.getLogger("stdout"), org.jboss.logmanager.Level.INFO),
new LoggingOutputStream(org.jboss.logmanager.Logger.getLogger("stderr"), org.jboss.logmanager.Level.ERROR)
);
StdioContext.setStdioContextSelector(new SimpleStdioContextSelector(context));
}
try {
Module.registerURLStreamHandlerFactoryModule(Module.getBootModuleLoader().loadModule("org.jboss.vfs"));
final ParsedOptions options = determineEnvironment(args, new Properties(WildFlySecurityManager.getSystemPropertiesPrivileged()), WildFlySecurityManager.getSystemEnvironmentPrivileged(), ServerEnvironment.LaunchType.APPCLIENT);
if(options == null) {
//this happens if --version was specified
return;
}
ServerEnvironment serverEnvironment = options.environment;
final List<String> clientArgs = options.clientArguments;
if (clientArgs.isEmpty()) {
STDERR.println(AppClientLogger.ROOT_LOGGER.appClientNotSpecified());
usage();
abort(null);
} else {
final QName rootElement = new QName(Namespace.CURRENT.getUriString(), "server");
final String file = clientArgs.get(0);
final List<String> params = clientArgs.subList(1, clientArgs.size());
final String deploymentName;
final String earPath;
int pos = file.lastIndexOf("#");
if (pos == -1) {
earPath = file;
deploymentName = null;
} else {
deploymentName = file.substring(pos + 1);
earPath = file.substring(0, pos);
}
final Bootstrap bootstrap = Bootstrap.Factory.newInstance();
final Bootstrap.Configuration configuration = new Bootstrap.Configuration(serverEnvironment);
configuration.setModuleLoader(Module.getBootModuleLoader());
final ExtensionRegistry extensionRegistry = configuration.getExtensionRegistry();
final AppClientXml parser = new AppClientXml(Module.getBootModuleLoader(), extensionRegistry);
final Bootstrap.ConfigurationPersisterFactory configurationPersisterFactory = new Bootstrap.ConfigurationPersisterFactory() {
@Override
public ExtensibleConfigurationPersister createConfigurationPersister(ServerEnvironment serverEnvironment, ExecutorService executorService) {
ApplicationClientConfigurationPersister persister = new ApplicationClientConfigurationPersister(earPath, deploymentName, options.hostUrl,options.propertiesFile, params,
serverEnvironment.getServerConfigurationFile().getBootFile(), rootElement, parser);
for (Namespace namespace : Namespace.domainValues()) {
if (!namespace.equals(Namespace.CURRENT)) {
persister.registerAdditionalRootElement(new QName(namespace.getUriString(), "server"), parser);
}
}
extensionRegistry.setWriterRegistry(persister);
return persister;
}
};
configuration.setConfigurationPersisterFactory(configurationPersisterFactory);
bootstrap.bootstrap(configuration, Collections.emptyList()).get();
}
} catch (Throwable t) {
abort(t);
}
}
private static void abort(Throwable t) {
try {
if (t != null) {
t.printStackTrace(STDERR);
}
} finally {
SystemExiter.abort(1);
}
}
public static ParsedOptions determineEnvironment(String[] args, Properties systemProperties, Map<String, String> systemEnvironment, ServerEnvironment.LaunchType launchType) {
List<String> clientArguments = new ArrayList<>();
ParsedOptions ret = new ParsedOptions();
ret.clientArguments = clientArguments;
final int argsLength = args.length;
String appClientConfig = "appclient.xml";
boolean clientArgs = false;
ProductConfig productConfig;
boolean hostSet = false;
String yamlFile = null;
for (int i = 0; i < argsLength; i++) {
final String arg = args[i];
try {
if (clientArgs) {
clientArguments.add(arg);
} else if (CommandLineConstants.VERSION.equals(arg) || CommandLineConstants.SHORT_VERSION.equals(arg)
|| CommandLineConstants.OLD_VERSION.equals(arg) || CommandLineConstants.OLD_SHORT_VERSION.equals(arg)) {
productConfig = ProductConfig.fromFilesystemSlot(Module.getBootModuleLoader(), WildFlySecurityManager.getPropertyPrivileged(ServerEnvironment.HOME_DIR, null), null);
STDOUT.println(productConfig.getPrettyVersionString());
return null;
} else if (CommandLineConstants.HELP.equals(arg) || CommandLineConstants.SHORT_HELP.equals(arg) || CommandLineConstants.OLD_HELP.equals(arg)) {
usage();
return null;
} else if (CommandLineConstants.PROPERTIES.equals(arg) || CommandLineConstants.OLD_PROPERTIES.equals(arg)
|| CommandLineConstants.SHORT_PROPERTIES.equals(arg)) {
// Set system properties from url/file
if (!processProperties(arg, args[++i])) {
return null;
}
} else if (arg.startsWith(CommandLineConstants.PROPERTIES)) {
String urlSpec = parseValue(arg, CommandLineConstants.PROPERTIES);
if (urlSpec == null || !processProperties(arg, urlSpec)) {
return null;
}
} else if (arg.startsWith(CommandLineConstants.SHORT_PROPERTIES)) {
String urlSpec = parseValue(arg, CommandLineConstants.SHORT_PROPERTIES);
if (urlSpec == null || !processProperties(arg, urlSpec)) {
return null;
}
} else if (arg.startsWith(CommandLineConstants.OLD_PROPERTIES)) {
String urlSpec = parseValue(arg, CommandLineConstants.OLD_PROPERTIES);
if (urlSpec == null || !processProperties(arg, urlSpec)) {
return null;
}
} else if (arg.equals(CommandLineConstants.SHORT_HOST) || arg.equals(CommandLineConstants.HOST)) {
if(ret.propertiesFile != null) {
throw AppClientLogger.ROOT_LOGGER.cannotSpecifyBothHostAndPropertiesFile();
}
hostSet = true;
ret.hostUrl = args[++i];
} else if (arg.startsWith(CommandLineConstants.SHORT_HOST)) {
if(ret.propertiesFile != null) {
throw AppClientLogger.ROOT_LOGGER.cannotSpecifyBothHostAndPropertiesFile();
}
hostSet = true;
ret.hostUrl = parseValue(arg, CommandLineConstants.SHORT_HOST);
} else if (arg.startsWith(CommandLineConstants.HOST)) {
if(ret.propertiesFile != null) {
throw AppClientLogger.ROOT_LOGGER.cannotSpecifyBothHostAndPropertiesFile();
}
hostSet = true;
ret.hostUrl = parseValue(arg, CommandLineConstants.HOST);
} else if (arg.startsWith(CommandLineConstants.CONNECTION_PROPERTIES)) {
if(hostSet) {
throw AppClientLogger.ROOT_LOGGER.cannotSpecifyBothHostAndPropertiesFile();
}
ret.propertiesFile = parseValue(arg, CommandLineConstants.CONNECTION_PROPERTIES);
} else if (arg.startsWith(CommandLineConstants.SYS_PROP)) {
// set a system property
String name, value;
int idx = arg.indexOf("=");
if (idx == -1) {
name = arg.substring(2);
value = "true";
} else {
name = arg.substring(2, idx);
value = arg.substring(idx + 1);
}
systemProperties.setProperty(name, value);
WildFlySecurityManager.setPropertyPrivileged(name, value);
} else if (arg.startsWith(CommandLineConstants.APPCLIENT_CONFIG)) {
appClientConfig = parseValue(arg, CommandLineConstants.APPCLIENT_CONFIG);
} else if (CommandLineConstants.SECMGR.equals(arg)) {
// ignore the argument as it's allowed, but passed to jboss-modules and not used here
} else if(ConfigurationExtensionFactory.isConfigurationExtensionSupported()
&& ConfigurationExtensionFactory.commandLineContainsArgument(arg)) {
int idx = arg.indexOf("=");
if (idx == -1) {
final int next = i + 1;
if (next < argsLength) {
yamlFile = args[next];
i++;
} else {
STDERR.println(AppClientLogger.ROOT_LOGGER.argumentExpected(arg));
usage();
return null;
}
} else {
yamlFile = arg.substring(idx + 1);
}
} else {
if (arg.startsWith("-")) {
STDOUT.println(AppClientLogger.ROOT_LOGGER.unknownOption(arg));
usage();
return null;
}
clientArgs = true;
clientArguments.add(arg);
}
} catch (IndexOutOfBoundsException e) {
STDERR.println(AppClientLogger.ROOT_LOGGER.argumentExpected(arg));
usage();
return null;
}
}
String hostControllerName = null; // No host controller unless in domain mode.
productConfig = ProductConfig.fromFilesystemSlot(Module.getBootModuleLoader(), WildFlySecurityManager.getPropertyPrivileged(ServerEnvironment.HOME_DIR, null), systemProperties);
ret.environment = new ServerEnvironment(hostControllerName, systemProperties, systemEnvironment, appClientConfig, null, launchType, null, productConfig,
System.currentTimeMillis(), false, false,null, null, null, yamlFile);
return ret;
}
private static String parseValue(final String arg, final String key) {
String value = null;
int splitPos = key.length();
if (arg.length() <= splitPos + 1 || arg.charAt(splitPos) != '=') {
usage();
} else {
value = arg.substring(splitPos + 1);
}
return value;
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
private static boolean processProperties(final String arg, final String urlSpec) {
URL url = null;
try {
url = makeURL(urlSpec);
Properties props = System.getProperties();
props.load(url.openConnection().getInputStream());
return true;
} catch (MalformedURLException e) {
STDERR.println(AppClientLogger.ROOT_LOGGER.malformedUrl(arg));
usage();
return false;
} catch (IOException e) {
STDERR.println(AppClientLogger.ROOT_LOGGER.cannotLoadProperties(url));
usage();
return false;
}
}
private static URL makeURL(String urlspec) throws MalformedURLException {
urlspec = urlspec.trim();
URL url;
try {
url = new URL(urlspec);
if (url.getProtocol().equals("file")) {
// make sure the file is absolute & canonical file url
File file = new File(url.getFile()).getCanonicalFile();
url = file.toURI().toURL();
}
} catch (Exception e) {
// make sure we have an absolute & canonical file url
try {
File file = new File(urlspec).getCanonicalFile();
url = file.toURI().toURL();
} catch (Exception n) {
throw new MalformedURLException(n.toString());
}
}
return url;
}
private static final class ParsedOptions {
ServerEnvironment environment;
List<String> clientArguments;
// by default we use http upgrade support of the Undertow web server
String hostUrl = "http-remoting://localhost:8080";
String propertiesFile;
}
}
| 16,792 | 46.304225 | 238 |
java
|
null |
wildfly-main/appclient/src/main/java/org/jboss/as/appclient/subsystem/AppClientServerConfiguration.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.appclient.subsystem;
import java.util.ArrayList;
import java.util.List;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.dmr.ModelNode;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXTENSION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
/**
* Class that contains the static application client server configuration
*
* @author Stuart Douglas
*/
class AppClientServerConfiguration {
private AppClientServerConfiguration() {
}
public static List<ModelNode> serverConfiguration(final String filePath, final String deploymentName, final String hostUrl, final String propertiesFileUrl, final List<String> parameters, List<ModelNode> xmlNodes) {
List<ModelNode> ret = new ArrayList<ModelNode>();
for (final ModelNode node : xmlNodes) {
ret.add(node);
}
appclient(ret, filePath, deploymentName, hostUrl, propertiesFileUrl, parameters);
return ret;
}
private static void appclient(List<ModelNode> nodes, final String filePath, final String deploymentName, final String hostUrl, final String propertiesFileUrl, final List<String> parameters) {
loadExtension(nodes, "org.jboss.as.appclient");
ModelNode add = Util.createAddOperation(PathAddress.pathAddress(AppClientExtension.SUBSYSTEM_PATH));
add.get(Constants.FILE).set(filePath);
if (deploymentName != null) {
add.get(Constants.DEPLOYMENT).set(deploymentName);
}
if (parameters.isEmpty()) {
add.get(Constants.PARAMETERS).setEmptyList();
} else {
for (String param : parameters) {
add.get(Constants.PARAMETERS).add(param);
}
}
if(hostUrl != null) {
add.get(Constants.HOST_URL).set(hostUrl);
}
if(propertiesFileUrl != null) {
add.get(Constants.CONNECTION_PROPERTIES_URL).set(propertiesFileUrl);
}
nodes.add(add);
}
private static void loadExtension(List<ModelNode> nodes, String moduleName) {
final ModelNode add = new ModelNode();
add.get(OP_ADDR).set(new ModelNode().setEmptyList()).add(EXTENSION, moduleName);
add.get(OP).set(ADD);
nodes.add(add);
}
}
| 3,558 | 39.443182 | 218 |
java
|
null |
wildfly-main/appclient/src/main/java/org/jboss/as/appclient/subsystem/CommandLineArgumentUsageImpl.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.appclient.subsystem;
import java.io.PrintStream;
import org.jboss.as.appclient.logging.AppClientLogger;
import org.jboss.as.controller.persistence.ConfigurationExtensionFactory;
import org.jboss.as.process.CommandLineArgumentUsage;
import org.jboss.as.process.CommandLineConstants;
public class CommandLineArgumentUsageImpl extends CommandLineArgumentUsage {
public static void init(){
addArguments(CommandLineConstants.APPCLIENT_CONFIG + "=<config>");
instructions.add(AppClientLogger.ROOT_LOGGER.argAppClientConfig());
addArguments( CommandLineConstants.SHORT_HELP, CommandLineConstants.HELP);
instructions.add(AppClientLogger.ROOT_LOGGER.argHelp());
addArguments(CommandLineConstants.HOST + "=<url>", CommandLineConstants.SHORT_HOST + "=<url>");
instructions.add(AppClientLogger.ROOT_LOGGER.argHost());
addArguments(CommandLineConstants.SHORT_PROPERTIES + "=<url>", CommandLineConstants.PROPERTIES + "=<url>");
instructions.add(AppClientLogger.ROOT_LOGGER.argProperties());
addArguments(CommandLineConstants.CONNECTION_PROPERTIES + "=<url>");
instructions.add(AppClientLogger.ROOT_LOGGER.argConnectionProperties());
addArguments(CommandLineConstants.SYS_PROP + "<name>[=value]");
instructions.add(AppClientLogger.ROOT_LOGGER.argSystemProperty());
addArguments(CommandLineConstants.SHORT_VERSION, CommandLineConstants.VERSION);
instructions.add(AppClientLogger.ROOT_LOGGER.argVersion());
addArguments(CommandLineConstants.SECMGR);
instructions.add(AppClientLogger.ROOT_LOGGER.argSecMgr());
if(ConfigurationExtensionFactory.isConfigurationExtensionSupported()) {
addArguments(ConfigurationExtensionFactory.getCommandLineUsageArguments());
instructions.add(ConfigurationExtensionFactory.getCommandLineInstructions());
}
}
public static void printUsage(final PrintStream out) {
init();
out.print(AppClientLogger.ROOT_LOGGER.usageDescription());
out.print(usage("appclient"));
}
}
| 3,145 | 43.309859 | 115 |
java
|
null |
wildfly-main/appclient/src/main/java/org/jboss/as/appclient/subsystem/AppClientSubsystemResourceDefinition.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.appclient.subsystem;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.StringListAttributeDefinition;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.OperationEntry;
import org.jboss.dmr.ModelType;
/**
* {@link org.jboss.as.controller.ResourceDefinition} for the App Client subsystem's root management resource.
* <p/>
* Note that in normal circumstances the app client subsystem will never be installed into a container that
* provides access to the management API
*
* @author Stuart Douglas
*/
public class AppClientSubsystemResourceDefinition extends SimpleResourceDefinition {
static final String MCF_CAPABILITY = "org.wildfly.management.model-controller-client-factory";
static final String EXECUTOR_CAPABILITY = "org.wildfly.management.executor";
public static final RuntimeCapability<Void> APPCLIENT_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.appclient", Void.class)
//.addRequirements(MCF_CAPABILITY, EXECUTOR_CAPABILITY) TODO determine why this breaks domain mode provisioning
.build();
public static final SimpleAttributeDefinition FILE =
new SimpleAttributeDefinitionBuilder(Constants.FILE, ModelType.STRING, false)
.setAllowExpression(true).build();
public static final SimpleAttributeDefinition DEPLOYMENT =
new SimpleAttributeDefinitionBuilder(Constants.DEPLOYMENT, ModelType.STRING, true)
.setAllowExpression(true).build();
public static final SimpleAttributeDefinition HOST_URL =
new SimpleAttributeDefinitionBuilder(Constants.HOST_URL, ModelType.STRING, true)
.setAllowExpression(true).build();
public static final SimpleAttributeDefinition CONNECTION_PROPERTIES_URL =
new SimpleAttributeDefinitionBuilder(Constants.CONNECTION_PROPERTIES_URL, ModelType.STRING, true)
.setAllowExpression(true).build();
public static final StringListAttributeDefinition PARAMETERS = new StringListAttributeDefinition.Builder(Constants.PARAMETERS)
.setRequired(false)
.setAllowExpression(true)
.build();
AppClientSubsystemResourceDefinition() {
super(new Parameters(AppClientExtension.SUBSYSTEM_PATH, AppClientExtension.getResourceDescriptionResolver())
.setAddHandler(AppClientSubsystemAdd.INSTANCE)
.setAddRestartLevel(OperationEntry.Flag.RESTART_ALL_SERVICES)
.setRemoveRestartLevel(OperationEntry.Flag.RESTART_ALL_SERVICES)
);
}
static final AttributeDefinition[] ATTRIBUTES = {
FILE,
DEPLOYMENT,
PARAMETERS,
CONNECTION_PROPERTIES_URL,
HOST_URL,
};
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
for (AttributeDefinition attr : ATTRIBUTES) {
resourceRegistration.registerReadOnlyAttribute(attr, null);
}
}
}
| 4,372 | 45.031579 | 136 |
java
|
null |
wildfly-main/appclient/src/main/java/org/jboss/as/appclient/subsystem/AppClientExtension.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.appclient.subsystem;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import java.util.List;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.Extension;
import org.jboss.as.controller.ExtensionContext;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SubsystemRegistration;
import org.jboss.as.controller.descriptions.NonResolvingResourceDescriptionResolver;
import org.jboss.as.controller.descriptions.ResourceDescriptionResolver;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.parsing.ExtensionParsingContext;
import org.jboss.as.controller.parsing.ParseUtils;
import org.jboss.as.controller.persistence.SubsystemMarshallingContext;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLElementWriter;
import org.jboss.staxmapper.XMLExtendedStreamReader;
import org.jboss.staxmapper.XMLExtendedStreamWriter;
/**
* Extension that hooks the application client work into the deployment
*
* @author Stuart Douglas
*/
public class AppClientExtension implements Extension {
public static final String NAMESPACE_1_0 = "urn:jboss:domain:appclient:1.0";
public static final String SUBSYSTEM_NAME = "appclient";
static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME);
private static final ModelVersion CURRENT_MODEL_VERSION = ModelVersion.create(1, 1, 0);
private static final ApplicationClientSubsystemParser parser = new ApplicationClientSubsystemParser();
@Override
public void initialize(final ExtensionContext context) {
final SubsystemRegistration subsystem = context.registerSubsystem(Constants.SUBSYSTEM_NAME, CURRENT_MODEL_VERSION);
subsystem.registerSubsystemModel(new AppClientSubsystemResourceDefinition());
subsystem.registerXMLElementWriter(parser);
}
@Override
public void initializeParsers(final ExtensionParsingContext context) {
context.setSubsystemXmlMapping(Constants.SUBSYSTEM_NAME, AppClientExtension.NAMESPACE_1_0, () -> parser);
}
static class ApplicationClientSubsystemParser implements XMLStreamConstants, XMLElementReader<List<ModelNode>>, XMLElementWriter<SubsystemMarshallingContext> {
/**
* {@inheritDoc}
*/
@Override
public void writeContent(XMLExtendedStreamWriter writer, SubsystemMarshallingContext context) throws XMLStreamException {
context.startSubsystemElement(AppClientExtension.NAMESPACE_1_0, false);
writer.writeEndElement();
}
/**
* {@inheritDoc}
*/
@Override
public void readElement(XMLExtendedStreamReader reader, List<ModelNode> list) throws XMLStreamException {
ParseUtils.requireNoAttributes(reader);
ParseUtils.requireNoContent(reader);
list.add(Util.createAddOperation(PathAddress.pathAddress(SUBSYSTEM_PATH)));
}
}
public static ResourceDescriptionResolver getResourceDescriptionResolver() {
return NonResolvingResourceDescriptionResolver.INSTANCE;
}
}
| 4,370 | 40.628571 | 163 |
java
|
null |
wildfly-main/appclient/src/main/java/org/jboss/as/appclient/subsystem/AppClientSubsystemAdd.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.appclient.subsystem;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.jboss.as.appclient.deployment.ActiveApplicationClientProcessor;
import org.jboss.as.appclient.deployment.AppClientJBossAllParser;
import org.jboss.as.appclient.deployment.ApplicationClientDependencyProcessor;
import org.jboss.as.appclient.logging.AppClientLogger;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.appclient.deployment.ApplicationClientManifestProcessor;
import org.jboss.as.appclient.deployment.ApplicationClientParsingDeploymentProcessor;
import org.jboss.as.appclient.deployment.ApplicationClientStartProcessor;
import org.jboss.as.appclient.deployment.ApplicationClientStructureProcessor;
import org.jboss.as.appclient.service.ApplicationClientDeploymentService;
import org.jboss.as.controller.AbstractBoottimeAddStepHandler;
import org.jboss.as.controller.CapabilityServiceBuilder;
import org.jboss.as.controller.ModelControllerClientFactory;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.server.AbstractDeploymentChainStep;
import org.jboss.as.server.DeploymentProcessorTarget;
import org.jboss.as.server.deployment.Phase;
import org.jboss.as.server.deployment.jbossallxml.JBossAllXmlParserRegisteringProcessor;
import org.jboss.dmr.ModelNode;
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 static org.jboss.as.appclient.subsystem.AppClientSubsystemResourceDefinition.APPCLIENT_CAPABILITY;
import static org.jboss.as.appclient.subsystem.AppClientSubsystemResourceDefinition.EXECUTOR_CAPABILITY;
import static org.jboss.as.appclient.subsystem.AppClientSubsystemResourceDefinition.MCF_CAPABILITY;
import static org.jboss.as.appclient.subsystem.Constants.CONNECTION_PROPERTIES_URL;
import static org.jboss.as.appclient.subsystem.Constants.HOST_URL;
/**
* Add operation handler for the application client subsystem.
*
* @author Stuart Douglas
*/
class AppClientSubsystemAdd extends AbstractBoottimeAddStepHandler {
public static final ServiceName APP_CLIENT_URI_SERVICE_NAME = ServiceName.JBOSS.append("ejb3", "ejbClientContext", "appClientUri");
public static final ServiceName APP_CLIENT_EJB_PROPERTIES_SERVICE_NAME = ServiceName.JBOSS.append("ejb3", "ejbClientContext", "appClientEjbProperties");
static final AppClientSubsystemAdd INSTANCE = new AppClientSubsystemAdd();
private final String[] EMPTY_STRING = new String[0];
private AppClientSubsystemAdd() {
//
}
protected void populateModel(ModelNode operation, ModelNode model) throws OperationFailedException {
for(AttributeDefinition attr : AppClientSubsystemResourceDefinition.ATTRIBUTES) {
attr.validateAndSet(operation, model);
}
}
protected void performBoottime(final OperationContext context, ModelNode operation, final ModelNode model) throws OperationFailedException {
final String deployment = AppClientSubsystemResourceDefinition.DEPLOYMENT.resolveModelAttribute(context, model).asString();
final File file = new File(AppClientSubsystemResourceDefinition.FILE.resolveModelAttribute(context, model).asString());
if (!file.exists()) {
context.setRollbackOnly();
throw AppClientLogger.ROOT_LOGGER.cannotFindAppClientFile(file.getAbsoluteFile());
}
final String hostUrl = model.hasDefined(HOST_URL) ? AppClientSubsystemResourceDefinition.HOST_URL.resolveModelAttribute(context, model).asString() : null;
final String connectionPropertiesUrl = model.hasDefined(CONNECTION_PROPERTIES_URL) ? AppClientSubsystemResourceDefinition.CONNECTION_PROPERTIES_URL.resolveModelAttribute(context, model).asString() : null;
final List<String> parameters = AppClientSubsystemResourceDefinition.PARAMETERS.unwrap(context,model);
context.addStep(new AbstractDeploymentChainStep() {
protected void execute(DeploymentProcessorTarget processorTarget) {
if (deployment != null && !deployment.isEmpty()) {
processorTarget.addDeploymentProcessor(Constants.SUBSYSTEM_NAME, Phase.STRUCTURE, Phase.STRUCTURE_APP_CLIENT, new ApplicationClientStructureProcessor(deployment));
}
processorTarget.addDeploymentProcessor(Constants.SUBSYSTEM_NAME, Phase.STRUCTURE, Phase.STRUCTURE_REGISTER_JBOSS_ALL_APPCLIENT, new JBossAllXmlParserRegisteringProcessor<>(AppClientJBossAllParser.ROOT_ELEMENT, AppClientJBossAllParser.ATTACHMENT_KEY, new AppClientJBossAllParser()));
processorTarget.addDeploymentProcessor(Constants.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_APP_CLIENT_XML, new ApplicationClientParsingDeploymentProcessor());
processorTarget.addDeploymentProcessor(Constants.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_APPLICATION_CLIENT_MANIFEST, new ApplicationClientManifestProcessor());
processorTarget.addDeploymentProcessor(Constants.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_APPLICATION_CLIENT_ACTIVE, new ActiveApplicationClientProcessor(deployment));
processorTarget.addDeploymentProcessor(Constants.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_APPLICATION_CLIENT, new ApplicationClientDependencyProcessor());
processorTarget.addDeploymentProcessor(Constants.SUBSYSTEM_NAME, Phase.INSTALL, Phase.INSTALL_APPLICATION_CLIENT, new ApplicationClientStartProcessor(parameters.toArray(EMPTY_STRING)));
}
}, OperationContext.Stage.RUNTIME);
CapabilityServiceBuilder<?> builder = context.getCapabilityServiceTarget().addCapability(APPCLIENT_CAPABILITY);
Consumer<ApplicationClientDeploymentService> consumer = builder.provides(APPCLIENT_CAPABILITY);
Supplier<ModelControllerClientFactory> mcfSupplier =
builder.requiresCapability(MCF_CAPABILITY, ModelControllerClientFactory.class);
Supplier<ExecutorService> esSupplier =
builder.requiresCapability(EXECUTOR_CAPABILITY, ExecutorService.class);
builder.setInstance(new ApplicationClientDeploymentService(consumer, file, mcfSupplier, esSupplier));
builder.install();
try {
if(connectionPropertiesUrl != null) {
context.getServiceTarget().addService(APP_CLIENT_URI_SERVICE_NAME, new ConstantService<>(null))
.install();
context.getServiceTarget().addService(APP_CLIENT_EJB_PROPERTIES_SERVICE_NAME, new ConstantService<>(connectionPropertiesUrl))
.install();
} else {
URI uri;
if (hostUrl == null) {
uri = new URI("remote+http://localhost:8080");
} else {
uri = new URI(hostUrl);
}
context.getServiceTarget().addService(APP_CLIENT_URI_SERVICE_NAME, new ConstantService<>(uri))
.install();
context.getServiceTarget().addService(APP_CLIENT_EJB_PROPERTIES_SERVICE_NAME, new ConstantService<>(connectionPropertiesUrl))
.install();
}
} catch (URISyntaxException e) {
throw new OperationFailedException(e);
}
}
private static final class ConstantService<T> implements Service<T> {
private final T value;
private ConstantService(T value) {
this.value = value;
}
@Override
public void start(StartContext startContext) throws StartException {
}
@Override
public void stop(StopContext stopContext) {
}
@Override
public T getValue() throws IllegalStateException, IllegalArgumentException {
return value;
}
}
}
| 9,203 | 52.511628 | 298 |
java
|
null |
wildfly-main/appclient/src/main/java/org/jboss/as/appclient/subsystem/ApplicationClientConfigurationPersister.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.appclient.subsystem;
import java.io.File;
import java.io.OutputStream;
import java.util.List;
import java.util.Set;
import javax.xml.namespace.QName;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.persistence.ConfigurationPersistenceException;
import org.jboss.as.controller.persistence.SubsystemMarshallingContext;
import org.jboss.as.controller.persistence.XmlConfigurationPersister;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLElementWriter;
/**
* Application client configuration.
*
* This configuration is currently hard coded to a minimal set of services required for app client boot
*
* @author Stuart Douglas
*/
public class ApplicationClientConfigurationPersister extends XmlConfigurationPersister {
/**
* The absolute path to the deployment archive
*/
private final String filePath;
/**
* The app client was specified with the myear.ear#appclient.jar syntax, if any
*/
private final String deploymentName;
/**
* Any additional parameters to pass to the application client
*/
private final List<String> parameters;
/**
* The URL of the AS7 instance to connect to
*/
private final String hostUrl;
/**
* This URL of an ejb-client.properties file
*/
private final String propertiesFileURL;
public ApplicationClientConfigurationPersister(final String filePath, final String deploymentName, final String hostUrl, final String propertiesFileUrl, final List<String> parameters, final File configFile, final QName element, final XMLElementReader<List<ModelNode>> xmlParser) {
super(configFile, element, xmlParser, null);
this.filePath = filePath;
this.deploymentName = deploymentName;
this.hostUrl = hostUrl;
this.parameters = parameters;
this.propertiesFileURL = propertiesFileUrl;
}
@Override
public PersistenceResource store(final ModelNode model, final Set<PathAddress> affectedAddresses) throws ConfigurationPersistenceException {
return new PersistenceResource() {
@Override
public void commit() {
}
@Override
public void rollback() {
}
};
}
@Override
public void marshallAsXml(final ModelNode model, final OutputStream output) throws ConfigurationPersistenceException {
}
@Override
public List<ModelNode> load() throws ConfigurationPersistenceException {
List<ModelNode> nodes = super.load();
return AppClientServerConfiguration.serverConfiguration(filePath, deploymentName, hostUrl, propertiesFileURL, parameters, nodes);
}
@Override
public void successfulBoot() throws ConfigurationPersistenceException {
}
// TODO once WFCORE-6362 is integrated remove this method
public String snapshot() throws ConfigurationPersistenceException {
return null;
}
@Override
public SnapshotInfo listSnapshots() {
return null;
}
@Override
public void deleteSnapshot(final String name) {
}
// TODO once WFCORE-6362 is integrated remove this method
public void registerSubsystemWriter(final String name, final XMLElementWriter<SubsystemMarshallingContext> writer) {
}
}
| 4,384 | 31.723881 | 284 |
java
|
null |
wildfly-main/appclient/src/main/java/org/jboss/as/appclient/subsystem/parsing/AppClientXml.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.appclient.subsystem.parsing;
import static javax.xml.stream.XMLStreamConstants.END_ELEMENT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING_GROUP;
import static org.jboss.as.controller.parsing.Namespace.DOMAIN_1_0;
import static org.jboss.as.controller.parsing.ParseUtils.isNoNamespaceAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequired;
import static org.jboss.as.controller.parsing.ParseUtils.nextElement;
import static org.jboss.as.controller.parsing.ParseUtils.requireNamespace;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoAttributes;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.appclient.logging.AppClientLogger;
import org.jboss.as.controller.extension.ExtensionRegistry;
import org.jboss.as.controller.logging.ControllerLogger;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.parsing.Attribute;
import org.jboss.as.controller.parsing.Element;
import org.jboss.as.controller.parsing.ExtensionXml;
import org.jboss.as.controller.parsing.Namespace;
import org.jboss.as.controller.parsing.ParseUtils;
import org.jboss.as.server.parsing.CommonXml;
import org.jboss.as.server.parsing.SocketBindingsXml;
import org.jboss.as.server.services.net.SocketBindingGroupResourceDefinition;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.jboss.modules.ModuleLoader;
import org.jboss.staxmapper.XMLExtendedStreamReader;
import org.jboss.staxmapper.XMLExtendedStreamWriter;
/**
* A mapper between an AS server's configuration model and XML representations, particularly {@code appclient.xml}.
*
* @author Stuart Douglas
*/
public class AppClientXml extends CommonXml {
private final ExtensionXml extensionXml;
public AppClientXml(final ModuleLoader loader, final ExtensionRegistry extensionRegistry) {
super(new AppClientSocketBindingsXml());
extensionXml = new ExtensionXml(loader, null, extensionRegistry);
}
public void readElement(final XMLExtendedStreamReader reader, final List<ModelNode> operationList)
throws XMLStreamException {
final ModelNode address = new ModelNode().setEmptyList();
if (Element.forName(reader.getLocalName()) != Element.SERVER) {
throw unexpectedElement(reader);
}
Namespace readerNS = Namespace.forUri(reader.getNamespaceURI());
switch (readerNS) {
case DOMAIN_1_0:
readServerElement_1_0(reader, address, operationList);
break;
case DOMAIN_1_1:
case DOMAIN_1_2:
case DOMAIN_1_3:
case DOMAIN_1_4:
case DOMAIN_1_5:
case DOMAIN_1_6:
case DOMAIN_1_7:
case DOMAIN_1_8:
case DOMAIN_2_0:
case DOMAIN_2_1:
case DOMAIN_2_2:
case DOMAIN_3_0:
case DOMAIN_4_0:
case DOMAIN_4_1:
case DOMAIN_4_2:
case DOMAIN_5_0:
case DOMAIN_6_0:
case DOMAIN_7_0:
case DOMAIN_8_0:
case DOMAIN_9_0:
case DOMAIN_10_0:
case DOMAIN_11_0:
case DOMAIN_12_0:
case DOMAIN_13_0:
case DOMAIN_14_0:
case DOMAIN_15_0:
case DOMAIN_16_0:
case DOMAIN_17_0:
readServerElement_1_1(readerNS, reader, address, operationList);
break;
default:
// Instead of having to list the remaining versions we just check it is actually a valid version.
for (Namespace current : Namespace.domainValues()) {
if (readerNS.equals(current)) {
readServerElement_18(readerNS, reader, address, operationList);
return;
}
}
throw unexpectedElement(reader);
}
}
/**
* Read the <server/> element based on version 1.0 of the schema.
*
* @param reader the xml stream reader
* @param address address of the parent resource of any resources this method will add
* @param list the list of boot operations to which any new operations should be added
* @throws XMLStreamException if a parsing error occurs
*/
private void readServerElement_1_0(final XMLExtendedStreamReader reader, final ModelNode address, final List<ModelNode> list)
throws XMLStreamException {
parseNamespaces(reader, address, list);
String serverName = null;
// attributes
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
switch (Namespace.forUri(reader.getAttributeNamespace(i))) {
case NONE: {
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NAME: {
serverName = value;
break;
}
default:
throw unexpectedAttribute(reader, i);
}
break;
}
case XML_SCHEMA_INSTANCE: {
switch (Attribute.forName(reader.getAttributeLocalName(i))) {
case SCHEMA_LOCATION: {
parseSchemaLocations(reader, address, list, i);
break;
}
case NO_NAMESPACE_SCHEMA_LOCATION: {
// todo, jeez
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
setServerName(address, list, serverName);
// elements - sequence
Element element = nextElement(reader, DOMAIN_1_0);
if (element == Element.EXTENSIONS) {
extensionXml.parseExtensions(reader, address, DOMAIN_1_0, list);
element = nextElement(reader, DOMAIN_1_0);
}
// System properties
if (element == Element.SYSTEM_PROPERTIES) {
parseSystemProperties(reader, address, DOMAIN_1_0, list, true);
element = nextElement(reader, DOMAIN_1_0);
}
if (element == Element.PATHS) {
parsePaths(reader, address, DOMAIN_1_0, list, true);
element = nextElement(reader, DOMAIN_1_0);
}
// Single profile
if (element == Element.PROFILE) {
parseServerProfile(reader, address, list);
element = nextElement(reader, DOMAIN_1_0);
}
// Interfaces
final Set<String> interfaceNames = new HashSet<String>();
if (element == Element.INTERFACES) {
parseInterfaces(reader, interfaceNames, address, DOMAIN_1_0, list, true);
element = nextElement(reader, DOMAIN_1_0);
}
// Single socket binding group
if (element == Element.SOCKET_BINDING_GROUP) {
parseSocketBindingGroup(reader, interfaceNames, address, DOMAIN_1_0, list);
element = nextElement(reader, DOMAIN_1_0);
}
if (element != null) {
throw unexpectedElement(reader);
}
}
/**
* Read the <server/> element based on version 1.1 of the schema.
*
* @param reader the xml stream reader
* @param address address of the parent resource of any resources this method will add
* @param list the list of boot operations to which any new operations should be added
* @throws XMLStreamException if a parsing error occurs
*/
private void readServerElement_1_1(final Namespace namespace, final XMLExtendedStreamReader reader, final ModelNode address, final List<ModelNode> list)
throws XMLStreamException {
parseNamespaces(reader, address, list);
String serverName = null;
// attributes
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
switch (Namespace.forUri(reader.getAttributeNamespace(i))) {
case NONE: {
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NAME: {
serverName = value;
break;
}
default:
throw unexpectedAttribute(reader, i);
}
break;
}
case XML_SCHEMA_INSTANCE: {
switch (Attribute.forName(reader.getAttributeLocalName(i))) {
case SCHEMA_LOCATION: {
parseSchemaLocations(reader, address, list, i);
break;
}
case NO_NAMESPACE_SCHEMA_LOCATION: {
// todo, jeez
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
setServerName(address, list, serverName);
// elements - sequence
Element element = nextElement(reader, namespace);
if (element == Element.EXTENSIONS) {
extensionXml.parseExtensions(reader, address, namespace, list);
element = nextElement(reader, namespace);
}
// System properties
if (element == Element.SYSTEM_PROPERTIES) {
parseSystemProperties(reader, address, namespace, list, true);
element = nextElement(reader, namespace);
}
if (element == Element.PATHS) {
parsePaths(reader, address, namespace, list, true);
element = nextElement(reader, namespace);
}
if (element == Element.VAULT) {
parseVault(reader, address, namespace, list);
element = nextElement(reader, namespace);
}
// Single profile
if (element == Element.PROFILE) {
parseServerProfile(reader, address, list);
element = nextElement(reader, namespace);
}
// Interfaces
final Set<String> interfaceNames = new HashSet<String>();
if (element == Element.INTERFACES) {
parseInterfaces(reader, interfaceNames, address, namespace, list, true);
element = nextElement(reader, namespace);
}
// Single socket binding group
if (element == Element.SOCKET_BINDING_GROUP) {
parseSocketBindingGroup(reader, interfaceNames, address, namespace, list);
element = nextElement(reader, namespace);
}
if (element != null) {
throw unexpectedElement(reader);
}
}
/**
* Read the <server/> element based on version 18 of the schema.
*
* @param reader the xml stream reader
* @param address address of the parent resource of any resources this method will add
* @param list the list of boot operations to which any new operations should be added
* @throws XMLStreamException if a parsing error occurs
*/
private void readServerElement_18(final Namespace namespace, final XMLExtendedStreamReader reader, final ModelNode address, final List<ModelNode> list)
throws XMLStreamException {
parseNamespaces(reader, address, list);
String serverName = null;
// attributes
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
switch (Namespace.forUri(reader.getAttributeNamespace(i))) {
case NONE: {
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NAME: {
serverName = value;
break;
}
default:
throw unexpectedAttribute(reader, i);
}
break;
}
case XML_SCHEMA_INSTANCE: {
switch (Attribute.forName(reader.getAttributeLocalName(i))) {
case SCHEMA_LOCATION: {
parseSchemaLocations(reader, address, list, i);
break;
}
case NO_NAMESPACE_SCHEMA_LOCATION: {
// todo, jeez
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
setServerName(address, list, serverName);
// elements - sequence
Element element = nextElement(reader, namespace);
if (element == Element.EXTENSIONS) {
extensionXml.parseExtensions(reader, address, namespace, list);
element = nextElement(reader, namespace);
}
// System properties
if (element == Element.SYSTEM_PROPERTIES) {
parseSystemProperties(reader, address, namespace, list, true);
element = nextElement(reader, namespace);
}
if (element == Element.PATHS) {
parsePaths(reader, address, namespace, list, true);
element = nextElement(reader, namespace);
}
// Single profile
if (element == Element.PROFILE) {
parseServerProfile(reader, address, list);
element = nextElement(reader, namespace);
}
// Interfaces
final Set<String> interfaceNames = new HashSet<String>();
if (element == Element.INTERFACES) {
parseInterfaces(reader, interfaceNames, address, namespace, list, true);
element = nextElement(reader, namespace);
}
// Single socket binding group
if (element == Element.SOCKET_BINDING_GROUP) {
parseSocketBindingGroup(reader, interfaceNames, address, namespace, list);
element = nextElement(reader, namespace);
}
if (element != null) {
throw unexpectedElement(reader);
}
}
private void parseSocketBindingGroup(final XMLExtendedStreamReader reader, final Set<String> interfaces,
final ModelNode address, final Namespace expectedNs, final List<ModelNode> updates) throws XMLStreamException {
// unique names for both socket-binding and outbound-socket-binding(s)
final Set<String> uniqueBindingNames = new HashSet<String>();
ModelNode op = Util.getEmptyOperation(ADD, null);
// Handle attributes
String socketBindingGroupName = null;
final EnumSet<Attribute> required = EnumSet.of(Attribute.NAME, Attribute.DEFAULT_INTERFACE);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
}
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NAME: {
socketBindingGroupName = value;
required.remove(attribute);
break;
}
case DEFAULT_INTERFACE: {
SocketBindingGroupResourceDefinition.DEFAULT_INTERFACE.parseAndSetParameter(value, op, reader);
required.remove(attribute);
break;
}
case PORT_OFFSET: {
SocketBindingGroupResourceDefinition.PORT_OFFSET.parseAndSetParameter(value, op, reader);
break;
}
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
ModelNode groupAddress = address.clone().add(SOCKET_BINDING_GROUP, socketBindingGroupName);
op.get(OP_ADDR).set(groupAddress);
updates.add(op);
// Handle elements
while (reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case SOCKET_BINDING: {
// FIXME JBAS-8825
final String bindingName = parseSocketBinding(reader, interfaces, groupAddress, updates);
if (!uniqueBindingNames.add(bindingName)) {
throw ControllerLogger.ROOT_LOGGER.alreadyDeclared(Element.SOCKET_BINDING.getLocalName(), Element.OUTBOUND_SOCKET_BINDING.getLocalName(), bindingName, Element.SOCKET_BINDING_GROUP.getLocalName(), socketBindingGroupName, reader.getLocation());
}
break;
}
case OUTBOUND_SOCKET_BINDING: {
final String bindingName = parseOutboundSocketBinding(reader, interfaces, groupAddress, updates);
if (!uniqueBindingNames.add(bindingName)) {
throw ControllerLogger.ROOT_LOGGER.alreadyDeclared(Element.SOCKET_BINDING.getLocalName(), Element.OUTBOUND_SOCKET_BINDING.getLocalName(), bindingName, Element.SOCKET_BINDING_GROUP.getLocalName(), socketBindingGroupName, reader.getLocation());
}
break;
}
default:
throw unexpectedElement(reader);
}
}
}
private void parseServerProfile(final XMLExtendedStreamReader reader, final ModelNode address, final List<ModelNode> list)
throws XMLStreamException {
// Attributes
requireNoAttributes(reader);
// Content
final Set<String> configuredSubsystemTypes = new HashSet<String>();
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
if (Element.forName(reader.getLocalName()) != Element.SUBSYSTEM) {
throw unexpectedElement(reader);
}
if (!configuredSubsystemTypes.add(reader.getNamespaceURI())) {
throw AppClientLogger.ROOT_LOGGER.duplicateSubsystemDeclaration(reader.getLocation());
}
// parse subsystem
final List<ModelNode> subsystems = new ArrayList<ModelNode>();
reader.handleAny(subsystems);
// Process subsystems
for (final ModelNode update : subsystems) {
// Process relative subsystem path address
final ModelNode subsystemAddress = address.clone();
for (final Property path : update.get(OP_ADDR).asPropertyList()) {
subsystemAddress.add(path.getName(), path.getValue().asString());
}
update.get(OP_ADDR).set(subsystemAddress);
list.add(update);
}
}
}
private void setServerName(final ModelNode address, final List<ModelNode> operationList, final String value) {
if (value != null && value.length() > 0) {
final ModelNode update = Util.getWriteAttributeOperation(address, NAME, value);
operationList.add(update);
}
}
static class AppClientSocketBindingsXml extends SocketBindingsXml {
@Override
protected void writeExtraAttributes(XMLExtendedStreamWriter writer, ModelNode bindingGroup) throws XMLStreamException {
SocketBindingGroupResourceDefinition.PORT_OFFSET.marshallAsAttribute(bindingGroup, writer);
}
}
}
| 22,405 | 40.339483 | 266 |
java
|
null |
wildfly-main/appclient/src/main/java/org/jboss/as/appclient/component/ApplicationClientComponentDescription.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.appclient.component;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.ComponentFactory;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.server.deployment.reflect.ClassReflectionIndex;
import org.jboss.invocation.InterceptorContext;
import org.jboss.modules.ModuleLoader;
import org.jboss.msc.service.ServiceName;
/**
* @author Stuart Douglas
*/
public final class ApplicationClientComponentDescription extends ComponentDescription {
public static final String APP_CLIENT_COMPONENT_NAME = "AppClientComponent";
public ApplicationClientComponentDescription(final String componentClassName, final EEModuleDescription moduleDescription, final ServiceName deploymentUnitServiceName) {
super(APP_CLIENT_COMPONENT_NAME, componentClassName, moduleDescription, deploymentUnitServiceName);
setExcludeDefaultInterceptors(true);
}
public boolean isIntercepted() {
return false;
}
@Override
public ComponentConfiguration createConfiguration(final ClassReflectionIndex classIndex, final ClassLoader moduleClassLoader, final ModuleLoader moduleLoader) {
final ComponentConfiguration configuration = super.createConfiguration(classIndex, moduleClassLoader, moduleLoader);
configuration.setInstanceFactory(new ComponentFactory() {
@Override
public ManagedReference create(final InterceptorContext context) {
return new ManagedReference() {
@Override
public void release() {
}
@Override
public Object getInstance() {
return null;
}
};
}
});
return configuration;
}
}
| 2,976 | 37.662338 | 173 |
java
|
null |
wildfly-main/metrics/src/test/java/org/wildfly/extension/metrics/Subsystem_1_0_ParsingTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.metrics;
import java.io.IOException;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc.
*/
public class Subsystem_1_0_ParsingTestCase extends AbstractSubsystemBaseTest {
public Subsystem_1_0_ParsingTestCase() {
super(MetricsExtension.SUBSYSTEM_NAME, new MetricsExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource("subsystem_1_0.xml");
}
@Override
protected String getSubsystemXsdPath() throws IOException {
return "schema/wildfly-metrics_1_0.xsd";
}
}
| 1,713 | 34.708333 | 78 |
java
|
null |
wildfly-main/metrics/src/main/java/org/wildfly/extension/metrics/MetricID.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.metrics;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
public class MetricID implements Comparable<MetricID> {
private final String metricName;
private final WildFlyMetricMetadata.MetricTag[] metricTags;
// keep a map of tags to ensure that the identity of the metrics does not differ if the
// tags are not in the same order in the array
private final Map<String, String> tags = new TreeMap<>();
public MetricID(String metricName, WildFlyMetricMetadata.MetricTag[] tags) {
this.metricName = metricName;
this.metricTags = tags;
for (WildFlyMetricMetadata.MetricTag tag : tags) {
this.tags.put(tag.getKey(), tag.getValue());
}
}
public String getMetricName() {
return metricName;
}
public WildFlyMetricMetadata.MetricTag[] getTags() {
return metricTags;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MetricID metricID = (MetricID) o;
return metricName.equals(metricID.metricName) &&
tags.equals(metricID.tags);
}
@Override
public int hashCode() {
return Objects.hash(metricName, tags);
}
@Override
public int compareTo(MetricID other) {
int compareVal = this.metricName.compareTo(other.metricName);
if (compareVal == 0) {
compareVal = this.tags.size() - other.tags.size();
if (compareVal == 0) {
Iterator<Map.Entry<String, String>> thisIterator = tags.entrySet().iterator();
Iterator<Map.Entry<String, String>> otherIterator = other.tags.entrySet().iterator();
while (thisIterator.hasNext() && otherIterator.hasNext()) {
Map.Entry<String, String> thisEntry = thisIterator.next();
Map.Entry<String, String> otherEntry = otherIterator.next();
compareVal = thisEntry.getKey().compareTo(otherEntry.getKey());
if (compareVal != 0) {
return compareVal;
} else {
compareVal = thisEntry.getValue().compareTo(otherEntry.getValue());
if (compareVal != 0) {
return compareVal;
}
}
}
}
}
return compareVal;
}
}
| 3,571 | 38.688889 | 101 |
java
|
null |
wildfly-main/metrics/src/main/java/org/wildfly/extension/metrics/WildFlyMetricRegistry.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.metrics;
import static java.util.Objects.requireNonNull;
import java.io.Closeable;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class WildFlyMetricRegistry implements Closeable, MetricRegistry {
/* Key is the metric name */
private Map<String, MetricMetadata> metadataMap = new HashMap();
private Map<MetricID, Metric> metricMap = new TreeMap<>();
private final ReadWriteLock lock = new ReentrantReadWriteLock();
@Override
public void close() {
lock.writeLock().lock();
try {
metricMap.clear();
metadataMap.clear();
} finally {
lock.writeLock().unlock();
}
}
Map<MetricID, Metric> getMetrics() {
return metricMap;
}
Map<String, MetricMetadata> getMetricMetadata() {
return metadataMap;
}
@Override
public synchronized void registerMetric(Metric metric, MetricMetadata metadata) {
requireNonNull(metadata);
requireNonNull(metric);
lock.writeLock().lock();
try {
MetricID metricID = metadata.getMetricID();
if (!metadataMap.containsKey(metadata.getMetricName())) {
metadataMap.put(metadata.getMetricName(), metadata);
}
metricMap.put(metricID, metric);
} finally {
lock.writeLock().unlock();
}
}
@Override
public void unregister(MetricID metricID) {
lock.writeLock().lock();
try {
metricMap.remove(metricID);
} finally {
lock.writeLock().unlock();
}
}
@Override
public void readLock() {
lock.readLock().lock();
}
@Override
public void unlock() {
lock.readLock().unlock();
}
}
| 2,956 | 29.173469 | 85 |
java
|
null |
wildfly-main/metrics/src/main/java/org/wildfly/extension/metrics/MetricRegistration.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.metrics;
import java.util.ArrayList;
import java.util.List;
public class MetricRegistration {
private final List<Runnable> registrationTasks = new ArrayList<>();
private final List<MetricID> unregistrationTasks = new ArrayList<>();
private final MetricRegistry registry;
public MetricRegistration(MetricRegistry registry) {
this.registry = registry;
}
public void register() { // synchronized to avoid registering same thing twice. Shouldn't really be possible; just being cautious
synchronized (registry) {
for (Runnable task : registrationTasks) {
task.run();
}
// This object will last until undeploy or server stop,
// so clean up and save memory
registrationTasks.clear();
}
}
public void unregister() {
synchronized (registry) {
for (MetricID id : unregistrationTasks) {
registry.unregister(id);
}
unregistrationTasks.clear();
}
}
public void registerMetric(WildFlyMetric metric, WildFlyMetricMetadata metadata) {
registry.registerMetric(metric, metadata);
}
public synchronized void addRegistrationTask(Runnable task) {
registrationTasks.add(task);
}
public void addUnregistrationTask(MetricID metricID) {
unregistrationTasks.add(metricID);
}
}
| 2,466 | 34.753623 | 133 |
java
|
null |
wildfly-main/metrics/src/main/java/org/wildfly/extension/metrics/MetricsCollectorService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.metrics;
import static org.wildfly.extension.metrics.MetricsSubsystemDefinition.CLIENT_FACTORY_CAPABILITY;
import static org.wildfly.extension.metrics.MetricsSubsystemDefinition.MANAGEMENT_EXECUTOR;
import static org.wildfly.extension.metrics.MetricsSubsystemDefinition.PROCESS_STATE_NOTIFIER;
import static org.wildfly.extension.metrics.MetricsSubsystemDefinition.WILDFLY_COLLECTOR;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.jboss.as.controller.LocalModelControllerClient;
import org.jboss.as.controller.ModelControllerClientFactory;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.ProcessStateNotifier;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
/**
* Service to create a metric collector
*/
public class MetricsCollectorService implements Service<MetricCollector> {
private final Supplier<ModelControllerClientFactory> modelControllerClientFactory;
private final Supplier<Executor> managementExecutor;
private final Supplier<ProcessStateNotifier> processStateNotifier;
private Consumer<MetricCollector> metricCollectorConsumer;
private MetricCollector metricCollector;
private LocalModelControllerClient modelControllerClient;
static void install(OperationContext context) {
ServiceBuilder<?> serviceBuilder = context.getServiceTarget().addService(WILDFLY_COLLECTOR);
Supplier<ModelControllerClientFactory> modelControllerClientFactory = serviceBuilder.requires(context.getCapabilityServiceName(CLIENT_FACTORY_CAPABILITY, ModelControllerClientFactory.class));
Supplier<Executor> managementExecutor = serviceBuilder.requires(context.getCapabilityServiceName(MANAGEMENT_EXECUTOR, Executor.class));
Supplier<ProcessStateNotifier> processStateNotifier = serviceBuilder.requires(context.getCapabilityServiceName(PROCESS_STATE_NOTIFIER, ProcessStateNotifier.class));
Consumer<MetricCollector> metricCollectorConsumer = serviceBuilder.provides(WILDFLY_COLLECTOR);
MetricsCollectorService service = new MetricsCollectorService(modelControllerClientFactory, managementExecutor, processStateNotifier, metricCollectorConsumer);
serviceBuilder.setInstance(service)
.install();
}
MetricsCollectorService(Supplier<ModelControllerClientFactory> modelControllerClientFactory, Supplier<Executor> managementExecutor,
Supplier<ProcessStateNotifier> processStateNotifier, Consumer<MetricCollector> metricCollectorConsumer) {
this.modelControllerClientFactory = modelControllerClientFactory;
this.managementExecutor = managementExecutor;
this.processStateNotifier = processStateNotifier;
this.metricCollectorConsumer = metricCollectorConsumer;
}
@Override
public void start(StartContext context) {
// [WFLY-11933] if RBAC is enabled, the local client does not have enough priviledges to read metrics
modelControllerClient = modelControllerClientFactory.get().createClient(managementExecutor.get());
metricCollector = new MetricCollector(modelControllerClient, processStateNotifier.get());
metricCollectorConsumer.accept(metricCollector);
}
@Override
public void stop(StopContext context) {
metricCollectorConsumer.accept(null);
metricCollector = null;
modelControllerClient.close();
}
@Override
public MetricCollector getValue() throws IllegalStateException, IllegalArgumentException {
return metricCollector;
}
}
| 4,773 | 48.216495 | 199 |
java
|
null |
wildfly-main/metrics/src/main/java/org/wildfly/extension/metrics/MetricMetadata.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.metrics;
import org.jboss.as.controller.client.helpers.MeasurementUnit;
public interface MetricMetadata {
static final String NONE = "none";
String getMetricName();
MetricTag[] getTags();
String getDescription();
MeasurementUnit getMeasurementUnit();
Type getType();
MetricID getMetricID();
default String getBaseMetricUnit() {
return baseMetricUnit(getMeasurementUnit());
}
static String baseMetricUnit(MeasurementUnit unit) {
if (unit == null) {
return NONE;
}
switch (unit.getBaseUnits()) {
case PERCENTAGE:
return "percent";
case BYTES:
case KILOBYTES:
case MEGABYTES:
case GIGABYTES:
case TERABYTES:
case PETABYTES:
return "bytes";
case BITS:
case KILOBITS:
case MEGABITS:
case GIGABITS:
case TERABITS:
case PETABITS:
return "bits";
case EPOCH_MILLISECONDS:
case EPOCH_SECONDS:
case NANOSECONDS:
case MILLISECONDS:
case MICROSECONDS:
case SECONDS:
case MINUTES:
case HOURS:
case DAYS:
return "seconds";
case JIFFYS:
return "jiffys";
case PER_JIFFY:
return "per-jiffy";
case PER_NANOSECOND:
case PER_MICROSECOND:
case PER_MILLISECOND:
case PER_SECOND:
case PER_MINUTE:
case PER_HOUR:
case PER_DAY:
return "per_second";
case CELSIUS:
return "degree_celsius";
case KELVIN:
return "kelvin";
case FAHRENHEIGHT:
return "degree_fahrenheit";
case NONE:
default:
return NONE;
}
}
enum Type {
COUNTER,
GAUGE;
@Override
public String toString() {
return this.name().toLowerCase();
}
}
class MetricTag {
private String key;
private String value;
public MetricTag(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
}
}
| 3,562 | 26.620155 | 70 |
java
|
null |
wildfly-main/metrics/src/main/java/org/wildfly/extension/metrics/MetricsSubsystemDefinition.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.metrics;
import java.util.Arrays;
import java.util.Collection;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PersistentResourceDefinition;
import org.jboss.as.controller.ServiceRemoveStepHandler;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.StringListAttributeDefinition;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.msc.service.ServiceName;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc.
*/
public class MetricsSubsystemDefinition extends PersistentResourceDefinition {
static final String CLIENT_FACTORY_CAPABILITY ="org.wildfly.management.model-controller-client-factory";
static final String MANAGEMENT_EXECUTOR ="org.wildfly.management.executor";
static final String PROCESS_STATE_NOTIFIER = "org.wildfly.management.process-state-notifier";
static final String HTTP_EXTENSIBILITY_CAPABILITY = "org.wildfly.management.http.extensible";
public static final String METRICS_HTTP_SECURITY_CAPABILITY = "org.wildfly.extension.metrics.http-context.security-enabled";
public static final String METRICS_SCAN_CAPABILITY = "org.wildfly.extension.metrics.scan";
private static final RuntimeCapability<Void> METRICS_COLLECTOR_RUNTIME_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.extension.metrics.wildfly-collector", MetricCollector.class)
.addRequirements(CLIENT_FACTORY_CAPABILITY, MANAGEMENT_EXECUTOR, PROCESS_STATE_NOTIFIER)
.build();
static final RuntimeCapability<Void> METRICS_HTTP_CONTEXT_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.extension.metrics.http-context", MetricsContextService.class)
.addRequirements(HTTP_EXTENSIBILITY_CAPABILITY)
.build();
public static final RuntimeCapability<Void> METRICS_REGISTRY_RUNTIME_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.extension.metrics.registry", WildFlyMetricRegistry.class)
.build();
static final RuntimeCapability METRICS_CAPABILITY =
RuntimeCapability.Builder.of("org.wildfly.management.http-context.metrics").build();
public static final ServiceName WILDFLY_COLLECTOR = METRICS_COLLECTOR_RUNTIME_CAPABILITY.getCapabilityServiceName();
static final AttributeDefinition SECURITY_ENABLED = SimpleAttributeDefinitionBuilder.create("security-enabled", ModelType.BOOLEAN)
.setDefaultValue(ModelNode.TRUE)
.setRequired(false)
.setRestartAllServices()
.setAllowExpression(true)
.build();
static final StringListAttributeDefinition EXPOSED_SUBSYSTEMS = new StringListAttributeDefinition.Builder("exposed-subsystems")
.setRequired(false)
.setRestartAllServices()
.build();
static final AttributeDefinition PREFIX = SimpleAttributeDefinitionBuilder.create("prefix", ModelType.STRING)
.setRequired(false)
.setRestartAllServices()
.setAllowExpression(true)
.build();
static final AttributeDefinition[] ATTRIBUTES = { SECURITY_ENABLED, EXPOSED_SUBSYSTEMS, PREFIX };
protected MetricsSubsystemDefinition() {
super(new SimpleResourceDefinition.Parameters(MetricsExtension.SUBSYSTEM_PATH,
MetricsExtension.getResourceDescriptionResolver(MetricsExtension.SUBSYSTEM_NAME))
.setAddHandler(MetricsSubsystemAdd.INSTANCE)
.setRemoveHandler(new ServiceRemoveStepHandler(MetricsSubsystemAdd.INSTANCE))
.addCapabilities(METRICS_COLLECTOR_RUNTIME_CAPABILITY, METRICS_HTTP_CONTEXT_CAPABILITY,
METRICS_REGISTRY_RUNTIME_CAPABILITY, METRICS_CAPABILITY));
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return Arrays.asList(ATTRIBUTES);
}
}
| 5,065 | 49.158416 | 190 |
java
|
null |
wildfly-main/metrics/src/main/java/org/wildfly/extension/metrics/Metric.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.metrics;
import java.util.OptionalDouble;
/**
* A representation of a metric.
* It is possibe that the value can not be computed (e.g. if it is backed by a WildFly
* management attribute value which is undefined).
*/
public interface Metric {
OptionalDouble getValue();
}
| 1,335 | 38.294118 | 86 |
java
|
null |
wildfly-main/metrics/src/main/java/org/wildfly/extension/metrics/MetricsSubsystemAdd.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.metrics;
import static org.jboss.as.controller.OperationContext.Stage.RUNTIME;
import static org.jboss.as.controller.OperationContext.Stage.VERIFY;
import static org.jboss.as.controller.PathAddress.EMPTY_ADDRESS;
import static org.jboss.as.server.deployment.Phase.INSTALL;
import static org.jboss.as.server.deployment.Phase.POST_MODULE_METRICS;
import static org.wildfly.extension.metrics.MetricsExtension.SUBSYSTEM_NAME;
import static org.wildfly.extension.metrics.MetricsSubsystemDefinition.METRICS_REGISTRY_RUNTIME_CAPABILITY;
import static org.wildfly.extension.metrics.MetricsSubsystemDefinition.WILDFLY_COLLECTOR;
import static org.wildfly.extension.metrics._private.MetricsLogger.LOGGER;
import java.util.List;
import java.util.function.Function;
import org.jboss.as.controller.AbstractBoottimeAddStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.registry.ImmutableManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.server.AbstractDeploymentChainStep;
import org.jboss.as.server.DeploymentProcessorTarget;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceController;
import org.wildfly.extension.metrics.deployment.DeploymentMetricProcessor;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc.
*/
class MetricsSubsystemAdd extends AbstractBoottimeAddStepHandler {
MetricsSubsystemAdd() {
super(MetricsSubsystemDefinition.ATTRIBUTES);
}
static final MetricsSubsystemAdd INSTANCE = new MetricsSubsystemAdd();
@Override
protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
super.performBoottime(context, operation, model);
List<String> exposedSubsystems = MetricsSubsystemDefinition.EXPOSED_SUBSYSTEMS.unwrap(context, model);
boolean exposeAnySubsystem = exposedSubsystems.remove("*");
String prefix = MetricsSubsystemDefinition.PREFIX.resolveModelAttribute(context, model).asStringOrNull();
boolean securityEnabled = MetricsSubsystemDefinition.SECURITY_ENABLED.resolveModelAttribute(context, model).asBoolean();
WildFlyMetricRegistryService.install(context);
MetricsCollectorService.install(context);
MetricsContextService.install(context, securityEnabled);
// If the MP Metrics module is not installed, we need to install the WF Metrics DPU and initiate a metrics
// collection. If MP Metrics *is* installed, then we do not need to do either of those things, as that module
// handles that instead.
if (!context.getCapabilityServiceSupport().hasCapability(MetricsSubsystemDefinition.METRICS_SCAN_CAPABILITY)) {
context.addStep(new AbstractDeploymentChainStep() {
public void execute(DeploymentProcessorTarget processorTarget) {
processorTarget.addDeploymentProcessor(SUBSYSTEM_NAME, INSTALL, POST_MODULE_METRICS, new DeploymentMetricProcessor(exposeAnySubsystem, exposedSubsystems, prefix));
}
}, RUNTIME);
// delay the registration of the metrics in the VERIFY stage so that all resources
// created during the RUNTIME phase will have been registered in the MRR.
context.addStep(new OperationStepHandler() {
@Override
public void execute(OperationContext operationContext, ModelNode modelNode) {
ServiceController<?> serviceController = context.getServiceRegistry(false).getService(WILDFLY_COLLECTOR);
MetricCollector metricCollector = MetricCollector.class.cast(serviceController.getValue());
ServiceController<?> wildflyRegistryController = context.getServiceRegistry(false).getService(METRICS_REGISTRY_RUNTIME_CAPABILITY.getCapabilityServiceName());
WildFlyMetricRegistry metricRegistry = WildFlyMetricRegistry.class.cast(wildflyRegistryController.getValue());
ImmutableManagementResourceRegistration rootResourceRegistration = context.getRootResourceRegistration();
Resource rootResource = context.readResourceFromRoot(EMPTY_ADDRESS);
MetricRegistration registration = new MetricRegistration(metricRegistry);
metricCollector.collectResourceMetrics(rootResource, rootResourceRegistration, Function.identity(),
exposeAnySubsystem, exposedSubsystems, prefix,
registration);
}
}, VERIFY);
}
LOGGER.activatingSubsystem();
}
}
| 5,864 | 52.807339 | 183 |
java
|
null |
wildfly-main/metrics/src/main/java/org/wildfly/extension/metrics/PrometheusExporter.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.metrics;
import java.util.HashSet;
import java.util.Map;
import java.util.OptionalDouble;
import java.util.Set;
import org.jboss.as.controller.client.helpers.MeasurementUnit;
import org.wildfly.extension.metrics.MetricMetadata.MetricTag;
public class PrometheusExporter {
private static final String LF = "\n";
public String export(WildFlyMetricRegistry registry) {
Set<String> alreadyExportedMetrics = new HashSet<String>();
StringBuilder out = new StringBuilder();
for (Map.Entry<MetricID, Metric> entry : registry.getMetrics().entrySet()) {
MetricID metricID = entry.getKey();
String metricName = metricID.getMetricName();
MetricMetadata metadata = registry.getMetricMetadata().get(metricName);
String prometheusMetricName = toPrometheusMetricName(metricID, metadata);
OptionalDouble metricValue = entry.getValue().getValue();
// if the metric does not return a value, we skip printing the HELP and TYPE
if (!metricValue.isPresent()) {
continue;
}
if (!alreadyExportedMetrics.contains(metricName)) {
out.append("# HELP " + prometheusMetricName + " " + metadata.getDescription());
out.append(LF);
out.append("# TYPE " + prometheusMetricName + " " + metadata.getType());
out.append(LF);
alreadyExportedMetrics.add(metricName);
}
double scaledValue = scaleToBaseUnit(metricValue.getAsDouble(), metadata.getMeasurementUnit());
// I'm pretty sure this is incorrect but that aligns with smallrye-metrics OpenMetricsExporter behaviour
if (metadata.getType() == MetricMetadata.Type.COUNTER && metadata.getMeasurementUnit() != MeasurementUnit.NONE) {
prometheusMetricName += "_" + metadata.getBaseMetricUnit();
}
out.append(prometheusMetricName + getTagsAsAString(metricID) + " " + scaledValue);
out.append(LF);
}
return out.toString();
}
private static double scaleToBaseUnit(double value, MeasurementUnit unit) {
return value * MeasurementUnit.calculateOffset(unit, unit.getBaseUnits());
}
private static String toPrometheusMetricName(MetricID metricID, MetricMetadata metadata) {
String prometheusName = metricID.getMetricName();
// change the Prometheus name depending on type and measurement unit
if (metadata.getType() == WildFlyMetricMetadata.Type.COUNTER) {
prometheusName += "_total";
} else {
// if it's a gauge, let's add the base unit to the prometheus name
String baseUnit = metadata.getBaseMetricUnit();
if (!MetricMetadata.NONE.equals(baseUnit)) {
prometheusName += "_" + baseUnit;
}
}
return prometheusName;
}
public static String getTagsAsAString(MetricID metricID) {
MetricTag[] tags = metricID.getTags();
if (tags.length == 0) {
return "";
}
StringBuilder out = new StringBuilder("{");
for (int i = 0; i < tags.length; i++) {
if (i > 0) {
out.append(",");
}
MetricTag tag = tags[i];
out.append(tag.getKey() + "=\"" + tag.getValue() + "\"");
}
return out.append("}").toString();
}
}
| 4,502 | 42.298077 | 125 |
java
|
null |
wildfly-main/metrics/src/main/java/org/wildfly/extension/metrics/MetricRegistry.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.metrics;
/**
* Provides a registry of metrics.
*/
public interface MetricRegistry {
/**
* Registers the given metric. Calls will block if another thread
* {@link #readLock() holds the registry read lock}.
*
* @param metric the metric. Cannot be {@code null}
* @param metadata metadata for the metric. Cannot be {@code null}
*/
void registerMetric(Metric metric, MetricMetadata metadata);
/**
* Unregisters the given metric, if it is registered. Calls will block if another thread
* {@link #readLock() holds the registry read lock}.
*
* @param metricID the id for the metric. Cannot be {@code null}
*/
void unregister(MetricID metricID);
/**
* Acquires a non-exclusive read lock that will cause calls from other threads
* to {@link #registerMetric(Metric, MetricMetadata)} or {@link #unregister(MetricID)}
* to block. Must be followed by a call to {@link #unlock()}.
*/
void readLock();
/**
* Releases the non-exclusive lock obtained by a call to {@link #readLock()}.
*/
void unlock();
}
| 2,164 | 36.327586 | 92 |
java
|
null |
wildfly-main/metrics/src/main/java/org/wildfly/extension/metrics/MetricCollector.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.metrics;
import static org.jboss.as.controller.PathAddress.EMPTY_ADDRESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ATTRIBUTES;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DESCRIPTION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.wildfly.extension.metrics.MetricMetadata.Type.COUNTER;
import static org.wildfly.extension.metrics.MetricMetadata.Type.GAUGE;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.Function;
import org.jboss.as.controller.ControlledProcessState;
import org.jboss.as.controller.LocalModelControllerClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.ProcessStateNotifier;
import org.jboss.as.controller.client.helpers.MeasurementUnit;
import org.jboss.as.controller.descriptions.DescriptionProvider;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ImmutableManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
public class MetricCollector {
private final LocalModelControllerClient modelControllerClient;
private final ProcessStateNotifier processStateNotifier;
public MetricCollector(LocalModelControllerClient modelControllerClient, ProcessStateNotifier processStateNotifier) {
this.modelControllerClient = modelControllerClient;
this.processStateNotifier = processStateNotifier;
}
// collect metrics from the resources
public synchronized void collectResourceMetrics(final Resource resource,
ImmutableManagementResourceRegistration managementResourceRegistration,
Function<PathAddress, PathAddress> resourceAddressResolver,
boolean exposeAnySubsystem,
List<String> exposedSubsystems,
String prefix,
MetricRegistration registration) {
collectResourceMetrics0(resource, managementResourceRegistration, EMPTY_ADDRESS, resourceAddressResolver, registration,
exposeAnySubsystem, exposedSubsystems, prefix);
// Defer the actual registration until the server is running and they can be collected w/o errors
PropertyChangeListener listener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (ControlledProcessState.State.RUNNING == evt.getNewValue()) {
registration.register();
} else if (ControlledProcessState.State.STOPPING == evt.getNewValue()) {
// Unregister so if this is a reload they won't still be around in a static cache in MetricsRegistry
// and cause problems when the server is starting
registration.unregister();
processStateNotifier.removePropertyChangeListener(this);
}
}
};
this.processStateNotifier.addPropertyChangeListener(listener);
// If server is already running, we won't get a change event so register now
if (ControlledProcessState.State.RUNNING == this.processStateNotifier.getCurrentState()) {
registration.register();
}
}
private void collectResourceMetrics0(final Resource current,
ImmutableManagementResourceRegistration managementResourceRegistration,
PathAddress address,
Function<PathAddress, PathAddress> resourceAddressResolver,
MetricRegistration registration, boolean exposeAnySubsystem, List<String> exposedSubsystems, String prefix) {
if (!isExposingMetrics(address, exposeAnySubsystem, exposedSubsystems)) {
return;
}
Map<String, AttributeAccess> attributes = managementResourceRegistration.getAttributes(address);
if (attributes == null) {
return;
}
ModelNode resourceDescription = null;
for (Map.Entry<String, AttributeAccess> entry : attributes.entrySet()) {
String attributeName = entry.getKey();
AttributeAccess attributeAccess = entry.getValue();
if (!isCollectibleMetric(attributeAccess)) {
continue;
}
if (resourceDescription == null) {
DescriptionProvider modelDescription = managementResourceRegistration.getModelDescription(address);
resourceDescription = modelDescription.getModelDescription(Locale.getDefault());
}
PathAddress resourceAddress = resourceAddressResolver.apply(address);
MeasurementUnit unit = attributeAccess.getAttributeDefinition().getMeasurementUnit();
boolean isCounter = attributeAccess.getFlags().contains(AttributeAccess.Flag.COUNTER_METRIC);
String attributeDescription = resourceDescription.get(ATTRIBUTES, attributeName, DESCRIPTION).asStringOrNull();
WildFlyMetric metric = new WildFlyMetric(modelControllerClient, resourceAddress, attributeName);
WildFlyMetricMetadata metadata = new WildFlyMetricMetadata(attributeName, resourceAddress, prefix, attributeDescription, unit, isCounter ? COUNTER : GAUGE);
registration.addRegistrationTask(() -> registration.registerMetric(metric, metadata));
registration.addUnregistrationTask(metadata.getMetricID());
}
for (String type : current.getChildTypes()) {
for (Resource.ResourceEntry entry : current.getChildren(type)) {
final PathElement pathElement = entry.getPathElement();
final PathAddress childAddress = address.append(pathElement);
collectResourceMetrics0(entry, managementResourceRegistration, childAddress, resourceAddressResolver, registration, exposeAnySubsystem, exposedSubsystems, prefix);
}
}
}
private boolean isExposingMetrics(PathAddress address, boolean exposeAnySubsystem, List<String> exposedSubsystems) {
// root resource
if (address.size() == 0) {
return true;
}
String subsystemName = getSubsystemName(address);
if (subsystemName != null) {
return exposeAnySubsystem || exposedSubsystems.contains(subsystemName);
}
// do not expose metrics for resources outside the subsystems and deployments.
return false;
}
private String getSubsystemName(PathAddress address) {
if (address.size() == 0) {
return null;
}
if (address.getElement(0).getKey().equals(SUBSYSTEM)) {
return address.getElement(0).getValue();
} else {
return getSubsystemName(address.subAddress(1));
}
}
private boolean isCollectibleMetric(AttributeAccess attributeAccess) {
if (attributeAccess.getAccessType() == AttributeAccess.AccessType.METRIC
&& attributeAccess.getStorageType() == AttributeAccess.Storage.RUNTIME) {
// handle only metrics with simple numerical types
ModelType type = attributeAccess.getAttributeDefinition().getType();
if (type == ModelType.INT ||
type == ModelType.LONG ||
type == ModelType.DOUBLE) {
return true;
}
}
return false;
}
}
| 9,016 | 49.657303 | 179 |
java
|
null |
wildfly-main/metrics/src/main/java/org/wildfly/extension/metrics/WildFlyMetricMetadata.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.metrics;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEPLOYMENT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBDEPLOYMENT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.wildfly.common.Assert.checkNotNullParamWithNullPointerException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.client.helpers.MeasurementUnit;
public class WildFlyMetricMetadata implements MetricMetadata {
private static final Pattern SNAKE_CASE_PATTERN = Pattern.compile("(?<=[a-z])[A-Z]");
private final String description;
private final MeasurementUnit unit;
private final Type type;
private final String attributeName;
private final PathAddress address;
private final String globalPrefix;
private String metricName;
private MetricTag[] tags;
private MetricID metricID;
public WildFlyMetricMetadata(String attributeName, PathAddress address, String prefix, String description, MeasurementUnit unit, Type type) {
this.attributeName = checkNotNullParamWithNullPointerException("attributeName", attributeName);
this.address = checkNotNullParamWithNullPointerException("address", address);
this.description = checkNotNullParamWithNullPointerException("description", description);
this.type = checkNotNullParamWithNullPointerException("type", type);
this.globalPrefix = prefix;
this.unit = unit != null ? unit : MeasurementUnit.NONE;
init();
}
private void init() {
String metricPrefix = "";
List<String> labelNames = new ArrayList<>();
List<String> labelValues = new ArrayList<>();
for (PathElement element: address) {
String key = element.getKey();
String value = element.getValue();
// prepend the subsystem or statistics name to the attribute
if (key.equals(SUBSYSTEM) || key.equals("statistics")) {
metricPrefix += value + "-";
continue;
}
labelNames.add(getPrometheusMetricName(key));
labelValues.add(value);
}
// if the resource address defines a deployment (without subdeployment),
if (labelNames.contains(DEPLOYMENT) && !labelNames.contains(SUBDEPLOYMENT)) {
labelNames.add(SUBDEPLOYMENT);
labelValues.add(labelValues.get(labelNames.indexOf(DEPLOYMENT)));
}
if (globalPrefix != null && !globalPrefix.isEmpty()) {
metricPrefix = globalPrefix + "-" + metricPrefix;
}
metricName = getPrometheusMetricName(metricPrefix + attributeName);
tags = new MetricTag[labelNames.size()];
for (int i = 0; i < labelNames.size(); i++) {
String name = labelNames.get(i);
String value = labelValues.get(i);
tags[i] = new MetricTag(name, value);
}
metricID = new MetricID(metricName, tags);
}
@Override
public String getMetricName() {
return metricName;
}
@Override
public MetricTag[] getTags() {
return tags;
}
@Override
public String getDescription() {
return description;
}
@Override
public MeasurementUnit getMeasurementUnit() {
return unit;
}
@Override
public Type getType() {
return type;
}
@Override
public MetricID getMetricID() {
return metricID;
}
static String getPrometheusMetricName(String name) {
name =name.replaceAll("[^\\w]+","_");
name = decamelize(name);
return name;
}
private static String decamelize(String in) {
Matcher m = SNAKE_CASE_PATTERN.matcher(in);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "_" + m.group().toLowerCase());
}
m.appendTail(sb);
return sb.toString().toLowerCase();
}
}
| 5,237 | 35.124138 | 145 |
java
|
null |
wildfly-main/metrics/src/main/java/org/wildfly/extension/metrics/MetricsContextService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.metrics;
import static org.wildfly.extension.metrics.MetricsSubsystemDefinition.HTTP_EXTENSIBILITY_CAPABILITY;
import static org.wildfly.extension.metrics.MetricsSubsystemDefinition.METRICS_HTTP_CONTEXT_CAPABILITY;
import static org.wildfly.extension.metrics.MetricsSubsystemDefinition.METRICS_HTTP_SECURITY_CAPABILITY;
import static org.wildfly.extension.metrics.MetricsSubsystemDefinition.METRICS_REGISTRY_RUNTIME_CAPABILITY;
import java.util.function.Consumer;
import java.util.function.Supplier;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.server.mgmt.domain.ExtensibleHttpManagement;
import org.jboss.msc.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc.
*/
public class MetricsContextService implements Service {
private static final String CONTEXT_NAME = "/metrics";
private final Consumer<MetricsContextService> consumer;
private final Supplier<ExtensibleHttpManagement> extensibleHttpManagement;
private Supplier<WildFlyMetricRegistry> wildflyMetricRegistry;
private final Supplier<Boolean> securityEnabledSupplier;
private final PrometheusExporter prometheusExporter = new PrometheusExporter();
private HttpHandler overrideableMetricHandler;
static void install(OperationContext context, boolean securityEnabled) {
ServiceBuilder<?> serviceBuilder = context.getServiceTarget().addService(METRICS_HTTP_CONTEXT_CAPABILITY.getCapabilityServiceName());
Supplier<ExtensibleHttpManagement> extensibleHttpManagement = serviceBuilder.requires(context.getCapabilityServiceName(HTTP_EXTENSIBILITY_CAPABILITY, ExtensibleHttpManagement.class));
Supplier<WildFlyMetricRegistry> wildflyMetricRegistry = serviceBuilder.requires(METRICS_REGISTRY_RUNTIME_CAPABILITY.getCapabilityServiceName());
Consumer<MetricsContextService> metricsContext = serviceBuilder.provides(METRICS_HTTP_CONTEXT_CAPABILITY.getCapabilityServiceName());
final Supplier<Boolean> securityEnabledSupplier;
if (context.getCapabilityServiceSupport().hasCapability(METRICS_HTTP_SECURITY_CAPABILITY)) {
securityEnabledSupplier = serviceBuilder.requires(ServiceName.parse(METRICS_HTTP_SECURITY_CAPABILITY));
} else {
securityEnabledSupplier = new Supplier<Boolean>() {
@Override
public Boolean get() {
return securityEnabled;
}
};
}
Service metricsContextService = new MetricsContextService(metricsContext, extensibleHttpManagement, wildflyMetricRegistry, securityEnabledSupplier);
serviceBuilder.setInstance(metricsContextService)
.install();
}
public MetricsContextService(Consumer<MetricsContextService> consumer, Supplier<ExtensibleHttpManagement> extensibleHttpManagement, Supplier<WildFlyMetricRegistry> wildflyMetricRegistry, Supplier<Boolean> securityEnabledSupplier) {
this.consumer = consumer;
this.extensibleHttpManagement = extensibleHttpManagement;
this.wildflyMetricRegistry = wildflyMetricRegistry;
this.securityEnabledSupplier = securityEnabledSupplier;
}
@Override
public void start(StartContext context) {
extensibleHttpManagement.get().addManagementHandler(CONTEXT_NAME, securityEnabledSupplier.get(), new HttpHandler() {
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
if (overrideableMetricHandler != null) {
overrideableMetricHandler.handleRequest(exchange);
return;
}
WildFlyMetricRegistry metricRegistry = wildflyMetricRegistry.get();
metricRegistry.readLock();
try {
String wildFlyMetrics = prometheusExporter.export(metricRegistry);
exchange.getResponseSender().send(wildFlyMetrics);
} finally {
metricRegistry.unlock();
}
}
});
consumer.accept(this);
}
@Override
public void stop(StopContext context) {
extensibleHttpManagement.get().removeContext(CONTEXT_NAME);
consumer.accept(null);
}
public void setOverrideableMetricHandler(HttpHandler handler) {
this.overrideableMetricHandler = handler;
}
}
| 5,717 | 47.05042 | 235 |
java
|
null |
wildfly-main/metrics/src/main/java/org/wildfly/extension/metrics/MetricsExtension.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.metrics;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import org.jboss.as.controller.Extension;
import org.jboss.as.controller.ExtensionContext;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SubsystemRegistration;
import org.jboss.as.controller.descriptions.ResourceDescriptionResolver;
import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver;
import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler;
import org.jboss.as.controller.parsing.ExtensionParsingContext;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.kohsuke.MetaInfServices;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2020 Red Hat inc.
*/
@MetaInfServices(Extension.class)
public class MetricsExtension implements Extension {
static final String EXTENSION_NAME = "org.wildfly.extension.metrics";
/**
* The name of our subsystem within the model.
*/
public static final String SUBSYSTEM_NAME = "metrics";
protected static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME);
private static final String RESOURCE_NAME = MetricsExtension.class.getPackage().getName() + ".LocalDescriptions";
protected static final ModelVersion VERSION_1_0_0 = ModelVersion.create(1, 0, 0);
private static final ModelVersion CURRENT_MODEL_VERSION = VERSION_1_0_0;
private static final MetricsParser_1_0 CURRENT_PARSER = new MetricsParser_1_0();
static ResourceDescriptionResolver getResourceDescriptionResolver(final String... keyPrefix) {
return getResourceDescriptionResolver(true, keyPrefix);
}
static ResourceDescriptionResolver getResourceDescriptionResolver(final boolean useUnprefixedChildTypes, final String... keyPrefix) {
StringBuilder prefix = new StringBuilder();
for (String kp : keyPrefix) {
if (prefix.length() > 0){
prefix.append('.');
}
prefix.append(kp);
}
return new StandardResourceDescriptionResolver(prefix.toString(), RESOURCE_NAME, MetricsExtension.class.getClassLoader(), true, useUnprefixedChildTypes);
}
@Override
public void initialize(ExtensionContext context) {
final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION);
subsystem.registerXMLElementWriter(CURRENT_PARSER);
final ManagementResourceRegistration registration = subsystem.registerSubsystemModel(new MetricsSubsystemDefinition());
registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE);
}
@Override
public void initializeParsers(ExtensionParsingContext context) {
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, MetricsParser_1_0.NAMESPACE, CURRENT_PARSER);
}
}
| 4,051 | 44.022222 | 161 |
java
|
null |
wildfly-main/metrics/src/main/java/org/wildfly/extension/metrics/WildFlyMetric.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.metrics;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT;
import static org.wildfly.extension.metrics._private.MetricsLogger.LOGGER;
import java.util.OptionalDouble;
import org.jboss.as.controller.LocalModelControllerClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.dmr.ModelNode;
public class WildFlyMetric implements Metric {
private static final ModelNode UNDEFINED = new ModelNode();
private LocalModelControllerClient modelControllerClient;
private final PathAddress address;
private final String attributeName;
static {
UNDEFINED.protect();
}
public WildFlyMetric(LocalModelControllerClient modelControllerClient, PathAddress address, String attributeName) {
this.modelControllerClient = modelControllerClient;
this.address = address;
this.attributeName = attributeName;
}
@Override
public OptionalDouble getValue() {
ModelNode result = readAttributeValue(address, attributeName);
if (result.isDefined()) {
try {
return OptionalDouble.of(result.asDouble());
} catch (Exception e) {
LOGGER.unableToConvertAttribute(attributeName, address, e);
}
}
return OptionalDouble.empty();
}
private ModelNode readAttributeValue(PathAddress address, String attributeName) {
final ModelNode readAttributeOp = new ModelNode();
readAttributeOp.get(OP).set(READ_ATTRIBUTE_OPERATION);
readAttributeOp.get(OP_ADDR).set(address.toModelNode());
readAttributeOp.get(ModelDescriptionConstants.INCLUDE_UNDEFINED_METRIC_VALUES).set(false);
readAttributeOp.get(NAME).set(attributeName);
ModelNode response = modelControllerClient.execute(readAttributeOp);
String error = getFailureDescription(response);
// TODO: Revisit this handling
if (error != null) {
// [WFLY-11933] if the value can not be read if the management resource is not accessible due to RBAC,
// it is logged it at a lower level.
if (error.contains("WFLYCTL0216")) {
LOGGER.debugf("Unable to read attribute %s: %s.", attributeName, error);
} else{
LOGGER.unableToReadAttribute(attributeName, address, error);
}
return UNDEFINED;
}
return response.get(RESULT);
}
private String getFailureDescription(ModelNode result) {
if (result.hasDefined(FAILURE_DESCRIPTION)) {
return result.get(FAILURE_DESCRIPTION).toString();
}
return null;
}
}
| 4,245 | 41.46 | 119 |
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.