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/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/TaskSchedulerServletContextListener.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.test.integration.domain; import org.jboss.logging.Logger; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicInteger; import jakarta.annotation.Resource; import jakarta.enterprise.concurrent.ManagedExecutorService; import jakarta.servlet.ServletContextEvent; import jakarta.servlet.ServletContextListener; import jakarta.servlet.annotation.WebListener; @WebListener public class TaskSchedulerServletContextListener implements ServletContextListener { static final Logger logger = Logger.getLogger(TaskSchedulerServletContextListener.class.getName()); @Resource private ManagedExecutorService executor; static class ReSchedulingTask implements Runnable { private static int tasksCounter = 0; private static final int MAX_TASKS = 10; private static AtomicInteger nextTaskID = new AtomicInteger(0); private Integer taskID; private Executor executor; public ReSchedulingTask(Executor executor) { tasksCounter++; this.executor = executor; this.taskID = nextTaskID.incrementAndGet(); } private void doIt() { logger.trace("Task #" + this.taskID + " is doing its job (sleeping) now..."); try { Thread.sleep(10000); } catch (InterruptedException e) { logger.trace("Task #" + this.taskID + " got interrupted!"); return; } logger.trace("... task #" + this.taskID + " has completed its job."); } @Override public void run() { // Doing my job doIt(); // Rescheduling a new instance of me logger.trace("Task #" + this.taskID + " is rescheduling a new task now..."); if (tasksCounter <= MAX_TASKS) { this.executor.execute(new ReSchedulingTask(this.executor)); } logger.trace("... task #" + this.taskID + " has completed rescheduling a new task."); } } @Override public void contextDestroyed(ServletContextEvent arg0) { logger.trace("Context destroyed."); } @Override public void contextInitialized(ServletContextEvent arg0) { logger.trace("Context initialized."); logger.trace("Got executor: " + this.executor); logger.trace("Now scheduling a task from the ServletContextListener..."); this.executor.execute(new ReSchedulingTask(this.executor)); logger.trace("... completed scheduling a new task from the ServletContextListener."); } }
3,642
35.79798
103
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/ExpressionSupportSmokeTestCase.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.test.integration.domain; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ACCESS_TYPE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ALTERNATIVES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ATTRIBUTES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.BOOT_TIME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CHILDREN; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CHILD_TYPE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXPRESSIONS_ALLOWED; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_DEFAULTS; 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.PATH; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_CHILDREN_NAMES_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_DESCRIPTION_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RELATIVE_TO; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REQUIRES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STORAGE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SYSTEM_PROPERTY; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE_TYPE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION; import static org.jboss.as.test.integration.domain.management.util.DomainTestUtils.createOperation; import static org.jboss.as.test.integration.domain.management.util.DomainTestUtils.executeForResult; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.domain.management.util.WildFlyManagedConfiguration; import org.jboss.dmr.ValueExpression; import org.jboss.logging.Logger; import org.junit.Assert; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.test.integration.domain.management.util.DomainLifecycleUtil; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.dmr.Property; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * Smoke test of expression support. * * @author Brian Stansberry (c) 2012 Red Hat Inc. */ public class ExpressionSupportSmokeTestCase extends BuildConfigurationTestBase { private static final Logger LOGGER = Logger.getLogger(ExpressionSupportSmokeTestCase.class); private static final Set<ModelType> COMPLEX_TYPES = Collections.unmodifiableSet(EnumSet.of(ModelType.LIST, ModelType.OBJECT, ModelType.PROPERTY)); private DomainLifecycleUtil domainPrimaryLifecycleUtil; private int conflicts; private int noSimple; private int noSimpleCollection; private int noComplexList; private int noObject; private int noComplexProperty; private int supportedUndefined; private int simple; private int simpleCollection; private int complexList; private int object; private int complexProperty; private final boolean immediateValidation = Boolean.getBoolean("immediate.expression.validation"); private final boolean logHandling = Boolean.getBoolean("expression.logging"); /** * Launch a primary HC in --admin-only. Iterate through all resources, converting any writable attribute that * support expressions and has a value or a default value to an expression (if it isn't already one), using the * value/default value as the expression default (so setting a system property isn't required). Then reload out of * --admin-only and confirm that the host's servers start correctly. Finally, read the resources from the host * and confirm that the expected values are there. * * @throws Exception if there is one */ @Test public void test() throws Exception { // Add some extra resources to get some more coverage addTestResources(); Map<PathAddress, Map<String, ModelNode>> expectedValues = new HashMap<PathAddress, Map<String, ModelNode>>(); setExpressions(PathAddress.EMPTY_ADDRESS, "primary", expectedValues); LOGGER.trace("Update statistics:"); LOGGER.trace("=================="); LOGGER.trace("conflicts: " + conflicts); LOGGER.trace("no expression simple: " + noSimple); LOGGER.trace("no expression simple collection: " + noSimpleCollection); LOGGER.trace("no expression complex list: " + noComplexList); LOGGER.trace("no expression object: " + noObject); LOGGER.trace("no expression complex property: " + noComplexProperty); LOGGER.trace("supported but undefined: " + supportedUndefined); LOGGER.trace("simple: " + simple); LOGGER.trace("simple collection: " + simpleCollection); LOGGER.trace("complex list: " + complexList); LOGGER.trace("object: " + object); LOGGER.trace("complex property: " + complexProperty); // restart back to normal mode ModelNode op = new ModelNode(); op.get(OP_ADDR).add(HOST, "primary"); op.get(OP).set("reload"); op.get("admin-only").set(false); domainPrimaryLifecycleUtil.executeAwaitConnectionClosed(op); // Try to reconnect to the hc domainPrimaryLifecycleUtil.connect(); // check that the servers are up domainPrimaryLifecycleUtil.awaitServers(System.currentTimeMillis()); validateExpectedValues(PathAddress.EMPTY_ADDRESS, expectedValues, "primary"); } @Before public void setUp() throws IOException { final WildFlyManagedConfiguration config = createConfiguration("domain.xml", "host.xml", getClass().getSimpleName()); config.setAdminOnly(true); config.setReadOnlyDomain(true); config.setReadOnlyHost(true); // Trigger the servers to fail on boot if there are runtime errors String hostProps = config.getHostCommandLineProperties(); hostProps = hostProps == null ? "" : hostProps; config.setHostCommandLineProperties(hostProps + "\n-Djboss.unsupported.fail-boot-on-runtime-failure=true"); domainPrimaryLifecycleUtil = new DomainLifecycleUtil(config); // domainPrimaryLifecycleUtil.getConfiguration().addHostCommandLineProperty("-agentlib:jdwp=transport=dt_socket,address=8787,server=y,suspend=y"); domainPrimaryLifecycleUtil.start(); // Start conflicts = noSimple = noSimpleCollection = noComplexList = noComplexProperty = noObject = noComplexProperty = supportedUndefined = simple = simpleCollection = object = complexProperty = complexList = 0; } @After public void tearDown() { if (domainPrimaryLifecycleUtil != null) { domainPrimaryLifecycleUtil.stop(); } } private void addTestResources() throws IOException, MgmtOperationException { PathAddress spAddr = PathAddress.pathAddress(PathElement.pathElement(SYSTEM_PROPERTY, "domain-test")); ModelNode op = createOperation(ADD, spAddr); op.get(VALUE).set("test"); op.get(BOOT_TIME).set(true); executeForResult(op, domainPrimaryLifecycleUtil.getDomainClient()); PathAddress hostSpAddr = PathAddress.pathAddress(PathElement.pathElement(HOST, "primary"), PathElement.pathElement(SYSTEM_PROPERTY, "host-test")); op.get(OP_ADDR).set(hostSpAddr.toModelNode()); executeForResult(op, domainPrimaryLifecycleUtil.getDomainClient()); PathAddress pathAddr = PathAddress.pathAddress(PathElement.pathElement(PATH, "domain-path-test")); op = createOperation(ADD, pathAddr); op.get(RELATIVE_TO).set("jboss.home.dir"); op.get(PATH).set("test"); executeForResult(op, domainPrimaryLifecycleUtil.getDomainClient()); PathAddress hostPathAddr = PathAddress.pathAddress(PathElement.pathElement(HOST, "primary"), PathElement.pathElement(PATH, "host-path-test")); op.get(OP_ADDR).set(hostPathAddr.toModelNode()); executeForResult(op, domainPrimaryLifecycleUtil.getDomainClient()); } private void setExpressions(PathAddress address, String hostName, Map<PathAddress, Map<String, ModelNode>> expectedValues) throws IOException, MgmtOperationException { ModelNode description = readResourceDescription(address); ModelNode resource = readResource(address, true, false); ModelNode resourceNoDefaults = readResource(address, false, false); Map<String, ModelNode> expressionAttrs = new HashMap<String, ModelNode>(); Map<String, ModelNode> otherAttrs = new HashMap<String, ModelNode>(); Map<String, ModelNode> expectedAttrs = new HashMap<String, ModelNode>(); organizeAttributes(address, description, resource, resourceNoDefaults, expressionAttrs, otherAttrs, expectedAttrs); for (Map.Entry<String, ModelNode> entry : expressionAttrs.entrySet()) { writeAttribute(address, entry.getKey(), entry.getValue()); } // Set the other attrs as well just to exercise the write-attribute handlers for (Map.Entry<String, ModelNode> entry : otherAttrs.entrySet()) { writeAttribute(address, entry.getKey(), entry.getValue()); } if (expectedAttrs.size() > 0 && immediateValidation) { // Validate that our write-attribute calls resulted in the expected values in the model ModelNode modifiedResource = readResource(address, true, true); for (Map.Entry<String, ModelNode> entry : expectedAttrs.entrySet()) { ModelNode expectedValue = entry.getValue(); ModelNode modVal = modifiedResource.get(entry.getKey()); validateAttributeValue(address, entry.getKey(), expectedValue, modVal); } } // Store the modified values for confirmation after HC reload expectedValues.put(address, expectedAttrs); // Recurse into children, being careful about what processes we are touching boolean isHost = address.size() == 1 && HOST.equals(address.getLastElement().getKey()); for (Property descProp : description.get(CHILDREN).asPropertyList()) { String childType = descProp.getName(); if (isHost && SERVER.equals(childType)) { continue; } boolean hostChild = address.size() == 0 && HOST.equals(childType); List<String> children = readChildrenNames(address, childType); for (String child : children) { if (!hostChild || hostName.equals(child)) { setExpressions(address.append(PathElement.pathElement(childType, child)), hostName, expectedValues); } } } } private void organizeAttributes(PathAddress address, ModelNode description, ModelNode resource, ModelNode resourceNoDefaults, Map<String, ModelNode> expressionAttrs, Map<String, ModelNode> otherAttrs, Map<String, ModelNode> expectedAttrs) { ModelNode attributeDescriptions = description.get(ATTRIBUTES); for (Property descProp : attributeDescriptions.asPropertyList()) { String attrName = descProp.getName(); ModelNode attrDesc = descProp.getValue(); if (isAttributeExcluded(address, attrName, attrDesc, resourceNoDefaults)) { continue; } ModelNode noDefaultValue = resourceNoDefaults.get(attrName); if (!noDefaultValue.isDefined()) { // We need to see if it's legal to set this attribute, or whether it's undefined // because an alternative attribute is defined or a required attribute is not defined. Set<String> base = new HashSet<String>(); base.add(attrName); if (attrDesc.hasDefined(REQUIRES)) { for (ModelNode node : attrDesc.get(REQUIRES).asList()) { base.add(node.asString()); } } boolean conflict = false; for (String baseAttr : base) { if (!resource.hasDefined(baseAttr)) { conflict = true; break; } ModelNode baseAttrAlts = attributeDescriptions.get(baseAttr, ALTERNATIVES); if (baseAttrAlts.isDefined()) { for (ModelNode alt : baseAttrAlts.asList()) { String altName = alt.asString(); if (resourceNoDefaults.hasDefined(alt.asString()) || expressionAttrs.containsKey(altName) || otherAttrs.containsKey(altName)) { conflict = true; break; } } } } if (conflict) { conflicts++; logHandling("Skipping conflicted attribute " + attrName + " at " + address.toModelNode().asString()); continue; } } ModelNode attrValue = resource.get(attrName); ModelType attrType = attrValue.getType(); if (attrDesc.get(EXPRESSIONS_ALLOWED).asBoolean(false)) { // If it's defined and not an expression, use the current value to create an expression if (attrType != ModelType.UNDEFINED && attrType != ModelType.EXPRESSION) { // Deal with complex types specially if (COMPLEX_TYPES.contains(attrType)) { ModelNode valueType = attrDesc.get(VALUE_TYPE); if (valueType.getType() == ModelType.TYPE) { // Simple collection whose elements support expressions handleSimpleCollection(address, attrName, attrValue, valueType.asType(), expressionAttrs, otherAttrs, expectedAttrs); } else if (valueType.isDefined()) { handleComplexCollection(address, attrName, attrValue, attrType, valueType, expressionAttrs, otherAttrs, expectedAttrs); } else { noSimple++; logNoExpressions(address, attrName); otherAttrs.put(attrName, attrValue); expectedAttrs.put(attrName, attrValue); } } else { if (attrType == ModelType.STRING) { checkForUnconvertedExpression(address, attrName, attrValue); } String expression = "${exp.test:" + attrValue.asString() + "}"; expressionAttrs.put(attrName, new ModelNode(expression)); expectedAttrs.put(attrName, new ModelNode().set(new ValueExpression(expression))); simple++; logHandling("Added expression to simple attribute " + attrName + " at " + address.toModelNode().asString()); } } else { if (attrType != ModelType.EXPRESSION) { supportedUndefined++; logHandling("Expression supported but value undefined on simple attribute " + attrName + " at " + address.toModelNode().asString()); } else { simple++; logHandling("Already found an expression on simple attribute " + attrName + " at " + address.toModelNode().asString()); } otherAttrs.put(attrName, attrValue); expectedAttrs.put(attrName, attrValue); } } else if (COMPLEX_TYPES.contains(attrType) && attrDesc.get(VALUE_TYPE).getType() != ModelType.TYPE && attrDesc.get(VALUE_TYPE).isDefined()) { handleComplexCollection(address, attrName, attrValue, attrType, attrDesc.get(VALUE_TYPE), expressionAttrs, otherAttrs, expectedAttrs); } else /*if (!attrDesc.hasDefined(DEPRECATED))*/ { noSimple++; logNoExpressions(address, attrName); otherAttrs.put(attrName, attrValue); expectedAttrs.put(attrName, attrValue); } } } private boolean isAttributeExcluded(PathAddress address, String attrName, ModelNode attrDesc, ModelNode resourceNoDefaults) { if (!attrDesc.get(ACCESS_TYPE).isDefined() || !attrDesc.get(ACCESS_TYPE).asString().equalsIgnoreCase("read-write")) { return true; } if (attrDesc.get(STORAGE).isDefined() && !attrDesc.get(STORAGE).asString().equalsIgnoreCase("configuration")) { return true; } if (attrDesc.get(ModelDescriptionConstants.DEPRECATED).isDefined()){ return true; } // Special cases if ("default-web-module".equals(attrName)) { if (address.size() > 1) { PathElement subPe = address.getElement(address.size() - 2); if ("subsystem".equals(subPe.getKey()) && "web".equals(subPe.getValue()) && "virtual-server".equals(address.getLastElement().getKey())) { // This is not allowed if "enable-welcome-root" is "true", which is overly complex to validate // so skip it return true; } } } else if ("policy-modules".equals(attrName) || "login-modules".equals(attrName)) { if (address.size() > 2) { PathElement subPe = address.getElement(address.size() - 3); if ("subsystem".equals(subPe.getKey()) && "security".equals(subPe.getValue()) && "security-domain".equals(address.getElement(address.size() - 2).getKey())) { // This is a kind of alias that shows child resources as a list. Validating it // after reload breaks because the real child resources get changed. It's deprecated, so // we could exclude all deprecated attributes, but for now I'd rather be specific return true; } } } else if ("virtual-nodes".equals(attrName)) { if (address.size() > 3) { PathElement subPe = address.getElement(address.size() - 3); PathElement containerPe = address.getElement(address.size() - 2); PathElement distPe = address.getElement(address.size()-1); if ("subsystem".equals(subPe.getKey()) && "infinispan".equals(subPe.getValue()) && "cache-container".equals(containerPe.getKey()) && "distributed-cache".equals(distPe.getKey())) { // This is a distributed cache attribute in Infinispan which has been deprecated return true; } } } else if (address.size() > 0 && "transactions".equals(address.getLastElement().getValue()) && "subsystem".equals(address.getLastElement().getKey())) { if (attrName.contains("jdbc")) { // Ignore jdbc store attributes unless jdbc store is enabled return !resourceNoDefaults.hasDefined("use-jdbc-store") || !resourceNoDefaults.get("use-jdbc-store").asBoolean(); } else if (attrName.contains("journal")) { // Ignore journal store attributes unless journal store is enabled return !resourceNoDefaults.hasDefined("use-journal-store") || !resourceNoDefaults.get("use-journal-store").asBoolean(); } } return false; } private void logNoExpressions(PathAddress address, String attrName) { if (logHandling) { logHandling("No expression support for attribute " + attrName + " at " + address.toModelNode().asString()); } } private void logHandling(String msg) { if (logHandling) { LOGGER.trace(msg); } } private void handleSimpleCollection(PathAddress address, String attrName, ModelNode attrValue, ModelType valueType, Map<String, ModelNode> expressionAttrs, Map<String, ModelNode> otherAttrs, Map<String, ModelNode> expectedAttrs) { if (COMPLEX_TYPES.contains(valueType)) { // Too complicated noSimpleCollection++; logNoExpressions(address, attrName); otherAttrs.put(attrName, attrValue); } else { boolean hasExpression = false; ModelNode updated = new ModelNode(); ModelNode expected = new ModelNode(); for (ModelNode item : attrValue.asList()) { ModelType itemType = item.getType(); if (itemType == ModelType.PROPERTY) { Property prop = item.asProperty(); ModelNode propVal = prop.getValue(); ModelType propValType = propVal.getType(); if (propVal.isDefined() && propValType != ModelType.EXPRESSION) { // Convert property value to expression if (propValType == ModelType.STRING) { checkForUnconvertedExpression(address, attrName, propVal); } String expression = "${exp.test:" + propVal.asString() + "}"; updated.get(prop.getName()).set(expression); expected.get(prop.getName()).set(new ModelNode().set(new ValueExpression(expression))); hasExpression = true; } else { updated.get(prop.getName()).set(propVal); expected.get(prop.getName()).set(propVal); } } else if (item.isDefined() && itemType != ModelType.EXPRESSION) { // Convert item to expression if (itemType == ModelType.STRING) { checkForUnconvertedExpression(address, attrName, item); } String expression = "${exp.test:" + item.asString() + "}"; updated.add(expression); expected.add(new ModelNode().set(new ValueExpression(expression))); hasExpression = true; } else { updated.add(item); expected.add(item); } } if (hasExpression) { simpleCollection++; logHandling("Added expression to SIMPLE " + attrValue.getType() + " attribute " + attrName + " at " + address.toModelNode().asString()); expressionAttrs.put(attrName, updated); expectedAttrs.put(attrName, expected); } else { // We didn't change anything noSimpleCollection++; logNoExpressions(address, attrName); otherAttrs.put(attrName, attrValue); expectedAttrs.put(attrName, attrValue); } } } private void handleComplexCollection(PathAddress address, String attrName, ModelNode attrValue, ModelType attrType, ModelNode valueTypeDesc, Map<String, ModelNode> expressionAttrs, Map<String, ModelNode> otherAttrs, Map<String, ModelNode> expectedAttrs) { switch (attrType) { case LIST: handleComplexList(address, attrName, attrValue, valueTypeDesc, expressionAttrs, otherAttrs, expectedAttrs); break; case OBJECT: handleComplexObject(address, attrName, attrValue, valueTypeDesc, expressionAttrs, otherAttrs, expectedAttrs); break; case PROPERTY: handleComplexProperty(address, attrName, attrValue, valueTypeDesc, expressionAttrs, otherAttrs, expectedAttrs); break; default: throw new IllegalArgumentException(attrType.toString()); } } private void handleComplexList(PathAddress address, String attrName, ModelNode attrValue, ModelNode valueTypeDesc, Map<String, ModelNode> expressionAttrs, Map<String, ModelNode> otherAttrs, Map<String, ModelNode> expectedAttrs) { ModelNode updatedList = new ModelNode().setEmptyList(); ModelNode expectedList = new ModelNode().setEmptyList(); boolean changed = false; for (ModelNode item : attrValue.asList()) { ModelNode updated = new ModelNode(); ModelNode toExpect = new ModelNode(); handleComplexItem(address, attrName, item, valueTypeDesc, updated, toExpect); changed |= !updated.equals(item); updatedList.add(updated); expectedList.add(toExpect); } if (changed) { complexList++; logHandling("Added expression to COMPLEX LIST attribute " + attrName + " at " + address.toModelNode().asString()); expressionAttrs.put(attrName, updatedList); expectedAttrs.put(attrName, expectedList); } else { noComplexList++; logNoExpressions(address, attrName); otherAttrs.put(attrName, attrValue); } } private void handleComplexObject(PathAddress address, String attrName, ModelNode attrValue, ModelNode valueTypeDesc, Map<String, ModelNode> expressionAttrs, Map<String, ModelNode> otherAttrs, Map<String, ModelNode> expectedAttrs) { ModelNode updated = new ModelNode(); ModelNode toExpect = new ModelNode(); handleComplexItem(address, attrName, attrValue, valueTypeDesc, updated, toExpect); if (!updated.equals(attrValue)) { object++; logHandling("Added expression to OBJECT attribute " + attrName + " at " + address.toModelNode().asString()); expressionAttrs.put(attrName, updated); expectedAttrs.put(attrName, toExpect); } else { noObject++; logNoExpressions(address, attrName); otherAttrs.put(attrName, attrValue); } } private void handleComplexProperty(PathAddress address, String attrName, ModelNode attrValue, ModelNode valueTypeDesc, Map<String, ModelNode> expressionAttrs, Map<String, ModelNode> otherAttrs, Map<String, ModelNode> expectedAttrs) { Property prop = attrValue.asProperty(); ModelNode propVal = prop.getValue(); ModelNode updatedPropVal = new ModelNode(); ModelNode propValToExpect = new ModelNode(); handleComplexItem(address, attrName, propVal, valueTypeDesc, updatedPropVal, propValToExpect); if (!updatedPropVal.equals(propVal)) { complexProperty++; ModelNode updatedProp = new ModelNode().set(prop.getName(), updatedPropVal); logHandling("Added expression to COMPLEX PROPERTY attribute " + attrName + " at " + address.toModelNode().asString()); expressionAttrs.put(attrName, updatedProp); expectedAttrs.put(attrName, new ModelNode().set(prop.getName(), propValToExpect)); } else { noComplexProperty++; logNoExpressions(address, attrName); otherAttrs.put(attrName, attrValue); } } private void handleComplexItem(PathAddress address, String attrName, ModelNode item, ModelNode valueTypeDesc, ModelNode updatedItem, ModelNode itemToExpect) { // Hack to deal with time unit processing Set<String> keys = valueTypeDesc.keys(); boolean timeAttr = keys.size() == 2 && keys.contains("time") && keys.contains("unit"); boolean changed = false; for (Property fieldProp : valueTypeDesc.asPropertyList()) { String fieldName = fieldProp.getName(); if (!item.has(fieldName)) { continue; } boolean timeunit = timeAttr && "unit".equals(fieldName); ModelNode fieldDesc = fieldProp.getValue(); ModelNode fieldValue = item.get(fieldName); ModelType valueType = fieldValue.getType(); if (valueType == ModelType.UNDEFINED || valueType == ModelType.EXPRESSION || COMPLEX_TYPES.contains(valueType) // too complex || !fieldDesc.get(EXPRESSIONS_ALLOWED).asBoolean(false)) { updatedItem.get(fieldName).set(fieldValue); itemToExpect.get(fieldName).set(fieldValue); } else { if (valueType == ModelType.STRING) { checkForUnconvertedExpression(address, attrName, item); } String valueString = timeunit ? fieldValue.asString().toLowerCase() : fieldValue.asString(); String expression = "${exp.test:" + valueString + "}"; updatedItem.get(fieldName).set(expression); itemToExpect.get(fieldName).set(new ModelNode().set(new ValueExpression(expression))); changed = true; } } if (!changed) { // Use unchanged 'item' updatedItem.set(item); itemToExpect.set(item); } } private ModelNode readResourceDescription(PathAddress address) throws IOException, MgmtOperationException { ModelNode op = createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, address); return executeForResult(op, domainPrimaryLifecycleUtil.getDomainClient()); } private ModelNode readResource(PathAddress address, boolean defaults, boolean failIfMissing) throws IOException, MgmtOperationException { try { ModelNode op = createOperation(READ_RESOURCE_OPERATION, address); op.get(INCLUDE_DEFAULTS).set(defaults); return executeForResult(op, domainPrimaryLifecycleUtil.getDomainClient()); } catch (MgmtOperationException e) { if (failIfMissing) { throw e; } return new ModelNode(); } } private void checkForUnconvertedExpression(PathAddress address, String attrName, ModelNode attrValue) { String text = attrValue.asString(); int start = text.indexOf("${"); if (start > -1) { if (text.indexOf("}") > start) { Assert.fail(address + " attribute " + attrName + " is storing an unconverted expression: " + text); } } } private void writeAttribute(PathAddress address, String attrName, ModelNode value) throws IOException, MgmtOperationException { ModelNode op = createOperation(WRITE_ATTRIBUTE_OPERATION, address); op.get(NAME).set(attrName); op.get(VALUE).set(value); executeForResult(op, domainPrimaryLifecycleUtil.getDomainClient()); } private List<String> readChildrenNames(PathAddress address, String childType) throws IOException, MgmtOperationException { ModelNode op = createOperation(READ_CHILDREN_NAMES_OPERATION, address); op.get(CHILD_TYPE).set(childType); ModelNode opResult = executeForResult(op, domainPrimaryLifecycleUtil.getDomainClient()); List<String> result = new ArrayList<String>(); for (ModelNode child : opResult.asList()) { result.add(child.asString()); } return result; } private void validateExpectedValues(PathAddress address, Map<PathAddress, Map<String, ModelNode>> expectedValues, String hostName) throws IOException, MgmtOperationException { Map<String, ModelNode> expectedModel = expectedValues.get(address); if (expectedModel != null && isValidatable(address)) { ModelNode resource = readResource(address, true, true); for (Map.Entry<String, ModelNode> entry : expectedModel.entrySet()) { String attrName = entry.getKey(); ModelNode expectedValue = entry.getValue(); ModelNode modVal = resource.get(entry.getKey()); validateAttributeValue(address, attrName, expectedValue, modVal); } } ModelNode description = readResourceDescription(address); // Recurse into children, being careful about what processes we are touching boolean isHost = address.size() == 1 && HOST.equals(address.getLastElement().getKey()); for (Property descProp : description.get(CHILDREN).asPropertyList()) { String childType = descProp.getName(); if (isHost && SERVER.equals(childType)) { continue; } boolean hostChild = address.size() == 0 && HOST.equals(childType); List<String> children = readChildrenNames(address, childType); for (String child : children) { if (!hostChild || hostName.equals(child)) { validateExpectedValues(address.append(PathElement.pathElement(childType, child)), expectedValues, hostName); } } } } private void validateAttributeValue(PathAddress address, String attrName, ModelNode expectedValue, ModelNode modelValue) { switch (expectedValue.getType()) { case EXPRESSION: { Assert.assertEquals(address + " attribute " + attrName + " value " + modelValue + " is an unconverted expression", expectedValue, modelValue); break; } case INT: case LONG: Assert.assertTrue(address + " attribute " + attrName + " is a valid type", modelValue.getType() == ModelType.INT || modelValue.getType() == ModelType.LONG); Assert.assertEquals(address + " -- " + attrName, expectedValue.asLong(), modelValue.asLong()); break; default: { Assert.assertEquals(address + " -- " + attrName, expectedValue, modelValue); } } } private boolean isValidatable(PathAddress address) { boolean result = true; if (address.size() > 1 && address.getLastElement().getKey().equals("bootstrap-context") && address.getLastElement().getValue().equals("default") && address.getElement(address.size() - 2).getKey().equals("subsystem") && address.getElement(address.size() - 2).getValue().equals("jca")) { // Jakarta Connectors subsystem doesn't persist this resource result = false; } return result; } }
37,746
50.286685
179
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/JVMServerPropertiesTestCase.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.test.integration.domain; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; 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.DIRECTORY_GROUPING; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ENABLED; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RELOAD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESTART_SERVERS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_CONFIG; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_GROUP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS; import static org.jboss.as.test.integration.domain.management.util.DomainTestSupport.safeClose; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.Properties; import java.util.PropertyPermission; import java.util.concurrent.TimeoutException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.client.helpers.domain.DomainClient; import org.jboss.as.controller.client.helpers.domain.ServerStatus; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.domain.management.util.DomainLifecycleUtil; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.integration.domain.management.util.DomainTestUtils; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.integration.management.util.PropertiesServlet; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** * Verifies the uses of jboss.server.[base,log,data,temp].dir properties as managed server JMV options. The test uses a * preconfigured domain with three server groups with a server on each server group. The above properties are used to * configure the host, server-group and server JVM settings. The test validates that these properties can be used and * contains the expected values. * * @author <a href="mailto:[email protected]">Yeray Borges</a> */ public class JVMServerPropertiesTestCase { protected static final PathElement SERVER_GROUP_ONE = PathElement.pathElement(SERVER_GROUP, "server-group-one"); protected static final PathElement SERVER_GROUP_TWO = PathElement.pathElement(SERVER_GROUP, "server-group-two"); protected static final PathElement SERVER_GROUP_THREE = PathElement.pathElement(SERVER_GROUP, "server-group-three"); protected static final PathElement HOST_PRIMARY = PathElement.pathElement(HOST, "primary"); protected static final PathElement SERVER_CONFIG_ONE = PathElement.pathElement(SERVER_CONFIG, "server-one"); protected static final PathElement SERVER_CONFIG_TWO = PathElement.pathElement(SERVER_CONFIG, "server-two"); protected static final PathElement SERVER_CONFIG_THREE = PathElement.pathElement(SERVER_CONFIG, "server-three"); public static final String BY_SERVER = "by-server"; public static final String BY_TYPE = "by-type"; private static DomainTestSupport testSupport; private static DomainLifecycleUtil primaryLifecycleUtil; private static final String PROP_SERVLET_APP = "propertiesServletTestApp"; private static final String PROP_SERVLET_APP_WAR = PROP_SERVLET_APP + ".war"; private static final String PROP_SERVLET_APP_URL = PROP_SERVLET_APP + PropertiesServlet.SERVLET_PATH; private static Path deploymentPath; @BeforeClass public static void setupDomain() throws Exception { final DomainTestSupport.Configuration configuration = DomainTestSupport.Configuration.create(JVMServerPropertiesTestCase.class.getSimpleName(), "domain-configs/domain-jvm-properties.xml", "host-configs/host-primary-jvm-properties.xml", null ); testSupport = DomainTestSupport.create(configuration); primaryLifecycleUtil = testSupport.getDomainPrimaryLifecycleUtil(); // Prepares the application deployment file WebArchive deployment = createDeployment(); deploymentPath = DomainTestSupport.getBaseDir(JVMServerPropertiesTestCase.class.getSimpleName()).toPath().resolve("deployments"); deploymentPath.toFile().mkdirs(); deployment.as(ZipExporter.class).exportTo(deploymentPath.resolve(PROP_SERVLET_APP_WAR).toFile(), true); testSupport.start(); primaryLifecycleUtil.awaitServers(TimeoutUtil.adjust(30 * 1000)); } @AfterClass public static void tearDownDomain() { testSupport.close(); testSupport = null; primaryLifecycleUtil = null; } @Test public void testServerProperties() throws IOException, MgmtOperationException, InterruptedException, TimeoutException { ModelNode op = createDeploymentOperation(deploymentPath.resolve(PROP_SERVLET_APP_WAR), SERVER_GROUP_ONE, SERVER_GROUP_TWO, SERVER_GROUP_THREE); DomainTestUtils.executeForResult(op, primaryLifecycleUtil.createDomainClient()); validateProperties("server-one", 8080, BY_SERVER); validateProperties("server-two", 8180, BY_SERVER); validateProperties("server-three", 8280, BY_SERVER); op = Util.getWriteAttributeOperation(PathAddress.pathAddress(HOST_PRIMARY), DIRECTORY_GROUPING, BY_TYPE); DomainTestUtils.executeForResult(op, primaryLifecycleUtil.createDomainClient()); op = Util.createEmptyOperation(RELOAD, PathAddress.pathAddress(HOST_PRIMARY)); op.get(RESTART_SERVERS).set(true); primaryLifecycleUtil.executeAwaitConnectionClosed(op); primaryLifecycleUtil.connect(); primaryLifecycleUtil.awaitHostController(System.currentTimeMillis()); DomainClient primaryClient = primaryLifecycleUtil.createDomainClient(); DomainTestUtils.waitUntilState(primaryClient, PathAddress.pathAddress(HOST_PRIMARY, SERVER_CONFIG_ONE), ServerStatus.STARTED.toString()); DomainTestUtils.waitUntilState(primaryClient, PathAddress.pathAddress(HOST_PRIMARY, SERVER_CONFIG_TWO), ServerStatus.STARTED.toString()); DomainTestUtils.waitUntilState(primaryClient, PathAddress.pathAddress(HOST_PRIMARY, SERVER_CONFIG_THREE), ServerStatus.STARTED.toString()); validateProperties("server-one", 8080, BY_TYPE); validateProperties("server-two", 8180, BY_TYPE); validateProperties("server-three", 8280, BY_TYPE); } private void validateProperties(String server, int port, String directoryGrouping) throws IOException { final Path serverHome = DomainTestSupport.getHostDir(JVMServerPropertiesTestCase.class.getSimpleName(), "primary").toPath(); final Path serverBaseDir = serverHome.resolve("servers").resolve(server); final Path serverLogDir = BY_SERVER.equals(directoryGrouping) ? serverBaseDir.resolve("log") : serverHome.resolve("log").resolve("servers").resolve(server); final Path serverDataDir = BY_SERVER.equals(directoryGrouping) ? serverBaseDir.resolve("data") : serverHome.resolve("data").resolve("servers").resolve(server); final Path serverTmpDir = BY_SERVER.equals(directoryGrouping) ? serverBaseDir.resolve("tmp") : serverHome.resolve("tmp").resolve("servers").resolve(server); String response = performHttpCall(DomainTestSupport.primaryAddress, port, PROP_SERVLET_APP_URL); Properties p = new Properties(); try (StringReader isr = new StringReader(response.replace("\\", "\\\\"))) { p.load(isr); } Assert.assertEquals(serverBaseDir.toAbsolutePath().toString(), p.getProperty("test.jboss.server.base.dir")); Assert.assertEquals(serverLogDir.toAbsolutePath().toString(), p.getProperty("test.jboss.server.log.dir")); Assert.assertEquals(serverDataDir.toAbsolutePath().toString(), p.getProperty("test.jboss.server.data.dir")); Assert.assertEquals(serverTmpDir.toAbsolutePath().toString(), p.getProperty("test.jboss.server.temp.dir")); } private static String performHttpCall(String host, int port, String context) throws IOException { URLConnection conn; InputStream in = null; BufferedReader input = null; InputStreamReader isr = null; try { URL url = new URL("http://" + TestSuiteEnvironment.formatPossibleIpv6Address(host) + ":" + port + "/" + context); conn = url.openConnection(); conn.setDoInput(true); in = conn.getInputStream(); isr = new InputStreamReader(in, StandardCharsets.UTF_8); input = new BufferedReader(isr); StringBuilder strBuilder = new StringBuilder(); String str; while (null != (str = input.readLine())) { strBuilder.append(str).append("\r\n"); } return strBuilder.toString(); } finally { safeClose(input); safeClose(isr); safeClose(in); } } private ModelNode createDeploymentOperation(Path deployment, PathElement... serverGroups) throws MalformedURLException { ModelNode content = new ModelNode(); content.get("url").set(deployment.toUri().toURL().toString()); ModelNode op = Util.createEmptyOperation(COMPOSITE, PathAddress.EMPTY_ADDRESS); ModelNode steps = op.get(STEPS); ModelNode step1 = steps.add(); step1.set(Util.createEmptyOperation(ADD, PathAddress.pathAddress(PathElement.pathElement(DEPLOYMENT, deployment.getFileName().toString())))); step1.get(CONTENT).add(content); for (PathElement serverGroup : serverGroups) { ModelNode sg = steps.add(); sg.set(Util.createEmptyOperation(ADD, PathAddress.pathAddress(serverGroup, PathElement.pathElement(DEPLOYMENT, deployment.getFileName().toString())))); sg.get(ENABLED).set(true); } return op; } public static WebArchive createDeployment() { WebArchive war = ShrinkWrap.create(WebArchive.class, PROP_SERVLET_APP_WAR); war.addClass(PropertiesServlet.class); war.addAsManifestResource(createPermissionsXmlAsset( new PropertyPermission("*", "read, write") ), "permissions.xml"); return war; } }
12,441
50.841667
167
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/management/cli/CloneProfileTestCase.java
/* * JBoss, Home of Professional Open Source * Copyright 2015, 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.test.integration.domain.management.cli; import org.apache.commons.io.FileUtils; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.integration.domain.suites.CLITestSuite; import org.jboss.as.test.integration.management.base.AbstractCliTestBase; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.jboss.logging.Logger; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; /** * Test for providing profile cloning ability (runtime (CLI)) to create * new profiles based on existing JBoss profiles. * * Test clone "default" profile to "clone-profile-test-case-default" profile. * * https://issues.jboss.org/browse/WFLY-4838 * * @author Marek Kopecky <[email protected]> */ public class CloneProfileTestCase extends AbstractCliTestBase { private static Logger log = Logger.getLogger(CloneProfileTestCase.class); private static final String ORIGINAL_PROFILE = "default"; private static final String NEW_PROFILE = "clone-profile-test-case-default"; /** * Domain configuration */ private static File domainCfg; @BeforeClass public static void before() throws Exception { DomainTestSupport domainSupport = CLITestSuite.createSupport(CloneProfileTestCase.class.getSimpleName()); AbstractCliTestBase.initCLI(DomainTestSupport.primaryAddress); File primaryDir = new File(domainSupport.getDomainPrimaryConfiguration().getDomainDirectory()); domainCfg = new File(primaryDir, "configuration" + File.separator + "testing-domain-standard.xml"); } @AfterClass public static void after() throws Exception { AbstractCliTestBase.closeCLI(); CLITestSuite.stopSupport(); } /** * Sends command line to CLI, validate and return output. * * @param line command line * @return CLI output */ private String cliRequest(String line, boolean successRequired) { log.trace(line); cli.sendLine(line); String output = cli.readOutput(); if (successRequired) { assertTrue("CLI command \"" + line + " doesn't contain \"success\"", output.contains("success")); } return output; } @Test public void testProfile() throws IOException { // get domain configuration String domainCfgContent = FileUtils.readFileToString(domainCfg); assertTrue("Domain configuration is not initialized correctly.", domainCfgContent.indexOf(NEW_PROFILE) == -1); // clone profile cliRequest("/profile=" + ORIGINAL_PROFILE + ":clone(to-profile=" + NEW_PROFILE + ")", true); // get and check submodules String originSubmodules = cliRequest("ls /profile=" + ORIGINAL_PROFILE + "/subsystem", false); String newSubmodules = cliRequest("ls /profile=" + NEW_PROFILE + "/subsystem", false); assertEquals("New profile has different submodules than origin profile.", originSubmodules, newSubmodules); // check domain configuration domainCfgContent = FileUtils.readFileToString(domainCfg); assertTrue("Domain configuration doesn't contain " + NEW_PROFILE + "profile.", domainCfgContent.indexOf(NEW_PROFILE) != -1); } }
4,410
37.692982
132
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/management/cli/DomainDeployWithRuntimeNameTestCase.java
/* * Copyright (C) 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 library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ package org.jboss.as.test.integration.domain.management.cli; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.jboss.as.domain.controller.logging.DomainControllerLogger; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.integration.domain.suites.CLITestSuite; import org.jboss.as.test.integration.management.base.AbstractCliTestBase; import org.jboss.as.test.integration.management.util.SimpleHelloWorldServlet; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.impl.base.exporter.zip.ZipExporterImpl; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * * @author <a href="mailto:[email protected]">Emmanuel Hugonnet</a> (c) 2013 Red Hat, inc. */ public class DomainDeployWithRuntimeNameTestCase extends AbstractCliTestBase { private File warFile; private static String[] serverGroups; public static final String RUNTIME_NAME = "SimpleServlet.war"; public static final String OTHER_RUNTIME_NAME = "OtherSimpleServlet.war"; private static final String APP_NAME = "simple1"; private static final String OTHER_APP_NAME = "simple2"; @BeforeClass public static void setup() throws Exception { CLITestSuite.createSupport(DomainDeployWithRuntimeNameTestCase.class.getSimpleName()); List<String> groups = new ArrayList<>(CLITestSuite.serverGroups.keySet()); Collections.sort(groups); serverGroups = groups.toArray(new String[groups.size()]); AbstractCliTestBase.initCLI(DomainTestSupport.primaryAddress); } private File createWarFile(String content) throws IOException { WebArchive war = ShrinkWrap.create(WebArchive.class, "HelloServlet.war"); war.addClass(SimpleHelloWorldServlet.class); war.addAsWebInfResource(SimpleHelloWorldServlet.class.getPackage(), "web.xml", "web.xml"); war.addAsWebResource(new StringAsset(content), "page.html"); File tempFile = new File(System.getProperty("java.io.tmpdir"), "HelloServlet.war"); new ZipExporterImpl(war).exportTo(tempFile, true); return tempFile; } @AfterClass public static void cleanup() throws Exception { AbstractCliTestBase.closeCLI(); CLITestSuite.stopSupport(); } @After public void undeployAll() { assertThat(warFile.delete(), is(true)); cli.sendLine("undeploy --all-relevant-server-groups " + APP_NAME, true); cli.sendLine("undeploy --all-relevant-server-groups " + OTHER_APP_NAME, true); } @Test public void testDeployWithSameRuntimeNameOnSameServerGroup() throws Exception { // deploy to group servers warFile = createWarFile("Version1"); cli.sendLine(buildDeployCommand(serverGroups[0], RUNTIME_NAME, APP_NAME)); checkURL("/SimpleServlet/hello", "SimpleHelloWorldServlet", serverGroups[0], false); checkURL("/SimpleServlet/page.html", "Version1", serverGroups[0], false); checkURL("/SimpleServlet/hello", "SimpleHelloWorldServlet", serverGroups[1], true); warFile = createWarFile("Shouldn't be deployed, as runtime already exist"); cli.sendLine(buildDeployCommand(serverGroups[0], RUNTIME_NAME, OTHER_APP_NAME), true); assertThat(cli.readOutput(), containsString(DomainControllerLogger.ROOT_LOGGER.runtimeNameMustBeUnique(APP_NAME, RUNTIME_NAME, serverGroups[0]).getMessage())); checkURL("/SimpleServlet/hello", "SimpleHelloWorldServlet", serverGroups[0], false); checkURL("/SimpleServlet/page.html", "Version1", serverGroups[0], false); } @Test public void testDeployWithSameRuntimeNameOnDifferentServerGroup() throws Exception { // deploy to group servers warFile = createWarFile("Version1"); cli.sendLine(buildDeployCommand(serverGroups[0], RUNTIME_NAME, APP_NAME)); checkURL("/SimpleServlet/hello", "SimpleHelloWorldServlet", serverGroups[0], false); checkURL("/SimpleServlet/page.html", "Version1", serverGroups[0], false); checkURL("/SimpleServlet/hello", "SimpleHelloWorldServlet", serverGroups[1], true); warFile = createWarFile("Version2"); cli.sendLine(buildDeployCommand(serverGroups[1], RUNTIME_NAME, OTHER_APP_NAME)); checkURL("/SimpleServlet/hello", "SimpleHelloWorldServlet", serverGroups[0], false); checkURL("/SimpleServlet/page.html", "Version1", serverGroups[0], false); checkURL("/SimpleServlet/hello", "SimpleHelloWorldServlet", serverGroups[1], false); checkURL("/SimpleServlet/page.html", "Version2", serverGroups[1], false); } @Test public void testDeployWithDifferentRuntimeNameOnDifferentServerGroup() throws Exception { // deploy to group servers warFile = createWarFile("Version1"); cli.sendLine(buildDeployCommand(serverGroups[0], RUNTIME_NAME, APP_NAME)); checkURL("/SimpleServlet/hello", "SimpleHelloWorldServlet", serverGroups[0], false); checkURL("/SimpleServlet/page.html", "Version1", serverGroups[0], false); checkURL("/SimpleServlet/hello", "SimpleHelloWorldServlet", serverGroups[1], true); warFile = createWarFile("Version3"); cli.sendLine(buildDeployCommand(serverGroups[1], OTHER_RUNTIME_NAME, OTHER_APP_NAME)); checkURL("/SimpleServlet/hello", "SimpleHelloWorldServlet", serverGroups[0], false); checkURL("/SimpleServlet/page.html", "Version1", serverGroups[0], false); checkURL("/OtherSimpleServlet/hello", "SimpleHelloWorldServlet", serverGroups[1], false); checkURL("/OtherSimpleServlet/page.html", "Version3", serverGroups[1], false); } private String buildDeployCommand(String serverGroup, String runtimeName, String name) { return "deploy --server-groups=" + serverGroup + " " + warFile.getAbsolutePath() + " --runtime-name=" + runtimeName + " --name=" + name; } private void checkURL(String path, String content, String serverGroup, boolean shouldFail) throws Exception { List<String> groupServers = new ArrayList<String>(); for (String server : CLITestSuite.serverGroups.get(serverGroup)) { groupServers.add(server); } for (Map.Entry<String, String> entry : CLITestSuite.hostAddresses.entrySet()) { String address = entry.getValue(); for (String server : CLITestSuite.hostServers.get(entry.getKey())) { if (!groupServers.contains(server)) { continue; // server not in the group } if (!CLITestSuite.serverStatus.get(server)) { continue; // server not started } int port = 8080 + CLITestSuite.portOffsets.get(server); URL url = new URL("http", address, port, path); boolean failed = false; try { String response = HttpRequest.get(url.toString(), 10, TimeUnit.SECONDS); assertThat(response, containsString(content)); } catch (Exception e) { failed = true; if (!shouldFail) { throw new Exception("Http request failed.", e); } } if (shouldFail) { assertThat(url.toString(), failed, is(true)); } } } } }
8,919
46.956989
167
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/management/cli/DeployAllServerGroupsTestCase.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.test.integration.domain.management.cli; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.net.URL; import java.util.Map; import java.util.concurrent.TimeUnit; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.integration.domain.suites.CLITestSuite; import org.jboss.as.test.integration.management.base.AbstractCliTestBase; import org.jboss.as.test.integration.management.util.SimpleServlet; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.impl.base.exporter.zip.ZipExporterImpl; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** * * @author Dominik Pospisil <[email protected]> */ public class DeployAllServerGroupsTestCase extends AbstractCliTestBase { private static File warFile; @BeforeClass public static void before() throws Exception { CLITestSuite.createSupport(DeployAllServerGroupsTestCase.class.getSimpleName()); WebArchive war = ShrinkWrap.create(WebArchive.class, "SimpleServlet.war"); war.addClass(SimpleServlet.class); war.addAsWebResource(new StringAsset("Version1"), "page.html"); String tempDir = System.getProperty("java.io.tmpdir"); warFile = new File(tempDir, "SimpleServlet.war"); new ZipExporterImpl(war).exportTo(warFile, true); AbstractCliTestBase.initCLI(DomainTestSupport.primaryAddress); } @AfterClass public static void after() throws Exception { AbstractCliTestBase.closeCLI(); Assert.assertTrue(warFile.delete()); CLITestSuite.stopSupport(); } @Test public void testDeployRedeployUndeploy() throws Exception { testDeploy(); testRedeploy(); testUndeploy(); } public void testDeploy() throws Exception { // deploy to all servers cli.sendLine("deploy --all-server-groups " + warFile.getAbsolutePath()); // check that the deployment is available on all servers checkURL("/SimpleServlet/SimpleServlet", "SimpleServlet"); } public void testRedeploy() throws Exception { // check we have original deployment checkURL("/SimpleServlet/page.html", "Version1"); // update the deployment - replace page.html WebArchive war = ShrinkWrap.create(WebArchive.class, "SimpleServlet.war"); war.addClass(SimpleServlet.class); war.addAsWebResource(new StringAsset("Version2"), "page.html"); new ZipExporterImpl(war).exportTo(warFile, true); // redeploy to all servers assertFalse(cli.sendLine("deploy --all-server-groups " + warFile.getAbsolutePath(), true)); // force redeploy cli.sendLine("deploy " + warFile.getAbsolutePath() + " --force"); // check that new version is running checkURL("/SimpleServlet/page.html", "Version2"); } public void testUndeploy() throws Exception { //undeploy cli.sendLine("undeploy --all-relevant-server-groups SimpleServlet.war"); // check undeployment checkURL("/SimpleServlet/SimpleServlet" , "SimpleServlet", true); } private void checkURL(String path, String content) throws Exception { checkURL(path, content, false); } private void checkURL(String path, String content, boolean shouldFail) throws Exception { for (Map.Entry<String, String> entry : CLITestSuite.hostAddresses.entrySet()) { String address = entry.getValue(); for (String server : CLITestSuite.hostServers.get(entry.getKey())) { if (! CLITestSuite.serverStatus.get(server)) continue; Integer portOffset = CLITestSuite.portOffsets.get(server); URL url = new URL("http", address, 8080 + portOffset, path); boolean failed = false; try { String response = HttpRequest.get(url.toString(), 10, TimeUnit.SECONDS); assertTrue(response.contains(content)); } catch (Exception e) { failed = true; if (!shouldFail) throw new Exception("Http request failed.", e); } if (shouldFail) assertTrue(failed); } } } }
5,580
36.456376
99
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/management/cli/RolloutPlanTestServlet.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.test.integration.domain.management.cli; import java.io.IOException; import java.io.PrintWriter; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.URL; import java.util.Date; import jakarta.servlet.ServletConfig; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.jboss.logging.Logger; /** * @author Dominik Pospisil <[email protected]> */ @WebServlet(urlPatterns = {"/RolloutServlet"}, loadOnStartup = 1) public class RolloutPlanTestServlet extends HttpServlet { public static final String BIND_PORT_PARAM = "bindPort"; public static final String OP_PARAM = "operation"; public static final String OP_BIND = "bind"; public static final String OP_UNBIND = "unbind"; private Date initDate; private int bindPort; private ServerSocket socket; private String host; private static final Logger log = Logger.getLogger(RolloutPlanTestServlet.class); protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { URL requestURL = new URL(request.getRequestURL().toString()); host = requestURL.getHost(); String op = request.getParameter(OP_PARAM); if (OP_BIND.equals(op)) { bindPort = Integer.valueOf(request.getParameter(BIND_PORT_PARAM)); bind(); } else if (OP_UNBIND.equals(op)) { unbind(); } response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.print(String.valueOf(initDate.getTime())); out.close(); } @Override public void init(ServletConfig config) throws ServletException { initDate = new Date(); super.init(config); log.trace("RolloutServlet initialized: " + String.valueOf(initDate.getTime())); } @Override public void destroy() { if (socket != null) { try { unbind(); } catch (ServletException se) {} } super.destroy(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } private void bind() throws ServletException { if (socket != null) { throw new ServletException("Already bound."); } try { socket = new ServerSocket(); socket.bind(new InetSocketAddress(host, bindPort)); log.trace("Bound to address " + host + " port " + bindPort + "."); } catch (IOException ioe) { throw new ServletException("Bind failed.", ioe); } } private void unbind() throws ServletException { if (socket == null) { throw new ServletException("Not bound."); } try { socket.close(); socket = null; log.trace("Unbound from address " + host + " port " + bindPort + "."); } catch (IOException ioe) { throw new ServletException("Unbind failed.", ioe); } } }
4,466
34.452381
91
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/management/cli/DataSourceTestCase.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.test.integration.domain.management.cli; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.util.Map; import org.jboss.as.test.integration.domain.driver.FooDriver; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.integration.domain.suites.CLITestSuite; import org.jboss.as.test.integration.management.base.AbstractCliTestBase; import org.jboss.as.test.integration.management.util.CLIOpResult; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.impl.base.exporter.zip.ZipExporterImpl; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * * @author Dominik Pospisil <[email protected]> */ public class DataSourceTestCase extends AbstractCliTestBase { private static String[] profileNames; private static final String[][] DS_PROPS = new String[][] { {"idle-timeout-minutes", "5"} }; @BeforeClass public static void before() throws Exception { CLITestSuite.createSupport(DataSourceTestCase.class.getSimpleName()); AbstractCliTestBase.initCLI(DomainTestSupport.primaryAddress); } @AfterClass public static void after() throws Exception { AbstractCliTestBase.closeCLI(); CLITestSuite.stopSupport(); } @Before public void init() { profileNames = CLITestSuite.serverProfiles.keySet().toArray(new String[CLITestSuite.serverProfiles.size()]); } @Test public void testDataSource() throws Exception { testAddDataSource("h2"); testModifyDataSource("h2"); testRemoveDataSource("h2"); } @Test public void testXaDataSource() throws Exception { testAddXaDataSource(); testModifyXaDataSource(); testRemoveXaDataSource(); } @Test public void testDataSourcewithHotDeployedJar() throws Exception { cli.sendLine("deploy --all-server-groups " + createDriverJarFile().getAbsolutePath()); testAddDataSource("foodriver.jar"); testModifyDataSource("foodriver.jar"); testRemoveDataSource("foodriver.jar"); } private File createDriverJarFile() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "foodriver.jar"); jar.addClass(FooDriver.class); jar.addAsResource(FooDriver.class.getPackage(), "java.sql.Driver", "META-INF/services/java.sql.Driver"); File tempFile = new File(System.getProperty("java.io.tmpdir"), "foodriver.jar"); new ZipExporterImpl(jar).exportTo(tempFile, true); return tempFile; } private void testAddDataSource(String driverName) throws Exception { // add data source cli.sendLine("data-source add --profile=" + profileNames[0] + " --jndi-name=java:jboss/datasources/TestDS_" + driverName +" --name=java:jboss/datasources/TestDS_" + driverName + " --driver-name=" + driverName + " --connection-url=jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); // check the data source is listed cli.sendLine("cd /profile=" + profileNames[0] + "/subsystem=datasources/data-source"); cli.sendLine("ls"); String ls = cli.readOutput(); assertTrue("Datasource not found: " + ls, ls.contains("java:jboss/datasources/TestDS_" + driverName)); // check that it is available through JNDI // TODO implement when @ArquillianResource InitialContext is done } private void testRemoveDataSource(String driverName) throws Exception { // remove data source cli.sendLine("data-source remove --profile=" + profileNames[0] + " --name=java:jboss/datasources/TestDS_" + driverName); //check the data source is not listed cli.sendLine("cd /profile=" + profileNames[0] + "/subsystem=datasources/data-source"); cli.sendLine("ls"); String ls = cli.readOutput(); assertFalse(ls.contains("java:jboss/datasources/TestDS_" + driverName)); } private void testModifyDataSource(String jndiName) throws Exception { StringBuilder cmd = new StringBuilder("data-source --profile=" + profileNames[0] + " --name=java:jboss/datasources/TestDS_" + jndiName); for (String[] props : DS_PROPS) { cmd.append(" --"); cmd.append(props[0]); cmd.append("="); cmd.append(props[1]); } cli.sendLine(cmd.toString()); // check that datasource was modified cli.sendLine("/profile=" + profileNames[0] + "/subsystem=datasources/data-source=java\\:jboss\\/datasources\\/TestDS_" + jndiName + ":read-resource(recursive=true)"); CLIOpResult result = cli.readAllAsOpResult(); assertTrue(result.isIsOutcomeSuccess()); assertTrue(result.getResult() instanceof Map); Map dsProps = (Map) result.getResult(); for (String[] props : DS_PROPS) assertTrue(dsProps.get(props[0]).equals(props[1])); } private void testAddXaDataSource() throws Exception { // add data source cli.sendLine("xa-data-source add --profile=" + profileNames[0] + " --jndi-name=java:jboss/datasources/TestXADS --name=java:jboss/datasources/TestXADS --driver-name=h2 --xa-datasource-properties=ServerName=localhost,PortNumber=50011"); //check the data source is listed cli.sendLine("cd /profile=" + profileNames[0] + "/subsystem=datasources/xa-data-source"); cli.sendLine("ls"); String ls = cli.readOutput(); assertTrue(ls.contains("java:jboss/datasources/TestXADS")); } private void testModifyXaDataSource() throws Exception { StringBuilder cmd = new StringBuilder("xa-data-source --profile=" + profileNames[0] + " --name=java:jboss/datasources/TestXADS"); for (String[] props : DS_PROPS) { cmd.append(" --"); cmd.append(props[0]); cmd.append("="); cmd.append(props[1]); } cli.sendLine(cmd.toString()); // check that datasource was modified cli.sendLine("/profile=" + profileNames[0] + "/subsystem=datasources/xa-data-source=java\\:jboss\\/datasources\\/TestXADS:read-resource(recursive=true)"); CLIOpResult result = cli.readAllAsOpResult(); assertTrue(result.isIsOutcomeSuccess()); assertTrue(result.getResult() instanceof Map); Map dsProps = (Map) result.getResult(); for (String[] props : DS_PROPS) assertTrue(dsProps.get(props[0]).equals(props[1])); } private void testRemoveXaDataSource() throws Exception { // remove data source cli.sendLine("xa-data-source remove --profile=" + profileNames[0] + " --name=java:jboss/datasources/TestXADS"); //check the data source is not listed cli.sendLine("cd /profile=" + profileNames[0] + "/subsystem=datasources/xa-data-source"); cli.sendLine("ls"); String ls = cli.readOutput(); Assert.assertNull(ls); } }
8,164
39.221675
298
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/management/cli/DeploySingleServerGroupTestCase.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.test.integration.domain.management.cli; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Map; import java.util.concurrent.TimeUnit; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.integration.domain.suites.CLITestSuite; import org.jboss.as.test.integration.management.base.AbstractCliTestBase; import org.jboss.as.test.integration.management.util.SimpleServlet; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.impl.base.exporter.zip.ZipExporterImpl; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** * * @author Dominik Pospisil <[email protected]> */ public class DeploySingleServerGroupTestCase extends AbstractCliTestBase { private static File warFile; private static String[] serverGroups; @BeforeClass public static void before() throws Exception { CLITestSuite.createSupport(DeploySingleServerGroupTestCase.class.getSimpleName()); WebArchive war = ShrinkWrap.create(WebArchive.class, "SimpleServlet.war"); war.addClass(SimpleServlet.class); war.addAsWebResource(new StringAsset("Version1"), "page.html"); String tempDir = System.getProperty("java.io.tmpdir"); warFile = new File(tempDir + File.separator + "SimpleServlet.war"); new ZipExporterImpl(war).exportTo(warFile, true); serverGroups = CLITestSuite.serverGroups.keySet().toArray(new String[CLITestSuite.serverGroups.size()]); AbstractCliTestBase.initCLI(DomainTestSupport.primaryAddress); } @AfterClass public static void after() throws Exception { AbstractCliTestBase.closeCLI(); if (warFile != null && warFile.exists()) { Assert.assertTrue(warFile.delete()); } CLITestSuite.stopSupport(); } @Test public void testDeployRedeployUndeploy() throws Exception { testDeploy(); testRedeploy(); testUndeploy(); } @Test public void testContentObjectDeploy() throws Exception { testWFLY3184(); testUndeploy(); } public void testDeploy() throws Exception { // deploy to group servers cli.sendLine("deploy --server-groups=" + serverGroups[0] + " " + warFile.getAbsolutePath()); // check that the deployment is available on all servers within the group and none outside checkURL("/SimpleServlet/SimpleServlet", "SimpleServlet", serverGroups[0]); checkURL("/SimpleServlet/SimpleServlet", "SimpleServlet", serverGroups[1], true); } public void testRedeploy() throws Exception { // check we have original deployment checkURL("/SimpleServlet/page.html", "Version1", serverGroups[0]); // update the deployment - replace page.html WebArchive war = ShrinkWrap.create(WebArchive.class, "SimpleServlet.war"); war.addClass(SimpleServlet.class); war.addAsWebResource(new StringAsset("Version2"), "page.html"); new ZipExporterImpl(war).exportTo(warFile, true); // redeploy to group servers assertFalse(cli.sendLine("deploy --server-groups=" + serverGroups[0] + " " + warFile.getAbsolutePath(), true)); // force redeploy cli.sendLine("deploy " + warFile.getAbsolutePath() + " --force"); // check that new version is running checkURL("/SimpleServlet/page.html", "Version2", serverGroups[0]); } public void testUndeploy() throws Exception { //undeploy cli.sendLine("undeploy --server-groups=" + serverGroups[0] + " SimpleServlet.war"); // check undeployment checkURL("/SimpleServlet/SimpleServlet" , "SimpleServlet", serverGroups[0], true); } private void testWFLY3184() throws Exception { // deploy to server cli.sendLine("/deployment="+ warFile.getName() +":add(content={url=" + warFile.toURI().toURL().toExternalForm() + "})"); cli.sendLine("/server-group=" + serverGroups[0] + "/deployment="+ warFile.getName() +":add(enabled=true)"); // check that the deployment is available on all servers within the group and none outside checkURL("/SimpleServlet/SimpleServlet", "SimpleServlet", serverGroups[0]); checkURL("/SimpleServlet/SimpleServlet", "SimpleServlet", serverGroups[1], true); } private void checkURL(String path, String content, String serverGroup) throws Exception { checkURL(path, content, serverGroup, false); } private void checkURL(String path, String content, String serverGroup, boolean shouldFail) throws Exception { ArrayList<String> groupServers = new ArrayList<String>(); Collections.addAll(groupServers, CLITestSuite.serverGroups.get(serverGroup)); for (Map.Entry<String, String> entry : CLITestSuite.hostAddresses.entrySet()) { String address = entry.getValue(); for (String server : CLITestSuite.hostServers.get(entry.getKey())) { if (! groupServers.contains(server)) continue; // server not in the group if (! CLITestSuite.serverStatus.get(server)) continue; // server not started Integer portOffset = CLITestSuite.portOffsets.get(server); URL url = new URL("http", address, 8080 + portOffset, path); boolean failed = false; try { String response = HttpRequest.get(url.toString(), 10, TimeUnit.SECONDS); assertTrue(response.contains(content)); } catch (Exception e) { failed = true; if (!shouldFail) throw new Exception("Http request failed.", e); } if (shouldFail) assertTrue(failed); } } } }
7,183
38.911111
128
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/management/cli/DomainDeploymentOverlayTestCase.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.test.integration.domain.management.cli; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_RUNTIME; 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_RESOURCE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING_GROUP; import static org.jboss.as.test.integration.domain.management.util.DomainTestSupport.validateResponse; import static org.junit.Assert.assertEquals; import java.io.File; import java.net.InetAddress; import java.net.URL; import java.util.concurrent.TimeUnit; import org.jboss.as.cli.CommandContext; import org.jboss.as.controller.client.helpers.domain.DomainClient; import org.jboss.as.network.NetworkUtils; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.integration.domain.suites.CLITestSuite; import org.jboss.as.test.integration.management.util.CLITestUtil; import org.jboss.as.test.integration.management.util.SimpleServlet; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.impl.base.exporter.zip.ZipExporterImpl; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * @author Alexey Loubyansky */ public class DomainDeploymentOverlayTestCase { private static final String SOCKET_BINDING_GROUP_NAME = "standard-sockets"; private static File war1; private static File war2; private static File war3; private static File webXml; private static File overrideXml; private static DomainTestSupport testSupport; private CommandContext ctx; private DomainClient client; @BeforeClass public static void before() throws Exception { String tempDir = System.getProperty("java.io.tmpdir"); WebArchive war; // deployment1 war = ShrinkWrap.create(WebArchive.class, "deployment0.war"); war.addClass(SimpleServlet.class); war.addAsWebInfResource("cli/deployment-overlay/web.xml", "web.xml"); war1 = new File(tempDir + File.separator + war.getName()); new ZipExporterImpl(war).exportTo(war1, true); war = ShrinkWrap.create(WebArchive.class, "deployment1.war"); war.addClass(SimpleServlet.class); war.addAsWebInfResource("cli/deployment-overlay/web.xml", "web.xml"); war2 = new File(tempDir + File.separator + war.getName()); new ZipExporterImpl(war).exportTo(war2, true); war = ShrinkWrap.create(WebArchive.class, "another.war"); war.addClass(SimpleServlet.class); war.addAsWebInfResource("cli/deployment-overlay/web.xml", "web.xml"); war3 = new File(tempDir + File.separator + war.getName()); new ZipExporterImpl(war).exportTo(war3, true); final URL overrideXmlUrl = DomainDeploymentOverlayTestCase.class.getClassLoader().getResource("cli/deployment-overlay/override.xml"); if(overrideXmlUrl == null) { Assert.fail("Failed to locate cli/deployment-overlay/override.xml"); } overrideXml = new File(overrideXmlUrl.toURI()); if(!overrideXml.exists()) { Assert.fail("Failed to locate cli/deployment-overlay/override.xml"); } final URL webXmlUrl = DomainDeploymentOverlayTestCase.class.getClassLoader().getResource("cli/deployment-overlay/web.xml"); if(webXmlUrl == null) { Assert.fail("Failed to locate cli/deployment-overlay/web.xml"); } webXml = new File(webXmlUrl.toURI()); if(!webXml.exists()) { Assert.fail("Failed to locate cli/deployment-overlay/web.xml"); } // Launch the domain testSupport = CLITestSuite.createSupport(DomainDeploymentOverlayTestCase.class.getSimpleName()); } @AfterClass public static void after() throws Exception { try { CLITestSuite.stopSupport(); testSupport = null; } finally { war1.delete(); war2.delete(); war3.delete(); } } @Before public void setUp() throws Exception { client = testSupport.getDomainPrimaryLifecycleUtil().createDomainClient(); ctx = CLITestUtil.getCommandContext(testSupport); ctx.connectController(); } @After public void tearDown() throws Exception { if(ctx != null) { ctx.handleSafe("undeploy --all-relevant-server-groups " + war1.getName()); ctx.handleSafe("undeploy --all-relevant-server-groups " + war2.getName()); ctx.handleSafe("undeploy --all-relevant-server-groups " + war3.getName()); ctx.handleSafe("deployment-overlay remove --name=overlay-test"); ctx.terminateSession(); ctx = null; } client.close(); client = null; } @Test public void testSimpleOverride() throws Exception { ctx.handle("deploy --server-groups=main-server-group,other-server-group " + war1.getAbsolutePath()); ctx.handle("deploy --server-groups=main-server-group,other-server-group " + war2.getAbsolutePath()); ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + " --deployments=" + war1.getName() + " --server-groups=main-server-group,other-server-group"); assertEquals("NON OVERRIDDEN", performHttpCall("primary", "main-one", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("primary", "main-one", "deployment1")); // assertEquals("NON OVERRIDDEN", performHttpCall("primary", "other-one", "deployment0")); // assertEquals("NON OVERRIDDEN", performHttpCall("primary", "other-one", "deployment1")); assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment1")); // assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "other-two", "deployment0")); // assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "other-two", "deployment1")); ctx.handle("deployment-overlay redeploy-affected --name=overlay-test"); assertEquals("OVERRIDDEN", performHttpCall("primary", "main-one", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("primary", "main-one", "deployment1")); // assertEquals("OVERRIDDEN", performHttpCall("primary", "other-one", "deployment0")); // assertEquals("NON OVERRIDDEN", performHttpCall("primary", "other-one", "deployment1")); assertEquals("OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment1")); // assertEquals("OVERRIDDEN", performHttpCall("secondary", "other-two", "deployment0")); // assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "other-two", "deployment1")); } @Test public void testSimpleOverrideWithRedeployAffected() throws Exception { ctx.handle("deploy --server-groups=main-server-group " + war1.getAbsolutePath()); ctx.handle("deploy --server-groups=main-server-group " + war2.getAbsolutePath()); ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + " --deployments=" + war1.getName() + " --server-groups=main-server-group --redeploy-affected"); assertEquals("OVERRIDDEN", performHttpCall("primary", "main-one", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("primary", "main-one", "deployment1")); assertEquals("OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment1")); } @Test public void testWildcardOverride() throws Exception { ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + " --deployments=deployment*.war --server-groups=main-server-group --redeploy-affected"); ctx.handle("deploy --server-groups=main-server-group " + war1.getAbsolutePath()); ctx.handle("deploy --server-groups=main-server-group " + war2.getAbsolutePath()); ctx.handle("deploy --server-groups=main-server-group " + war3.getAbsolutePath()); assertEquals("OVERRIDDEN", performHttpCall("primary", "main-one", "deployment0")); assertEquals("OVERRIDDEN", performHttpCall("primary", "main-one", "deployment1")); assertEquals("NON OVERRIDDEN", performHttpCall("primary", "main-one", "another")); assertEquals("OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment0")); assertEquals("OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment1")); assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "main-three", "another")); } @Test public void testWildcardOverrideWithRedeployAffected() throws Exception { ctx.handle("deploy --server-groups=main-server-group " + war1.getAbsolutePath()); ctx.handle("deploy --server-groups=main-server-group " + war2.getAbsolutePath()); ctx.handle("deploy --server-groups=main-server-group " + war3.getAbsolutePath()); ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + " --deployments=deployment*.war --server-groups=main-server-group --redeploy-affected"); assertEquals("OVERRIDDEN", performHttpCall("primary", "main-one", "deployment0")); assertEquals("OVERRIDDEN", performHttpCall("primary", "main-one", "deployment1")); assertEquals("NON OVERRIDDEN", performHttpCall("primary", "main-one", "another")); assertEquals("OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment0")); assertEquals("OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment1")); assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "main-three", "another")); } @Test public void testMultipleLinks() throws Exception { ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + " --deployments=" + war1.getName() + " --server-groups=main-server-group"); ctx.handle("deploy --server-groups=main-server-group " + war1.getAbsolutePath()); ctx.handle("deploy --server-groups=main-server-group " + war2.getAbsolutePath()); ctx.handle("deploy --server-groups=main-server-group " + war3.getAbsolutePath()); assertEquals("OVERRIDDEN", performHttpCall("primary", "main-one", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("primary", "main-one", "deployment1")); assertEquals("NON OVERRIDDEN", performHttpCall("primary", "main-one", "another")); assertEquals("OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment1")); assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "main-three", "another")); ctx.handle("deployment-overlay link --name=overlay-test --deployments=a*.war --server-groups=main-server-group"); assertEquals("OVERRIDDEN", performHttpCall("primary", "main-one", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("primary", "main-one", "deployment1")); assertEquals("NON OVERRIDDEN", performHttpCall("primary", "main-one", "another")); assertEquals("OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment1")); assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "main-three", "another")); ctx.handle("/server-group=main-server-group/deployment=" + war1.getName() + ":redeploy"); ctx.handle("/server-group=main-server-group/deployment=" + war2.getName() + ":redeploy"); ctx.handle("/server-group=main-server-group/deployment=" + war3.getName() + ":redeploy"); assertEquals("OVERRIDDEN", performHttpCall("primary", "main-one", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("primary", "main-one", "deployment1")); assertEquals("OVERRIDDEN", performHttpCall("primary", "main-one", "another")); assertEquals("OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment1")); assertEquals("OVERRIDDEN", performHttpCall("secondary", "main-three", "another")); ctx.handle("deployment-overlay link --name=overlay-test --deployments=" + war2.getName() + " --redeploy-affected --server-groups=main-server-group"); assertEquals("OVERRIDDEN", performHttpCall("primary", "main-one", "deployment0")); assertEquals("OVERRIDDEN", performHttpCall("primary", "main-one", "deployment1")); assertEquals("OVERRIDDEN", performHttpCall("primary", "main-one", "another")); assertEquals("OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment0")); assertEquals("OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment1")); assertEquals("OVERRIDDEN", performHttpCall("secondary", "main-three", "another")); ctx.handle("deployment-overlay remove --name=overlay-test --deployments=" + war2.getName() + " --redeploy-affected --server-groups=main-server-group"); assertEquals("OVERRIDDEN", performHttpCall("primary", "main-one", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("primary", "main-one", "deployment1")); assertEquals("OVERRIDDEN", performHttpCall("primary", "main-one", "another")); assertEquals("OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment1")); assertEquals("OVERRIDDEN", performHttpCall("secondary", "main-three", "another")); ctx.handle("deployment-overlay remove --name=overlay-test --deployments=a*.war --server-groups=main-server-group"); assertEquals("OVERRIDDEN", performHttpCall("primary", "main-one", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("primary", "main-one", "deployment1")); assertEquals("OVERRIDDEN", performHttpCall("primary", "main-one", "another")); assertEquals("OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment1")); assertEquals("OVERRIDDEN", performHttpCall("secondary", "main-three", "another")); ctx.handle("/server-group=main-server-group/deployment=" + war1.getName() + ":redeploy"); ctx.handle("/server-group=main-server-group/deployment=" + war2.getName() + ":redeploy"); ctx.handle("/server-group=main-server-group/deployment=" + war3.getName() + ":redeploy"); ctx.handle("deployment-overlay remove --name=overlay-test --content=WEB-INF/web.xml --redeploy-affected"); assertEquals("NON OVERRIDDEN", performHttpCall("primary", "main-one", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("primary", "main-one", "deployment1")); assertEquals("NON OVERRIDDEN", performHttpCall("primary", "main-one", "another")); assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment1")); assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "main-three", "another")); ctx.handle("deployment-overlay upload --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + " --redeploy-affected"); assertEquals("OVERRIDDEN", performHttpCall("primary", "main-one", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("primary", "main-one", "deployment1")); assertEquals("NON OVERRIDDEN", performHttpCall("primary", "main-one", "another")); assertEquals("OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment1")); assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "main-three", "another")); } @Test public void testRedeployAffected() throws Exception { ctx.handle("deploy --server-groups=main-server-group " + war1.getAbsolutePath()); ctx.handle("deploy --server-groups=main-server-group " + war2.getAbsolutePath()); ctx.handle("deploy --server-groups=main-server-group " + war3.getAbsolutePath()); ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath()); ctx.handle("deployment-overlay link --name=overlay-test --deployments=deployment0.war,a*.war --server-groups=main-server-group"); assertEquals("NON OVERRIDDEN", performHttpCall("primary", "main-one", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("primary", "main-one", "deployment1")); assertEquals("NON OVERRIDDEN", performHttpCall("primary", "main-one", "another")); assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment1")); assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "main-three", "another")); ctx.handle("deployment-overlay redeploy-affected --name=overlay-test"); assertEquals("OVERRIDDEN", performHttpCall("primary", "main-one", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("primary", "main-one", "deployment1")); assertEquals("OVERRIDDEN", performHttpCall("primary", "main-one", "another")); assertEquals("OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment0")); assertEquals("NON OVERRIDDEN", performHttpCall("secondary", "main-three", "deployment1")); assertEquals("OVERRIDDEN", performHttpCall("secondary", "main-three", "another")); } private String performHttpCall(String host, String server, String deployment) throws Exception { ModelNode op = new ModelNode(); op.get(OP).set(READ_RESOURCE_OPERATION); op.get(OP_ADDR).add(HOST, host).add(SERVER, server).add(SOCKET_BINDING_GROUP, SOCKET_BINDING_GROUP_NAME).add(SOCKET_BINDING, "http"); op.get(INCLUDE_RUNTIME).set(true); ModelNode socketBinding = validateResponse(client.execute(op)); URL url = new URL("http", NetworkUtils.formatAddress(InetAddress.getByName(socketBinding.get("bound-address").asString())), socketBinding.get("bound-port").asInt(), "/" + deployment + "/SimpleServlet?env-entry=overlay-test"); return HttpRequest.get(url.toExternalForm(), 10, TimeUnit.SECONDS).trim(); } }
21,012
56.100543
159
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/management/cli/JmsTestCase.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.test.integration.domain.management.cli; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.integration.domain.suites.CLITestSuite; import org.jboss.as.test.integration.management.base.AbstractCliTestBase; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * * @author Dominik Pospisil <[email protected]> */ public class JmsTestCase extends AbstractCliTestBase { private static String profileName; @BeforeClass public static void before() throws Exception { CLITestSuite.createSupport(JmsTestCase.class.getSimpleName()); AbstractCliTestBase.initCLI(DomainTestSupport.primaryAddress); } @AfterClass public static void after() throws Exception { AbstractCliTestBase.closeCLI(); CLITestSuite.stopSupport(); } @Before public void init() { profileName = CLITestSuite.serverProfiles.keySet().iterator().next(); } @Test public void testAddRemoveJmsQueue() throws Exception { testAddJmsQueue(); testRemoveJmsQueue(); } @Test public void testAddRemoveJmsTopic() throws Exception { testAddJmsTopic(); testRemoveJmsTopic(); } private void testAddJmsQueue() throws Exception { // check the queue is not registered cli.sendLine("cd /profile=" + profileName + "/subsystem=messaging-activemq/server=default/jms-queue"); cli.sendLine("ls"); String ls = cli.readOutput(); assertFalse(ls.contains("testJmsQueue")); // create queue cli.sendLine("jms-queue add --profile=" + profileName + " --queue-address=testJmsQueue --entries=testJmsQueue"); // check it is listed cli.sendLine("cd /profile=" + profileName + "/subsystem=messaging-activemq/server=default/jms-queue"); cli.sendLine("ls"); ls = cli.readOutput(); assertTrue(ls.contains("testJmsQueue")); } private void testRemoveJmsQueue() throws Exception { // create queue cli.sendLine("jms-queue remove --profile=" + profileName + " --queue-address=testJmsQueue"); // check it is listed cli.sendLine("cd /profile=" + profileName + "/subsystem=messaging-activemq/server=default/jms-queue"); cli.sendLine("ls"); String ls = cli.readOutput(); assertFalse(ls.contains("testJmsQueue")); } private void testAddJmsTopic() throws Exception { // check the queue is not registered cli.sendLine("cd /profile=" + profileName + "/subsystem=messaging-activemq/server=default/jms-topic"); cli.sendLine("ls"); String ls = cli.readOutput(); assertFalse(ls.contains("testJmsTopic")); // create topic cli.sendLine("jms-topic add --profile=" + profileName + " --topic-address=testJmsTopic --entries=testJmsTopic"); // check it is listed cli.sendLine("cd /profile=" + profileName + "/subsystem=messaging-activemq/server=default/jms-topic"); cli.sendLine("ls"); ls = cli.readOutput(); assertTrue(ls.contains("testJmsTopic")); } private void testRemoveJmsTopic() throws Exception { // create queue cli.sendLine("jms-topic remove --profile=" + profileName + " --topic-address=testJmsTopic"); // check it is listed cli.sendLine("cd /profile=" + profileName + "/subsystem=messaging-activemq/server=default/jms-topic"); cli.sendLine("ls"); String ls = cli.readOutput(); assertFalse(ls.contains("testJmsTopic")); } }
4,768
34.857143
120
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/management/cli/RolloutPlanTestCase.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.test.integration.domain.management.cli; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import java.io.File; import java.net.SocketPermission; import java.net.URL; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.integration.domain.management.util.RolloutPlanBuilder; import org.jboss.as.test.integration.domain.suites.CLITestSuite; import org.jboss.as.test.integration.management.base.AbstractCliTestBase; import org.jboss.as.test.integration.management.util.CLIOpResult; import org.jboss.as.test.shared.RetryTaskExecutor; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.impl.base.exporter.zip.ZipExporterImpl; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** * * @author Dominik Pospisil <[email protected]> */ public class RolloutPlanTestCase extends AbstractCliTestBase { private static File warFile; private static final int TEST_PORT = 8081; private static final String[] serverGroups = new String[] {"main-server-group", "other-server-group", "test-server-group"}; @BeforeClass public static void before() throws Exception { CLITestSuite.createSupport(RolloutPlanTestCase.class.getSimpleName()); final WebArchive war = ShrinkWrap.create(WebArchive.class, "RolloutPlanTestCase.war"); war.addClass(RolloutPlanTestServlet.class); war.addAsManifestResource(createPermissionsXmlAsset( new SocketPermission(TestSuiteEnvironment.formatPossibleIpv6Address(CLITestSuite.hostAddresses.get("primary")) + ":" + TEST_PORT, "listen,resolve"), // main-one new SocketPermission(TestSuiteEnvironment.formatPossibleIpv6Address(CLITestSuite.hostAddresses.get("primary")) + ":" + (TEST_PORT + 350), "listen,resolve")), // main-three "permissions.xml"); String tempDir = System.getProperty("java.io.tmpdir"); warFile = new File(tempDir + File.separator + "RolloutPlanTestCase.war"); new ZipExporterImpl(war).exportTo(warFile, true); AbstractCliTestBase.initCLI(DomainTestSupport.primaryAddress); // add another server group to default profile cli.sendLine("/server-group=test-server-group:add(profile=default,socket-binding-group=standard-sockets)"); cli.sendLine("/server-group=test-server-group/jvm=default:add"); // add a server to the group cli.sendLine("/host=primary/server-config=test-one:add(group=test-server-group,socket-binding-port-offset=700"); cli.sendLine("/host=primary/server-config=test-one/interface=public:add(inet-address=" + CLITestSuite.hostAddresses.get("primary") + ")"); CLITestSuite.addServer("test-one", "primary", "test-server-group","default", 700, true); // start main-two cli.sendLine("/host=primary/server-config=main-two:start(blocking=true)"); CLIOpResult res = cli.readAllAsOpResult(); Assert.assertTrue(res.isIsOutcomeSuccess()); waitUntilState("main-two", "STARTED"); // start test-one cli.sendLine("/host=primary/server-config=test-one:start(blocking=true)"); res = cli.readAllAsOpResult(); Assert.assertTrue(res.isIsOutcomeSuccess()); waitUntilState("test-one", "STARTED"); } @AfterClass public static void after() throws Exception { if (warFile.exists()){ //noinspection ResultOfMethodCallIgnored warFile.delete(); } // stop test-one cli.sendLine("/host=primary/server-config=test-one:stop(blocking=true)"); CLIOpResult res = cli.readAllAsOpResult(); Assert.assertTrue(res.isIsOutcomeSuccess()); waitUntilState("test-one", "STOPPED"); // stop main-two cli.sendLine("/host=primary/server-config=main-two:stop(blocking=true)"); res = cli.readAllAsOpResult(); Assert.assertTrue(res.isIsOutcomeSuccess()); waitUntilState("main-two", "DISABLED"); AbstractCliTestBase.closeCLI(); CLITestSuite.stopSupport(); } @After public void afterTest() throws Exception { // undeploy helper servlets cli.sendLine("undeploy RolloutPlanTestCase.war --all-relevant-server-groups", true); // remove socket binding cli.sendLine("/socket-binding-group=standard-sockets/socket-binding=test-binding:remove(){allow-resource-service-restart=true}", true); } @Test public void testInSeriesRolloutPlan() throws Exception { // create rollout plans // 1st plan RolloutPlanBuilder planBuilder = new RolloutPlanBuilder(); planBuilder.addGroup(serverGroups[0], new RolloutPlanBuilder.RolloutPolicy(true, null, null)); planBuilder.addGroup(serverGroups[1], new RolloutPlanBuilder.RolloutPolicy(true, null, null)); planBuilder.addGroup(serverGroups[2], new RolloutPlanBuilder.RolloutPolicy(true, null, null)); String rolloutPlan = planBuilder.buildAsString(); cli.sendLine("rollout-plan add --name=testPlan --content=" + rolloutPlan); // 2nd with reversed order planBuilder = new RolloutPlanBuilder(); planBuilder.addGroup(serverGroups[2], new RolloutPlanBuilder.RolloutPolicy(true, null, null)); planBuilder.addGroup(serverGroups[1], new RolloutPlanBuilder.RolloutPolicy(true, null, null)); planBuilder.addGroup(serverGroups[0], new RolloutPlanBuilder.RolloutPolicy(true, null, null)); rolloutPlan = planBuilder.buildAsString(); cli.sendLine("rollout-plan add --name=testPlan2 --content=" + rolloutPlan); // check they are listed cli.sendLine("cd /management-client-content=rollout-plans/rollout-plan"); cli.sendLine("ls"); String ls = cli.readOutput(); Assert.assertTrue(ls.contains("testPlan")); Assert.assertTrue(ls.contains("testPlan2")); // deploy using 1st prepared rollout plan cli.sendLine("deploy " + warFile.getAbsolutePath() + " --all-server-groups --headers={rollout id=testPlan}"); // check that the apps were deployed in correct order // get application deployment times from servers long mainOneTime = Long.valueOf(checkURL("main-one", false)); long mainTwoTime = Long.valueOf(checkURL("main-two", false)); long mainThreeTime = Long.valueOf(checkURL("main-three", false)); long otherTwoTime = Long.valueOf(checkURL("other-two", false)); long testOneTime = Long.valueOf(checkURL("test-one", false)); Assert.assertTrue(mainOneTime < otherTwoTime); Assert.assertTrue(mainTwoTime < otherTwoTime); Assert.assertTrue(mainThreeTime < otherTwoTime); Assert.assertTrue(otherTwoTime < testOneTime); // undeploy apps cli.sendLine("undeploy RolloutPlanTestCase.war --all-relevant-server-groups"); // deploy using 2nd plan cli.sendLine("deploy " + warFile.getAbsolutePath() + " --all-server-groups --headers={rollout id=testPlan2}"); // check that the apps were deployed in reversed order mainOneTime = Long.valueOf(checkURL("main-one", false)); mainTwoTime = Long.valueOf(checkURL("main-two", false)); mainThreeTime = Long.valueOf(checkURL("main-three", false)); otherTwoTime = Long.valueOf(checkURL("other-two", false)); testOneTime = Long.valueOf(checkURL("test-one", false)); Assert.assertTrue(mainOneTime > otherTwoTime); Assert.assertTrue(mainTwoTime > otherTwoTime); Assert.assertTrue(mainThreeTime > otherTwoTime); Assert.assertTrue(otherTwoTime > testOneTime); // remove rollout plans cli.sendLine("rollout-plan remove --name=testPlan"); cli.sendLine("rollout-plan remove --name=testPlan2"); // check plans are no more listed cli.sendLine("cd /management-client-content=rollout-plans"); cli.sendLine("ls"); ls = cli.readOutput(); Assert.assertFalse(ls.contains("testPlan")); Assert.assertFalse(ls.contains("testPlan2")); } /** * Tests rollout plan with non-zero maxFailedServers attribute. */ @Test public void testMaxFailServersRolloutPlan() throws Exception { // deploy helper servlets cli.sendLine("deploy " + warFile.getAbsolutePath() + " --all-server-groups"); checkURL("main-one", false, "/RolloutPlanTestCase/RolloutServlet"); checkURL("main-two", false, "/RolloutPlanTestCase/RolloutServlet"); checkURL("main-three", false, "/RolloutPlanTestCase/RolloutServlet"); checkURL("test-one", false, "/RolloutPlanTestCase/RolloutServlet"); // prepare socket binding cli.sendLine("/socket-binding-group=standard-sockets/socket-binding=test-binding:add(interface=public,port=" + TEST_PORT + ")"); // create plan with max fail server set to 1 RolloutPlanBuilder planBuilder = new RolloutPlanBuilder(); planBuilder.addGroup(serverGroups[0], new RolloutPlanBuilder.RolloutPolicy(true, null, 1)); planBuilder.addGroup(serverGroups[1], new RolloutPlanBuilder.RolloutPolicy(true, null, 1)); planBuilder.addGroup(serverGroups[2], new RolloutPlanBuilder.RolloutPolicy(true, null, 1)); String rolloutPlan = planBuilder.buildAsString(); cli.sendLine("rollout-plan add --name=maxFailOnePlan --content=" + rolloutPlan); // 1st scenario - main-one should fail, but the whole operation should succeed // let the helper server bind to test port to prevent successful subsequent add connector operation on main-one checkURL("main-one", false, "/RolloutPlanTestCase/RolloutServlet?operation=bind&bindPort=" + TEST_PORT); CLIOpResult ret = testAddConnector("maxFailOnePlan"); Assert.assertTrue(ret.isIsOutcomeSuccess()); Assert.assertFalse(getServerStatus("main-one", ret)); Assert.assertTrue(getServerStatus("main-two", ret)); Assert.assertTrue(getServerStatus("main-three", ret)); Assert.assertTrue(getServerStatus("test-one", ret)); ret = testRemoveConnector("maxFailOnePlan"); Assert.assertTrue(ret.isIsOutcomeSuccess()); Assert.assertFalse(getServerStatus("main-one", ret)); Assert.assertTrue(getServerStatus("main-two", ret)); Assert.assertTrue(getServerStatus("main-three", ret)); Assert.assertTrue(getServerStatus("test-one", ret)); // 2nd scenario - main-one and main-three failures -> main-two should be rolled back but the operation succeed checkURL("main-three", false, "/RolloutPlanTestCase/RolloutServlet?operation=bind&bindPort=" + String.valueOf(TEST_PORT + CLITestSuite.portOffsets.get("main-three"))); ret = testAddConnector("maxFailOnePlan"); Assert.assertTrue(ret.isIsOutcomeSuccess()); Assert.assertFalse(getServerStatus("main-one", ret)); Assert.assertFalse(getServerStatus("main-two", ret)); Assert.assertFalse(getServerStatus("main-three", ret)); Assert.assertTrue(getServerStatus("test-one", ret)); testCleanupConnector("maxFailOnePlan"); // remove rollout plan cli.sendLine("rollout-plan remove --name=maxFailOnePlan"); } /** * Tests rollout plan with non-zero maxFailurePercentage attribute. */ @Test public void testMaxFailServersPercentageRolloutPlan() throws Exception { // deploy helper servlets cli.sendLine("deploy " + warFile.getAbsolutePath() + " --all-server-groups"); // prepare socket binding cli.sendLine("/socket-binding-group=standard-sockets/socket-binding=test-binding:add(interface=public,port=" + TEST_PORT + ")"); // create plan with max fail server percentage set to 40% RolloutPlanBuilder planBuilder = new RolloutPlanBuilder(); planBuilder.addGroup(serverGroups[0], new RolloutPlanBuilder.RolloutPolicy(true, 40, 0)); planBuilder.addGroup(serverGroups[1], new RolloutPlanBuilder.RolloutPolicy(true, 40, 0)); planBuilder.addGroup(serverGroups[2], new RolloutPlanBuilder.RolloutPolicy(true, 40, 0)); String rolloutPlan = planBuilder.buildAsString(); cli.sendLine("rollout-plan add --name=maxFailPercPlan --content=" + rolloutPlan); // 1st scenario - server-one should fail, but the whole operation should succeed checkURL("main-one", false, "/RolloutPlanTestCase/RolloutServlet?operation=bind&bindPort=" + TEST_PORT); CLIOpResult ret = testAddConnector("maxFailPercPlan"); Assert.assertTrue(ret.isIsOutcomeSuccess()); Assert.assertFalse(getServerStatus("main-one", ret)); Assert.assertTrue(getServerStatus("main-two", ret)); Assert.assertTrue(getServerStatus("main-three", ret)); Assert.assertTrue(getServerStatus("test-one", ret)); ret = testRemoveConnector("maxFailPercPlan"); Assert.assertTrue(ret.isIsOutcomeSuccess()); Assert.assertFalse(getServerStatus("main-one", ret)); Assert.assertTrue(getServerStatus("main-two", ret)); Assert.assertTrue(getServerStatus("main-three", ret)); Assert.assertTrue(getServerStatus("test-one", ret)); // 2nd scenario - main-one and main-three should fail -> main-two should be rolled back but the operation succeed checkURL("main-three", false, "/RolloutPlanTestCase/RolloutServlet?operation=bind&bindPort=" + String.valueOf(TEST_PORT + CLITestSuite.portOffsets.get("main-three"))); ret = testAddConnector("maxFailPercPlan"); Assert.assertTrue(ret.isIsOutcomeSuccess()); Assert.assertFalse(getServerStatus("main-one", ret)); Assert.assertFalse(getServerStatus("main-two", ret)); Assert.assertFalse(getServerStatus("main-three", ret)); Assert.assertTrue(getServerStatus("test-one", ret)); testCleanupConnector("maxFailPercPlan"); // remove rollout plan cli.sendLine("rollout-plan remove --name=maxFailPercPlan"); } /** * Tests rollout plan with RollbackAcrossGroups set to true. */ @Test public void testRollbackAcrossGroupsRolloutPlan() throws Exception { // deploy helper servlets cli.sendLine("deploy " + warFile.getAbsolutePath() + " --all-server-groups"); checkURL("main-one", false, "/RolloutPlanTestCase/RolloutServlet"); checkURL("main-two", false, "/RolloutPlanTestCase/RolloutServlet"); checkURL("main-three", false, "/RolloutPlanTestCase/RolloutServlet"); checkURL("test-one", false, "/RolloutPlanTestCase/RolloutServlet"); // prepare socket binding cli.sendLine("/socket-binding-group=standard-sockets/socket-binding=test-binding:add(interface=public,port=" + TEST_PORT + ")"); // create plan with max fail server set to 1 RolloutPlanBuilder planBuilder = new RolloutPlanBuilder(); planBuilder.addGroup(serverGroups[0], new RolloutPlanBuilder.RolloutPolicy(true, null, 1)); planBuilder.addGroup(serverGroups[1], new RolloutPlanBuilder.RolloutPolicy(true, null, 1)); planBuilder.addGroup(serverGroups[2], new RolloutPlanBuilder.RolloutPolicy(true, null, 1)); planBuilder.setRollBackAcrossGroups(true); String rolloutPlan = planBuilder.buildAsString(); cli.sendLine("rollout-plan add --name=groupsRollbackPlan --content=" + rolloutPlan); // let the main-one ane main-three fail, main two rollback and then test-one rollback // let the helper server bind to test port to prevent successful subsequent add connector operation on main-one checkURL("main-one", false, "/RolloutPlanTestCase/RolloutServlet?operation=bind&bindPort=" + TEST_PORT); checkURL("main-three", false, "/RolloutPlanTestCase/RolloutServlet?operation=bind&bindPort=" + String.valueOf(TEST_PORT + CLITestSuite.portOffsets.get("main-three"))); CLIOpResult ret = testAddConnector("groupsRollbackPlan"); Assert.assertFalse(ret.isIsOutcomeSuccess()); Assert.assertFalse(getServerStatus("main-one", ret)); Assert.assertFalse(getServerStatus("main-two", ret)); Assert.assertFalse(getServerStatus("main-three", ret)); Assert.assertFalse(getServerStatus("test-one", ret)); // remove rollout plan cli.sendLine("rollout-plan remove --name=groupsRollbackPlan"); } private CLIOpResult testAddConnector(String rolloutPlanId) throws Exception { cli.sendLine("/profile=default/subsystem=undertow/server=default-server/http-listener="+rolloutPlanId+":add" + "(socket-binding=test-binding)" + "{rollout id=" + rolloutPlanId + "}", true); return cli.readAllAsOpResult(); } private CLIOpResult testRemoveConnector(String rolloutPlanId) throws Exception { cli.sendLine("/profile=default/subsystem=undertow/server=default-server/http-listener="+rolloutPlanId+":remove" + "{rollout id=" + rolloutPlanId + "; allow-resource-service-restart=true}"); return cli.readAllAsOpResult(); } private void testCleanupConnector(String rolloutPlanId) throws Exception { CLIOpResult ret = testRemoveConnector(rolloutPlanId); Assert.assertTrue(ret.isIsOutcomeSuccess()); Assert.assertTrue(getServerStatus("test-one", ret)); boolean gotNoResponse = false; for (String server : new String[]{"main-one", "main-two", "main-three"}) { try { Assert.assertFalse(getServerStatus(server, ret)); } catch (NoResponseException e) { if (gotNoResponse) { throw e; } gotNoResponse = true; } } Assert.assertTrue("received no response from one server", gotNoResponse); } private boolean getServerStatus(String serverName, CLIOpResult result) throws Exception { Map groups = (Map) result.getServerGroups(); for (Object group : groups.values()) { Map hosts = (Map)((Map)group).get("host"); if (hosts != null) { for (Object value : hosts.values()) { Map serverResults = (Map)value; Map serverResult = (Map)serverResults.get(serverName); if (serverResult != null) { Map serverResponse = (Map)serverResult.get("response"); String serverOutcome = (String) serverResponse.get("outcome"); return "success".equals(serverOutcome); } } } } throw new NoResponseException(serverName); } private static String checkURL(String server, boolean shouldFail) throws Exception { return checkURL(server, shouldFail, "/RolloutPlanTestCase/RolloutServlet"); } private static String checkURL(String server, boolean shouldFail, String path) throws Exception { String address = CLITestSuite.hostAddresses.get(getServerHost(server)); Integer portOffset = CLITestSuite.portOffsets.get(server); URL url = new URL("http", address, 8080 + portOffset, path); boolean failed = false; String response = null; try { response = HttpRequest.get(url.toString(), 60, TimeUnit.SECONDS); } catch (Exception e) { failed = true; if (!shouldFail) throw new Exception("Http request failed.", e); } if (shouldFail) Assert.assertTrue(failed); return response; } private static String getServerHost(String server) { for(Entry<String, String[]> hostEntry : CLITestSuite.hostServers.entrySet()) { for (String hostServer : hostEntry.getValue()) if (hostServer.equals(server)) return hostEntry.getKey(); } return null; } private static void waitUntilState(final String serverName, final String state) throws TimeoutException { final String serverHost = CLITestSuite.getServerHost(serverName); RetryTaskExecutor<Void> taskExecutor = new RetryTaskExecutor<Void>(); taskExecutor.retryTask(new Callable<Void>() { public Void call() throws Exception { cli.sendLine("/host=" + serverHost + "/server-config=" + serverName + ":read-attribute(name=status)"); CLIOpResult res = cli.readAllAsOpResult(); if (! res.getResult().equals(state)) throw new Exception("Server not in state."); return null; } }); } private static class NoResponseException extends Exception { private static final long serialVersionUID = 1L; private NoResponseException(String serverName) { super("Status of the server " + serverName + " not found in operation result."); } } }
22,486
46.946695
188
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/driver/FooDriver.java
package org.jboss.as.test.integration.domain.driver; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverPropertyInfo; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.Properties; import java.util.logging.Logger; /** * Created by maeste on 10/1/15. */ public class FooDriver implements Driver { @Override public Connection connect(String url, Properties info) throws SQLException { return null; } @Override public boolean acceptsURL(String url) throws SQLException { return false; } @Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { return new DriverPropertyInfo[0]; } @Override public int getMajorVersion() { return 0; } @Override public int getMinorVersion() { return 0; } @Override public boolean jdbcCompliant() { return false; } @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { return null; } }
1,108
21.18
98
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/suites/GlobalDirectoryLibrary.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.domain.suites; /** * @author Tomas Terem ([email protected]) **/ public interface GlobalDirectoryLibrary { String get(); }
1,193
36.3125
70
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/suites/DeploymentManagementTestCase.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.test.integration.domain.suites; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; 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.ENABLED; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FULL_REPLACE_DEPLOYMENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INPUT_STREAM_INDEX; 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.REMOVE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REPLACE_DEPLOYMENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RUNTIME_NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_GROUP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.TO_REPLACE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.UPLOAD_DEPLOYMENT_STREAM; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.UPLOAD_DEPLOYMENT_URL; import static org.jboss.as.test.integration.domain.management.util.DomainTestSupport.cleanFile; import static org.jboss.as.test.integration.domain.management.util.DomainTestSupport.safeClose; import static org.jboss.as.test.integration.domain.management.util.DomainTestSupport.validateResponse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.net.URL; import java.net.URLConnection; import java.util.Collections; import java.util.List; import org.jboss.as.controller.HashUtil; import org.jboss.as.controller.client.Operation; import org.jboss.as.controller.client.OperationBuilder; import org.jboss.as.test.integration.domain.management.util.DomainLifecycleUtil; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.exporter.ExplodedExporter; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * Test of various management operations involving deployment. * * @author Brian Stansberry (c) 2011 Red Hat Inc. */ public class DeploymentManagementTestCase { private static final String TEST = "test.war"; private static final String TEST2 = "test2.war"; private static final String REPLACEMENT = "test.war.v2"; private static final ModelNode ROOT_ADDRESS = new ModelNode(); private static final ModelNode ROOT_DEPLOYMENT_ADDRESS = new ModelNode(); private static final ModelNode ROOT_REPLACEMENT_ADDRESS = new ModelNode(); private static final ModelNode MAIN_SERVER_GROUP_ADDRESS = new ModelNode(); private static final ModelNode MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS = new ModelNode(); private static final ModelNode OTHER_SERVER_GROUP_ADDRESS = new ModelNode(); private static final ModelNode OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS = new ModelNode(); private static final ModelNode MAIN_RUNNING_SERVER_ADDRESS = new ModelNode(); private static final ModelNode MAIN_RUNNING_SERVER_DEPLOYMENT_ADDRESS = new ModelNode(); private static final ModelNode OTHER_RUNNING_SERVER_ADDRESS = new ModelNode(); private static final ModelNode OTHER_RUNNING_SERVER_GROUP_ADDRESS = new ModelNode(); static { ROOT_ADDRESS.setEmptyList(); ROOT_ADDRESS.protect(); ROOT_DEPLOYMENT_ADDRESS.add(DEPLOYMENT, TEST); ROOT_DEPLOYMENT_ADDRESS.protect(); ROOT_REPLACEMENT_ADDRESS.add(DEPLOYMENT, REPLACEMENT); ROOT_REPLACEMENT_ADDRESS.protect(); MAIN_SERVER_GROUP_ADDRESS.add(SERVER_GROUP, "main-server-group"); MAIN_SERVER_GROUP_ADDRESS.protect(); MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS.add(SERVER_GROUP, "main-server-group"); MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS.add(DEPLOYMENT, TEST); MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS.protect(); OTHER_SERVER_GROUP_ADDRESS.add(SERVER_GROUP, "other-server-group"); OTHER_SERVER_GROUP_ADDRESS.protect(); OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS.add(SERVER_GROUP, "other-server-group"); OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS.add(DEPLOYMENT, TEST); OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS.protect(); MAIN_RUNNING_SERVER_ADDRESS.add(HOST, "primary"); MAIN_RUNNING_SERVER_ADDRESS.add(SERVER, "main-one"); MAIN_RUNNING_SERVER_ADDRESS.protect(); MAIN_RUNNING_SERVER_DEPLOYMENT_ADDRESS.add(HOST, "primary"); MAIN_RUNNING_SERVER_DEPLOYMENT_ADDRESS.add(SERVER, "main-one"); MAIN_RUNNING_SERVER_DEPLOYMENT_ADDRESS.add(DEPLOYMENT, TEST); MAIN_RUNNING_SERVER_DEPLOYMENT_ADDRESS.protect(); OTHER_RUNNING_SERVER_ADDRESS.add(HOST, "secondary"); OTHER_RUNNING_SERVER_ADDRESS.add(SERVER, "other-two"); OTHER_RUNNING_SERVER_ADDRESS.protect(); OTHER_RUNNING_SERVER_GROUP_ADDRESS.add(HOST, "secondary"); OTHER_RUNNING_SERVER_GROUP_ADDRESS.add(SERVER, "other-two"); OTHER_RUNNING_SERVER_GROUP_ADDRESS.add(DEPLOYMENT, TEST); OTHER_RUNNING_SERVER_GROUP_ADDRESS.protect(); } private static DomainTestSupport testSupport; private static WebArchive webArchive; private static WebArchive webArchive2; private static File tmpDir; @BeforeClass public static void setupDomain() throws Exception { // Create our deployments webArchive = ShrinkWrap.create(WebArchive.class, TEST); ClassLoader tccl = Thread.currentThread().getContextClassLoader(); URL index = tccl.getResource("helloWorld/index.html"); webArchive.addAsWebResource(index, "index.html"); webArchive2 = ShrinkWrap.create(WebArchive.class, TEST); index = tccl.getResource("helloWorld/index.html"); webArchive2.addAsWebResource(index, "index.html"); index = tccl.getResource("helloWorld/index2.html"); webArchive2.addAsWebResource(index, "index2.html"); // Make versions on the filesystem for URL-based deploy and for unmanaged content testing tmpDir = new File("target/deployments/" + DeploymentManagementTestCase.class.getSimpleName()); new File(tmpDir, "archives").mkdirs(); new File(tmpDir, "exploded").mkdirs(); webArchive.as(ZipExporter.class).exportTo(new File(tmpDir, "archives/" + TEST), true); webArchive.as(ExplodedExporter.class).exportExploded(new File(tmpDir, "exploded")); // Launch the domain testSupport = DomainTestSuite.createSupport(DeploymentManagementTestCase.class.getSimpleName()); } @AfterClass public static void tearDownDomain() throws Exception { try { testSupport = null; DomainTestSuite.stopSupport(); } finally { cleanFile(tmpDir); } } /** * Validate that there are no deployments; try and clean if there are. * * @throws Exception */ @Before @After public void confirmNoDeployments() throws Exception { List<ModelNode> deploymentList = getDeploymentList(ROOT_ADDRESS); if (deploymentList.size() > 0) { cleanDeployments(); } deploymentList = getDeploymentList(new ModelNode()); assertEquals("Deployments are removed from the domain", 0, deploymentList.size()); try { performHttpCall(DomainTestSupport.primaryAddress, 8080); fail(TEST + " is available on main-one"); } catch (IOException good) { // good } try { performHttpCall(DomainTestSupport.secondaryAddress, 8630); fail(TEST + " is available on other-three"); } catch (IOException good) { // good } } /** * Remove all deployments from the model. * * @throws IOException */ private void cleanDeployments() throws IOException { List<ModelNode> deploymentList = getDeploymentList(MAIN_SERVER_GROUP_ADDRESS); for (ModelNode deployment : deploymentList) { removeDeployment(deployment.asString(), MAIN_SERVER_GROUP_ADDRESS); } deploymentList = getDeploymentList(OTHER_SERVER_GROUP_ADDRESS); for (ModelNode deployment : deploymentList) { removeDeployment(deployment.asString(), OTHER_SERVER_GROUP_ADDRESS); } deploymentList = getDeploymentList(ROOT_ADDRESS); for (ModelNode deployment : deploymentList) { removeDeployment(deployment.asString(), ROOT_ADDRESS); } } @Test public void testDeploymentViaUrl() throws Exception { String url = new File(tmpDir, "archives/" + TEST).toURI().toURL().toString(); ModelNode content = new ModelNode(); content.get("url").set(url); ModelNode composite = createDeploymentOperation(content, MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS, OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS); executeOnPrimary(composite); performHttpCall(DomainTestSupport.primaryAddress, 8080); performHttpCall(DomainTestSupport.secondaryAddress, 8630); } @Test public void testDeploymentViaStream() throws Exception { ModelNode content = new ModelNode(); content.get(INPUT_STREAM_INDEX).set(0); ModelNode composite = createDeploymentOperation(content, MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS, OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS); OperationBuilder builder = new OperationBuilder(composite, true); builder.addInputStream(webArchive.as(ZipExporter.class).exportAsInputStream()); executeOnPrimary(builder.build()); performHttpCall(DomainTestSupport.primaryAddress, 8080); performHttpCall(DomainTestSupport.secondaryAddress, 8630); } @Test public void testUploadURL() throws Exception { String url = new File(tmpDir, "archives/" + TEST).toURI().toURL().toString(); ModelNode op = getEmptyOperation(UPLOAD_DEPLOYMENT_URL, ROOT_ADDRESS); op.get("url").set(url); byte[] hash = executeOnPrimary(op).asBytes(); testDeploymentViaHash(hash); } @Test public void testUploadStream() throws Exception { ModelNode op = getEmptyOperation(UPLOAD_DEPLOYMENT_STREAM, ROOT_ADDRESS); op.get(INPUT_STREAM_INDEX).set(0); OperationBuilder builder = new OperationBuilder(op, true); builder.addInputStream(webArchive.as(ZipExporter.class).exportAsInputStream()); byte[] hash = executeOnPrimary(builder.build()).asBytes(); testDeploymentViaHash(hash); } private void testDeploymentViaHash(byte[] hash) throws Exception { ModelNode content = new ModelNode(); content.get("hash").set(hash); ModelNode composite = createDeploymentOperation(content, MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS, OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS); executeOnPrimary(composite); performHttpCall(DomainTestSupport.primaryAddress, 8080); performHttpCall(DomainTestSupport.secondaryAddress, 8630); } @Test public void testDomainAddOnly() throws Exception { ModelNode op = getEmptyOperation(UPLOAD_DEPLOYMENT_STREAM, ROOT_ADDRESS); op.get(INPUT_STREAM_INDEX).set(0); OperationBuilder builder = new OperationBuilder(op, true); builder.addInputStream(webArchive.as(ZipExporter.class).exportAsInputStream()); byte[] hash = executeOnPrimary(builder.build()).asBytes(); ModelNode content = new ModelNode(); content.get("hash").set(hash); ModelNode composite = createDeploymentOperation(content); executeOnPrimary(composite); } @Test public void testUnmanagedArchiveDeployment() throws Exception { ModelNode content = new ModelNode(); content.get("archive").set(true); content.get("path").set(new File(tmpDir, "archives/" + TEST).getAbsolutePath()); ModelNode composite = createDeploymentOperation(content, MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS, OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS); executeOnPrimary(composite); performHttpCall(DomainTestSupport.primaryAddress, 8080); performHttpCall(DomainTestSupport.secondaryAddress, 8630); } @Test public void testUnmanagedExplodedDeployment() throws Exception { ModelNode content = new ModelNode(); content.get("archive").set(false); content.get("path").set(new File(tmpDir, "exploded/" + TEST).getAbsolutePath()); ModelNode composite = createDeploymentOperation(content, MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS, OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS); executeOnPrimary(composite); performHttpCall(DomainTestSupport.primaryAddress, 8080); performHttpCall(DomainTestSupport.secondaryAddress, 8630); } @Test public void testUndeploy() throws Exception { // Establish the deployment testDeploymentViaStream(); undeployTest(); } @Test public void testUnmanagedArchiveUndeploy() throws Exception { // Establish the deployment testUnmanagedArchiveDeployment(); undeployTest(); } @Test public void testUnmanagedExplodedUndeploy() throws Exception { // Establish the deployment testUnmanagedExplodedDeployment(); undeployTest(); } private void undeployTest() throws Exception { ModelNode op = getEmptyOperation("undeploy", OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS); executeOnPrimary(op); // Thread.sleep(1000); try { performHttpCall(DomainTestSupport.secondaryAddress, 8630); fail("Webapp still accessible following undeploy"); } catch (IOException good) { // desired result } } @Test public void testRedeploy() throws Exception { // Establish the deployment testDeploymentViaStream(); redeployTest(); } @Test public void testUnmanagedArchiveRedeploy() throws Exception { // Establish the deployment testUnmanagedArchiveDeployment(); redeployTest(); } @Test public void testUnmanagedExplodedRedeploy() throws Exception { // Establish the deployment testUnmanagedExplodedDeployment(); redeployTest(); } private void redeployTest() throws IOException { ModelNode op = getEmptyOperation("redeploy", OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS); executeOnPrimary(op); performHttpCall(DomainTestSupport.secondaryAddress, 8630); } @Test public void testReplace() throws Exception { // Establish the deployment testDeploymentViaStream(); ModelNode content = new ModelNode(); content.get(INPUT_STREAM_INDEX).set(0); ModelNode op = createDeploymentReplaceOperation(content, MAIN_SERVER_GROUP_ADDRESS, OTHER_SERVER_GROUP_ADDRESS); OperationBuilder builder = new OperationBuilder(op, true); builder.addInputStream(webArchive.as(ZipExporter.class).exportAsInputStream()); executeOnPrimary(builder.build()); // Thread.sleep(1000); performHttpCall(DomainTestSupport.primaryAddress, 8080); performHttpCall(DomainTestSupport.secondaryAddress, 8630); } @Test public void testUnmanagedArchiveReplace() throws Exception { // Establish the deployment testUnmanagedArchiveDeployment(); ModelNode content = new ModelNode(); content.get("archive").set(true); content.get("path").set(new File(tmpDir, "archives/" + TEST).getAbsolutePath()); ModelNode op = createDeploymentReplaceOperation(content, MAIN_SERVER_GROUP_ADDRESS, OTHER_SERVER_GROUP_ADDRESS); executeOnPrimary(op); // Thread.sleep(1000); performHttpCall(DomainTestSupport.primaryAddress, 8080); performHttpCall(DomainTestSupport.secondaryAddress, 8630); } @Test public void testUnmanagedExplodedReplace() throws Exception { // Establish the deployment testUnmanagedArchiveDeployment(); ModelNode content = new ModelNode(); content.get("archive").set(false); content.get("path").set(new File(tmpDir, "exploded/" + TEST).getAbsolutePath()); ModelNode op = createDeploymentReplaceOperation(content, MAIN_SERVER_GROUP_ADDRESS, OTHER_SERVER_GROUP_ADDRESS); executeOnPrimary(op); // Thread.sleep(1000); performHttpCall(DomainTestSupport.primaryAddress, 8080); performHttpCall(DomainTestSupport.secondaryAddress, 8630); } @Test public void testUnmanagedArchiveReplaceManaged() throws Exception { // Establish the deployment testDeploymentViaStream(); ModelNode content = new ModelNode(); content.get("archive").set(true); content.get("path").set(new File(tmpDir, "archives/" + TEST).getAbsolutePath()); ModelNode op = createDeploymentReplaceOperation(content, MAIN_SERVER_GROUP_ADDRESS, OTHER_SERVER_GROUP_ADDRESS); executeOnPrimary(op); // Thread.sleep(1000); performHttpCall(DomainTestSupport.primaryAddress, 8080); performHttpCall(DomainTestSupport.secondaryAddress, 8630); } @Test public void testUnmanagedExplodedReplaceManaged() throws Exception { // Establish the deployment testDeploymentViaStream(); ModelNode content = new ModelNode(); content.get("archive").set(false); content.get("path").set(new File(tmpDir, "exploded/" + TEST).getAbsolutePath()); ModelNode op = createDeploymentReplaceOperation(content, MAIN_SERVER_GROUP_ADDRESS, OTHER_SERVER_GROUP_ADDRESS); executeOnPrimary(op); //Thread.sleep(1000); performHttpCall(DomainTestSupport.primaryAddress, 8080); performHttpCall(DomainTestSupport.secondaryAddress, 8630); } @Test public void testManagedReplaceUnmanaged() throws Exception { // Establish the deployment testUnmanagedArchiveDeployment(); ModelNode content = new ModelNode(); content.get(INPUT_STREAM_INDEX).set(0); ModelNode op = createDeploymentReplaceOperation(content, MAIN_SERVER_GROUP_ADDRESS, OTHER_SERVER_GROUP_ADDRESS); OperationBuilder builder = new OperationBuilder(op, true); builder.addInputStream(webArchive.as(ZipExporter.class).exportAsInputStream()); executeOnPrimary(builder.build()); // Thread.sleep(1000); performHttpCall(DomainTestSupport.primaryAddress, 8080); performHttpCall(DomainTestSupport.secondaryAddress, 8630); } @Test public void testFullReplaceViaStream() throws Exception { // Establish the deployment testDeploymentViaStream(); ModelNode content = new ModelNode(); content.get(INPUT_STREAM_INDEX).set(0); ModelNode op = createDeploymentFullReplaceOperation(content); OperationBuilder builder = new OperationBuilder(op, true); builder.addInputStream(webArchive.as(ZipExporter.class).exportAsInputStream()); executeOnPrimary(builder.build()); // Thread.sleep(1000); performHttpCall(DomainTestSupport.primaryAddress, 8080); performHttpCall(DomainTestSupport.secondaryAddress, 8630); } @Test public void testFullReplaceViaUrl() throws Exception { // Establish the deployment testDeploymentViaStream(); String url = new File(tmpDir, "archives/" + TEST).toURI().toURL().toString(); ModelNode content = new ModelNode(); content.get("url").set(url); ModelNode op = createDeploymentFullReplaceOperation(content); executeOnPrimary(op); //Thread.sleep(1000); performHttpCall(DomainTestSupport.primaryAddress, 8080); performHttpCall(DomainTestSupport.secondaryAddress, 8630); } @Test public void testFullReplaceViaHash() throws Exception { // Establish the deployment testDeploymentViaStream(); byte[] original = getHash(ROOT_DEPLOYMENT_ADDRESS); String url = new File(tmpDir, "archives/" + TEST).toURI().toURL().toString(); ModelNode op = getEmptyOperation(UPLOAD_DEPLOYMENT_URL, ROOT_ADDRESS); op.get("url").set(url); byte[] hash = executeOnPrimary(op).asBytes(); ModelNode content = new ModelNode(); content.get("hash").set(hash); op = createDeploymentFullReplaceOperation(content); executeOnPrimary(op); // Check that the original content got removed! testRemovedContent(testSupport.getDomainPrimaryLifecycleUtil(), original); testRemovedContent(testSupport.getDomainSecondaryLifecycleUtil(), original); //Thread.sleep(1000); performHttpCall(DomainTestSupport.primaryAddress, 8080); performHttpCall(DomainTestSupport.secondaryAddress, 8630); } @Test public void testFullReplaceDifferentFile() throws Exception { // Establish the deployment testDeploymentViaStream(); ModelNode content = new ModelNode(); content.get(INPUT_STREAM_INDEX).set(0); ModelNode op = createDeploymentFullReplaceOperation(content); OperationBuilder builder = new OperationBuilder(op, true); builder.addInputStream(webArchive2.as(ZipExporter.class).exportAsInputStream()); executeOnPrimary(builder.build()); //Thread.sleep(1000); performHttpCall(DomainTestSupport.primaryAddress, 8080); performHttpCall(DomainTestSupport.secondaryAddress, 8630); } @Test public void testUnmanagedArchiveFullReplace() throws Exception { // Establish the deployment testUnmanagedArchiveDeployment(); ModelNode content = new ModelNode(); content.get("archive").set(true); content.get("path").set(new File(tmpDir, "archives/" + TEST).getAbsolutePath()); ModelNode op = createDeploymentFullReplaceOperation(content); executeOnPrimary(op); //Thread.sleep(1000); performHttpCall(DomainTestSupport.primaryAddress, 8080); performHttpCall(DomainTestSupport.secondaryAddress, 8630); } @Test public void testUnmanagedExplodedFullReplace() throws Exception { // Establish the deployment testUnmanagedExplodedDeployment(); ModelNode content = new ModelNode(); content.get("archive").set(false); content.get("path").set(new File(tmpDir, "exploded/" + TEST).getAbsolutePath()); ModelNode op = createDeploymentFullReplaceOperation(content); executeOnPrimary(op); //Thread.sleep(1000); performHttpCall(DomainTestSupport.primaryAddress, 8080); performHttpCall(DomainTestSupport.secondaryAddress, 8630); } @Test public void testUnmanagedArchiveFullReplaceManaged() throws Exception { // Establish the deployment testDeploymentViaStream(); ModelNode content = new ModelNode(); content.get("archive").set(true); content.get("path").set(new File(tmpDir, "archives/" + TEST).getAbsolutePath()); ModelNode op = createDeploymentFullReplaceOperation(content); executeOnPrimary(op); //Thread.sleep(1000); performHttpCall(DomainTestSupport.primaryAddress, 8080); performHttpCall(DomainTestSupport.secondaryAddress, 8630); } @Test public void testUnmanagedExplodedFullReplaceManaged() throws Exception { // Establish the deployment testDeploymentViaStream(); ModelNode content = new ModelNode(); content.get("archive").set(false); content.get("path").set(new File(tmpDir, "exploded/" + TEST).getAbsolutePath()); ModelNode op = createDeploymentFullReplaceOperation(content); executeOnPrimary(op); //Thread.sleep(1000); performHttpCall(DomainTestSupport.primaryAddress, 8080); performHttpCall(DomainTestSupport.secondaryAddress, 8630); } @Test public void testManagedFullReplaceUnmanaged() throws Exception { // Establish the deployment testUnmanagedExplodedDeployment(); ModelNode content = new ModelNode(); content.get(INPUT_STREAM_INDEX).set(0); ModelNode op = createDeploymentFullReplaceOperation(content); OperationBuilder builder = new OperationBuilder(op, true); builder.addInputStream(webArchive.as(ZipExporter.class).exportAsInputStream()); executeOnPrimary(builder.build()); //Thread.sleep(1000); performHttpCall(DomainTestSupport.primaryAddress, 8080); performHttpCall(DomainTestSupport.secondaryAddress, 8630); } @Test public void testServerGroupRuntimeName() throws Exception { ModelNode content = new ModelNode(); content.get(INPUT_STREAM_INDEX).set(0); ModelNode composite = createDeploymentOperation(content, OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS); // Chnage the runtime name in the sg op composite.get("steps").get(1).get(RUNTIME_NAME).set("test1.war"); OperationBuilder builder = new OperationBuilder(composite, true); builder.addInputStream(webArchive.as(ZipExporter.class).exportAsInputStream()); executeOnPrimary(builder.build()); performHttpCall(DomainTestSupport.secondaryAddress, 8630, "test1"); } @Test public void testDeployToSingleServerGroup() throws Exception { ModelNode content = new ModelNode(); content.get(INPUT_STREAM_INDEX).set(0); ModelNode composite = createDeploymentOperation(content, OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS); OperationBuilder builder = new OperationBuilder(composite, true); builder.addInputStream(webArchive.as(ZipExporter.class).exportAsInputStream()); executeOnPrimary(builder.build()); performHttpCall(DomainTestSupport.secondaryAddress, 8630); try { performHttpCall(DomainTestSupport.primaryAddress, 8080); fail("Webapp deployed to unselected server group"); } catch (IOException ioe) { // good } } @Test public void testDeploymentsWithSameHash() throws Exception { final ModelNode rootDeploymentAddress2 = new ModelNode(); rootDeploymentAddress2.add(DEPLOYMENT, "test2"); rootDeploymentAddress2.protect(); final ModelNode otherServerGroupDeploymentAddress2 = new ModelNode(); otherServerGroupDeploymentAddress2.add(SERVER_GROUP, "other-server-group"); otherServerGroupDeploymentAddress2.add(DEPLOYMENT, "test2"); otherServerGroupDeploymentAddress2.protect(); class LocalMethods { Operation createDeploymentOperation(ModelNode rootDeploymentAddress, ModelNode serverGroupDeploymentAddress) { ModelNode composite = getEmptyOperation(COMPOSITE, ROOT_ADDRESS); ModelNode steps = composite.get(STEPS); ModelNode step = steps.add(); step.set(getEmptyOperation(ADD, rootDeploymentAddress)); ModelNode content = new ModelNode(); content.get(INPUT_STREAM_INDEX).set(0); step.get(CONTENT).add(content); step = steps.add(); step.set(getEmptyOperation(ADD, serverGroupDeploymentAddress)); step.get(ENABLED).set(true); OperationBuilder builder = new OperationBuilder(composite, true); builder.addInputStream(webArchive.as(ZipExporter.class).exportAsInputStream()); return builder.build(); } ModelNode createRemoveOperation(ModelNode rootDeploymentAddress, ModelNode serverGroupDeploymentAddress) { ModelNode composite = getEmptyOperation(COMPOSITE, ROOT_ADDRESS); ModelNode steps = composite.get(STEPS); ModelNode step = steps.add(); step.set(getEmptyOperation(REMOVE, serverGroupDeploymentAddress)); step = steps.add(); step.set(getEmptyOperation(REMOVE, rootDeploymentAddress)); return composite; } } LocalMethods localMethods = new LocalMethods(); try { executeOnPrimary(localMethods.createDeploymentOperation(ROOT_DEPLOYMENT_ADDRESS, MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS)); try { executeOnPrimary(localMethods.createDeploymentOperation(rootDeploymentAddress2, otherServerGroupDeploymentAddress2)); } finally { executeOnPrimary(localMethods.createRemoveOperation(rootDeploymentAddress2, otherServerGroupDeploymentAddress2)); } ModelNode undeploySg = getEmptyOperation(REMOVE, MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS); executeOnPrimary(undeploySg); ModelNode deploySg = getEmptyOperation(ADD, MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS); deploySg.get(ENABLED).set(true); executeOnPrimary(deploySg); } finally { executeOnPrimary(localMethods.createRemoveOperation(ROOT_DEPLOYMENT_ADDRESS, MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS)); } } // @Test // public void testRollToServerGroup() throws Exception { // // TODO // fail("unimplemented"); // } // // @Test // public void testRollToServers() throws Exception { // // TODO // fail("unimplemented"); // } // // private void rolloutPlanTest(final ModelNode rolloutPlan) throws Exception { // ModelNode content = new ModelNode(); // content.get(INPUT_STREAM_INDEX).set(0); // ModelNode composite = createDeploymentOperation(content, MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS, OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS); // // ModelNode plan = composite.get(OPERATION_HEADERS, ROLLOUT_PLAN).set(rolloutPlan); // // OperationBuilder builder = OperationBuilder.Factory.create(composite); // builder.addInputStream(webArchive.as(ZipExporter.class).exportAsInputStream()); // // executeOnPrimary(builder.build()); // // performHttpCall(DomainTestSupport.primaryAddress, 8080); // performHttpCall(DomainTestSupport.secondaryAddress, 8630); // // } private static ModelNode executeOnPrimary(ModelNode op) throws IOException { return validateResponse(testSupport.getDomainPrimaryLifecycleUtil().getDomainClient().execute(op)); } private static ModelNode executeOnPrimary(Operation op) throws IOException { return validateResponse(testSupport.getDomainPrimaryLifecycleUtil().getDomainClient().execute(op)); } private static ModelNode createDeploymentOperation(ModelNode content, ModelNode... serverGroupAddressses) { ModelNode composite = getEmptyOperation(COMPOSITE, ROOT_ADDRESS); ModelNode steps = composite.get(STEPS); ModelNode step1 = steps.add(); step1.set(getEmptyOperation(ADD, ROOT_DEPLOYMENT_ADDRESS)); step1.get(CONTENT).add(content); for (ModelNode serverGroup : serverGroupAddressses) { ModelNode sg = steps.add(); sg.set(getEmptyOperation(ADD, serverGroup)); sg.get(ENABLED).set(true); } return composite; } private static ModelNode createDeploymentReplaceOperation(ModelNode content, ModelNode... serverGroupAddressses) { ModelNode composite = getEmptyOperation(COMPOSITE, ROOT_ADDRESS); ModelNode steps = composite.get(STEPS); ModelNode step1 = steps.add(); step1.set(getEmptyOperation(ADD, ROOT_REPLACEMENT_ADDRESS)); step1.get(RUNTIME_NAME).set(TEST); step1.get(CONTENT).add(content); for (ModelNode serverGroup : serverGroupAddressses) { ModelNode sgr = steps.add(); sgr.set(getEmptyOperation(REPLACE_DEPLOYMENT, serverGroup)); sgr.get(ENABLED).set(true); sgr.get(NAME).set(REPLACEMENT); sgr.get(TO_REPLACE).set(TEST); } return composite; } private static ModelNode createDeploymentFullReplaceOperation(ModelNode content) { ModelNode op = getEmptyOperation(FULL_REPLACE_DEPLOYMENT, ROOT_ADDRESS); op.get(NAME).set(TEST); op.get(CONTENT).add(content); return op; } private static List<ModelNode> getDeploymentList(ModelNode address) throws IOException { ModelNode op = getEmptyOperation("read-children-names", address); op.get("child-type").set("deployment"); ModelNode response = testSupport.getDomainPrimaryLifecycleUtil().getDomainClient().execute(op); ModelNode result = validateResponse(response); return result.isDefined() ? result.asList() : Collections.<ModelNode>emptyList(); } private static void removeDeployment(String deploymentName, ModelNode address) throws IOException { ModelNode deplAddr = new ModelNode(); deplAddr.set(address); deplAddr.add("deployment", deploymentName); ModelNode op = getEmptyOperation(REMOVE, deplAddr); ModelNode response = testSupport.getDomainPrimaryLifecycleUtil().getDomainClient().execute(op); validateResponse(response); } private static ModelNode getEmptyOperation(String operationName, ModelNode address) { ModelNode op = new ModelNode(); op.get(OP).set(operationName); if (address != null) { op.get(OP_ADDR).set(address); } else { // Just establish the standard structure; caller can fill in address later op.get(OP_ADDR); } return op; } static byte[] getHash(final ModelNode address) throws IOException { final ModelNode operation = new ModelNode(); operation.get(OP).set(READ_ATTRIBUTE_OPERATION); operation.get(OP_ADDR).set(address); operation.get(NAME).set(CONTENT); return executeOnPrimary(operation).get(0).get("hash").asBytes(); } private static void performHttpCall(String host, int port) throws IOException { performHttpCall(host, port, "test"); } private static void performHttpCall(String host, int port, String context) throws IOException { URLConnection conn = null; InputStream in = null; StringWriter writer = new StringWriter(); try { URL url = new URL("http://" + TestSuiteEnvironment.formatPossibleIpv6Address(host) + ":" + port + "/" + context + "/index.html"); conn = url.openConnection(); conn.setDoInput(true); in = new BufferedInputStream(conn.getInputStream()); int i = in.read(); while (i != -1) { writer.write((char) i); i = in.read(); } assertTrue(writer.toString().indexOf("Hello World") > -1); } finally { safeClose(in); safeClose(writer); } } static void testRemovedContent(final DomainLifecycleUtil util, final byte[] hash) { final File home = new File(util.getConfiguration().getDomainDirectory()); // Domain contents final File data = new File(home, "data"); final File contents = new File(data, "content"); checkRemoved(contents, hash); } static void checkRemoved(final File root, final byte[] hash) { final String sha1 = HashUtil.bytesToHexString(hash); final String partA = sha1.substring(0,2); final String partB = sha1.substring(2); final File da = new File(root, partA); final File db = new File(da, partB); final File content = new File(db, "content"); Assert.assertFalse(content.getAbsolutePath(), content.exists()); Assert.assertFalse(db.getAbsolutePath(), db.exists()); if (da.exists()) { String[] children = da.list(); Assert.assertTrue(da.getAbsolutePath(), children != null && children.length > 0); } } }
38,417
39.102296
144
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/suites/GlobalDirectoryDomainTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.domain.suites; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; 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.ENABLED; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_RUNTIME; 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.OUTCOME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PATH; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROFILE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_GROUP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS; import static org.jboss.as.test.integration.domain.management.util.DomainTestSupport.cleanFile; import static org.jboss.as.test.integration.domain.management.util.DomainTestSupport.safeClose; import static org.jboss.as.test.integration.domain.management.util.DomainTestSupport.validateResponse; import static org.junit.Assert.assertEquals; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.net.URL; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.Collections; import java.util.List; import org.apache.commons.io.FileUtils; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.domain.management.util.DomainLifecycleUtil; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.exporter.ExplodedExporter; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * Test for global directory * * @author Tomas Terem ([email protected]) */ public class GlobalDirectoryDomainTestCase { private static final String TEST = "test.war"; private static final String REPLACEMENT = "test.war.v2"; private static final ModelNode ROOT_ADDRESS = new ModelNode(); private static final ModelNode ROOT_DEPLOYMENT_ADDRESS = new ModelNode(); private static final ModelNode ROOT_REPLACEMENT_ADDRESS = new ModelNode(); private static final ModelNode MAIN_SERVER_GROUP_ADDRESS = new ModelNode(); private static final ModelNode MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS = new ModelNode(); private static final ModelNode OTHER_SERVER_GROUP_ADDRESS = new ModelNode(); private static final ModelNode OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS = new ModelNode(); private static final ModelNode MAIN_RUNNING_SERVER_ADDRESS = new ModelNode(); private static final ModelNode MAIN_RUNNING_SERVER_DEPLOYMENT_ADDRESS = new ModelNode(); private static final ModelNode OTHER_RUNNING_SERVER_ADDRESS = new ModelNode(); private static final ModelNode OTHER_RUNNING_SERVER_GROUP_ADDRESS = new ModelNode(); protected static final String SUBSYSTEM_EE = "ee"; protected static final Path GLOBAL_DIRECTORY_PATH = new File(TestSuiteEnvironment.getTmpDir(), "global-directory").toPath(); protected static final File GLOBAL_DIRECTORY_FILE = GLOBAL_DIRECTORY_PATH.toFile(); protected static final String GLOBAL_DIRECTORY_NAME = "global-directory"; protected static final File TEMP_DIR = new File(TestSuiteEnvironment.getTmpDir(), "jars"); static { ROOT_ADDRESS.setEmptyList(); ROOT_ADDRESS.protect(); ROOT_DEPLOYMENT_ADDRESS.add(DEPLOYMENT, TEST); ROOT_DEPLOYMENT_ADDRESS.protect(); ROOT_REPLACEMENT_ADDRESS.add(DEPLOYMENT, REPLACEMENT); ROOT_REPLACEMENT_ADDRESS.protect(); MAIN_SERVER_GROUP_ADDRESS.add(SERVER_GROUP, "main-server-group"); MAIN_SERVER_GROUP_ADDRESS.protect(); MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS.add(SERVER_GROUP, "main-server-group"); MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS.add(DEPLOYMENT, TEST); MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS.protect(); OTHER_SERVER_GROUP_ADDRESS.add(SERVER_GROUP, "other-server-group"); OTHER_SERVER_GROUP_ADDRESS.protect(); OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS.add(SERVER_GROUP, "other-server-group"); OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS.add(DEPLOYMENT, TEST); OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS.protect(); MAIN_RUNNING_SERVER_ADDRESS.add(HOST, "primary"); MAIN_RUNNING_SERVER_ADDRESS.add(SERVER, "main-one"); MAIN_RUNNING_SERVER_ADDRESS.protect(); MAIN_RUNNING_SERVER_DEPLOYMENT_ADDRESS.add(HOST, "primary"); MAIN_RUNNING_SERVER_DEPLOYMENT_ADDRESS.add(SERVER, "main-one"); MAIN_RUNNING_SERVER_DEPLOYMENT_ADDRESS.add(DEPLOYMENT, TEST); MAIN_RUNNING_SERVER_DEPLOYMENT_ADDRESS.protect(); OTHER_RUNNING_SERVER_ADDRESS.add(HOST, "secondary"); OTHER_RUNNING_SERVER_ADDRESS.add(SERVER, "other-two"); OTHER_RUNNING_SERVER_ADDRESS.protect(); OTHER_RUNNING_SERVER_GROUP_ADDRESS.add(HOST, "secondary"); OTHER_RUNNING_SERVER_GROUP_ADDRESS.add(SERVER, "other-two"); OTHER_RUNNING_SERVER_GROUP_ADDRESS.add(DEPLOYMENT, TEST); OTHER_RUNNING_SERVER_GROUP_ADDRESS.protect(); } private static DomainTestSupport testSupport; private static File tmpDir; @BeforeClass public static void setupDomain() { if (Files.notExists(Paths.get(TEMP_DIR.toString()))) { TEMP_DIR.mkdirs(); } if (Files.notExists(GLOBAL_DIRECTORY_PATH)) { GLOBAL_DIRECTORY_PATH.toFile().mkdirs(); } WebArchive webArchive = ShrinkWrap.create(WebArchive.class, TEST).addClasses(GlobalDirectoryDeployment.class) .addAsWebInfResource(new StringAsset("<?xml version=\"1.0\" encoding=\"UTF-8\"?><web-app><servlet-mapping>\n" + " <servlet-name>jakarta.ws.rs.core.Application</servlet-name>\n" + " <url-pattern>/*</url-pattern>\n" + " </servlet-mapping></web-app>"), "web.xml"); JavaArchive library = ShrinkWrap.create(JavaArchive.class, "library.jar").addClasses(GlobalDirectoryLibrary.class); library.as(ZipExporter.class).exportTo(new File(TEMP_DIR, "library.jar"), true); JavaArchive libraryImpl = ShrinkWrap.create(JavaArchive.class, "libraryImpl.jar").addClasses(GlobalDirectoryLibraryImpl.class); libraryImpl.as(ZipExporter.class).exportTo(new File(TEMP_DIR, "libraryImpl.jar"), true); tmpDir = new File("target/deployments/" + GlobalDirectoryDomainTestCase.class.getSimpleName()); new File(tmpDir, "archives").mkdirs(); new File(tmpDir, "exploded").mkdirs(); File archiveFile = new File(tmpDir, "archives/" + TEST); webArchive.as(ZipExporter.class).exportTo(archiveFile, true); webArchive.as(ExplodedExporter.class).exportExploded(new File(tmpDir, "exploded")); testSupport = DomainTestSuite.createSupport(GlobalDirectoryDomainTestCase.class.getSimpleName()); } @AfterClass public static void tearDownDomain() throws Exception { try { testSupport = null; DomainTestSuite.stopSupport(); } finally { cleanFile(tmpDir); } FileUtils.deleteDirectory(GLOBAL_DIRECTORY_PATH.toFile()); FileUtils.deleteDirectory(TEMP_DIR); } /** * Validate that there are no deployments; try and clean if there are. * * @throws Exception */ @Before @After public void confirmNoDeployments() throws Exception { List<ModelNode> deploymentList = getDeploymentList(ROOT_ADDRESS); if (deploymentList.size() > 0) { cleanDeployments(); } deploymentList = getDeploymentList(new ModelNode()); assertEquals("Deployments are removed from the domain", 0, deploymentList.size()); } /** * Remove all deployments from the model. * * @throws IOException */ private void cleanDeployments() throws IOException { List<ModelNode> deploymentList = getDeploymentList(MAIN_SERVER_GROUP_ADDRESS); for (ModelNode deployment : deploymentList) { removeDeployment(deployment.asString(), MAIN_SERVER_GROUP_ADDRESS); } deploymentList = getDeploymentList(OTHER_SERVER_GROUP_ADDRESS); for (ModelNode deployment : deploymentList) { removeDeployment(deployment.asString(), OTHER_SERVER_GROUP_ADDRESS); } deploymentList = getDeploymentList(ROOT_ADDRESS); for (ModelNode deployment : deploymentList) { removeDeployment(deployment.asString(), ROOT_ADDRESS); } } /** * Test for basic functionality of global directory. * 1. Copy jars to global directory * 2. Define global-directory by CLI command * 3. Reload the server Groups * 4. Check if global-directory is registered properly * 5. Deploy test application deployment * 6. Call some method from global-directory in deployment and verify method output * * @throws Exception */ @Test public void testBasic() throws Exception { copyLibraryToGlobalDirectory("library"); copyLibraryToGlobalDirectory("libraryImpl"); registerGlobalDirectory(GLOBAL_DIRECTORY_NAME, "default"); registerGlobalDirectory(GLOBAL_DIRECTORY_NAME, "other"); reloadServerGroup(testSupport.getDomainPrimaryLifecycleUtil(), PathAddress.pathAddress(MAIN_SERVER_GROUP_ADDRESS)); reloadServerGroup(testSupport.getDomainPrimaryLifecycleUtil(), PathAddress.pathAddress(OTHER_SERVER_GROUP_ADDRESS)); verifyProperlyRegistered(GLOBAL_DIRECTORY_NAME, GLOBAL_DIRECTORY_PATH.toString(), "default"); verifyProperlyRegistered(GLOBAL_DIRECTORY_NAME, GLOBAL_DIRECTORY_PATH.toString(), "other"); String url = new File(tmpDir, "archives/" + TEST).toURI().toURL().toString(); ModelNode content = new ModelNode(); content.get("url").set(url); ModelNode composite = createDeploymentOperation(content, MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS, OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS); executeOnPrimary(composite); String response = performHttpCall(DomainTestSupport.primaryAddress, 8080, "test/global-directory/library"); assertEquals("HELLO WORLD", response); response = performHttpCall(DomainTestSupport.secondaryAddress, 8630, "test/global-directory/library"); assertEquals("HELLO WORLD", response); removeGlobalDirectory(GLOBAL_DIRECTORY_NAME, "default"); removeGlobalDirectory(GLOBAL_DIRECTORY_NAME, "other"); verifyDoesNotExist(GLOBAL_DIRECTORY_NAME, "default"); verifyDoesNotExist(GLOBAL_DIRECTORY_NAME, "other"); reloadServerGroup(testSupport.getDomainPrimaryLifecycleUtil(), PathAddress.pathAddress(MAIN_SERVER_GROUP_ADDRESS)); reloadServerGroup(testSupport.getDomainPrimaryLifecycleUtil(), PathAddress.pathAddress(OTHER_SERVER_GROUP_ADDRESS)); } private void copyLibraryToGlobalDirectory(String name) throws IOException { if (Files.notExists(GLOBAL_DIRECTORY_PATH)) { GLOBAL_DIRECTORY_PATH.toFile().mkdirs(); } Path jarPath = new File(TEMP_DIR, name + ".jar").toPath(); Files.copy(jarPath, new File(GLOBAL_DIRECTORY_FILE, name + ".jar").toPath(), StandardCopyOption.REPLACE_EXISTING); } /** * Verify if is global directory is registered and contains right path * * @param name Name of global directory for verify * @param path Expected set path for current global directory */ private ModelNode verifyProperlyRegistered(String name, String path, String profile) throws IOException { ModelNode response = readGlobalDirectory(name, profile); ModelNode outcome = response.get(OUTCOME); assertThat("Read resource of global directory " + name + " failure!", outcome.asString(), is(SUCCESS)); final ModelNode result = response.get(RESULT); assertThat("Global directory " + name + " have set wrong path!", result.get(PATH).asString(), is(path)); return response; } /** * Read resource command for global directory * * @param name Name of global directory */ private ModelNode readGlobalDirectory(String name, String profile) throws IOException { // /profile=<<profile>>/subsystem=ee/global-directory=<<name>>:read-resource final ModelNode address = new ModelNode(); address.add(PROFILE, profile) .add(SUBSYSTEM, SUBSYSTEM_EE) .add(GLOBAL_DIRECTORY_NAME, name) .protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set(READ_RESOURCE_OPERATION); operation.get(INCLUDE_RUNTIME).set(true); operation.get(OP_ADDR).set(address); return testSupport.getDomainPrimaryLifecycleUtil().getDomainClient().execute(operation); } /** * Verify that global directory doesn't exist * * @param name Name of global directory for verify */ private ModelNode verifyDoesNotExist(String name, String profile) throws IOException { ModelNode response = readGlobalDirectory(name, profile); ModelNode outcome = response.get(OUTCOME); assertThat("Global directory " + name + " still exist!", outcome.asString(), not(SUCCESS)); return response; } /** * Register global directory * Verify the response for success * * @param name Name of new global directory */ private ModelNode registerGlobalDirectory(String name, String profile) throws IOException { return registerGlobalDirectory(name, GLOBAL_DIRECTORY_PATH.toString(), profile, true); } /** * Register global directory * * @param name Name of new global directory * @param path * @param expectSuccess If is true verify the response for success, If is false only return operation result */ private ModelNode registerGlobalDirectory(String name, String path, String profile, boolean expectSuccess) throws IOException { // /profile=<<profile>>/subsystem=ee/global-directory=<<name>>:add(path=<<path>>) final ModelNode address = new ModelNode(); address.add(PROFILE, profile) .add(SUBSYSTEM, SUBSYSTEM_EE) .add(GLOBAL_DIRECTORY_NAME, name) .protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set(ADD); operation.get(INCLUDE_RUNTIME).set(true); operation.get(OP_ADDR).set(address); operation.get(PATH).set(path); ModelNode response = testSupport.getDomainPrimaryLifecycleUtil().getDomainClient().execute(operation); ModelNode outcome = response.get(OUTCOME); if (expectSuccess) { assertThat("Registration of global directory " + name + " failure!", outcome.asString(), is(SUCCESS)); } return response; } /** * Remove global directory * * @param name Name of global directory for removing */ protected ModelNode removeGlobalDirectory(String name, String profile) throws IOException { // /profile=<<profile>>/subsystem=ee/global-directory=<<name>>:remove final ModelNode address = new ModelNode(); address.add(PROFILE, profile) .add(SUBSYSTEM, SUBSYSTEM_EE) .add(GLOBAL_DIRECTORY_NAME, name) .protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set(REMOVE); operation.get(INCLUDE_RUNTIME).set(true); operation.get(OP_ADDR).set(address); ModelNode response = testSupport.getDomainPrimaryLifecycleUtil().getDomainClient().execute(operation); ModelNode outcome = response.get(OUTCOME); assertThat("Remove of global directory " + name + " failure!", outcome.asString(), is(SUCCESS)); return response; } private static ModelNode executeOnPrimary(ModelNode op) throws IOException { return validateResponse(testSupport.getDomainPrimaryLifecycleUtil().getDomainClient().execute(op)); } private static ModelNode createDeploymentOperation(ModelNode content, ModelNode... serverGroupAddressses) { ModelNode composite = getEmptyOperation(COMPOSITE, ROOT_ADDRESS); ModelNode steps = composite.get(STEPS); ModelNode step1 = steps.add(); step1.set(getEmptyOperation(ADD, ROOT_DEPLOYMENT_ADDRESS)); step1.get(CONTENT).add(content); for (ModelNode serverGroup : serverGroupAddressses) { ModelNode sg = steps.add(); sg.set(getEmptyOperation(ADD, serverGroup)); sg.get(ENABLED).set(true); } return composite; } private static List<ModelNode> getDeploymentList(ModelNode address) throws IOException { ModelNode op = getEmptyOperation("read-children-names", address); op.get("child-type").set("deployment"); ModelNode response = testSupport.getDomainPrimaryLifecycleUtil().getDomainClient().execute(op); ModelNode result = validateResponse(response); return result.isDefined() ? result.asList() : Collections.<ModelNode>emptyList(); } private static void removeDeployment(String deploymentName, ModelNode address) throws IOException { ModelNode deplAddr = new ModelNode(); deplAddr.set(address); deplAddr.add("deployment", deploymentName); ModelNode op = getEmptyOperation(REMOVE, deplAddr); ModelNode response = testSupport.getDomainPrimaryLifecycleUtil().getDomainClient().execute(op); validateResponse(response); } private static ModelNode getEmptyOperation(String operationName, ModelNode address) { ModelNode op = new ModelNode(); op.get(OP).set(operationName); if (address != null) { op.get(OP_ADDR).set(address); } else { // Just establish the standard structure; caller can fill in address later op.get(OP_ADDR); } return op; } private static String performHttpCall(String host, int port, String context) throws IOException { URLConnection conn; InputStream in = null; StringWriter writer = new StringWriter(); try { URL url = new URL("http://" + TestSuiteEnvironment.formatPossibleIpv6Address(host) + ":" + port + "/" + context); conn = url.openConnection(); conn.setDoInput(true); in = new BufferedInputStream(conn.getInputStream()); int i = in.read(); while (i != -1) { writer.write((char) i); i = in.read(); } return writer.toString(); } finally { safeClose(in); safeClose(writer); } } private void reloadServerGroup(DomainLifecycleUtil domainPrimaryLifecycleUtil, PathAddress address) { ModelNode reload = Util.createEmptyOperation("reload-servers", address); reload.get("blocking").set("true"); domainPrimaryLifecycleUtil.executeForResult(reload); } }
21,992
45.398734
142
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/suites/ReadEnvironmentVariablesTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.domain.suites; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_RUNTIME; 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_RESOURCE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING_GROUP; import static org.jboss.as.test.integration.domain.management.util.DomainTestSupport.validateResponse; import static org.jboss.as.test.shared.PermissionUtils.createPermissionsXmlAsset; import java.io.InputStream; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.apache.http.impl.client.HttpClients; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.junit.Assert; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.jboss.as.controller.client.helpers.domain.DeploymentPlan; import org.jboss.as.controller.client.helpers.domain.DeploymentPlanResult; import org.jboss.as.controller.client.helpers.domain.DomainClient; import org.jboss.as.controller.client.helpers.domain.DomainDeploymentManager; import org.jboss.as.test.integration.domain.management.util.DomainLifecycleUtil; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.xnio.IoUtils; /** * * @author <a href="[email protected]">Kabir Khan</a> */ public class ReadEnvironmentVariablesTestCase { private static DomainTestSupport testSupport; private static DomainLifecycleUtil domainPrimaryLifecycleUtil; private static DomainLifecycleUtil domainSecondaryLifecycleUtil; @BeforeClass public static void setupDomain() throws Exception { testSupport = DomainTestSuite.createSupport(ReadEnvironmentVariablesTestCase.class.getSimpleName()); domainPrimaryLifecycleUtil = testSupport.getDomainPrimaryLifecycleUtil(); domainSecondaryLifecycleUtil = testSupport.getDomainSecondaryLifecycleUtil(); } @AfterClass public static void tearDownDomain() throws Exception { DomainTestSuite.stopSupport(); testSupport = null; domainPrimaryLifecycleUtil = null; domainSecondaryLifecycleUtil = null; } @Test public void testReadEnvironmentVariablesForServers() throws Exception { DomainClient client = domainPrimaryLifecycleUtil.createDomainClient(); DomainDeploymentManager manager = client.getDeploymentManager(); try { //Deploy the archive String archiveName = "env-test.war"; WebArchive archive = ShrinkWrap.create(WebArchive.class, archiveName).addClass(EnvironmentTestServlet.class); archive.addAsResource(new StringAsset("Manifest-Version: 1.0\nDependencies: org.jboss.dmr \n"),"META-INF/MANIFEST.MF"); archive.addAsManifestResource(createPermissionsXmlAsset(new RuntimePermission("getenv.*")), "permissions.xml"); final InputStream contents = archive.as(ZipExporter.class).exportAsInputStream(); try { DeploymentPlan plan = manager.newDeploymentPlan() .add("env-test.war", contents) .deploy("env-test.war") .toServerGroup("main-server-group") .toServerGroup("other-server-group") .build(); DeploymentPlanResult result = manager.execute(plan).get(); Assert.assertTrue(result.isValid()); } finally { IoUtils.safeClose(contents); } Map<String, String> env = getEnvironmentVariables(client, "primary", "main-one", "standard-sockets"); checkEnvironmentVariable(env, "DOMAIN_TEST_MAIN_GROUP", "main_group"); checkEnvironmentVariable(env, "DOMAIN_TEST_SERVER", "server"); checkEnvironmentVariable(env, "DOMAIN_TEST_JVM", "jvm"); env = getEnvironmentVariables(client, "secondary", "main-three", "standard-sockets"); checkEnvironmentVariable(env, "DOMAIN_TEST_MAIN_GROUP", "main_group"); Assert.assertFalse(env.containsKey("DOMAIN_TEST_SERVER")); Assert.assertFalse(env.containsKey("DOMAIN_TEST_JVM")); env = getEnvironmentVariables(client, "secondary", "other-two", "other-sockets"); Assert.assertFalse(env.containsKey("DOMAIN_TEST_MAIN_GROUP")); Assert.assertFalse(env.containsKey("DOMAIN_TEST_SERVER")); Assert.assertFalse(env.containsKey("DOMAIN_TEST_JVM")); } finally { DeploymentPlanResult result = manager.execute(manager.newDeploymentPlan().undeploy("env-test.war").build()).get(); Assert.assertTrue(result.isValid()); IoUtils.safeClose(client); } } private void checkEnvironmentVariable(Map<String, String> env, String name, String expected) { Assert.assertTrue(env.containsKey(name)); Assert.assertEquals(expected, env.get(name)); } private Map<String, String> getEnvironmentVariables(DomainClient client, String host, String server, String socketBindingGroup) throws Exception { ModelNode op = new ModelNode(); op.get(OP).set(READ_RESOURCE_OPERATION); op.get(OP_ADDR).add(HOST, host).add(SERVER, server).add(SOCKET_BINDING_GROUP, socketBindingGroup).add(SOCKET_BINDING, "http"); op.get(INCLUDE_RUNTIME).set(true); ModelNode socketBinding = validateResponse(client.execute(op)); URL url = new URL("http", TestSuiteEnvironment.formatPossibleIpv6Address(socketBinding.get("bound-address").asString()), socketBinding.get("bound-port").asInt(), "/env-test/env"); HttpGet get = new HttpGet(url.toURI()); HttpClient httpClient = HttpClients.createDefault(); HttpResponse response = httpClient.execute(get); ModelNode env = ModelNode.fromJSONStream(response.getEntity().getContent()); Map<String, String> environment = new HashMap<String, String>(); for (Property property : env.asPropertyList()) { environment.put(property.getName(), property.getValue().asProperty().getName()); } return environment; } }
8,177
48.563636
150
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/suites/EnvironmentTestServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.domain.suites; import java.io.IOException; import java.io.PrintWriter; import java.util.Map; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.jboss.dmr.ModelNode; @WebServlet(urlPatterns= {"/env"}) public class EnvironmentTestServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ModelNode node = new ModelNode(); Map<String, String> env = System.getenv(); for (Map.Entry<String, String> entry : env.entrySet()) { node.get(entry.getKey(), entry.getValue()); } resp.setContentType("application/json"); final PrintWriter out = resp.getWriter(); try { node.writeJSONString(out, true); } finally { out.close(); } } }
2,125
36.298246
113
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/suites/DeploymentOverlayTestCase.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.test.integration.domain.suites; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; 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.ENABLED; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_RUNTIME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INPUT_STREAM_INDEX; 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_RESOURCE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_GROUP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING_GROUP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS; import static org.jboss.as.test.integration.domain.management.util.DomainTestSupport.cleanFile; import static org.jboss.as.test.integration.domain.management.util.DomainTestSupport.validateResponse; import static org.junit.Assert.assertEquals; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; import org.jboss.as.cli.Util; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.Operation; import org.jboss.as.controller.client.OperationBuilder; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.controller.client.helpers.domain.DomainClient; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.shared.FileUtils; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.exporter.ExplodedExporter; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * Test of various management operations involving deployment overlays */ public class DeploymentOverlayTestCase { public static final String TEST_OVERLAY = "test"; public static final String TEST_WILDCARD = "test-server"; private static final String TEST = "test.war"; private static final String REPLACEMENT = "test.war.v2"; private static final ModelNode ROOT_ADDRESS = new ModelNode(); private static final ModelNode ROOT_DEPLOYMENT_ADDRESS = new ModelNode(); private static final ModelNode ROOT_REPLACEMENT_ADDRESS = new ModelNode(); private static final ModelNode MAIN_SERVER_GROUP_ADDRESS = new ModelNode(); private static final ModelNode MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS = new ModelNode(); private static final ModelNode MAIN_RUNNING_SERVER_ADDRESS = new ModelNode(); private static final ModelNode MAIN_RUNNING_SERVER_DEPLOYMENT_ADDRESS = new ModelNode(); static { ROOT_ADDRESS.setEmptyList(); ROOT_ADDRESS.protect(); ROOT_DEPLOYMENT_ADDRESS.add(DEPLOYMENT, TEST); ROOT_DEPLOYMENT_ADDRESS.protect(); ROOT_REPLACEMENT_ADDRESS.add(DEPLOYMENT, REPLACEMENT); ROOT_REPLACEMENT_ADDRESS.protect(); MAIN_SERVER_GROUP_ADDRESS.add(SERVER_GROUP, "main-server-group"); MAIN_SERVER_GROUP_ADDRESS.protect(); MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS.add(SERVER_GROUP, "main-server-group"); MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS.add(DEPLOYMENT, TEST); MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS.protect(); MAIN_RUNNING_SERVER_ADDRESS.add(HOST, "primary"); MAIN_RUNNING_SERVER_ADDRESS.add(SERVER, "main-one"); MAIN_RUNNING_SERVER_ADDRESS.protect(); MAIN_RUNNING_SERVER_DEPLOYMENT_ADDRESS.add(HOST, "primary"); MAIN_RUNNING_SERVER_DEPLOYMENT_ADDRESS.add(SERVER, "main-one"); MAIN_RUNNING_SERVER_DEPLOYMENT_ADDRESS.add(DEPLOYMENT, TEST); MAIN_RUNNING_SERVER_DEPLOYMENT_ADDRESS.protect(); } private static DomainTestSupport testSupport; private static WebArchive webArchive; private static File tmpDir; @BeforeClass public static void setupDomain() throws Exception { // Create our deployment webArchive = ShrinkWrap.create(WebArchive.class, TEST); webArchive.addAsWebInfResource("deploymentoverlay/web.xml", "web.xml"); webArchive.addClass(DeploymentOverlayServlet.class); // Make versions on the filesystem for URL-based deploy and for unmanaged content testing tmpDir = new File("target/deployments/" + DeploymentOverlayTestCase.class.getSimpleName()); new File(tmpDir, "archives").mkdirs(); new File(tmpDir, "exploded").mkdirs(); File archiveTarget = new File(tmpDir, "archives/" + TEST); webArchive.as(ZipExporter.class).exportTo(archiveTarget, true); webArchive.as(ExplodedExporter.class).exportExploded(new File(tmpDir, "exploded")); // Launch the domain testSupport = DomainTestSuite.createSupport(DeploymentOverlayTestCase.class.getSimpleName()); } @AfterClass public static void tearDownDomain() throws Exception { try { testSupport = null; DomainTestSuite.stopSupport(); } finally { cleanFile(tmpDir); } } /** * Validate that there are no deployments; try and clean if there are. * * @throws Exception */ @Before @After public void confirmNoDeployments() throws Exception { List<ModelNode> deploymentList = getDeploymentList(ROOT_ADDRESS); if (deploymentList.size() > 0) { cleanDeployments(); } deploymentList = getDeploymentList(new ModelNode()); assertEquals("Deployments are removed from the domain", 0, deploymentList.size()); } /** * Remove all deployments from the model. * * @throws java.io.IOException */ private void cleanDeployments() throws IOException { List<ModelNode> deploymentList = getDeploymentList(MAIN_SERVER_GROUP_ADDRESS); for (ModelNode deployment : deploymentList) { removeDeployment(deployment.asString(), MAIN_SERVER_GROUP_ADDRESS); } deploymentList = getDeploymentList(ROOT_ADDRESS); for (ModelNode deployment : deploymentList) { removeDeployment(deployment.asString(), ROOT_ADDRESS); } } public void setupDeploymentOverride() throws Exception { ModelNode op = new ModelNode(); op.get(ModelDescriptionConstants.OP_ADDR).set(ModelDescriptionConstants.DEPLOYMENT_OVERLAY, TEST_OVERLAY); op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD); executeOnPrimary(op); //add an override that will not be linked via a wildcard //add the content op = new ModelNode(); OperationBuilder builder = new OperationBuilder(op, true); ModelNode addr = new ModelNode(); addr.add(ModelDescriptionConstants.DEPLOYMENT_OVERLAY, TEST_OVERLAY); addr.add(ModelDescriptionConstants.CONTENT, "WEB-INF/web.xml"); op.get(ModelDescriptionConstants.OP_ADDR).set(addr); op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD); op.get(ModelDescriptionConstants.CONTENT).get(INPUT_STREAM_INDEX).set(0); builder.addInputStream(getClass().getClassLoader().getResourceAsStream("deploymentoverlay/override.xml")); executeOnPrimary(builder.build()); //add the non-wildcard link to the server group op = new ModelNode(); addr = new ModelNode(); addr.add(ModelDescriptionConstants.SERVER_GROUP, "main-server-group"); addr.add(ModelDescriptionConstants.DEPLOYMENT_OVERLAY, TEST_OVERLAY); op.get(ModelDescriptionConstants.OP_ADDR).set(addr); op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD); executeOnPrimary(op); op = new ModelNode(); addr = new ModelNode(); addr.add(ModelDescriptionConstants.SERVER_GROUP, "main-server-group"); addr.add(ModelDescriptionConstants.DEPLOYMENT_OVERLAY, TEST_OVERLAY); addr.add(ModelDescriptionConstants.DEPLOYMENT, "test.war"); op.get(ModelDescriptionConstants.OP_ADDR).set(addr); op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD); executeOnPrimary(op); //add the wildard link final ModelNode composite = new ModelNode(); final OperationBuilder opBuilder = new OperationBuilder(composite, true); composite.get(Util.OPERATION).set(Util.COMPOSITE); composite.get(Util.ADDRESS).setEmptyList(); final ModelNode steps = composite.get(Util.STEPS); op = new ModelNode(); op.get(ModelDescriptionConstants.OP_ADDR).set(ModelDescriptionConstants.DEPLOYMENT_OVERLAY, TEST_WILDCARD); op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD); steps.add(op); op = new ModelNode(); addr = new ModelNode(); addr.add(ModelDescriptionConstants.DEPLOYMENT_OVERLAY, TEST_WILDCARD); addr.add(ModelDescriptionConstants.CONTENT, "WEB-INF/web.xml"); op.get(ModelDescriptionConstants.OP_ADDR).set(addr); op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD); op.get(ModelDescriptionConstants.CONTENT).get(ModelDescriptionConstants.BYTES).set(FileUtils.readFile(getClass().getClassLoader().getResource("deploymentoverlay/wildcard-override.xml")).getBytes()); steps.add(op); op = new ModelNode(); addr = new ModelNode(); addr.add(ModelDescriptionConstants.DEPLOYMENT_OVERLAY, TEST_WILDCARD); addr.add(ModelDescriptionConstants.CONTENT, "wildcard-new-file.txt"); op.get(ModelDescriptionConstants.OP_ADDR).set(addr); op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD); op.get(ModelDescriptionConstants.CONTENT).get(ModelDescriptionConstants.INPUT_STREAM_INDEX).set(0); opBuilder.addInputStream(new ByteArrayInputStream("new file".getBytes(StandardCharsets.UTF_8))); steps.add(op); //add the non-wildcard link to the server group op = new ModelNode(); addr = new ModelNode(); addr.add(ModelDescriptionConstants.SERVER_GROUP, "main-server-group"); addr.add(ModelDescriptionConstants.DEPLOYMENT_OVERLAY, TEST_WILDCARD); op.get(ModelDescriptionConstants.OP_ADDR).set(addr); op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD); steps.add(op); op = new ModelNode(); addr = new ModelNode(); addr.add(ModelDescriptionConstants.SERVER_GROUP, "main-server-group"); addr.add(ModelDescriptionConstants.DEPLOYMENT_OVERLAY, TEST_WILDCARD); addr.add(ModelDescriptionConstants.DEPLOYMENT, "*.war"); op.get(ModelDescriptionConstants.OP_ADDR).set(addr); op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD); steps.add(op); executeOnPrimary(opBuilder.build()); } /** * This test creates and links two deployment overlays, does a deployment, and then tests that the overlay has taken effect * @throws Exception */ @Test public void testDeploymentOverlayInDomainMode() throws Exception { setupDeploymentOverride(); ModelNode content = new ModelNode(); content.get(INPUT_STREAM_INDEX).set(0); ModelNode composite = createDeploymentOperation(content, MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS); OperationBuilder builder = new OperationBuilder(composite, true); builder.addInputStream(webArchive.as(ZipExporter.class).exportAsInputStream()); executeOnPrimary(builder.build()); DomainClient client = testSupport.getDomainPrimaryLifecycleUtil().createDomainClient(); Assert.assertEquals("OVERRIDDEN", performHttpCall(client, "primary", "main-one", "standard-sockets", "/test/servlet")); Assert.assertEquals("OVERRIDDEN", performHttpCall(client, "secondary", "main-three", "standard-sockets", "/test/servlet")); Assert.assertEquals("new file", performHttpCall(client, "primary", "main-one", "standard-sockets", "/test/wildcard-new-file.txt")); Assert.assertEquals("new file", performHttpCall(client, "secondary", "main-three", "standard-sockets", "/test/wildcard-new-file.txt")); //Remove the wildcard overlay ModelNode op = Operations.createRemoveOperation(PathAddress.pathAddress(ModelDescriptionConstants.SERVER_GROUP, "main-server-group") .append(ModelDescriptionConstants.DEPLOYMENT_OVERLAY, TEST_WILDCARD) .append(ModelDescriptionConstants.DEPLOYMENT, "*.war") .toModelNode()); op.get("redeploy-affected").set(true); executeOnPrimary(op); Assert.assertEquals("OVERRIDDEN", performHttpCall(client, "primary", "main-one", "standard-sockets", "/test/servlet")); Assert.assertEquals("OVERRIDDEN", performHttpCall(client, "secondary", "main-three", "standard-sockets", "/test/servlet")); Assert.assertEquals("<html><head><title>Error</title></head><body>Not Found</body></html>", performHttpCall(client, "primary", "main-one", "standard-sockets", "/test/wildcard-new-file.txt")); Assert.assertEquals("<html><head><title>Error</title></head><body>Not Found</body></html>", performHttpCall(client, "secondary", "main-three", "standard-sockets", "/test/wildcard-new-file.txt")); op = Operations.createRemoveOperation(PathAddress.pathAddress(ModelDescriptionConstants.SERVER_GROUP, "main-server-group") .append(ModelDescriptionConstants.DEPLOYMENT_OVERLAY, TEST_OVERLAY) .append(ModelDescriptionConstants.DEPLOYMENT, "test.war") .toModelNode()); op.get("redeploy-affected").set(true); executeOnPrimary(op); Assert.assertEquals("NON OVERRIDDEN", performHttpCall(client, "primary", "main-one", "standard-sockets", "/test/servlet")); Assert.assertEquals("NON OVERRIDDEN", performHttpCall(client, "secondary", "main-three", "standard-sockets", "/test/servlet")); Assert.assertEquals("<html><head><title>Error</title></head><body>Not Found</body></html>", performHttpCall(client, "primary", "main-one", "standard-sockets", "/test/wildcard-new-file.txt")); Assert.assertEquals("<html><head><title>Error</title></head><body>Not Found</body></html>", performHttpCall(client, "secondary", "main-three", "standard-sockets", "/test/wildcard-new-file.txt")); } private String performHttpCall(DomainClient client, String host, String server, String socketBindingGroup, String path) throws Exception { ModelNode op = new ModelNode(); op.get(OP).set(READ_RESOURCE_OPERATION); op.get(OP_ADDR).add(HOST, host).add(SERVER, server).add(SOCKET_BINDING_GROUP, socketBindingGroup).add(SOCKET_BINDING, "http"); op.get(INCLUDE_RUNTIME).set(true); ModelNode socketBinding = validateResponse(client.execute(op)); URL url = new URL("http", TestSuiteEnvironment.formatPossibleIpv6Address(socketBinding.get("bound-address").asString()), socketBinding.get("bound-port").asInt(), path); HttpGet get = new HttpGet(url.toURI()); HttpClient httpClient = HttpClients.createDefault(); HttpResponse response = httpClient.execute(get); return getContent(response); } public static String getContent(HttpResponse response) throws IOException { InputStreamReader reader = new InputStreamReader(response.getEntity().getContent(),StandardCharsets.UTF_8); StringBuilder content = new StringBuilder(); char[] buffer = new char[8]; int c; while ((c = reader.read(buffer)) != -1) { content.append(buffer, 0, c); } reader.close(); return content.toString(); } private static ModelNode executeOnPrimary(ModelNode op) throws IOException { return validateResponse(testSupport.getDomainPrimaryLifecycleUtil().getDomainClient().execute(op)); } private static ModelNode executeOnPrimary(Operation op) throws IOException { return validateResponse(testSupport.getDomainPrimaryLifecycleUtil().getDomainClient().execute(op)); } private static ModelNode createDeploymentOperation(ModelNode content, ModelNode... serverGroupAddressses) { ModelNode composite = getEmptyOperation(COMPOSITE, ROOT_ADDRESS); ModelNode steps = composite.get(STEPS); ModelNode step1 = steps.add(); step1.set(getEmptyOperation(ADD, ROOT_DEPLOYMENT_ADDRESS)); step1.get(CONTENT).add(content); for (ModelNode serverGroup : serverGroupAddressses) { ModelNode sg = steps.add(); sg.set(getEmptyOperation(ADD, serverGroup)); sg.get(ENABLED).set(true); } return composite; } private static List<ModelNode> getDeploymentList(ModelNode address) throws IOException { ModelNode op = getEmptyOperation("read-children-names", address); op.get("child-type").set("deployment"); ModelNode response = testSupport.getDomainPrimaryLifecycleUtil().getDomainClient().execute(op); ModelNode result = validateResponse(response); return result.isDefined() ? result.asList() : Collections.<ModelNode>emptyList(); } private static void removeDeployment(String deploymentName, ModelNode address) throws IOException { ModelNode deplAddr = new ModelNode(); deplAddr.set(address); deplAddr.add("deployment", deploymentName); ModelNode op = getEmptyOperation(REMOVE, deplAddr); ModelNode response = testSupport.getDomainPrimaryLifecycleUtil().getDomainClient().execute(op); validateResponse(response); } private static ModelNode getEmptyOperation(String operationName, ModelNode address) { ModelNode op = new ModelNode(); op.get(OP).set(operationName); if (address != null) { op.get(OP_ADDR).set(address); } else { // Just establish the standard structure; caller can fill in address later op.get(OP_ADDR); } return op; } }
20,586
49.090024
206
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/suites/ModelPersistenceTestCase.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.test.integration.domain.suites; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; 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.OUTCOME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.jboss.as.cli.operation.OperationFormatException; import org.jboss.as.cli.operation.impl.DefaultOperationRequestBuilder; import org.jboss.as.controller.client.OperationBuilder; import org.jboss.as.controller.client.helpers.domain.DomainClient; import org.jboss.as.test.integration.domain.management.util.DomainLifecycleUtil; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.integration.management.util.ModelUtil; import org.jboss.as.test.integration.management.util.SimpleServlet; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.impl.base.exporter.zip.ZipExporterImpl; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** * Tests both automated and manual configuration model persistence snapshot generation. * * @author Dominik Pospisil <[email protected]> */ public class ModelPersistenceTestCase { enum Host { PRIMARY, SECONDARY } private class CfgFileDescription { CfgFileDescription(int version, File file, long hash) { this.version = version; this.file = file; this.hash = hash; } public int version; public File file; public long hash; } private static DomainTestSupport domainSupport; private static DomainLifecycleUtil domainPrimaryLifecycleUtil; private static DomainLifecycleUtil domainSecondaryLifecycleUtil; private static final String DOMAIN_HISTORY_DIR = "domain_xml_history"; private static final String HOST_HISTORY_DIR = "host_xml_history"; private static final String CONFIG_DIR = "configuration"; private static final String CURRENT_DIR = "current"; private static final String PRIMARY_DIR = "primary"; private static final String SECONDARY_DIR = "secondary"; private static final String DOMAIN_NAME = "testing-domain-standard"; private static final String PRIMARY_NAME = "testing-host-primary"; private static final String SECONDARY_NAME = "testing-host-secondary"; private static File domainCurrentCfgDir; private static File primaryCurrentCfgDir; private static File secondaryCurrentCfgDir; private static File domainLastCfgFile; private static File primaryLastCfgFile; private static File secondaryLastCfgFile; @BeforeClass public static void initDomain() throws Exception { domainSupport = DomainTestSuite.createSupport(ModelPersistenceTestCase.class.getSimpleName()); domainPrimaryLifecycleUtil = domainSupport.getDomainPrimaryLifecycleUtil(); domainSecondaryLifecycleUtil = domainSupport.getDomainSecondaryLifecycleUtil(); File primaryDir = new File(domainSupport.getDomainPrimaryConfiguration().getDomainDirectory()); File secondaryDir = new File(domainSupport.getDomainSecondaryConfiguration().getDomainDirectory()); domainCurrentCfgDir = new File(primaryDir, CONFIG_DIR + File.separator + DOMAIN_HISTORY_DIR + File.separator + CURRENT_DIR); primaryCurrentCfgDir = new File(primaryDir, CONFIG_DIR + File.separator + HOST_HISTORY_DIR + File.separator + CURRENT_DIR); secondaryCurrentCfgDir = new File(secondaryDir, CONFIG_DIR + File.separator + HOST_HISTORY_DIR + File.separator + CURRENT_DIR); domainLastCfgFile = new File(primaryDir, CONFIG_DIR + File.separator + DOMAIN_HISTORY_DIR + File.separator + DOMAIN_NAME + ".last.xml"); primaryLastCfgFile = new File(primaryDir, CONFIG_DIR + File.separator + HOST_HISTORY_DIR + File.separator + PRIMARY_NAME + ".last.xml"); secondaryLastCfgFile = new File(secondaryDir, CONFIG_DIR + File.separator + HOST_HISTORY_DIR + File.separator + SECONDARY_NAME + ".last.xml"); } @AfterClass public static void shutdownDomain() { domainSupport = null; domainPrimaryLifecycleUtil = null; domainSecondaryLifecycleUtil = null; DomainTestSuite.stopSupport(); } @Test public void testSimpleDomainOperation() throws Exception { ModelNode op = ModelUtil.createOpNode("profile=default/subsystem=ee", WRITE_ATTRIBUTE_OPERATION); op.get(NAME).set("ear-subdeployments-isolated"); op.get(VALUE).set(true); testDomainOperation(op); op.get(VALUE).set(false); testDomainOperation(op); } @Test public void testCompositeDomainOperation() throws Exception { ModelNode[] steps = new ModelNode[2]; steps[0] = ModelUtil.createOpNode("profile=default/subsystem=ee", WRITE_ATTRIBUTE_OPERATION); steps[0].get(NAME).set("ear-subdeployments-isolated"); steps[0].get(VALUE).set(true); steps[1] = ModelUtil.createOpNode("system-property=model-persistence-test", ADD); steps[1].get(VALUE).set("test"); testDomainOperation(ModelUtil.createCompositeNode(steps)); steps[0].get(VALUE).set(false); steps[1] = ModelUtil.createOpNode("system-property=model-persistence-test", REMOVE); testDomainOperation(ModelUtil.createCompositeNode(steps)); } private void testDomainOperation(ModelNode operation) throws Exception { DomainClient client = domainPrimaryLifecycleUtil.getDomainClient(); CfgFileDescription lastBackupDesc = getLatestBackup(domainCurrentCfgDir); CfgFileDescription lastPrimaryBackupDesc = getLatestBackup(primaryCurrentCfgDir); CfgFileDescription lastSecondaryBackupDesc = getLatestBackup(secondaryCurrentCfgDir); long lastFileHash = domainLastCfgFile.exists() ? FileUtils.checksumCRC32(domainLastCfgFile) : -1; // execute operation so the model gets updated executeOperation(client, operation); // check that the automated snapshot of the domain has been generated CfgFileDescription newBackupDesc = getLatestBackup(domainCurrentCfgDir); Assert.assertNotNull("Model snapshot not found.", newBackupDesc); // check that the version is incremented by one Assert.assertTrue(lastBackupDesc.version == newBackupDesc.version - 1); // check that the both primary and secondary host snapshot have not been generated CfgFileDescription newPrimaryBackupDesc = getLatestBackup(primaryCurrentCfgDir); CfgFileDescription newSecondaryBackupDesc = getLatestBackup(secondaryCurrentCfgDir); Assert.assertTrue(lastPrimaryBackupDesc.version == newPrimaryBackupDesc.version); Assert.assertTrue(lastSecondaryBackupDesc.version == newSecondaryBackupDesc.version); // check that the last cfg file has changed Assert.assertTrue(lastFileHash != FileUtils.checksumCRC32(domainLastCfgFile)); } @Test public void testDomainOperationRollback() throws Exception { DomainClient client = domainPrimaryLifecycleUtil.getDomainClient(); CfgFileDescription lastDomainBackupDesc = getLatestBackup(domainCurrentCfgDir); CfgFileDescription lastPrimaryBackupDesc = getLatestBackup(primaryCurrentCfgDir); CfgFileDescription lastSecondaryBackupDesc = getLatestBackup(secondaryCurrentCfgDir); // execute operation so the model gets updated ModelNode op = ModelUtil.createOpNode("system-property=model-persistence-test", "add"); op.get(VALUE).set("test"); executeAndRollbackOperation(client, op); // check that the model has not been updated CfgFileDescription newDomainBackupDesc = getLatestBackup(domainCurrentCfgDir); CfgFileDescription newPrimaryBackupDesc = getLatestBackup(primaryCurrentCfgDir); CfgFileDescription newSecondaryBackupDesc = getLatestBackup(secondaryCurrentCfgDir); // check that the configs did not change Assert.assertTrue(lastDomainBackupDesc.version == newDomainBackupDesc.version); Assert.assertTrue(lastPrimaryBackupDesc.version == newPrimaryBackupDesc.version); Assert.assertTrue(lastSecondaryBackupDesc.version == newSecondaryBackupDesc.version); } @Test public void testSimpleHostOperation() throws Exception { // using primary DC ModelNode op = ModelUtil.createOpNode("host=primary/system-property=model-persistence-test", ADD); op.get(VALUE).set("test"); testHostOperation(op, Host.PRIMARY, Host.PRIMARY); op = ModelUtil.createOpNode("host=primary/system-property=model-persistence-test", REMOVE); testHostOperation(op, Host.PRIMARY, Host.PRIMARY); op = ModelUtil.createOpNode("host=secondary/system-property=model-persistence-test", ADD); op.get(VALUE).set("test"); testHostOperation(op, Host.PRIMARY, Host.SECONDARY); op = ModelUtil.createOpNode("host=secondary/system-property=model-persistence-test", REMOVE); testHostOperation(op, Host.PRIMARY, Host.SECONDARY); // using secondary HC op = ModelUtil.createOpNode("host=secondary/system-property=model-persistence-test", ADD); op.get(VALUE).set("test"); testHostOperation(op, Host.SECONDARY, Host.SECONDARY); op = ModelUtil.createOpNode("host=secondary/system-property=model-persistence-test", REMOVE); testHostOperation(op, Host.SECONDARY, Host.SECONDARY); } @Test public void testCompositeHostOperation() throws Exception { // test op on primary using primary controller ModelNode[] steps = new ModelNode[2]; steps[0] = ModelUtil.createOpNode("host=primary/system-property=model-persistence-test", ADD); steps[0].get(VALUE).set("test"); steps[1] = ModelUtil.createOpNode("host=primary/system-property=model-persistence-test", "write-attribute"); steps[1].get(NAME).set("value"); steps[1].get(VALUE).set("test2"); testHostOperation(ModelUtil.createCompositeNode(steps),Host.PRIMARY, Host.PRIMARY); ModelNode op = ModelUtil.createOpNode("host=primary/system-property=model-persistence-test", REMOVE); testHostOperation(op,Host.PRIMARY, Host.PRIMARY); // test op on secondary using primary controller steps[0] = ModelUtil.createOpNode("host=secondary/system-property=model-persistence-test", ADD); steps[0].get(VALUE).set("test"); steps[1] = ModelUtil.createOpNode("host=secondary/system-property=model-persistence-test", "write-attribute"); steps[1].get(NAME).set("value"); steps[1].get(VALUE).set("test2"); testHostOperation(ModelUtil.createCompositeNode(steps),Host.PRIMARY, Host.SECONDARY); op = ModelUtil.createOpNode("host=secondary/system-property=model-persistence-test", REMOVE); testHostOperation(op,Host.PRIMARY, Host.SECONDARY); // test op on secondary using secondary controller steps[0] = ModelUtil.createOpNode("host=secondary/system-property=model-persistence-test", ADD); steps[0].get(VALUE).set("test"); steps[1] = ModelUtil.createOpNode("host=secondary/system-property=model-persistence-test", "write-attribute"); steps[1].get(NAME).set("value"); steps[1].get(VALUE).set("test2"); testHostOperation(ModelUtil.createCompositeNode(steps), Host.SECONDARY, Host.SECONDARY); op = ModelUtil.createOpNode("host=secondary/system-property=model-persistence-test", REMOVE); testHostOperation(op, Host.SECONDARY, Host.SECONDARY); } @Test public void testHostOperationRollback() throws Exception { DomainClient client = domainPrimaryLifecycleUtil.getDomainClient(); for (Host host : Host.values()) { CfgFileDescription lastDomainBackupDesc = getLatestBackup(domainCurrentCfgDir); CfgFileDescription lastPrimaryBackupDesc = getLatestBackup(primaryCurrentCfgDir); CfgFileDescription lastSecondaryBackupDesc = getLatestBackup(secondaryCurrentCfgDir); // execute operation so the model gets updated ModelNode op = host.equals(Host.PRIMARY) ? ModelUtil.createOpNode("host=primary/system-property=model-persistence-test", "add") : ModelUtil.createOpNode("host=secondary/system-property=model-persistence-test", "add") ; op.get(VALUE).set("test"); executeAndRollbackOperation(client, op); // check that the model has not been updated CfgFileDescription newDomainBackupDesc = getLatestBackup(domainCurrentCfgDir); CfgFileDescription newPrimaryBackupDesc = getLatestBackup(primaryCurrentCfgDir); CfgFileDescription newSecondaryBackupDesc = getLatestBackup(secondaryCurrentCfgDir); // check that the configs did not change Assert.assertTrue(lastDomainBackupDesc.version == newDomainBackupDesc.version); Assert.assertTrue(lastPrimaryBackupDesc.version == newPrimaryBackupDesc.version); Assert.assertTrue(lastSecondaryBackupDesc.version == newSecondaryBackupDesc.version); } } private void testHostOperation(ModelNode operation, Host controller, Host target) throws Exception { DomainClient client = controller.equals(Host.PRIMARY) ? domainPrimaryLifecycleUtil.getDomainClient() : domainSecondaryLifecycleUtil.getDomainClient(); CfgFileDescription lastDomainBackupDesc = getLatestBackup(domainCurrentCfgDir); CfgFileDescription lastPrimaryBackupDesc = getLatestBackup(primaryCurrentCfgDir); CfgFileDescription lastSecondaryBackupDesc = getLatestBackup(secondaryCurrentCfgDir); long lastDomainFileHash = domainLastCfgFile.exists() ? FileUtils.checksumCRC32(domainLastCfgFile) : -1; long lastPrimaryFileHash = primaryLastCfgFile.exists() ? FileUtils.checksumCRC32(primaryLastCfgFile) : -1; long lastSecondaryFileHash = secondaryLastCfgFile.exists() ? FileUtils.checksumCRC32(secondaryLastCfgFile) : -1; // execute operation so the model gets updated executeOperation(client, operation); // check that the automated snapshot of the domain has not been generated CfgFileDescription newDomainBackupDesc = getLatestBackup(domainCurrentCfgDir); Assert.assertTrue(lastDomainBackupDesc.version == newDomainBackupDesc.version); // check that only the appropriate host snapshot has been generated CfgFileDescription newPrimaryBackupDesc = getLatestBackup(primaryCurrentCfgDir); CfgFileDescription newSecondaryBackupDesc = getLatestBackup(secondaryCurrentCfgDir); if (target == Host.PRIMARY) { Assert.assertTrue(lastPrimaryBackupDesc.version == newPrimaryBackupDesc.version - 1); Assert.assertTrue(lastSecondaryBackupDesc.version == newSecondaryBackupDesc.version); Assert.assertTrue(lastPrimaryFileHash != FileUtils.checksumCRC32(primaryLastCfgFile)); Assert.assertTrue(lastSecondaryFileHash == FileUtils.checksumCRC32(secondaryLastCfgFile)); } else { Assert.assertTrue(lastPrimaryBackupDesc.version == newPrimaryBackupDesc.version); Assert.assertTrue(lastSecondaryBackupDesc.version == newSecondaryBackupDesc.version - 1); Assert.assertTrue(lastPrimaryFileHash == FileUtils.checksumCRC32(primaryLastCfgFile)); Assert.assertTrue(lastSecondaryFileHash != FileUtils.checksumCRC32(secondaryLastCfgFile)); } Assert.assertTrue(lastDomainBackupDesc.version == newDomainBackupDesc.version); Assert.assertTrue(lastDomainFileHash == FileUtils.checksumCRC32(domainLastCfgFile)); } @Test public void testTakeAndDeleteSnapshot() throws Exception { DomainClient client = domainPrimaryLifecycleUtil.getDomainClient(); // take snapshot ModelNode op = ModelUtil.createOpNode(null, "take-snapshot"); ModelNode result = executeOperation(client, op); // check that the snapshot file exists String snapshotFileName = result.asString(); File snapshotFile = new File(snapshotFileName); Assert.assertTrue(snapshotFile.exists()); // compare with current cfg long snapshotHash = FileUtils.checksumCRC32(snapshotFile); long lastHash = FileUtils.checksumCRC32(domainLastCfgFile); Assert.assertTrue(snapshotHash == lastHash); // delete snapshot op = ModelUtil.createOpNode(null, "delete-snapshot"); op.get("name").set(snapshotFile.getName()); executeOperation(client, op); // check that the file is deleted Assert.assertFalse("Snapshot file still exists.", snapshotFile.exists()); } private CfgFileDescription getLatestBackup(File dir) throws IOException { int lastVersion = 0; File lastFile = null; File[] children; if (dir.isDirectory() && (children = dir.listFiles()) != null) { for (File file : children) { String fileName = file.getName(); String[] nameParts = fileName.split("\\."); if (! (nameParts[0].contains(DOMAIN_NAME) || nameParts[0].contains(PRIMARY_NAME) || nameParts[0].contains(SECONDARY_NAME) )) { continue; } if (!nameParts[2].equals("xml")) { continue; } int version = Integer.valueOf(nameParts[1].substring(1)); if (version > lastVersion) { lastVersion = version; lastFile = file; } } } return new CfgFileDescription(lastVersion, lastFile, (lastFile != null) ? FileUtils.checksumCRC32(lastFile) : 0); } protected ModelNode executeOperation(DomainClient client, final ModelNode op) throws IOException, MgmtOperationException { return executeOperation(client, op, true); } protected ModelNode executeOperation(DomainClient client, final ModelNode op, boolean unwrapResult) throws IOException, MgmtOperationException { ModelNode ret = client.execute(op); if (!unwrapResult) { return ret; } if (!SUCCESS.equals(ret.get(OUTCOME).asString())) { throw new MgmtOperationException("Management operation failed: " + ret.get(FAILURE_DESCRIPTION), op, ret); } return ret.get(RESULT); } protected void executeAndRollbackOperation(DomainClient client, final ModelNode op) throws IOException, OperationFormatException { ModelNode addDeploymentOp = ModelUtil.createOpNode("deployment=malformedDeployment.war", "add"); addDeploymentOp.get("content").get(0).get("input-stream-index").set(0); DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder(); builder.setOperationName("deploy"); builder.addNode("deployment", "malformedDeployment.war"); ModelNode[] steps = new ModelNode[3]; steps[0] = op; steps[1] = addDeploymentOp; steps[2] = builder.buildRequest(); ModelNode compositeOp = ModelUtil.createCompositeNode(steps); OperationBuilder ob = new OperationBuilder(compositeOp, true); ob.addInputStream(new FileInputStream(getBrokenWar())); ModelNode ret = client.execute(ob.build()); Assert.assertFalse(SUCCESS.equals(ret.get(OUTCOME).asString())); } private static File getBrokenWar() { WebArchive war = ShrinkWrap.create(WebArchive.class, "malformedDeployment.war"); war.addClass(SimpleServlet.class); war.addAsWebInfResource(new StringAsset("Malformed"), "web.xml"); File brokenWar = new File(System.getProperty("java.io.tmpdir") + File.separator + "malformedDeployment.war"); brokenWar.deleteOnExit(); new ZipExporterImpl(war).exportTo(brokenWar, true); return brokenWar; } }
22,090
48.866817
148
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/suites/DeploymentOverlayServlet.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.test.integration.domain.suites; import java.io.IOException; import javax.naming.InitialContext; import javax.naming.NamingException; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author Stuart Douglas */ @WebServlet(urlPatterns = "/servlet") public class DeploymentOverlayServlet extends HttpServlet { @Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { try { final String result = (String) new InitialContext().lookup("java:comp//env/simpleString"); resp.getWriter().write(result); resp.getWriter().close(); } catch (NamingException e) { throw new RuntimeException(e); } } }
1,977
37.038462
125
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/suites/DomainTestSuite.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.test.integration.domain.suites; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; /** * Simple {@code Suite} test wrapper to start the domain only once for multiple * test cases using the same domain configuration. * * @author Emanuel Muckenhuber */ @RunWith(Suite.class) @Suite.SuiteClasses ({ DatasourceTestCase.class, DeploymentManagementTestCase.class, DeploymentOverlayTestCase.class, GlobalDirectoryDomainTestCase.class, JcaCCMRuntimeOnlyProfileOpsTestCase.class, ModelPersistenceTestCase.class, ReadEnvironmentVariablesTestCase.class }) public class DomainTestSuite { private static boolean initializedLocally = false; private static volatile DomainTestSupport support; // This can only be called from tests as part of this suite public static synchronized DomainTestSupport createSupport(final String testName) { if(support == null) { start(testName); } return support; } // This can only be called from tests as part of this suite public static synchronized void stopSupport() { if(! initializedLocally) { stop(); } } private static synchronized void start(final String name) { try { support = DomainTestSupport.createAndStartDefaultSupport(name); } catch (Exception e) { throw new RuntimeException(e); } } private static synchronized void stop() { if(support != null) { support.stop(); support = null; } } @BeforeClass public static synchronized void beforeClass() { initializedLocally = true; start(DomainTestSuite.class.getSimpleName()); } @AfterClass public static synchronized void afterClass() { stop(); } }
3,064
30.927083
87
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/suites/JcaCCMRuntimeOnlyProfileOpsTestCase.java
/* * * Copyright 2017 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.test.integration.domain.suites; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_GROUPS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.dmr.ModelNode; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * Test cached-connection-manager runtime-only ops registered against domain profile resources */ public class JcaCCMRuntimeOnlyProfileOpsTestCase { private static final PathAddress PRIMARY = PathAddress.pathAddress(ModelDescriptionConstants.HOST, "primary"); private static final PathAddress SECONDARY = PathAddress.pathAddress(ModelDescriptionConstants.HOST, "secondary"); private static final PathElement MAIN_ONE = PathElement.pathElement("server", "main-one"); private static final PathElement MAIN_THREE = PathElement.pathElement("server", "main-three"); private static final PathAddress PROFILE = PathAddress.pathAddress("profile", "default"); private static final PathElement SUBSYSTEM = PathElement.pathElement("subsystem", "jca"); private static final PathElement CCM = PathElement.pathElement("cached-connection-manager", "cached-connection-manager"); private static DomainTestSupport testSupport; private static ModelControllerClient client; @BeforeClass public static void setupDomain() throws Exception { testSupport = DomainTestSuite.createSupport(JcaCCMRuntimeOnlyProfileOpsTestCase.class.getSimpleName()); client = testSupport.getDomainPrimaryLifecycleUtil().getDomainClient(); } @AfterClass public static void tearDownDomain() throws Exception { client.close(); client = null; testSupport = null; DomainTestSuite.stopSupport(); } @Test public void testGetNumberOfConnections() throws IOException { final String opName = "get-number-of-connections"; ModelNode op = Util.createEmptyOperation(opName, PROFILE.append(SUBSYSTEM).append(CCM)); ModelNode response = executeOp(op, SUCCESS); assertFalse(response.toString(), response.hasDefined(RESULT)); // handler doesn't set a result on profile assertTrue(response.toString(), response.hasDefined(SERVER_GROUPS, "main-server-group", "host", "primary", "main-one", "response", "result", "TX")); assertTrue(response.toString(), response.hasDefined(SERVER_GROUPS, "main-server-group", "host", "primary", "main-one", "response", "result", "NonTX")); assertEquals(0, response.get(SERVER_GROUPS, "main-server-group", "host", "primary", "main-one", "response", "result", "TX").asInt()); assertEquals(0, response.get(SERVER_GROUPS, "main-server-group", "host", "primary", "main-one", "response", "result", "NonTX").asInt()); assertTrue(response.toString(), response.hasDefined(SERVER_GROUPS, "main-server-group", "host", "secondary", "main-three", "response", "result", "TX")); assertTrue(response.toString(), response.hasDefined(SERVER_GROUPS, "main-server-group", "host", "secondary", "main-three", "response", "result", "NonTX")); assertEquals(0, response.get(SERVER_GROUPS, "main-server-group", "host", "secondary", "main-three", "response", "result", "TX").asInt()); assertEquals(0, response.get(SERVER_GROUPS, "main-server-group", "host", "secondary", "main-three", "response", "result", "NonTX").asInt()); // Now check direct invocation on servers op = Util.createEmptyOperation(opName, PRIMARY.append(MAIN_ONE).append(SUBSYSTEM).append(CCM)); response = executeOp(op, SUCCESS); assertEquals(0, response.get(RESULT).get("TX").asInt()); assertEquals(0, response.get(RESULT).get("NonTX").asInt()); op = Util.createEmptyOperation(opName, SECONDARY.append(MAIN_THREE).append(SUBSYSTEM).append(CCM)); response = executeOp(op, SUCCESS); assertEquals(0, response.get(RESULT).get("TX").asInt()); assertEquals(0, response.get(RESULT).get("NonTX").asInt()); } @Test public void testListConnections() throws IOException { final String opName = "list-connections"; ModelNode op = Util.createEmptyOperation(opName, PROFILE.append(SUBSYSTEM).append(CCM)); ModelNode response = executeOp(op, SUCCESS); assertFalse(response.toString(), response.hasDefined(RESULT)); // handler doesn't set a result on profile assertTrue(response.toString(), response.has(SERVER_GROUPS, "main-server-group", "host", "primary", "main-one", "response", "result", "TX")); assertTrue(response.toString(), response.has(SERVER_GROUPS, "main-server-group", "host", "primary", "main-one", "response", "result", "NonTX")); assertTrue(response.toString(), response.has(SERVER_GROUPS, "main-server-group", "host", "secondary", "main-three", "response", "result", "TX")); assertTrue(response.toString(), response.has(SERVER_GROUPS, "main-server-group", "host", "secondary", "main-three", "response", "result", "NonTX")); // Now check direct invocation on servers op = Util.createEmptyOperation(opName, PRIMARY.append(MAIN_ONE).append(SUBSYSTEM).append(CCM)); response = executeOp(op, SUCCESS); assertTrue(response.has(RESULT, "TX")); assertTrue(response.has(RESULT, "NonTX")); op = Util.createEmptyOperation(opName, SECONDARY.append(MAIN_THREE).append(SUBSYSTEM).append(CCM)); response = executeOp(op, SUCCESS); assertTrue(response.has(RESULT, "TX")); assertTrue(response.has(RESULT, "NonTX")); } private static ModelNode executeOp(ModelNode op, String outcome) throws IOException { ModelNode response = client.execute(op); assertTrue(response.toString(), response.hasDefined(OUTCOME)); assertEquals(response.toString(), outcome, response.get(OUTCOME).asString()); return response; } }
7,233
53.390977
163
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/suites/GlobalDirectoryDeployment.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.domain.suites; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; /** * @author Tomas Terem ([email protected]) **/ @Path("global-directory") public class GlobalDirectoryDeployment { @Path("/library") @GET @Produces("text/plain") public String get() { GlobalDirectoryLibrary globalDirectoryLibrary = new GlobalDirectoryLibraryImpl(); return globalDirectoryLibrary.get(); } }
1,510
34.97619
89
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/suites/CLITestSuite.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.test.integration.domain.suites; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import org.jboss.as.test.integration.domain.management.cli.DataSourceTestCase; import org.jboss.as.test.integration.domain.management.cli.DeployAllServerGroupsTestCase; import org.jboss.as.test.integration.domain.management.cli.DeploySingleServerGroupTestCase; import org.jboss.as.test.integration.domain.management.cli.DomainDeployWithRuntimeNameTestCase; import org.jboss.as.test.integration.domain.management.cli.DomainDeploymentOverlayTestCase; import org.jboss.as.test.integration.domain.management.cli.JmsTestCase; import org.jboss.as.test.integration.domain.management.cli.CloneProfileTestCase; import org.jboss.as.test.integration.domain.management.cli.RolloutPlanTestCase; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; /** * * @author Dominik Pospisil <[email protected]> */ @RunWith(Suite.class) @Suite.SuiteClasses({ JmsTestCase.class, DeployAllServerGroupsTestCase.class, DeploySingleServerGroupTestCase.class, DomainDeploymentOverlayTestCase.class, RolloutPlanTestCase.class, DomainDeployWithRuntimeNameTestCase.class, DataSourceTestCase.class, CloneProfileTestCase.class }) public class CLITestSuite { public static final Map<String, String[]> hostServers = new HashMap<String, String[]>(); public static final Map<String, String> hostAddresses = new HashMap<String, String>(); public static final Map<String, String[]> serverGroups = new HashMap<String, String[]>(); public static final Map<String, Integer> portOffsets = new HashMap<String, Integer>(); public static final Map<String, String[]> serverProfiles = new HashMap<String, String[]>(); public static final Map<String, Boolean> serverStatus = new HashMap<String, Boolean>(); private static boolean initializedLocally = false; private static volatile DomainTestSupport support; // This can only be called from tests as part of this suite public static synchronized DomainTestSupport createSupport(final String testName) { if(support == null) { start(testName); } return support; } // This can only be called from tests as part of this suite public static synchronized void stopSupport() { if(! initializedLocally) { stop(); } } private static synchronized void start(final String name) { try { support = DomainTestSupport.createAndStartDefaultSupport(name); } catch (Exception e) { throw new RuntimeException(e); } } private static synchronized void stop() { if(support != null) { support.stop(); support = null; } } @BeforeClass public static void initSuite() throws Exception { initializedLocally = true; start(CLITestSuite.class.getSimpleName()); hostServers.put("primary", new String[]{"main-one", "main-two", "other-one"}); hostServers.put("secondary", new String[]{"main-three", "main-four", "other-two"}); hostAddresses.put("primary", DomainTestSupport.primaryAddress); hostAddresses.put("secondary", DomainTestSupport.secondaryAddress); serverGroups.put("main-server-group", new String[]{"main-one", "main-two", "main-three", "main-four"}); serverGroups.put("other-server-group", new String[]{"other-one", "other-two"}); serverProfiles.put("default", new String[]{"main-server-group"}); serverProfiles.put("ha", new String[]{"other-server-group"}); portOffsets.put("main-one", 0); portOffsets.put("main-two", 150); portOffsets.put("other-one", 250); portOffsets.put("main-three", 350); portOffsets.put("main-four", 450); portOffsets.put("other-two", 550); serverStatus.put("main-one", true); serverStatus.put("main-two", false); serverStatus.put("main-three", true); serverStatus.put("main-four", false); serverStatus.put("other-one", false); serverStatus.put("other-two", true); } @AfterClass public static void tearDownSuite() { stop(); } public static void addServer(String serverName, String hostName, String groupName, String profileName, int portOffset, boolean status) { LinkedList<String> hservers = new LinkedList<String>(Arrays.asList(hostServers.get(hostName))); hservers.add(serverName); hostServers.put(hostName, hservers.toArray(new String[hservers.size()])); LinkedList<String> gservers = new LinkedList<String>(); if (serverGroups.containsKey(groupName)) { gservers.addAll(Arrays.asList(serverGroups.get(groupName))); } gservers.add(serverName); serverGroups.put(groupName, gservers.toArray(new String[gservers.size()])); LinkedList<String> pgroups = new LinkedList<String>(); if (serverProfiles.containsKey(profileName)) { pgroups.addAll(Arrays.asList(serverProfiles.get(profileName))); } pgroups.add(groupName); serverProfiles.put(profileName, pgroups.toArray(new String[pgroups.size()])); portOffsets.put(serverName, portOffset); serverStatus.put(serverName, status); } public static String getServerHost(String serverName) { for(Map.Entry<String,String[]> entry : hostServers.entrySet()) { if (Arrays.asList(entry.getValue()).contains(serverName)) { return entry.getKey(); } } return null; } }
6,850
39.779762
140
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/suites/DatasourceTestCase.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.test.integration.domain.suites; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST; 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.SERVER; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.test.integration.domain.management.util.DomainTestSupport.validateResponse; import java.io.IOException; import org.jboss.as.controller.client.helpers.domain.DomainClient; import org.jboss.as.test.integration.domain.management.util.DomainLifecycleUtil; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.dmr.ModelNode; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * Basic tests of datasource support in a managed domain. * * @author Brian Stansberry (c) 2012 Red Hat Inc. */ public class DatasourceTestCase { private static DomainTestSupport testSupport; private static DomainLifecycleUtil domainPrimaryLifecycleUtil; private static DomainLifecycleUtil domainSecondaryLifecycleUtil; private static final ModelNode ROOT_ADDRESS = new ModelNode().setEmptyList(); private static final ModelNode PRIMARY_ROOT_ADDRESS = new ModelNode().add(HOST, "primary"); private static final ModelNode SECONDARY_ROOT_ADDRESS = new ModelNode().add(HOST, "secondary"); private static final ModelNode MAIN_RUNNING_SERVER_ADDRESS = new ModelNode().add(HOST, "primary").add(SERVER, "main-one"); private static final ModelNode MAIN_RUNNING_SERVER_DS_ADDRESS = new ModelNode().add(HOST, "primary") .add(SERVER, "main-one").add(SUBSYSTEM, "datasources").add("data-source", "ExampleDS"); static { ROOT_ADDRESS.protect(); PRIMARY_ROOT_ADDRESS.protect(); SECONDARY_ROOT_ADDRESS.protect(); MAIN_RUNNING_SERVER_ADDRESS.protect(); MAIN_RUNNING_SERVER_DS_ADDRESS.protect(); } @BeforeClass public static void setupDomain() throws Exception { testSupport = DomainTestSuite.createSupport(DatasourceTestCase.class.getSimpleName()); domainPrimaryLifecycleUtil = testSupport.getDomainPrimaryLifecycleUtil(); domainSecondaryLifecycleUtil = testSupport.getDomainSecondaryLifecycleUtil(); } @AfterClass public static void tearDownDomain() throws Exception { testSupport = null; domainPrimaryLifecycleUtil = null; domainSecondaryLifecycleUtil = null; DomainTestSuite.stopSupport(); } private DomainClient primaryClient; private DomainClient secondaryClient; @Before public void setup() throws Exception { primaryClient = domainPrimaryLifecycleUtil.getDomainClient(); secondaryClient = domainSecondaryLifecycleUtil.getDomainClient(); } @Test public void testDatasourceConnection() throws IOException { // AS7-6062 -- validate that ExampleDS works on a domain server ModelNode response = primaryClient.execute(getEmptyOperation("test-connection-in-pool", MAIN_RUNNING_SERVER_DS_ADDRESS)); validateResponse(response); } private static ModelNode getEmptyOperation(String operationName, ModelNode address) { ModelNode op = new ModelNode(); op.get(OP).set(operationName); if (address != null) { op.get(OP_ADDR).set(address); } else { // Just establish the standard structure; caller can fill in address later op.get(OP_ADDR).setEmptyList(); } return op; } }
4,809
41.192982
129
java
null
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/suites/GlobalDirectoryLibraryImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.domain.suites; /** * @author Tomas Terem ([email protected]) **/ public class GlobalDirectoryLibraryImpl implements GlobalDirectoryLibrary { private String s1 = "HELLO WORLD"; public String get() { return s1; } }
1,299
36.142857
75
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/DomainAdjuster.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, 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.test.integration.domain.mixed; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADDRESS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.AUTO_START; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CHILD_TYPE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXTENSION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROFILE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_CHILDREN_NAMES_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_CONFIG; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_GROUP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING_GROUP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SYSTEM_PROPERTY; import static org.jboss.as.test.integration.domain.management.util.DomainTestUtils.executeForResult; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.client.helpers.domain.DomainClient; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.domain.management.util.DomainTestUtils; import org.jboss.as.test.integration.domain.mixed.eap740.DomainAdjuster740; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; import org.junit.Assert; /** * Adjusts the domain configuration for the legacy server version. The default implementation trims down the domain * model to only include the following profiles, socket-binding-groups and server-groups * <uL> * <li>{@code /profile=full-ha}</li> * <li>{@code /socket-binding-group=full-ha-sockets}</li> * <li>{@code /server-group=other-server-group}</li> * <li>{@code /server-group=main-server-group}</li> * </uL> * Subclasses can then further execute operations to put the model in a state which can be transformed to a legacy * version. * * @author <a href="mailto:[email protected]">Kabir Khan</a> */ public class DomainAdjuster { private final String MAIN_SERVER_GROUP = "main-server-group"; private final String OTHER_SERVER_GROUP = "other-server-group"; private static final Set<String> UNUSED_SERVER_GROUP_ATTRIBUTES = new HashSet<>(Arrays.asList("management-subsystem-endpoint", "deployment", "deployment-overlay", "jvm", "system-property")); static void adjustForVersion(final DomainClient client, final Version.AsVersion asVersion, final String profile, final boolean withPrimaryServers) throws Exception { final DomainAdjuster adjuster; switch (asVersion) { case EAP_7_4_0: adjuster = new DomainAdjuster740(); break; default: adjuster = new DomainAdjuster(); } adjuster.adjust(client, profile, withPrimaryServers); } final void adjust(final DomainClient client, String profile, boolean withPrimaryServers) throws Exception { //Trim it down so we have only //profile=full-ha, //the main-server-group and other-server-group //socket-binding-group = full-ha-sockets final List<String> allProfiles = getAllChildrenOfType(client, PathAddress.EMPTY_ADDRESS, PROFILE); final ModelNode serverGroup = removeServerGroups(client, profile); for (String profileName : allProfiles) { if (profile.equals(profileName)) { continue; } removeProfile(client, profileName); } final String socketBindingGroup = serverGroup.get(SOCKET_BINDING_GROUP).asString(); removeUnusedSocketBindingGroups(client, socketBindingGroup); removeIpv4SystemProperty(client); // We don't want any standard host-excludes as the tests are meant to see what happens // with the current configs on legacy secondaries removeHostExcludes(client); // Mixed Domain tests always use the full build instead of alternating between ee-dist and dist. If the DC is not an EAP server, we need to remove here // the pre-configured extensions provided by WildFly full build to adjust the current domain to work with a node running EAP which does not contain // those extensions. // We remove here these extensions and subsystems configured by default if they are in the current configuration, this makes this code capable to work for wildfly and EAP final PathAddress profileAddress = PathAddress.pathAddress(PROFILE, profile); removeSubsystemExtensionIfExist(client, profileAddress.append(SUBSYSTEM, "microprofile-jwt-smallrye"), PathAddress.pathAddress(EXTENSION, "org.wildfly.extension.microprofile.jwt-smallrye")); removeSubsystemExtensionIfExist(client, profileAddress.append(SUBSYSTEM, "microprofile-config-smallrye"), PathAddress.pathAddress(EXTENSION, "org.wildfly.extension.microprofile.config-smallrye")); removeSubsystemExtensionIfExist(client, profileAddress.append(SUBSYSTEM, "opentelemetry"), PathAddress.pathAddress(EXTENSION, "org.wildfly.extension.opentelemetry")); //Version specific changes final List<ModelNode> adjustments = adjustForVersion(client, PathAddress.pathAddress(PROFILE, profile), withPrimaryServers); if (withPrimaryServers) { adjustments.addAll(reconfigureServers()); } applyVersionAdjustments(client, adjustments); } private void removeIpv4SystemProperty(final DomainClient client) throws Exception { //The standard domain configuration contains -Djava.net.preferIPv4Stack=true, remove that DomainTestUtils.executeForResult( Util.createRemoveOperation(PathAddress.pathAddress(SYSTEM_PROPERTY, "java.net.preferIPv4Stack")), client); } private void removeHostExcludes(DomainClient client) throws Exception { final List<String> allHostExcludes = getAllChildrenOfType(client, PathAddress.EMPTY_ADDRESS, "host-exclude"); for (String exclude : allHostExcludes) { DomainTestUtils.executeForResult( Util.createRemoveOperation(PathAddress.pathAddress("host-exclude", exclude)), client); } } /** * Adjust the Domain configuration to work properly with the expected secondary. * * @param client The domain client. * @param profileAddress The address of the profile that is being used. * @param withPrimaryServer Whether the Dc has managed servers. * @return The List of Operations that need to be executed to adjust the domain. * @throws Exception */ protected List<ModelNode> adjustForVersion(final DomainClient client, final PathAddress profileAddress, final boolean withPrimaryServer) throws Exception { return Collections.emptyList(); } private void removeProfile(final DomainClient client, final String name) throws Exception { executeForResult(Util.createRemoveOperation(PathAddress.pathAddress(PROFILE, name)), client); } private List<String> getAllChildrenOfType(final DomainClient client, final PathAddress parent, final String type) throws Exception { final ModelNode op = Util.createEmptyOperation(READ_CHILDREN_NAMES_OPERATION, parent); op.get(CHILD_TYPE).set(type); final ModelNode result = executeForResult(op, client); final List<String> childNames = new ArrayList<>(); for (ModelNode nameNode : result.asList()) { childNames.add(nameNode.asString()); } return childNames; } private ModelNode removeServerGroups(final DomainClient client, String profile) throws Exception { final ModelNode op = Util.createEmptyOperation(READ_RESOURCE_OPERATION, PathAddress.pathAddress(PathElement.pathElement(SERVER_GROUP))); final ModelNode results = executeForResult(op, client); ModelNode group = null; for (ModelNode result : results.asList()) { String groupName = PathAddress.pathAddress(result.get(ADDRESS)).getLastElement().getValue(); if (OTHER_SERVER_GROUP.equals(groupName)) { group = result.get(RESULT); } else if (MAIN_SERVER_GROUP.equals(groupName)) { //We'll update it afterwards because we have servers using it now } else { ModelNode remove = Util.createRemoveOperation(PathAddress.pathAddress(result.get(ADDRESS))); executeForResult(remove, client); } } Assert.assertNotNull(group); //Update main-server-group as a copy of other-server-group (cuts down on the amount of profiles needed) final PathAddress mainServerGroupAddress = PathAddress.pathAddress(SERVER_GROUP, MAIN_SERVER_GROUP); for (Property property : group.asPropertyList()) { ModelNode updateMain; if (!UNUSED_SERVER_GROUP_ATTRIBUTES.contains(property.getName())) { if (PROFILE.equals(property.getName())) { updateMain = Util.getWriteAttributeOperation(mainServerGroupAddress, property.getName(), profile); } else { if (property.getValue().isDefined()) { updateMain = Util.getWriteAttributeOperation(mainServerGroupAddress, property.getName(), property.getValue()); } else { updateMain = Util.getUndefineAttributeOperation(mainServerGroupAddress, property.getName()); } } executeForResult(updateMain, client); } } final PathAddress otherServerGroupAddress = PathAddress.pathAddress(SERVER_GROUP, OTHER_SERVER_GROUP); for (Property property : group.asPropertyList()) { ModelNode updateOther; if (!UNUSED_SERVER_GROUP_ATTRIBUTES.contains(property.getName())) { if (PROFILE.equals(property.getName())) { updateOther = Util.getWriteAttributeOperation(otherServerGroupAddress, property.getName(), profile); } else { if (property.getValue().isDefined()) { updateOther = Util.getWriteAttributeOperation(mainServerGroupAddress, property.getName(), property.getValue()); } else { updateOther = Util.getUndefineAttributeOperation(mainServerGroupAddress, property.getName()); } } executeForResult(updateOther, client); } } return group; } private void removeUnusedSocketBindingGroups(final DomainClient client, final String keepGroup) throws Exception { final List<String> allGroups = getAllChildrenOfType(client, PathAddress.EMPTY_ADDRESS, SOCKET_BINDING_GROUP); for (String groupName : allGroups) { if (!keepGroup.equals(groupName)) { ModelNode remove = Util.createRemoveOperation(PathAddress.pathAddress(PathAddress.pathAddress(SOCKET_BINDING_GROUP, groupName))); executeForResult(remove, client); } } } /** * Returns the class name of the http auth module. This uses the wildfly version. Adjusters for AS 7/EAP 6 should * override this method and return * {@code org.wildfly.extension.undertow.security.jaspi.modules.HTTPSchemeServerAuthModule} * * @return the auth module */ protected String getJaspiTestAuthModuleName() { return "org.wildfly.extension.undertow.security.jaspi.modules.HTTPSchemeServerAuthModule"; } private void applyVersionAdjustments(DomainClient client, List<ModelNode> operations) throws Exception { if (operations.isEmpty()) { return; } for (ModelNode op : operations) { DomainTestUtils.executeForResult(op, client); } } private Collection<? extends ModelNode> reconfigureServers() { final List<ModelNode> list = new ArrayList<>(); //Reconfigure primary servers final PathAddress primaryHostAddress = PathAddress.pathAddress(HOST, "primary"); list.add(Util.getWriteAttributeOperation(primaryHostAddress.append(SERVER_CONFIG, "server-one"), AUTO_START, true)); list.add(Util.getWriteAttributeOperation(primaryHostAddress.append(SERVER_CONFIG, "server-one"), ModelDescriptionConstants.GROUP, "main-server-group")); list.add(Util.getUndefineAttributeOperation(primaryHostAddress.append(SERVER_CONFIG, "server-one"), ModelDescriptionConstants.SOCKET_BINDING_PORT_OFFSET)); list.add(Util.getWriteAttributeOperation(primaryHostAddress.append(SERVER_CONFIG, "server-two"), AUTO_START, true)); list.add(Util.getWriteAttributeOperation(primaryHostAddress.append(SERVER_CONFIG, "server-two"), ModelDescriptionConstants.SOCKET_BINDING_PORT_OFFSET, 100)); return list; } private void removeSubsystemExtensionIfExist(DomainClient client, PathAddress subsystem, PathAddress extension) throws IOException { try { DomainTestUtils.executeForResult(Util.getReadResourceOperation(subsystem), client); DomainTestUtils.executeForResult(Util.createRemoveOperation(subsystem), client); } catch (MgmtOperationException e) { // ignored, the subsystem does not exist } try { DomainTestUtils.executeForResult(Util.getReadResourceOperation(extension), client); DomainTestUtils.executeForResult(Util.createRemoveOperation(extension), client); } catch (MgmtOperationException e) { // ignored, the extension does not exist } } }
15,595
52.965398
204
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/MixedDomainTestSupport.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.domain.mixed; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.concurrent.TimeUnit; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.client.helpers.domain.DomainClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.domain.management.util.DomainLifecycleUtil; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.integration.domain.management.util.DomainTestUtils; import org.jboss.as.test.integration.domain.management.util.WildFlyManagedConfiguration; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.junit.Assert; import org.junit.Assume; /** * @author <a href="[email protected]">Kabir Khan</a> */ public class MixedDomainTestSupport extends DomainTestSupport { public static final String STANDARD_DOMAIN_CONFIG = "copied-primary-config/domain.xml"; private static final String JBOSS_DOMAIN_SERVER_ARGS = "jboss.domain.server.args"; private static final int TEST_VM_VERSION; static { String spec = System.getProperty("java.specification.version"); TEST_VM_VERSION = "1.8".equals(spec) ? 8 : Integer.parseInt(spec); } private final Version.AsVersion version; private final boolean adjustDomain; private final boolean legacyConfig; private final boolean withPrimaryServers; private final String profile; private MixedDomainTestSupport(Version.AsVersion version, String testClass, String domainConfig, String primaryConfig, String secondaryConfig, String jbossHome, String profile, boolean adjustDomain, boolean legacyConfig, boolean withPrimaryServers) throws Exception { super(testClass, domainConfig, primaryConfig, secondaryConfig, configWithDisabledAsserts(null), configWithDisabledAsserts(jbossHome)); this.version = version; this.adjustDomain = adjustDomain; this.legacyConfig = legacyConfig; this.withPrimaryServers = withPrimaryServers; this.profile = profile; configureSecondaryJavaHome(); } private static WildFlyManagedConfiguration configWithDisabledAsserts(String jbossHome){ WildFlyManagedConfiguration config = new WildFlyManagedConfiguration(jbossHome); config.setEnableAssertions(false); return config; } public static MixedDomainTestSupport create(String testClass, Version.AsVersion version) throws Exception { return create(testClass, version, STANDARD_DOMAIN_CONFIG, "primary-config/host.xml", "secondary-config/host-secondary.xml", "full-ha", true, false, false); } public static MixedDomainTestSupport create(String testClass, Version.AsVersion version, String domainConfig, boolean adjustDomain, boolean legacyConfig) throws Exception { return create(testClass, version, domainConfig, "primary-config/host.xml", "secondary-config/host-secondary.xml", "full-ha", adjustDomain, legacyConfig, false); } public static MixedDomainTestSupport create(String testClass, Version.AsVersion version, String domainConfig, String profile, boolean adjustDomain, boolean legacyConfig, boolean withPrimaryServers) throws Exception { return create(testClass, version, domainConfig, "primary-config/host.xml", "secondary-config/host-secondary.xml", profile, adjustDomain, legacyConfig, withPrimaryServers); } public static MixedDomainTestSupport create(String testClass, Version.AsVersion version, String domainConfig, String primaryConfig, String secondaryConfig, String profile, boolean adjustDomain, boolean legacyConfig, boolean withPrimaryServers) throws Exception { final File dir = OldVersionCopier.getOldVersionDir(version).toFile(); return new MixedDomainTestSupport(version, testClass, domainConfig, primaryConfig, secondaryConfig, dir.getAbsolutePath(), profile, adjustDomain, legacyConfig, withPrimaryServers); } public static MixedDomainTestSupport create(String testClass, Version.AsVersion version, String domainConfig, String primaryConfig, String secondaryConfig, boolean adjustDomain, boolean legacyConfig) throws Exception { final File dir = OldVersionCopier.getOldVersionDir(version).toFile(); return new MixedDomainTestSupport(version, testClass, domainConfig, primaryConfig, secondaryConfig, dir.getAbsolutePath(), "full-ha", adjustDomain, legacyConfig, false); } public void start() { if (adjustDomain) { startAndAdjust(); } else { super.start(); } if (!legacyConfig) { // The non-legacy config tests assume host=secondary/server=server-one is auto-start and running startSecondaryServer(); } } private void startSecondaryServer() { DomainClient client = getDomainPrimaryLifecycleUtil().getDomainClient(); PathElement hostElement = PathElement.pathElement("host", "secondary"); try { PathAddress pa = PathAddress.pathAddress(hostElement, PathElement.pathElement("server-config", "server-one")); DomainTestUtils.executeForResult(Util.getUndefineAttributeOperation(pa, "auto-start"), client); DomainTestUtils.executeForResult(Util.createEmptyOperation("start", pa), client); } catch (IOException | MgmtOperationException e) { throw new RuntimeException(e); } long timeout = TimeoutUtil.adjust(20000); long expired = System.currentTimeMillis() + timeout; ModelNode op = Util.getReadAttributeOperation(PathAddress.pathAddress(hostElement, PathElement.pathElement("server", "server-one")), "server-state"); do { try { ModelNode state = DomainTestUtils.executeForResult(op, client); if ("running".equalsIgnoreCase(state.asString())) { return; } } catch (IOException | MgmtOperationException e) { // ignore and try again } try { TimeUnit.MILLISECONDS.sleep(250L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); Assert.fail(); } } while (System.currentTimeMillis() < expired); Assert.fail("Secondary server-one did not start within " + timeout + " ms"); } private void configureSecondaryJavaHome() { // Look for properties pointing to a java home to use for the legacy host. // Look for homes for the max JVM version the host can handle, working back to the min it can handle. // We could start with the oldest and work forward, but that would likely result in all versions testing // against the oldest VM. Starting with the newest will increase coverage by increasing the probability // of different VM versions being used across the overall set of legacy host versions. String javaHome = null; for (int i = Math.min(version.getMaxVMVersion(), TEST_VM_VERSION - 1); i >= version.getMinVMVersion() && javaHome == null; i--) { javaHome = System.getProperty("jboss.test.legacy.host.java" + i + ".home"); } if (javaHome != null) { WildFlyManagedConfiguration cfg = getDomainSecondaryConfiguration(); cfg.setJavaHome(javaHome); cfg.setControllerJavaHome(javaHome); System.out.println("Set legacy host controller to use " + javaHome + " as JAVA_HOME"); } else { // Ignore the test if the secondary cannot run using the current VM version Assume.assumeTrue(TEST_VM_VERSION <= version.getMaxVMVersion()); Assume.assumeTrue(TEST_VM_VERSION >= version.getMinVMVersion()); } } private void startAndAdjust() { String jbossDomainServerArgsValue = null; try { //Start the primary in admin only and reconfigure the domain with what //we want to test in the mixed domain and have the DomainAdjuster //strip down the domain model to something more workable. The domain //adjusters will also make adjustments for the legacy version being //tested. DomainLifecycleUtil primaryUtil = getDomainPrimaryLifecycleUtil(); primaryUtil.getConfiguration().setAdminOnly(true); //primaryUtil.getConfiguration().addHostCommandLineProperty("-agentlib:jdwp=transport=dt_socket,address=8787,server=y,suspend=y"); primaryUtil.start(); if (legacyConfig) { LegacyConfigAdjuster.adjustForVersion(primaryUtil.getDomainClient(), version); } else { DomainAdjuster.adjustForVersion(primaryUtil.getDomainClient(), version, profile, withPrimaryServers); } //Now reload the primary in normal mode primaryUtil.executeAwaitConnectionClosed(Util.createEmptyOperation("reload", PathAddress.pathAddress(HOST, "primary"))); primaryUtil.connect(); primaryUtil.awaitHostController(System.currentTimeMillis()); //Start the secondary hosts DomainLifecycleUtil secondaryUtil = getDomainSecondaryLifecycleUtil(); if (secondaryUtil != null) { //secondaryUtil.getConfiguration().addHostCommandLineProperty("-agentlib:jdwp=transport=dt_socket,address=8787,server=y,suspend=y"); secondaryUtil.start(); } } catch (Exception e) { throw new RuntimeException(e); } } static String copyDomainFile() { final Path originalDomainXml = loadFile("target", "wildfly", "domain", "configuration", "domain.xml"); return copyDomainFile(originalDomainXml); } static String copyDomainFile(final Path originalDomainXml) { final Path targetDirectory = createDirectory("target", "test-classes", "copied-primary-config"); final Path copiedDomainXml = targetDirectory.resolve("domain.xml"); try { Files.copy(originalDomainXml, copiedDomainXml, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new RuntimeException(e); } return STANDARD_DOMAIN_CONFIG; } static Path loadLegacyDomainXml(Version.AsVersion version) { String number = version.getVersion().replace('.', '-'); final String fileName; switch (version.basename) { case Version.EAP: fileName = "eap-" + number + ".xml"; break; case Version.WILDFLY: default: fileName = "wildfly-" + number + ".xml"; } return loadFile("..", "integration", "manualmode", "src", "test", "resources", "legacy-configs", "domain", fileName); } private static Path loadFile(String first, String... parts) { final Path p = Paths.get(first, parts); Assert.assertTrue(p.toAbsolutePath() + " does not exist", Files.exists(p)); return p; } private static Path createDirectory(String first, String... parts) { Path p = Paths.get(first, parts); try { Path dir = Files.createDirectories(p); Assert.assertTrue(Files.exists(dir)); return dir; } catch (IOException e) { throw new RuntimeException(e); } } }
13,180
46.413669
159
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/LegacyConfigTest.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.test.integration.domain.mixed; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.helpers.domain.DomainClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.integration.domain.management.util.DomainTestUtils; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Tests secondary behavior in a mixed domain when the primary has booted with a legacy domain.xml. * * @author Brian Stansberry */ public abstract class LegacyConfigTest { private static final PathElement SECONDARY = PathElement.pathElement("host", "secondary"); private static final PathAddress TEST_SERVER_CONFIG = PathAddress.pathAddress(SECONDARY, PathElement.pathElement("server-config", "legacy-server")); private static final PathAddress TEST_SERVER = PathAddress.pathAddress(SECONDARY, PathElement.pathElement("server", "legacy-server")); private static final PathAddress TEST_SERVER_GROUP = PathAddress.pathAddress("server-group", "legacy-group"); private static final Map<String, String> STD_PROFILES; static { final Map<String, String> stdProfiles = new HashMap<>(); stdProfiles.put("default", "standard-sockets"); stdProfiles.put("ha", "ha-sockets"); stdProfiles.put("full", "full-sockets"); stdProfiles.put("full-ha", "full-ha-sockets"); STD_PROFILES = Collections.unmodifiableMap(stdProfiles); } private static DomainTestSupport support; @Before public void init() throws Exception { support = MixedDomainTestSuite.getSupport(this.getClass()); } @Test public void testServerLaunching() throws IOException, MgmtOperationException, InterruptedException { DomainClient client = support.getDomainPrimaryLifecycleUtil().getDomainClient(); for (Map.Entry<String, String> entry : getProfilesToTest().entrySet()) { String profile = entry.getKey(); String sbg = entry.getValue(); try { installTestServer(client, profile, sbg); awaitServerLaunch(client, profile); validateServerProfile(client, profile); verifyHttp(profile); } finally { cleanTestServer(client); } } } private void installTestServer(ModelControllerClient client, String profile, String sbg) throws IOException, MgmtOperationException { ModelNode op = Util.createAddOperation(TEST_SERVER_GROUP); op.get("profile").set(profile); op.get("socket-binding-group").set(sbg); DomainTestUtils.executeForResult(op, client); op = Util.createAddOperation(TEST_SERVER_CONFIG); op.get("group").set("legacy-group"); DomainTestUtils.executeForResult(op, client); DomainTestUtils.executeForResult(Util.createEmptyOperation("start", TEST_SERVER_CONFIG), client); } private void awaitServerLaunch(ModelControllerClient client, String profile) throws InterruptedException { long timeout = System.currentTimeMillis() + TimeoutUtil.adjust(20000); ModelNode op = Util.getReadAttributeOperation(TEST_SERVER, "server-state"); do { try { ModelNode state = DomainTestUtils.executeForResult(op, client); if ("running".equalsIgnoreCase(state.asString())) { return; } } catch (IOException | MgmtOperationException e) { // ignore and try again } TimeUnit.MILLISECONDS.sleep(250L); } while (System.currentTimeMillis() < timeout); Assert.fail("Server did not start using " + profile); } private void validateServerProfile(ModelControllerClient client, String profile) throws IOException, MgmtOperationException { ModelNode op = Util.getReadAttributeOperation(TEST_SERVER, "profile-name"); ModelNode result = DomainTestUtils.executeForResult(op, client); Assert.assertEquals(profile, result.asString()); } private void verifyHttp(String profile) { try { URLConnection connection = new URL("http://" + TestSuiteEnvironment.formatPossibleIpv6Address(DomainTestSupport.secondaryAddress) + ":8080").openConnection(); connection.connect(); } catch (IOException e) { Assert.fail("Cannot connect to profile " + profile + " " + e.toString()); } } private void cleanTestServer(ModelControllerClient client) { try { ModelNode op = Util.createEmptyOperation("stop", TEST_SERVER_CONFIG); op.get("blocking").set(true); DomainTestUtils.executeForResult(op, client); } catch (MgmtOperationException | IOException e) { e.printStackTrace(); } finally { try { DomainTestUtils.executeForResult(Util.createRemoveOperation(TEST_SERVER_CONFIG), client); } catch (MgmtOperationException | IOException e) { e.printStackTrace(); } finally { try { DomainTestUtils.executeForResult(Util.createRemoveOperation(TEST_SERVER_GROUP), client); } catch (MgmtOperationException | IOException e) { e.printStackTrace(); } } } } protected Map<String, String> getProfilesToTest() { return new HashMap<>(STD_PROFILES); } }
6,688
39.295181
170
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/SimpleMixedDomainTest.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.domain.mixed; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CHILD_TYPE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CLONE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.COMPOSITE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CORE_SERVICE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXTENSION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.IGNORED_RESOURCES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.IGNORED_RESOURCE_TYPE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_RUNTIME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INTERFACE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MANAGEMENT_CLIENT_CONTENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAMES; 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.OUTCOME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROFILE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROXIES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_CHILDREN_NAMES_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RECURSIVE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESTART_SERVERS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RUNNING_SERVER; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_GROUP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING_GROUP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SYSTEM_PROPERTY; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.TO_PROFILE; import static org.junit.Assert.assertEquals; import java.net.URL; import java.net.URLConnection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.client.helpers.domain.DomainClient; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.controller.operations.global.MapOperations; import org.jboss.as.test.integration.domain.management.util.DomainLifecycleUtil; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.integration.domain.management.util.DomainTestUtils; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import org.xnio.IoUtils; /** * * @author <a href="[email protected]">Kabir Khan</a> */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public abstract class SimpleMixedDomainTest { private static final String ACTIVE_PROFILE = "full-ha"; MixedDomainTestSupport support; Version.AsVersion version; @Before public void init() throws Exception { support = MixedDomainTestSuite.getSupport(this.getClass()); version = MixedDomainTestSuite.getVersion(this.getClass()); } @AfterClass public static synchronized void afterClass() { MixedDomainTestSuite.afterClass(); } @Test public void test00001_ServerRunning() throws Exception { URLConnection connection = new URL("http://" + TestSuiteEnvironment.formatPossibleIpv6Address(DomainTestSupport.secondaryAddress) + ":8080").openConnection(); connection.connect(); } @Test public void test00002_Versioning() throws Exception { DomainClient primaryClient = support.getDomainPrimaryLifecycleUtil().createDomainClient(); ModelNode primaryModel; try { primaryModel = readDomainModelForVersions(primaryClient); } finally { IoUtils.safeClose(primaryClient); } DomainClient secondaryClient = support.getDomainSecondaryLifecycleUtil().createDomainClient(); ModelNode secondaryModel; try { secondaryModel = readDomainModelForVersions(secondaryClient); } finally { IoUtils.safeClose(secondaryClient); } cleanupKnownDifferencesInModelsForVersioningCheck(primaryModel, secondaryModel); //The version fields should be the same assertEquals(primaryModel, secondaryModel); } @Test public void test00010_JgroupsTransformers() throws Exception { final DomainClient primaryClient = support.getDomainPrimaryLifecycleUtil().createDomainClient(); try { // Check composite operation final ModelNode compositeOp = new ModelNode(); compositeOp.get(OP).set(COMPOSITE); compositeOp.get(OP_ADDR).setEmptyList(); compositeOp.get(STEPS).add(createProtocolPutPropertyOperation("tcp", "MPING", "send_on_all_interfaces", "true")); compositeOp.get(STEPS).add(createProtocolPutPropertyOperation("tcp", "MPING", "receive_on_all_interfaces", "true")); DomainTestUtils.executeForResult(compositeOp, primaryClient); } finally { IoUtils.safeClose(primaryClient); } } /** * Tests test-connection-in-pool() of ExampleDS. * * @throws Exception */ @Test public void test00011_ExampleDSConnection() throws Exception{ PathAddress exampleDSAddress = PathAddress.pathAddress(PathElement.pathElement(HOST, "secondary"), PathElement.pathElement(RUNNING_SERVER, "server-one"), PathElement.pathElement(SUBSYSTEM, "datasources"), PathElement.pathElement("data-source", "ExampleDS")); DomainClient primaryClient = support.getDomainPrimaryLifecycleUtil().createDomainClient(); try { ModelNode op = Util.createOperation("test-connection-in-pool", PathAddress.pathAddress(exampleDSAddress)); ModelNode response = primaryClient.execute(op); assertEquals(op.toString() + '\n' + response.toString(), SUCCESS, response.get(OUTCOME).asString()); } finally { IoUtils.safeClose(primaryClient); } } //Do this one last since it changes the host model of the secondary hosts @Test public void test99999_ProfileClone() throws Exception { if (version.getMajor() == 6) { //EAP 6 does not have the clone operation profileCloneEap6x(); } else { //EAP 7 does not have the clone operation profileCloneEap7x(); } } private void profileCloneEap6x() throws Exception { //EAP 6 does not have the clone operation //For an EAP 7 secondary we will need another test since EAP 7 allows the clone operation. // However EAP 7 will need to take into account the ignore-unused-configuration // setting which does not exist in 6.x final DomainClient primaryClient = support.getDomainPrimaryLifecycleUtil().createDomainClient(); final DomainClient secondaryClient = support.getDomainSecondaryLifecycleUtil().createDomainClient(); try { final PathAddress newProfileAddress = PathAddress.pathAddress(PROFILE, "new-profile"); //Create a new profile (so that we can ignore it on the host later) DomainTestUtils.executeForResult(Util.createAddOperation(newProfileAddress), primaryClient); //Attempt to clone it. It should fail since the transformers reject it. final ModelNode clone = Util.createEmptyOperation(CLONE, newProfileAddress); clone.get(TO_PROFILE).set("cloned"); DomainTestUtils.executeForFailure(clone, primaryClient); //Ignore the new profile on the secondary and reload final PathAddress ignoredResourceAddress = PathAddress.pathAddress(HOST, "secondary") .append(CORE_SERVICE, IGNORED_RESOURCES).append(IGNORED_RESOURCE_TYPE, PROFILE); final ModelNode ignoreNewProfile = Util.createAddOperation(ignoredResourceAddress); ignoreNewProfile.get(NAMES).add("new-profile"); DomainTestUtils.executeForResult(ignoreNewProfile, secondaryClient); //Reload secondary so ignore takes effect reloadHost(support.getDomainSecondaryLifecycleUtil(), "secondary"); //Clone should work now that the new profile is ignored DomainTestUtils.executeForResult(clone, primaryClient); //Adding a subsystem to the cloned profile should fail since the profile does not exist on the secondary DomainTestUtils.executeForFailure(Util.createAddOperation(PathAddress.pathAddress(PROFILE, "cloned").append(SUBSYSTEM, "jmx")), primaryClient); //Reload secondary reloadHost(support.getDomainSecondaryLifecycleUtil(), "secondary"); //Reloading should have brought over the cloned profile, so adding a subsystem should now work DomainTestUtils.executeForResult(Util.createAddOperation(PathAddress.pathAddress(PROFILE, "cloned").append(SUBSYSTEM, "jmx")), primaryClient); } finally { IoUtils.safeClose(secondaryClient); IoUtils.safeClose(primaryClient); } } private void profileCloneEap7x() throws Exception { // EAP 7 allows the clone operation. // However EAP 7 will need to take into account the ignore-unused-configuration // setting which does not exist in 6.x final DomainClient primaryClient = support.getDomainPrimaryLifecycleUtil().createDomainClient(); final DomainClient secondaryClient = support.getDomainSecondaryLifecycleUtil().createDomainClient(); try { final PathAddress newProfileAddress = PathAddress.pathAddress(PROFILE, "new-profile"); //Create a new profile (so that we can ignore it on the host later) DomainTestUtils.executeForResult(Util.createAddOperation(newProfileAddress), primaryClient); //Attempt to clone it. It should work but not exist on the secondary since unused configuration is ignored final ModelNode clone = Util.createEmptyOperation(CLONE, newProfileAddress); clone.get(TO_PROFILE).set("cloned"); DomainTestUtils.executeForResult(clone, primaryClient); //Check the new profile does not exist on the secondary final ModelNode readChildrenNames = Util.createEmptyOperation(READ_CHILDREN_NAMES_OPERATION, PathAddress.EMPTY_ADDRESS); readChildrenNames.get(CHILD_TYPE).set(PROFILE); ModelNode result = DomainTestUtils.executeForResult(readChildrenNames, secondaryClient); List<ModelNode> list = result.asList(); Assert.assertEquals(1, list.size()); Assert.assertEquals(list.toString(), "full-ha", list.get(0).asString()); //Update the server group to use the new profile DomainTestUtils.executeForResult( Util.getWriteAttributeOperation(PathAddress.pathAddress(SERVER_GROUP, "other-server-group"), PROFILE, "new-profile"), primaryClient); //Check the profiles result = DomainTestUtils.executeForResult(readChildrenNames, secondaryClient); list = result.asList(); Assert.assertEquals(1, list.size()); Assert.assertEquals(list.toString(), "new-profile", list.get(0).asString()); } finally { IoUtils.safeClose(secondaryClient); IoUtils.safeClose(primaryClient); } } /* !!!!!!!!! ADD TESTS IN NUMERICAL ORDER !!!!!!!!!! Please observe the test<5 digits>_ pattern for the names to ensure the order */ private DomainClient reloadHost(DomainLifecycleUtil lifecycleUtil, String host) throws Exception { ModelNode reload = Util.createEmptyOperation("reload", PathAddress.pathAddress(HOST, host)); reload.get(RESTART_SERVERS).set(false); lifecycleUtil.executeAwaitConnectionClosed(reload); lifecycleUtil.connect(); lifecycleUtil.awaitHostController(System.currentTimeMillis()); return lifecycleUtil.createDomainClient(); } private static ModelNode createProtocolPutPropertyOperation(String stackName, String protocolName, String propertyName, String propertyValue) { PathAddress address = PathAddress.pathAddress(PathElement.pathElement(PROFILE, ACTIVE_PROFILE)) .append(PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, "jgroups")) .append(PathElement.pathElement("stack", stackName)) .append(PathElement.pathElement("protocol", protocolName)); ModelNode operation = Util.createOperation(MapOperations.MAP_PUT_DEFINITION, address); operation.get(ModelDescriptionConstants.NAME).set("properties"); operation.get("key").set(propertyName); operation.get(ModelDescriptionConstants.VALUE).set(propertyValue); return operation; } private Set<ModelNode> getAllChildren(ModelNode modules) { HashSet<ModelNode> set = new HashSet<ModelNode>(); for (Property prop : modules.asPropertyList()) { set.add(prop.getValue()); } return set; } private void cleanupKnownDifferencesInModelsForVersioningCheck(ModelNode primaryModel, ModelNode secondaryModel) { //First get rid of any undefined crap cleanUndefinedNodes(primaryModel); cleanUndefinedNodes(secondaryModel); } private void cleanUndefinedNodes(ModelNode model) { Set<String> removals = new HashSet<String>(); for (String key : model.keys()) { if (!model.hasDefined(key)) { removals.add(key); } } for (String key : removals) { model.remove(key); } } private ModelNode readDomainModelForVersions(DomainClient domainClient) throws Exception { ModelNode op = new ModelNode(); op.get(OP).set(READ_RESOURCE_OPERATION); op.get(OP_ADDR).setEmptyList(); op.get(RECURSIVE).set(true); op.get(INCLUDE_RUNTIME).set(false); op.get(PROXIES).set(false); ModelNode model = DomainTestUtils.executeForResult(op, domainClient); model.remove(EXTENSION); model.remove(HOST); model.remove(INTERFACE); model.remove(MANAGEMENT_CLIENT_CONTENT); model.remove(PROFILE); model.remove(SERVER_GROUP); model.remove(SOCKET_BINDING_GROUP); model.remove(SYSTEM_PROPERTY); model.remove(CORE_SERVICE); return model; } }
16,798
47.412104
166
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/KernelBehaviorTestSuite.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.domain.mixed; /** * Base class for a test suite that uses a minimal domain config in order * to not have to deal with subsystem configuration compatibility issues * across releases in tests that are focused on the behavior of the kernel. * * @author Brian Stansberry */ public class KernelBehaviorTestSuite extends MixedDomainTestSuite { /** * Call this from a @BeforeClass method * * @param testClass the test/suite class * @return */ protected static MixedDomainTestSupport getSupport(Class<?> testClass) { return getSupport(testClass, "primary-config/domain-minimal.xml", null, null, Profile.DEFAULT, false, false, false); } }
1,745
38.681818
124
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/RBACConfigTestCase.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.test.integration.domain.mixed; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ACCESS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.APPLICATION_CLASSIFICATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.AUTHORIZATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.BASE_ROLE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CLASSIFICATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CONFIGURED_APPLICATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CONFIGURED_REQUIRES_WRITE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CONSTRAINT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CORE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CORE_SERVICE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILED; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOSTS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST_SCOPED_ROLE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_ALL; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MANAGEMENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROVIDER; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ROLE_MAPPING; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RUNNING_SERVER; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SENSITIVITY_CLASSIFICATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_GROUPS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_GROUP_SCOPED_ROLE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.TYPE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VAULT_EXPRESSION; import static org.junit.Assert.assertEquals; import java.io.IOException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.dmr.ModelNode; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; /** * Tests that RBAC configuration is properly handled in a mixed-domain. * * @author Brian Stansberry */ public class RBACConfigTestCase { private static final PathAddress RBAC_BASE = PathAddress.pathAddress(PathElement.pathElement(CORE_SERVICE, MANAGEMENT), PathElement.pathElement(ACCESS, AUTHORIZATION)); private static final PathAddress SERVER_ONE = PathAddress.pathAddress(PathElement.pathElement(HOST, "secondary"), PathElement.pathElement(RUNNING_SERVER, "server-one")); private static ModelControllerClient primaryClient; private static ModelControllerClient secondaryClient; @Before public void init() throws Exception { DomainTestSupport support = KernelBehaviorTestSuite.getSupport(this.getClass()); primaryClient = support.getDomainPrimaryLifecycleUtil().getDomainClient(); secondaryClient = support.getDomainSecondaryLifecycleUtil().getDomainClient(); } @AfterClass public static synchronized void afterClass() { KernelBehaviorTestSuite.afterClass(); primaryClient = secondaryClient = null; } @Test public void testWriteRBACProvider() throws IOException { modifyTest(RBAC_BASE, PROVIDER); } @Test public void testAddRoleMapping() throws IOException { PathAddress address = RBAC_BASE.append(ROLE_MAPPING, "Operator"); String attribute = INCLUDE_ALL; ModelNode value = ModelNode.TRUE; ModelNode addOp = Util.createAddOperation(address); addOp.get(attribute).set(value); addTest(address, attribute, value, addOp); } @Test public void testAddHostScopedRole() throws IOException { PathAddress address = RBAC_BASE.append(HOST_SCOPED_ROLE, "WFCORE-1622_H"); String attribute = BASE_ROLE; ModelNode value = new ModelNode("Operator"); ModelNode addOp = Util.createAddOperation(address); addOp.get(attribute).set(value); addOp.get(HOSTS).add("secondary"); addTest(address, attribute, value, addOp); } @Test public void testAddServerGroupScopedRole() throws IOException { PathAddress address = RBAC_BASE.append(SERVER_GROUP_SCOPED_ROLE, "WFCORE-1622_S"); String attribute = BASE_ROLE; ModelNode value = new ModelNode("Operator"); ModelNode addOp = Util.createAddOperation(address); addOp.get(attribute).set(value); addOp.get(SERVER_GROUPS).add("main-server-group"); addTest(address, attribute, value, addOp); } @Test public void testModifySensitivityConstraint() throws IOException { PathAddress mapping = RBAC_BASE.append(CONSTRAINT, SENSITIVITY_CLASSIFICATION) .append(TYPE, CORE) .append(CLASSIFICATION, "socket-config"); modifyTest(mapping, CONFIGURED_REQUIRES_WRITE, ModelNode.TRUE, true); } @Test public void testModifyServerSSLSensitivityConstraint() throws IOException { PathAddress mapping = RBAC_BASE.append(CONSTRAINT, SENSITIVITY_CLASSIFICATION) .append(TYPE, CORE) .append(CLASSIFICATION, "server-ssl"); modifyTest(mapping, CONFIGURED_REQUIRES_WRITE, ModelNode.TRUE, getSupportsServerSSL()); } @Test public void testModifyApplicationConstraint() throws IOException { PathAddress mapping = RBAC_BASE.append(CONSTRAINT, APPLICATION_CLASSIFICATION) .append(TYPE, CORE) .append(CLASSIFICATION, "deployment"); modifyTest(mapping, CONFIGURED_APPLICATION, ModelNode.TRUE, true); } @Test public void testModifySensitiveExpressionsConstraint() throws IOException { PathAddress mapping = RBAC_BASE.append(CONSTRAINT, VAULT_EXPRESSION); modifyTest(mapping, CONFIGURED_REQUIRES_WRITE, ModelNode.TRUE, true); } /** Override this to return false in subclasses that test EAP < 6.4.7 */ protected boolean getSupportsServerSSL() { return true; } private void modifyTest(PathAddress base, String attribute) throws IOException { ModelNode primaryValue = executeForResult(Util.getReadAttributeOperation(base, attribute), primaryClient); ModelNode secondaryValue = executeForResult(Util.getReadAttributeOperation(base, attribute), secondaryClient); assertEquals(primaryValue, secondaryValue); ModelNode serverValue = executeForResult(Util.getReadAttributeOperation(SERVER_ONE.append(base), attribute), primaryClient); assertEquals(primaryValue, serverValue); // Write the same value, so we don't need to clean up. executeForResult(Util.getWriteAttributeOperation(base, attribute, primaryValue), primaryClient); ModelNode newPrimaryValue = executeForResult(Util.getReadAttributeOperation(base, attribute), primaryClient); assertEquals(primaryValue, newPrimaryValue); secondaryValue = executeForResult(Util.getReadAttributeOperation(base, attribute), secondaryClient); assertEquals(primaryValue, secondaryValue); serverValue = executeForResult(Util.getReadAttributeOperation(SERVER_ONE.append(base), attribute), primaryClient); assertEquals(primaryValue, serverValue); } private void modifyTest(PathAddress base, String attribute, ModelNode newValue, boolean expectSecondaryEffect) throws IOException { ModelNode primaryValue = executeForResult(Util.getReadAttributeOperation(base, attribute), primaryClient); if (expectSecondaryEffect) { ModelNode secondaryValue = executeForResult(Util.getReadAttributeOperation(base, attribute), secondaryClient); assertEquals(primaryValue, secondaryValue); ModelNode serverValue = executeForResult(Util.getReadAttributeOperation(SERVER_ONE.append(base), attribute), primaryClient); assertEquals(primaryValue, serverValue); } else { executeForFailure(Util.getReadAttributeOperation(base, attribute), secondaryClient); executeForFailure(Util.getReadAttributeOperation(SERVER_ONE.append(base), attribute), primaryClient); } // Write the same value, so we don't need to clean up. Throwable caught = null; executeForResult(Util.getWriteAttributeOperation(base, attribute, newValue), primaryClient); try { ModelNode newPrimaryValue = executeForResult(Util.getReadAttributeOperation(base, attribute), primaryClient); assertEquals(newValue, newPrimaryValue); if (expectSecondaryEffect) { ModelNode secondaryValue = executeForResult(Util.getReadAttributeOperation(base, attribute), secondaryClient); assertEquals(newValue, secondaryValue); ModelNode serverValue = executeForResult(Util.getReadAttributeOperation(SERVER_ONE.append(base), attribute), primaryClient); assertEquals(newValue, serverValue); } else { executeForFailure(Util.getReadAttributeOperation(base, attribute), secondaryClient); executeForFailure(Util.getReadAttributeOperation(SERVER_ONE.append(base), attribute), primaryClient); } } catch (Exception | Error e) { caught = e; throw e; } finally { if (!newValue.equals(primaryValue)) { try { executeForResult(Util.getWriteAttributeOperation(base, attribute, primaryValue), primaryClient); } catch (RuntimeException e) { if (caught == null) { throw e; } else { e.printStackTrace(System.out); } } } } } private void addTest(PathAddress address, String attribute, ModelNode value, ModelNode addOp) { Throwable caught = null; executeForResult(addOp, primaryClient); try { ModelNode primaryValue = executeForResult(Util.getReadAttributeOperation(address, attribute), primaryClient); assertEquals(value, primaryValue); ModelNode secondaryValue = executeForResult(Util.getReadAttributeOperation(address, attribute), secondaryClient); assertEquals(value, secondaryValue); ModelNode serverValue = executeForResult(Util.getReadAttributeOperation(SERVER_ONE.append(address), attribute), primaryClient); assertEquals(value, serverValue); } catch (Exception | Error e) { caught = e; throw e; } finally { try { executeForResult(Util.createRemoveOperation(address), primaryClient); } catch (RuntimeException e) { if (caught == null) { throw e; } else { e.printStackTrace(System.out); } } } } private ModelNode executeForResult(ModelNode op, ModelControllerClient client) { try { ModelNode response = client.execute(op); assertEquals(op.toString() + '\n' + response.toString(), SUCCESS, response.get(OUTCOME).asString()); return response.get(RESULT); } catch (IOException e) { throw new RuntimeException(e); } } private ModelNode executeForFailure(ModelNode op, ModelControllerClient client) { try { ModelNode response = client.execute(op); assertEquals(op.toString() + '\n' + response.toString(), FAILED, response.get(OUTCOME).asString()); return response; } catch (IOException e) { throw new RuntimeException(e); } } }
13,282
46.780576
140
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/ElytronOnlyPrimarySmokeTestCase.java
/* * * Copyright 2017 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.test.integration.domain.mixed; import org.junit.AfterClass; public class ElytronOnlyPrimarySmokeTestCase extends SimpleMixedDomainTest { @Override public void init() throws Exception { support = ElytronOnlyPrimaryTestSuite.getSupport(this.getClass()); version = ElytronOnlyPrimaryTestSuite.getVersion(this.getClass()); } @AfterClass public static synchronized void afterClass() { ElytronOnlyPrimaryTestSuite.afterClass(); } }
1,101
29.611111
76
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/OldVersionCopier.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.domain.mixed; import org.jboss.logging.Logger; import java.io.File; import java.io.IOException; import java.net.URI; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; import java.util.Comparator; import java.util.HashMap; import java.util.Map; /** * @author <a href="[email protected]">Kabir Khan</a> * @author Tomaz Cerar */ class OldVersionCopier { private static final String OLD_VERSIONS_DIR = "jboss.test.mixed.domain.dir"; private static final Logger log = Logger.getLogger(OldVersionCopier.class.getName()); private final Version.AsVersion version; private final Path oldVersionsBaseDir; private final Path targetOldVersions = Paths.get("target/old-versions/"); private OldVersionCopier(Version.AsVersion version, Path oldVersionsBaseDir) { this.version = version; this.oldVersionsBaseDir = oldVersionsBaseDir; } static Path getOldVersionDir(Version.AsVersion version) { OldVersionCopier copier = new OldVersionCopier(version, obtainOldVersionsDir()); copier.cleanUnneededInstances(); Path result = copier.getExpandedPath(); if (Files.exists(result) && Files.isDirectory(result) && Files.exists(result.resolve("jboss-modules.jar"))) { //verify expanded version is proper return result; } return copier.expandAsInstance(version); } private void cleanUnneededInstances() { // WFLY-12021 if we're using version X assume we don't need the expanded zip // for any other version any more. So delete it to reduce the peak disk footprint // of a testsuite execution. for (Version.AsVersion asVersion : Version.AsVersion.values()) { if (asVersion != version) { Path versionRoot = targetOldVersions.resolve(asVersion.getFullVersionName()); if (versionRoot.toFile().exists() && versionRoot.toFile().isDirectory()) { log.infof("Cleaning legacy installation at %s", versionRoot); try { //noinspection ResultOfMethodCallIgnored Files.walk(versionRoot).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); } catch (IOException e) { log.errorf(e, "Failed cleaning legacy installation at %s", versionRoot); } } } } } private static Path obtainOldVersionsDir() { String error = "System property '" + OLD_VERSIONS_DIR + "' must be set to a directory containing old versions"; String oldVersionsDir = System.getProperty(OLD_VERSIONS_DIR); if (oldVersionsDir == null) { throw new RuntimeException(error); } Path file = Paths.get(oldVersionsDir); if (Files.notExists(file) || !Files.isDirectory(file)) { throw new RuntimeException(error); } return file; } private Path getExpandedPath() { return targetOldVersions.resolve(version.getFullVersionName()); } private Path expandAsInstance(Version.AsVersion version) { createIfNotExists(targetOldVersions); final String path = resolveZipFileName(version); Path file = oldVersionsBaseDir.resolve(path); if (Files.notExists(file)) { throw new RuntimeException("Old version not found in " + file.toAbsolutePath().toString()); } try { return expandAsInstance(file); } catch (Exception e) { throw new RuntimeException(e); } } private Path expandAsInstance(final Path file) throws Exception { Path versionDir = getExpandedPath(); createIfNotExists(versionDir); unzip(file, versionDir); return versionDir; } private static boolean shouldSkip(Path path) { String entryName = path.toString(); if (entryName.endsWith("/docs/") || entryName.endsWith("/bundles/")) { return true; } else if (entryName.endsWith("/bin/")) { return true; } else if (entryName.endsWith("/eap/dir/")) { //console files return true; } else if (entryName.contains("/welcome-content/") && !entryName.endsWith("/welcome-content/")) { //Create the directory but don't include any files return true; } return false; } private void createIfNotExists(Path file) { if (Files.notExists(file)) { try { Files.createDirectories(file); } catch (IOException e) { throw new RuntimeException("Could not create " + targetOldVersions, e); } } } private static FileSystem createZipFileSystem(Path zipFilename) throws IOException { // convert the filename to a URI final URI uri = URI.create("jar:file:" + zipFilename.toUri().getPath()); final Map<String, String> env = new HashMap<>(); return FileSystems.newFileSystem(uri, env); } /** * Unzips the specified zip file to the specified destination directory. * Replaces any files in the destination, if they already exist. */ private void unzip(Path zipFilename, Path destDir) throws IOException { if (Files.notExists(destDir)) { Files.createDirectories(destDir); } try (FileSystem zipFileSystem = createZipFileSystem(zipFilename)) { final Path root = zipFileSystem.getPath("/"); Files.walkFileTree(verifyZipContents(root), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { final Path destFile = (Paths.get(destDir.toString(), file.subpath(1, file.getNameCount()).toString())); //we skip first folder /*if (!destFile.toString().endsWith(".jar")&&!destFile.toString().endsWith(".xml")) { System.out.printf("Extracting file %s to %s\n", file, destFile); }*/ Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING); return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (dir.getNameCount() == 1) { return FileVisitResult.CONTINUE; } final Path dirToCreate = Paths.get(destDir.toString(), dir.subpath(1, dir.getNameCount()).toString()); if (shouldSkip(dir)) { //System.out.println("skipping, " + dir); return FileVisitResult.SKIP_SUBTREE; } if (Files.notExists(dirToCreate)) { Files.createDirectory(dirToCreate); } return FileVisitResult.CONTINUE; } }); } } private static Path verifyZipContents(Path root) throws IOException { boolean read = false; Path result = root; for (Path c : Files.newDirectoryStream(root)) { if (!read) { result = c; read = true; } else { throw new RuntimeException("Zip contains more than one directory, something is wrong!"); } } return result; } private static String resolveZipFileName(final Version.AsVersion requested) { final String value = System.getProperty("override.mixed.domain." + requested.getVersion()); if (value != null) { return value; } return requested.getZipFileName(); } }
9,173
38.543103
153
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/LegacyConfigAdjuster.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.test.integration.domain.mixed; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CHILD_TYPE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROFILE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_CHILDREN_NAMES_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SYSTEM_PROPERTY; import java.util.ArrayList; import java.util.List; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.helpers.domain.DomainClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.domain.management.util.DomainTestUtils; import org.jboss.dmr.ModelNode; /** * Analogue to {@link DomainAdjuster}, but for use when the domain is running with a legacy domain.xml * rather than the current standard domain.xml. So the scope of expected adjustments is expected to be * considerably smaller. * * @author Brian Stansberry */ public class LegacyConfigAdjuster { protected LegacyConfigAdjuster() { } static void adjustForVersion(final DomainClient client, final Version.AsVersion asVersion) throws Exception { final LegacyConfigAdjuster adjuster = new LegacyConfigAdjuster(); adjuster.adjust(client); } final void adjust(final DomainClient client) throws Exception { removeIpv4SystemProperty(client); //Version specific changes ModelNode read = Util.createEmptyOperation(READ_CHILDREN_NAMES_OPERATION, PathAddress.EMPTY_ADDRESS); read.get(CHILD_TYPE).set(PROFILE); ModelNode result = DomainTestUtils.executeForResult(read, client); for (ModelNode profile : result.asList()) { final List<ModelNode> adjustments = adjustForVersion(client, PathAddress.pathAddress(PROFILE, profile.asString())); applyVersionAdjustments(client, adjustments); } } private void removeIpv4SystemProperty(final DomainClient client) throws Exception { //The standard domain configuration contains -Djava.net.preferIPv4Stack=true, remove that DomainTestUtils.executeForResult( Util.createRemoveOperation(PathAddress.pathAddress(SYSTEM_PROPERTY, "java.net.preferIPv4Stack")), client); } protected List<ModelNode> adjustForVersion(final DomainClient client, final PathAddress profileAddress) throws Exception { return new ArrayList<>(); } private void applyVersionAdjustments(DomainClient client, List<ModelNode> operations) throws Exception { if (operations.size() == 0) { return; } for (ModelNode op : operations) { DomainTestUtils.executeForResult(op, client); } } }
3,355
38.023256
127
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/MixedDomainTestSuite.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.domain.mixed; import static org.junit.Assert.assertEquals; import java.nio.file.Path; import org.junit.AfterClass; /** * * @author <a href="[email protected]">Kabir Khan</a> */ public class MixedDomainTestSuite { public enum Profile { FULL("full"), FULL_HA("full-ha"), DEFAULT("default"); private final String profileName; Profile(String profileName) { this.profileName = profileName; } public String getProfile() { return profileName; } } private static MixedDomainTestSupport support; private static Version.AsVersion version; static Version.AsVersion getVersion(Class<?> testClass) { final Version version = testClass.getAnnotation(Version.class); if (version == null) { throw new IllegalArgumentException("No @Version"); } if (MixedDomainTestSuite.version != null) { assertEquals(MixedDomainTestSuite.version, version.value()); } MixedDomainTestSuite.version = version.value(); return version.value(); } /** * Call this from a @BeforeClass method * * @param testClass the test/suite class */ protected static MixedDomainTestSupport getSupport(Class<?> testClass) { return getSupport(testClass, Profile.FULL_HA, false); } protected static MixedDomainTestSupport getSupport(Class<?> testClass, boolean withPrimaryServers) { return getSupport(testClass, Profile.FULL_HA, withPrimaryServers); } protected static MixedDomainTestSupport getSupport(Class<?> testClass, Profile profile, boolean withPrimaryServers) { if (support == null) { final String copiedDomainXml = MixedDomainTestSupport.copyDomainFile(); return getSupport(testClass, copiedDomainXml, profile, true, false, withPrimaryServers); } return support; } /** * Call this from a @BeforeClass method * * @param testClass the test/suite class */ protected static MixedDomainTestSupport getSupport(Class<?> testClass, String primaryConfig, String secondaryConfig, Profile profile, boolean withPrimaryServers) { return getSupport(testClass, primaryConfig, secondaryConfig, profile, true, false, withPrimaryServers); } protected static MixedDomainTestSupport getSupport(Class<?> testClass, String primaryConfig, boolean adjustDomain, boolean legacyConfig, boolean withPrimaryServers) { return getSupport(testClass, primaryConfig, null, Profile.FULL_HA, adjustDomain, legacyConfig, withPrimaryServers); } /** * Call this from a @BeforeClass method * * @param testClass the test/suite class */ protected static MixedDomainTestSupport getSupport(Class<?> testClass, String primaryConfig, String secondaryConfig, Profile profile, boolean adjustDomain, boolean legacyConfig, boolean withPrimaryServers) { if (support == null) { final String copiedDomainXml = MixedDomainTestSupport.copyDomainFile(); return getSupport(testClass, copiedDomainXml, primaryConfig, secondaryConfig, profile, adjustDomain, legacyConfig, withPrimaryServers); } return support; } protected static MixedDomainTestSupport getSupport(Class<?> testClass, String primaryConfig, String secondaryConfig) { if (support == null) { final String copiedDomainXml = MixedDomainTestSupport.copyDomainFile(); return getSupport(testClass, copiedDomainXml, primaryConfig, secondaryConfig, Profile.FULL_HA, true, false, false); } return support; } /** * Call this from a @BeforeClass method * * @param testClass the test/suite class * @param version the version of the legacy secondary. */ protected static MixedDomainTestSupport getSupportForLegacyConfig(Class<?> testClass, Version.AsVersion version) { if (support == null) { final Path originalDomainXml = MixedDomainTestSupport.loadLegacyDomainXml(version); final String copiedDomainXml = MixedDomainTestSupport.copyDomainFile(originalDomainXml); return getSupport(testClass, copiedDomainXml, Profile.FULL_HA, true, true, false); } return support; } static MixedDomainTestSupport getSupport(Class<?> testClass, String domainConfig, Profile profile, boolean adjustDomain, boolean legacyConfig, boolean withPrimaryServers) { return getSupport(testClass, domainConfig, null, null, profile, adjustDomain, legacyConfig, withPrimaryServers); } static MixedDomainTestSupport getSupport(Class<?> testClass, String domainConfig, String primaryConfig, String secondaryConfig, Profile profile, boolean adjustDomain, boolean legacyConfig, boolean withPrimaryServers) { if (support == null) { final Version.AsVersion version = getVersion(testClass); final MixedDomainTestSupport testSupport; try { if (domainConfig != null) { if(primaryConfig != null || secondaryConfig != null) { testSupport = MixedDomainTestSupport.create(testClass.getSimpleName(), version, domainConfig, primaryConfig, secondaryConfig, profile.getProfile(), adjustDomain, legacyConfig, withPrimaryServers); } else { testSupport = MixedDomainTestSupport.create(testClass.getSimpleName(), version, domainConfig, profile.getProfile(), adjustDomain, legacyConfig, withPrimaryServers); } } else { testSupport = MixedDomainTestSupport.create(testClass.getSimpleName(), version); } } catch (Exception e) { MixedDomainTestSuite.version = null; throw (e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e)); } try { //Start the domain with adjustments to domain.xml testSupport.start(); support = testSupport; } catch (Exception e) { testSupport.close(); throw new RuntimeException(e); } } return support; } protected Version.AsVersion getVersion() { return version; } private static synchronized void stop() { version = null; if(support != null) { support.close(); support = null; } } @AfterClass public static synchronized void afterClass() { stop(); } }
7,682
40.755435
222
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/ElytronOnlyPrimaryTestSuite.java
/* * * Copyright 2017 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.test.integration.domain.mixed; /** * Base class for a test suite that uses a minimal domain config and primary host that has only elytron security */ public class ElytronOnlyPrimaryTestSuite extends MixedDomainTestSuite { protected static MixedDomainTestSupport getSupport(Class<?> testClass) { return getSupport(testClass, "primary-config/host-primary-elytron.xml", "secondary-config/host-secondary.xml"); } }
1,071
32.5
112
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/Version.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.domain.mixed; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.jboss.as.controller.ModelVersion; import org.junit.Assume; /** * * @author <a href="[email protected]">Kabir Khan</a> */ @Retention(RetentionPolicy.RUNTIME) @Target(value=ElementType.TYPE) public @interface Version { AsVersion value(); String WILDFLY = "wildfly-"; String EAP = "jboss-eap-"; enum AsVersion { EAP_7_4_0(EAP, 7, 4, 0, 11, 8, "EAP7.4", ModelVersion.create(16, 0)), ; final String basename; private final int major; private final int minor; private final int micro; private final int maxVM; private final int minVM; final String version; final String hostExclude; final ModelVersion modelVersion; /** * Metadata related to the server version we are using as secondary * @param basename Base name of the server, used to locate the zip file that contains the secondary under test. * @param major Major release number * @param minor Minor release number * @param micro Micro release number * @param maxVM The maximum Java version under which a legacy host can properly execute tests * @param minVM The minimum Java version under which a legacy host can properly execute tests * @param hostExclude The host-exclude name that represents this secondary * @param modelVersion The Kernel version of this secondary */ AsVersion(String basename, int major, int minor, int micro, int maxVM, int minVM, String hostExclude, ModelVersion modelVersion){ this.basename = basename; this.major = major; this.minor = minor; this.micro = micro; this.version = major + "." + minor + "." + micro; this.maxVM = maxVM; this.minVM = minVM; this.hostExclude = hostExclude; this.modelVersion = modelVersion; } public String getBaseName() { return basename; } public String getVersion() { return version; } public String getFullVersionName() { return basename + version; } public String getZipFileName() { if (basename.equals(EAP)) { return getFullVersionName() + ".zip"; } else { return getFullVersionName() + ".Final.zip"; } } public int getMajor() { return major; } public int getMinor() { return minor; } public int getMicro() { return micro; } /** * Gets the maximum Java version under which a legacy host can properly * execute tests. */ public int getMaxVMVersion() { return maxVM; } /** * Gets the minimum Java version under which a legacy host can properly * execute tests. */ public int getMinVMVersion() { return minVM; } /** * Checks whether the current VM version exceeds the maximum version under which a legacy host can properly * execute tests. The check is disabled if system property "jboss.test.host.secondary.jvmhome" is set. */ public void assumeMaxVM() { if (System.getProperty("jboss.test.host.secondary.jvmhome") == null) { String javaSpecVersion = System.getProperty("java.specification.version"); int vm = "1.8".equals(javaSpecVersion) ? 8 : Integer.parseInt(javaSpecVersion); Assume.assumeFalse(vm > maxVM); } } public String getHostExclude() { return hostExclude; } public ModelVersion getModelVersion() { return modelVersion; } int compare(int major, int minor) { if (this.major < major) { return -1; } if (this.major > major) { return 1; } if (this.minor == minor) { return 0; } return this.minor < minor ? -1 : 1; } } }
5,439
31.771084
137
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/PatchRemoteHostTest.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, 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.test.integration.domain.mixed; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CORE_SERVICE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST; 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.RESTART; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SHUTDOWN; import static org.jboss.as.patching.Constants.MISC; import static org.jboss.as.patching.HashUtils.hashFile; import static org.jboss.as.patching.IoUtils.NO_CONTENT; import static org.jboss.as.patching.IoUtils.newFile; import static org.jboss.as.patching.metadata.ModificationType.ADD; import static org.jboss.as.test.integration.domain.mixed.patching.PatchingTestUtil.createPatchXMLFile; import static org.jboss.as.test.integration.domain.mixed.patching.PatchingTestUtil.createZippedPatchFile; import static org.jboss.as.test.integration.domain.mixed.patching.PatchingTestUtil.dump; import static org.jboss.as.test.integration.domain.mixed.patching.PatchingTestUtil.touch; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.Comparator; import java.util.Map; import java.util.stream.Stream; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.Operation; import org.jboss.as.controller.client.OperationBuilder; import org.jboss.as.patching.metadata.ContentModification; import org.jboss.as.patching.metadata.MiscContentItem; import org.jboss.as.patching.metadata.Patch; import org.jboss.as.patching.metadata.PatchBuilder; import org.jboss.as.process.protocol.StreamUtils; import org.jboss.as.test.integration.domain.management.util.DomainLifecycleUtil; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.integration.domain.management.util.DomainTestUtils; import org.jboss.as.test.integration.domain.management.util.WildFlyManagedConfiguration; import org.jboss.as.test.integration.management.base.AbstractCliTestBase; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.as.version.ProductConfig; import org.jboss.dmr.ModelNode; import org.jboss.modules.LocalModuleLoader; import org.jboss.modules.Module; import org.jboss.modules.ModuleLoader; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Tests we can patch and rollback a legacy host by using the patch high level commands and management operations. */ public class PatchRemoteHostTest extends AbstractCliTestBase { private static final int EXIT_CODE_HOST_TIMEOUT = TimeoutUtil.adjust(30); protected static final PathAddress HOST_SECONDARY = PathAddress.pathAddress(HOST, "secondary"); protected static final PathAddress CORE_SERVICE_PATCHING = PathAddress.pathAddress(CORE_SERVICE, "patching"); private static final Path TARGET_DIR = Paths.get(System.getProperty("basedir", ".")).resolve("target"); private static DomainLifecycleUtil primaryLifecycleUtil; private static DomainLifecycleUtil secondaryLifecycleUtil; private static MixedDomainTestSupport support; private static Path tempDir; private static ProductVersion secondaryProductVersion; @Before public void init() throws Exception { Assert.assertNotNull("This class is designed to be invoked from a parent test case that utilizes the @Version annotation to specify the target server version.", support); tempDir = Files.createTempDirectory(TARGET_DIR, "patch-remote-host-test-"); } @After public void cleanup() throws Exception { if (tempDir != null && tempDir.toFile().exists()) { try (Stream<Path> walk = Files.walk(tempDir)) { walk.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); } } } public static void setup(Class<?> testClass) throws IOException { support = MixedDomainTestSuite.getSupport(testClass); primaryLifecycleUtil = support.getDomainPrimaryLifecycleUtil(); secondaryLifecycleUtil = support.getDomainSecondaryLifecycleUtil(); WildFlyManagedConfiguration configuration = secondaryLifecycleUtil.getConfiguration(); secondaryProductVersion = new ProductVersion(configuration); } @Test public void testPatchCommand() throws Exception { try { AbstractCliTestBase.initCLI(DomainTestSupport.primaryAddress); // sanity check to validate we are connected to the primary DC and not to the secondary one final String primaryHostName = primaryLifecycleUtil.getConfiguration().getHostName(); final String secondaryHostName = secondaryLifecycleUtil.getConfiguration().getHostName(); Assert.assertTrue(cli.sendLine(" :query(select=[\"host\"])", false)); String response = cli.readOutput(); Assert.assertTrue(response.contains(primaryHostName)); Assert.assertTrue(response.contains(secondaryHostName)); // Patch high level commands are no longer available against primary host AssertionError exception = assertThrows(AssertionError.class, () -> { cli.sendLine("patch info --host=" + primaryHostName); }); String expectedMessage = "command is not supported on this host controller"; String actualMessage = exception.getMessage(); assertTrue(actualMessage, actualMessage.contains(expectedMessage)); // works against the secondary Assert.assertTrue(cli.sendLine("patch info --host=" + secondaryHostName, false)); final String patchID = "secondary-host-domain-patch"; final File patch = createOneOffPatchAddingMiscFile(patchID, secondaryProductVersion.getVersion()); cli.sendLine("patch apply " + patch.getAbsolutePath() + " --host=" + secondaryHostName); cli.close(); cli = null; // Restart the secondary final ModelControllerClient client = primaryLifecycleUtil.getDomainClient(); restartSecondary(client); // Connect CLI again and verify the patch was installed AbstractCliTestBase.initCLI(DomainTestSupport.primaryAddress); Assert.assertTrue(cli.sendLine("patch info --patch-id=" + patchID + " --host=" + secondaryHostName, false)); // rollback the latest patch Assert.assertTrue(cli.sendLine("patch rollback --reset-configuration=false --host=" + secondaryHostName, false)); cli.close(); cli = null; // restart the secondary restartSecondary(client); // Connect CLI again and verify the patch is no longer installed AbstractCliTestBase.initCLI(DomainTestSupport.primaryAddress); // Patch high level commands are no longer available against primary host exception = assertThrows(AssertionError.class, () -> { cli.sendLine("patch info --patch-id=" + patchID + " --host=" + secondaryHostName); }); //"WFLYPAT0021: Patch 'secondary-host-domain-patch' not found in history." expectedMessage = "WFLYPAT0021:"; actualMessage = exception.getMessage(); assertTrue(actualMessage, actualMessage.contains(expectedMessage)); } finally { if (cli.isConnected()) { cli.close(); } } } @Test public void testPatchMgmtOperation() throws Exception { final ModelControllerClient client = primaryLifecycleUtil.getDomainClient(); final ModelNode patchOp = new ModelNode(); patchOp.get(OP).set("patch"); patchOp.get(OP_ADDR).set(HOST_SECONDARY.append(CORE_SERVICE_PATCHING).toModelNode()); final String patchID = "simple-domain-patch"; final File patch = createOneOffPatchAddingMiscFile(patchID, secondaryProductVersion.getVersion()); final Operation op = OperationBuilder.create(patchOp).addFileAsAttachment(patch).build(); try { DomainTestUtils.executeForResult(op, client); } finally { StreamUtils.safeClose(op); } // Restart the secondary restartSecondary(client); final ModelNode patchesOp = new ModelNode(); patchesOp.get(OP).set(READ_ATTRIBUTE_OPERATION); patchesOp.get(OP_ADDR).set(HOST_SECONDARY.append(CORE_SERVICE_PATCHING).toModelNode()); patchesOp.get(NAME).set("patches"); // Check the applied patch final ModelNode entry = new ModelNode().set(patchID); Assert.assertTrue(DomainTestUtils.executeForResult(patchesOp, client).asList().contains(entry)); // Rollback final ModelNode rollback = new ModelNode(); rollback.get(OP).set("rollback"); rollback.get(OP_ADDR).set(HOST_SECONDARY.append(CORE_SERVICE_PATCHING).toModelNode()); rollback.get("patch-id").set(patchID); rollback.get("reset-configuration").set(false); DomainTestUtils.executeForResult(rollback, client); // Restart restartSecondary(client); // Check there is no patch applied Assert.assertTrue(DomainTestUtils.executeForResult(patchesOp, client).asList().isEmpty()); } static class ProductVersion { private final String product; private final String version; public ProductVersion(WildFlyManagedConfiguration configuration) throws IOException { final Path jbossHomeDir = Paths.get(configuration.getJbossHome()); final Path modulesRoot = jbossHomeDir.resolve("modules") .resolve("system") .resolve("layers") .resolve("base") .toAbsolutePath(); // Load the current product conf final LocalModuleLoader loader = new LocalModuleLoader(new File[]{modulesRoot.toFile()}); try { final Module module = loader.loadModule("org.jboss.as.version"); final Class<?> clazz = module.getClassLoader().loadClass("org.jboss.as.version.ProductConfig"); final Method resolveName = clazz.getMethod("resolveName"); final Method resolveVersion = clazz.getMethod("resolveVersion"); final Constructor<?> constructor = clazz.getConstructor(ModuleLoader.class, String.class, Map.class); final Object productConfig = constructor.newInstance(loader, jbossHomeDir.toAbsolutePath().toString(), Collections.emptyMap()); product = (String) resolveName.invoke(productConfig); version = (String) resolveVersion.invoke(productConfig); } catch (Exception e) { throw new RuntimeException(modulesRoot.toString(), e); } } public String getProduct() { return product; } public String getVersion() { return version; } } void restartSecondary(final ModelControllerClient client) throws Exception { final ModelNode restart = new ModelNode(); restart.get(OP).set(SHUTDOWN); restart.get(OP_ADDR).set(HOST_SECONDARY.toModelNode()); restart.get(RESTART).set(true); DomainTestUtils.executeForResult(restart, client); secondaryLifecycleUtil.awaitForProcessExitCode(EXIT_CODE_HOST_TIMEOUT); secondaryLifecycleUtil.start(); secondaryLifecycleUtil.awaitHostController(System.currentTimeMillis()); } private File createOneOffPatchAddingMiscFile(String patchID, String asVersion) throws Exception { File oneOffPatchDir = Files.createDirectories(tempDir.resolve(patchID)).toFile(); ContentModification miscFileAdded = addMisc(oneOffPatchDir, patchID, "test content", "awesomeDirectory", "awesomeFile"); ProductConfig productConfig = new ProductConfig(secondaryProductVersion.getProduct(), asVersion, "main"); Patch oneOffPatch = PatchBuilder.create().setPatchId(patchID).setDescription("A one-off patch adding a misc file.") .oneOffPatchIdentity(productConfig.getProductName(), productConfig.getProductVersion()).getParent() .addContentModification(miscFileAdded).build(); createPatchXMLFile(oneOffPatchDir, oneOffPatch); return createZippedPatchFile(oneOffPatchDir, patchID); } public static ContentModification addMisc(File patchDir, String patchElementID, String content, String... fileSegments) throws IOException { File miscDir = newFile(patchDir, patchElementID, MISC); File addedFile = touch(miscDir, fileSegments); dump(addedFile, content); byte[] newHash = hashFile(addedFile); String[] subdir = new String[fileSegments.length - 1]; System.arraycopy(fileSegments, 0, subdir, 0, fileSegments.length - 1); ContentModification fileAdded = new ContentModification(new MiscContentItem(addedFile.getName(), subdir, newHash), NO_CONTENT, ADD); return fileAdded; } }
14,887
47.025806
178
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/MixedDeploymentOverlayTestCase.java
/* * Copyright 2017 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.test.integration.domain.mixed; import static org.hamcrest.CoreMatchers.containsString; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ARCHIVE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.BYTES; 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.DEPLOYMENT_OVERLAY; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ENABLED; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_DEFAULTS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_RUNTIME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INPUT_STREAM_INDEX; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RUNTIME_NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_GROUP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.UNDEPLOY; import static org.junit.Assert.assertFalse; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.hamcrest.CoreMatchers; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.client.Operation; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.controller.client.helpers.domain.DomainClient; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.integration.domain.management.util.DomainTestUtils; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.threads.AsyncFuture; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; /** * * @author Emmanuel Hugonnet (c) 2017 Red Hat, inc. */ public class MixedDeploymentOverlayTestCase { private static final int TIMEOUT = TimeoutUtil.adjust(20000); private static final String DEPLOYMENT_NAME = "deployment.war"; private static final String MAIN_RUNTIME_NAME = "main-deployment.war"; private static final String OTHER_RUNTIME_NAME = "other-deployment.war"; private static final PathElement DEPLOYMENT_PATH = PathElement.pathElement(DEPLOYMENT, DEPLOYMENT_NAME); private static final PathElement DEPLOYMENT_OVERLAY_PATH = PathElement.pathElement(DEPLOYMENT_OVERLAY, "test-overlay"); private static final PathElement MAIN_SERVER_GROUP = PathElement.pathElement(SERVER_GROUP, "main-server-group"); private static final PathElement OTHER_SERVER_GROUP = PathElement.pathElement(SERVER_GROUP, "other-server-group"); private static MixedDomainTestSupport testSupport; private static DomainClient primaryClient; private static DomainClient secondaryClient; private Path overlayPath; public static void setupDomain() { testSupport = MixedDomainTestSuite.getSupport(MixedDeploymentOverlayTestCase.class, false); primaryClient = testSupport.getDomainPrimaryLifecycleUtil().getDomainClient(); secondaryClient = testSupport.getDomainSecondaryLifecycleUtil().getDomainClient(); } @AfterClass public static void tearDownDomain() throws Exception { testSupport = null; primaryClient.close(); primaryClient = null; secondaryClient.close(); secondaryClient = null; MixedDomainTestSuite.afterClass(); } @Before public void setUpDeployment() throws Exception { // Create our deployment and overlays WebArchive webArchive = ShrinkWrap.create(WebArchive.class, DEPLOYMENT_NAME); ClassLoader tccl = Thread.currentThread().getContextClassLoader(); webArchive.addAsWebResource(tccl.getResource("helloWorld/index.html"), "index.html"); overlayPath = new File(tccl.getResource("helloWorld/index_fr.html").toURI()).toPath(); ModelNode result; try (InputStream is = webArchive.as(ZipExporter.class).exportAsInputStream()){ AsyncFuture<ModelNode> future = primaryClient.executeAsync(addDeployment(is), null); result = awaitSimpleOperationExecution(future); } assertTrue(Operations.isSuccessfulOutcome(result)); ModelNode contentNode = readDeploymentResource(PathAddress.pathAddress(DEPLOYMENT_PATH)).require(CONTENT).require(0); assertTrue(contentNode.get(ARCHIVE).asBoolean(true)); } @After public void cleanup() throws IOException { try { cleanDeployment(); } catch (MgmtOperationException e) { // ignored } } @Test public void testInstallAndOverlayDeploymentOnDC() throws IOException, MgmtOperationException { //Let's deploy it on main-server-group executeAsyncForResult(primaryClient, deployOnServerGroup(MAIN_SERVER_GROUP, MAIN_RUNTIME_NAME)); performHttpCall(DomainTestSupport.secondaryAddress, 8280, "main-deployment/index.html", "Hello World"); if(isUndertowSupported()) { performHttpCall(DomainTestSupport.primaryAddress, 8080, "main-deployment/index.html", "Hello World"); } try { performHttpCall(DomainTestSupport.secondaryAddress, 8380, "main-deployment/index.html", "Hello World"); fail("'test' is available on secondary server-two"); } catch (IOException good) { // good } executeAsyncForResult(primaryClient, deployOnServerGroup(OTHER_SERVER_GROUP, OTHER_RUNTIME_NAME)); try { performHttpCall(DomainTestSupport.secondaryAddress, 8280, "other-deployment/index.html", "Hello World"); fail("'test' is available on primary server-one"); } catch (IOException good) { // good } performHttpCall(DomainTestSupport.secondaryAddress, 8380, "other-deployment/index.html", "Hello World"); if (isUndertowSupported()) { performHttpCall(DomainTestSupport.primaryAddress, 8180, "other-deployment/index.html", "Hello World"); } executeAsyncForResult(primaryClient, Operations.createOperation(ADD, PathAddress.pathAddress(DEPLOYMENT_OVERLAY_PATH).toModelNode())); //Add some content executeAsyncForResult(primaryClient, addOverlayContent(overlayPath)); //Add overlay on server-groups executeAsyncForResult(primaryClient, Operations.createOperation(ADD, PathAddress.pathAddress(MAIN_SERVER_GROUP, DEPLOYMENT_OVERLAY_PATH).toModelNode())); executeAsyncForResult(primaryClient, Operations.createOperation(ADD, PathAddress.pathAddress(MAIN_SERVER_GROUP, DEPLOYMENT_OVERLAY_PATH, PathElement.pathElement(DEPLOYMENT, MAIN_RUNTIME_NAME)).toModelNode())); executeAsyncForResult(primaryClient, Operations.createOperation(ADD, PathAddress.pathAddress(MAIN_SERVER_GROUP, DEPLOYMENT_OVERLAY_PATH, PathElement.pathElement(DEPLOYMENT, OTHER_RUNTIME_NAME)).toModelNode())); executeAsyncForResult(primaryClient, Operations.createOperation(ADD, PathAddress.pathAddress(OTHER_SERVER_GROUP, DEPLOYMENT_OVERLAY_PATH).toModelNode())); executeAsyncForResult(primaryClient, Operations.createOperation(ADD, PathAddress.pathAddress(OTHER_SERVER_GROUP, DEPLOYMENT_OVERLAY_PATH, PathElement.pathElement(DEPLOYMENT, OTHER_RUNTIME_NAME)).toModelNode())); //No deployment have been redeployed so overlay isn't really active if (isUndertowSupported()) { performHttpCall(DomainTestSupport.primaryAddress, 8080, "main-deployment/index.html", "Hello World"); performHttpCall(DomainTestSupport.primaryAddress, 8180, "other-deployment/index.html", "Hello World"); } performHttpCall(DomainTestSupport.secondaryAddress, 8280, "main-deployment/index.html", "Hello World"); performHttpCall(DomainTestSupport.secondaryAddress, 8380, "other-deployment/index.html", "Hello World"); ModelNode redeployNothingOperation = Operations.createOperation("redeploy-links", PathAddress.pathAddress(MAIN_SERVER_GROUP, DEPLOYMENT_OVERLAY_PATH).toModelNode()); redeployNothingOperation.get("deployments").setEmptyList(); redeployNothingOperation.get("deployments").add(OTHER_RUNTIME_NAME);//Doesn't exist redeployNothingOperation.get("deployments").add("inexisting.jar"); executeAsyncForResult(primaryClient, redeployNothingOperation); //Check that nothing happened //Only main-server-group deployments have been redeployed so overlay isn't active for other-server-group deployments if (isUndertowSupported()) { performHttpCall(DomainTestSupport.primaryAddress, 8080, "main-deployment/index.html", "Hello World"); performHttpCall(DomainTestSupport.primaryAddress, 8180, "other-deployment/index.html", "Hello World"); } performHttpCall(DomainTestSupport.secondaryAddress, 8280, "main-deployment/index.html", "Hello World"); performHttpCall(DomainTestSupport.secondaryAddress, 8380, "other-deployment/index.html", "Hello World"); executeAsyncForResult(primaryClient, Operations.createOperation("redeploy-links", PathAddress.pathAddress(MAIN_SERVER_GROUP, DEPLOYMENT_OVERLAY_PATH).toModelNode())); //Only main-server-group deployments have been redeployed so overlay isn't active for other-server-group deployments if (isUndertowSupported()) { performHttpCall(DomainTestSupport.primaryAddress, 8080, "main-deployment/index.html", "Bonjour le monde"); performHttpCall(DomainTestSupport.primaryAddress, 8180, "other-deployment/index.html", "Hello World"); } performHttpCall(DomainTestSupport.secondaryAddress, 8280, "main-deployment/index.html", "Bonjour le monde"); performHttpCall(DomainTestSupport.secondaryAddress, 8380, "other-deployment/index.html", "Hello World"); executeAsyncForResult(primaryClient, Operations.createOperation(REMOVE, PathAddress.pathAddress(MAIN_SERVER_GROUP, DEPLOYMENT_OVERLAY_PATH, PathElement.pathElement(DEPLOYMENT, MAIN_RUNTIME_NAME)).toModelNode())); executeAsyncForResult(primaryClient, Operations.createOperation(REMOVE, PathAddress.pathAddress(MAIN_SERVER_GROUP, DEPLOYMENT_OVERLAY_PATH, PathElement.pathElement(DEPLOYMENT, OTHER_RUNTIME_NAME)).toModelNode())); executeAsyncForResult(primaryClient, Operations.createOperation("redeploy-links", PathAddress.pathAddress(DEPLOYMENT_OVERLAY_PATH).toModelNode())); //Only other-server-group deployments have been redeployed because we have removed the overlay from main-server-group if(isUndertowSupported()) { performHttpCall(DomainTestSupport.primaryAddress, 8080, "main-deployment/index.html", "Bonjour le monde"); performHttpCall(DomainTestSupport.primaryAddress, 8180, "other-deployment/index.html", "Bonjour le monde"); } performHttpCall(DomainTestSupport.secondaryAddress, 8280, "main-deployment/index.html", "Bonjour le monde"); performHttpCall(DomainTestSupport.secondaryAddress, 8380, "other-deployment/index.html", "Bonjour le monde"); //Falling call to redeploy-links redeployNothingOperation = Operations.createOperation("redeploy-links", PathAddress.pathAddress(DEPLOYMENT_OVERLAY_PATH).toModelNode()); redeployNothingOperation.get("deployments").setEmptyList(); redeployNothingOperation.get("deployments").add(OTHER_RUNTIME_NAME); redeployNothingOperation.get("deployments").add("inexisting.jar"); executeAsyncForResult(primaryClient, redeployNothingOperation); //Check that nothing happened redeployNothingOperation = Operations.createOperation("redeploy-links", PathAddress.pathAddress(OTHER_SERVER_GROUP, DEPLOYMENT_OVERLAY_PATH).toModelNode()); redeployNothingOperation.get("deployments").setEmptyList(); redeployNothingOperation.get("deployments").add(OTHER_RUNTIME_NAME); executeAsyncForFailure(secondaryClient, redeployNothingOperation, getUnknowOperationErrorCode()); //Removing overlay for other-server-group deployments with affected set to true so those will be redeployed but not the deployments of main-server-group ModelNode removeLinkOp = Operations.createOperation(REMOVE, PathAddress.pathAddress(OTHER_SERVER_GROUP, DEPLOYMENT_OVERLAY_PATH, PathElement.pathElement(DEPLOYMENT, OTHER_RUNTIME_NAME)).toModelNode()); removeLinkOp.get("redeploy-affected").set(true); executeAsyncForResult(primaryClient, removeLinkOp); if(isUndertowSupported()) { performHttpCall(DomainTestSupport.primaryAddress, 8080, "main-deployment/index.html", "Bonjour le monde"); performHttpCall(DomainTestSupport.primaryAddress, 8180, "other-deployment/index.html", "Hello World"); } performHttpCall(DomainTestSupport.secondaryAddress, 8280, "main-deployment/index.html", "Bonjour le monde"); performHttpCall(DomainTestSupport.secondaryAddress, 8380, "other-deployment/index.html", "Hello World"); //Redeploying main-server-group deployment called main-deployment.war executeAsyncForResult(primaryClient, Operations.createOperation(ADD, PathAddress.pathAddress(OTHER_SERVER_GROUP, DEPLOYMENT_OVERLAY_PATH, PathElement.pathElement(DEPLOYMENT, OTHER_RUNTIME_NAME)).toModelNode())); executeAsyncForResult(primaryClient, Operations.createOperation(ADD, PathAddress.pathAddress(MAIN_SERVER_GROUP, DEPLOYMENT_OVERLAY_PATH, PathElement.pathElement(DEPLOYMENT, MAIN_RUNTIME_NAME)).toModelNode())); ModelNode redeployOp = Operations.createOperation("redeploy-links", PathAddress.pathAddress(MAIN_SERVER_GROUP, DEPLOYMENT_OVERLAY_PATH).toModelNode()); redeployOp.get("deployments").setEmptyList(); redeployOp.get("deployments").add(MAIN_RUNTIME_NAME); executeAsyncForResult(primaryClient, redeployOp); if (isUndertowSupported()) { performHttpCall(DomainTestSupport.primaryAddress, 8080, "main-deployment/index.html", "Bonjour le monde"); performHttpCall(DomainTestSupport.primaryAddress, 8180, "other-deployment/index.html", "Hello World"); } performHttpCall(DomainTestSupport.secondaryAddress, 8280, "main-deployment/index.html", "Bonjour le monde"); performHttpCall(DomainTestSupport.secondaryAddress, 8380, "other-deployment/index.html", "Hello World"); //Redeploying main-server-group deployment called other-deployment.war redeployOp = Operations.createOperation("redeploy-links", PathAddress.pathAddress(OTHER_SERVER_GROUP, DEPLOYMENT_OVERLAY_PATH).toModelNode()); redeployOp.get("deployments").setEmptyList(); redeployOp.get("deployments").add(OTHER_RUNTIME_NAME); executeAsyncForResult(primaryClient, redeployOp); if (isUndertowSupported()) { performHttpCall(DomainTestSupport.primaryAddress, 8080, "main-deployment/index.html", "Bonjour le monde"); performHttpCall(DomainTestSupport.primaryAddress, 8180, "other-deployment/index.html", "Bonjour le monde"); } performHttpCall(DomainTestSupport.secondaryAddress, 8280, "main-deployment/index.html", "Bonjour le monde"); performHttpCall(DomainTestSupport.secondaryAddress, 8380, "other-deployment/index.html", "Bonjour le monde"); //Remove all CLI style "deployment-overlay remove --name=overlay-test " ModelNode cliRemoveOverlay = Operations.createCompositeOperation(); cliRemoveOverlay.get(STEPS).add(Operations.createOperation(REMOVE, PathAddress.pathAddress(MAIN_SERVER_GROUP, DEPLOYMENT_OVERLAY_PATH).toModelNode())); cliRemoveOverlay.get(STEPS).add(Operations.createOperation(REMOVE, PathAddress.pathAddress(OTHER_SERVER_GROUP, DEPLOYMENT_OVERLAY_PATH).toModelNode())); cliRemoveOverlay.get(STEPS).add(Operations.createOperation(REMOVE, PathAddress.pathAddress(DEPLOYMENT_OVERLAY_PATH).toModelNode())); executeAsyncForResult(primaryClient, cliRemoveOverlay); } private void executeAsyncForResult(DomainClient client, ModelNode op) { AsyncFuture<ModelNode> future = client.executeAsync(op, null); ModelNode response = awaitSimpleOperationExecution(future); assertTrue(response.toJSONString(true), Operations.isSuccessfulOutcome(response)); } private void executeAsyncForFailure(DomainClient client, ModelNode op, String failureDescription) { AsyncFuture<ModelNode> future = client.executeAsync(op, null); ModelNode response = awaitSimpleOperationExecution(future); assertFalse(response.toJSONString(true), Operations.isSuccessfulOutcome(response)); assertThat(Operations.getFailureDescription(response).asString(), containsString(failureDescription)); } private ModelNode addOverlayContent(Path overlay) throws IOException { ModelNode op = Operations.createOperation(ADD, PathAddress.pathAddress(DEPLOYMENT_OVERLAY_PATH).append(CONTENT, "index.html").toModelNode()); try (ByteArrayOutputStream content = new ByteArrayOutputStream()) { Files.copy(overlay, content); op.get(CONTENT).get(BYTES).set(content.toByteArray()); } return op; } private void performHttpCall(String host, int port, String path, String expected) throws IOException { URL url = new URL("http://" + TestSuiteEnvironment.formatPossibleIpv6Address(host) + ":" + port + "/" + path); URLConnection conn = url.openConnection(); conn.setDoInput(true); try (InputStream in = new BufferedInputStream(conn.getInputStream()); StringWriter writer = new StringWriter()) { int i = in.read(); while (i != -1) { writer.write((char) i); i = in.read(); } String content = writer.toString(); assertThat(content, CoreMatchers.containsString(expected)); } } private ModelNode readDeploymentResource(PathAddress address) { ModelNode operation = Operations.createReadResourceOperation(address.toModelNode()); operation.get(INCLUDE_RUNTIME).set(true); operation.get(INCLUDE_DEFAULTS).set(true); AsyncFuture<ModelNode> future = primaryClient.executeAsync(operation, null); ModelNode result = awaitSimpleOperationExecution(future); assertTrue(Operations.isSuccessfulOutcome(result)); return Operations.readResult(result); } private ModelNode awaitSimpleOperationExecution(Future<ModelNode> future) { try { return future.get(TIMEOUT, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e.getCause()); } catch (TimeoutException e) { future.cancel(true); throw new RuntimeException(e); } } private Operation addDeployment(InputStream attachment) throws MalformedURLException { ModelNode operation = Operations.createAddOperation(PathAddress.pathAddress(DEPLOYMENT_PATH).toModelNode()); ModelNode content = new ModelNode(); content.get(INPUT_STREAM_INDEX).set(0); operation.get(CONTENT).add(content); return Operation.Factory.create(operation, Collections.singletonList(attachment)); } private ModelNode deployOnServerGroup(PathElement group, String runtimeName) throws MalformedURLException { ModelNode operation = Operations.createOperation(ADD, PathAddress.pathAddress(group, DEPLOYMENT_PATH).toModelNode()); operation.get(RUNTIME_NAME).set(runtimeName); operation.get(ENABLED).set(true); return operation; } private ModelNode undeployAndRemoveOp() throws MalformedURLException { ModelNode op = new ModelNode(); op.get(OP).set(COMPOSITE); ModelNode steps = op.get(STEPS); ModelNode sgDep = PathAddress.pathAddress(MAIN_SERVER_GROUP, DEPLOYMENT_PATH).toModelNode(); steps.add(Operations.createOperation(UNDEPLOY, sgDep)); steps.add(Operations.createRemoveOperation(sgDep)); sgDep = PathAddress.pathAddress(OTHER_SERVER_GROUP, DEPLOYMENT_PATH).toModelNode(); steps.add(Operations.createOperation(UNDEPLOY, sgDep)); steps.add(Operations.createRemoveOperation(sgDep)); steps.add(Operations.createRemoveOperation(PathAddress.pathAddress(DEPLOYMENT_PATH).toModelNode())); steps.add(Operations.createRemoveOperation(PathAddress.pathAddress(MAIN_SERVER_GROUP, DEPLOYMENT_OVERLAY_PATH).toModelNode())); steps.add(Operations.createRemoveOperation(PathAddress.pathAddress(OTHER_SERVER_GROUP, DEPLOYMENT_OVERLAY_PATH).toModelNode())); steps.add(Operations.createRemoveOperation(PathAddress.pathAddress(DEPLOYMENT_OVERLAY_PATH).toModelNode())); return op; } private void cleanDeployment() throws IOException, MgmtOperationException { DomainTestUtils.executeForResult(undeployAndRemoveOp(), primaryClient); } protected boolean isUndertowSupported() { return true; } protected String getUnknowOperationErrorCode() { Version version = this.getClass().getAnnotation(Version.class); if (version.value().compare(7, 1) < 0) { return "WFLYCTL0031"; } return "WFLYDC0032"; } }
23,519
62.0563
221
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/MixedDomainDeploymentTest.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.domain.mixed; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD_CONTENT; 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.ENABLED; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EMPTY; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INPUT_STREAM_INDEX; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REPLACE_DEPLOYMENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RUNTIME_NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_GROUP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.TARGET_PATH; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.TO_REPLACE; import static org.jboss.as.controller.operations.common.Util.createAddOperation; import static org.jboss.as.controller.operations.common.Util.createEmptyOperation; import static org.jboss.as.controller.operations.common.Util.createRemoveOperation; import static org.jboss.as.test.integration.domain.management.util.DomainTestSupport.validateResponse; import static org.jboss.as.test.integration.domain.management.util.DomainTestSupport.validateFailedResponse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.xnio.IoUtils.safeClose; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.net.URL; import java.net.URLConnection; import java.util.Collections; import java.util.List; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.Operation; import org.jboss.as.controller.client.OperationBuilder; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.exporter.ExplodedExporter; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.AfterClass; import org.junit.Assume; import org.junit.Before; import org.junit.Test; /** * * @author <a href="[email protected]">Kabir Khan</a> */ public abstract class MixedDomainDeploymentTest { private static final String TEST = "test.war"; private static final String REPLACEMENT = "test.war.v2"; private static final PathAddress ROOT_DEPLOYMENT_ADDRESS = PathAddress.pathAddress(DEPLOYMENT, TEST); private static final PathAddress ROOT_REPLACEMENT_ADDRESS = PathAddress.pathAddress(DEPLOYMENT, REPLACEMENT); private static final PathAddress OTHER_SERVER_GROUP_ADDRESS = PathAddress.pathAddress(SERVER_GROUP, "other-server-group"); private static final PathAddress OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS = OTHER_SERVER_GROUP_ADDRESS.append(DEPLOYMENT, TEST); private static final PathAddress MAIN_SERVER_GROUP_ADDRESS = PathAddress.pathAddress(SERVER_GROUP, "main-server-group"); private static final PathAddress MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS = MAIN_SERVER_GROUP_ADDRESS.append(DEPLOYMENT, TEST); private WebArchive webArchive; private WebArchive webArchive2; private MixedDomainTestSupport testSupport; private File tmpDir; @Before public void setupDomain() throws Exception { // Create our deployments webArchive = ShrinkWrap.create(WebArchive.class, TEST); ClassLoader tccl = Thread.currentThread().getContextClassLoader(); URL index = tccl.getResource("helloWorld/index.html"); webArchive.addAsWebResource(index, "index.html"); webArchive2 = ShrinkWrap.create(WebArchive.class, TEST); index = tccl.getResource("helloWorld/index.html"); webArchive2.addAsWebResource(index, "index.html"); index = tccl.getResource("helloWorld/index2.html"); webArchive2.addAsWebResource(index, "index2.html"); // Make versions on the filesystem for URL-based deploy and for unmanaged content testing tmpDir = new File("target/deployments/" + this.getClass().getSimpleName()); new File(tmpDir, "archives").mkdirs(); new File(tmpDir, "exploded").mkdirs(); webArchive.as(ZipExporter.class).exportTo(new File(tmpDir, "archives/" + TEST), true); webArchive.as(ExplodedExporter.class).exportExploded(new File(tmpDir, "exploded")); // Launch the domain testSupport = MixedDomainTestSuite.getSupport(this.getClass()); confirmNoDeployments(); } @AfterClass public static synchronized void afterClass() { MixedDomainTestSuite.afterClass(); } /** * Validate that there are no deployments; try and clean if there are. * * @throws Exception */ @After public void confirmNoDeployments() throws Exception { List<ModelNode> deploymentList = getDeploymentList(PathAddress.EMPTY_ADDRESS); if (deploymentList.size() > 0) { cleanDeployments(); } deploymentList = getDeploymentList(PathAddress.EMPTY_ADDRESS); assertEquals("Deployments are removed from the domain", 0, deploymentList.size()); try { performHttpCall(DomainTestSupport.primaryAddress, 8080); fail(TEST + " is available on main-one"); } catch (IOException good) { // good } try { performHttpCall(DomainTestSupport.secondaryAddress, 8630); fail(TEST + " is available on other-three"); } catch (IOException good) { // good } } @Test public void testDeploymentViaUrl() throws Exception { String url = new File(tmpDir, "archives/" + TEST).toURI().toURL().toString(); ModelNode content = new ModelNode(); content.get("url").set(url); ModelNode composite = createDeploymentOperation(content, OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS, MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS); executeOnPrimary(composite); performHttpCall(DomainTestSupport.secondaryAddress, 8080); } @Test public void testDeploymentViaStream() throws Exception { ModelNode content = new ModelNode(); content.get(INPUT_STREAM_INDEX).set(0); ModelNode composite = createDeploymentOperation(content, OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS, MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS); OperationBuilder builder = new OperationBuilder(composite, true); builder.addInputStream(webArchive.as(ZipExporter.class).exportAsInputStream()); executeOnPrimary(builder.build()); performHttpCall(DomainTestSupport.secondaryAddress, 8080); } @Test public void testUnmanagedArchiveDeployment() throws Exception { ModelNode content = new ModelNode(); content.get("archive").set(true); content.get("path").set(new File(tmpDir, "archives/" + TEST).getAbsolutePath()); ModelNode composite = createDeploymentOperation(content, OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS, MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS); executeOnPrimary(composite); performHttpCall(DomainTestSupport.secondaryAddress, 8080); } @Test public void testUnmanagedExplodedDeployment() throws Exception { ModelNode content = new ModelNode(); content.get("archive").set(false); content.get("path").set(new File(tmpDir, "exploded/" + TEST).getAbsolutePath()); ModelNode composite = createDeploymentOperation(content, OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS, MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS); executeOnPrimary(composite); performHttpCall(DomainTestSupport.secondaryAddress, 8080); } protected boolean supportManagedExplodedDeployment() { return true; } @Test public void testExplodedEmptyDeployment() throws Exception { ModelNode empty = new ModelNode(); empty.get(EMPTY).set(true); ModelNode composite = createDeploymentOperation(empty, OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS, MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS); if (supportManagedExplodedDeployment()) { executeOnPrimary(composite); } else { ModelNode failure = executeForFailureOnPrimary(composite); assertTrue(failure.toJSONString(true), failure.toJSONString(true).contains("WFLYCTL0421:")); } } @Test public void testExplodedDeployment() throws Exception { // TODO WFLY-9634 Assume.assumeFalse(supportManagedExplodedDeployment()); ModelNode composite = createEmptyOperation(COMPOSITE, PathAddress.EMPTY_ADDRESS); ModelNode steps = composite.get(STEPS); ModelNode op = createAddOperation(ROOT_DEPLOYMENT_ADDRESS); op.get(CONTENT).setEmptyList(); ModelNode empty = new ModelNode(); empty.get(EMPTY).set(true); op.get(CONTENT).add(empty); steps.add(op); op = createEmptyOperation(ADD_CONTENT, ROOT_DEPLOYMENT_ADDRESS); op.get(CONTENT).setEmptyList(); ModelNode file = new ModelNode(); file.get(TARGET_PATH).set("index.html"); file.get(INPUT_STREAM_INDEX).set(0); op.get(CONTENT).add(file); file = new ModelNode(); file.get(TARGET_PATH).set("index2.html"); file.get(INPUT_STREAM_INDEX).set(1); op.get(CONTENT).add(file); steps.add(op); ModelNode sg = steps.add(); sg.set(createAddOperation(OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS)); sg.get(ENABLED).set(true); sg = steps.add(); sg.set(createAddOperation(MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS)); sg.get(ENABLED).set(true); ClassLoader tccl = Thread.currentThread().getContextClassLoader(); OperationBuilder builder = new OperationBuilder(composite); builder.addInputStream(tccl.getResourceAsStream("helloWorld/index.html")); builder.addInputStream(tccl.getResourceAsStream("helloWorld/index2.html")); if (supportManagedExplodedDeployment()) { executeOnPrimary(builder.build()); performHttpCall(DomainTestSupport.secondaryAddress, 8080); } else { ModelNode failure = executeForFailureOnPrimary(builder.build()); assertTrue(failure.toJSONString(true), failure.toJSONString(true).contains("WFLYCTL0421:")); } } @Test public void testUndeploy() throws Exception { // Establish the deployment testDeploymentViaStream(); undeployTest(); } @Test public void testUnmanagedArchiveUndeploy() throws Exception { // Establish the deployment testUnmanagedArchiveDeployment(); undeployTest(); } @Test public void testUnmanagedExplodedUndeploy() throws Exception { // Establish the deployment testUnmanagedExplodedDeployment(); undeployTest(); } @Test public void testRedeploy() throws Exception { // Establish the deployment testDeploymentViaStream(); redeployTest(); } @Test public void testUnmanagedArchiveRedeploy() throws Exception { // Establish the deployment testUnmanagedArchiveDeployment(); redeployTest(); } @Test public void testUnmanagedExplodedRedeploy() throws Exception { // Establish the deployment testUnmanagedExplodedDeployment(); redeployTest(); } @Test public void testReplace() throws Exception { // Establish the deployment testDeploymentViaStream(); ModelNode content = new ModelNode(); content.get(INPUT_STREAM_INDEX).set(0); ModelNode op = createDeploymentReplaceOperation(content, OTHER_SERVER_GROUP_ADDRESS, MAIN_SERVER_GROUP_ADDRESS); OperationBuilder builder = new OperationBuilder(op, true); builder.addInputStream(webArchive.as(ZipExporter.class).exportAsInputStream()); executeOnPrimary(builder.build()); performHttpCall(DomainTestSupport.secondaryAddress, 8080); } private void redeployTest() throws IOException { ModelNode op = createEmptyOperation("redeploy", OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS); executeOnPrimary(op); performHttpCall(DomainTestSupport.secondaryAddress, 8080); } private void undeployTest() throws Exception { ModelNode op = createEmptyOperation("undeploy", OTHER_SERVER_GROUP_DEPLOYMENT_ADDRESS); executeOnPrimary(op); // Thread.sleep(1000); try { performHttpCall(DomainTestSupport.secondaryAddress, 8080); fail("Webapp still accessible following undeploy"); } catch (IOException good) { // desired result } } /** * Remove all deployments from the model. * * @throws IOException */ private void cleanDeployments() throws IOException { List<ModelNode> deploymentList = getDeploymentList(OTHER_SERVER_GROUP_ADDRESS); for (ModelNode deployment : deploymentList) { removeDeployment(deployment.asString(), OTHER_SERVER_GROUP_ADDRESS); } deploymentList = getDeploymentList(MAIN_SERVER_GROUP_ADDRESS); for (ModelNode deployment : deploymentList) { removeDeployment(deployment.asString(), MAIN_SERVER_GROUP_ADDRESS); } deploymentList = getDeploymentList(PathAddress.EMPTY_ADDRESS); for (ModelNode deployment : deploymentList) { removeDeployment(deployment.asString(), PathAddress.EMPTY_ADDRESS); } } private ModelNode executeOnPrimary(ModelNode op) throws IOException { return validateResponse(testSupport.getDomainPrimaryLifecycleUtil().getDomainClient().execute(op)); } private ModelNode executeOnPrimary(Operation op) throws IOException { return validateResponse(testSupport.getDomainPrimaryLifecycleUtil().getDomainClient().execute(op)); } private ModelNode executeForFailureOnPrimary(ModelNode op) throws IOException { return validateFailedResponse(testSupport.getDomainPrimaryLifecycleUtil().getDomainClient().execute(op)); } private ModelNode executeForFailureOnPrimary(Operation op) throws IOException { return validateFailedResponse(testSupport.getDomainPrimaryLifecycleUtil().getDomainClient().execute(op)); } private ModelNode createDeploymentOperation(ModelNode content, PathAddress... serverGroupAddressses) { ModelNode composite = createEmptyOperation(COMPOSITE, PathAddress.EMPTY_ADDRESS); ModelNode steps = composite.get(STEPS); ModelNode step1 = steps.add(); step1.set(createAddOperation(ROOT_DEPLOYMENT_ADDRESS)); step1.get(CONTENT).add(content); for (PathAddress serverGroup : serverGroupAddressses) { ModelNode sg = steps.add(); sg.set(createAddOperation(serverGroup)); sg.get(ENABLED).set(true); } return composite; } private ModelNode createDeploymentReplaceOperation(ModelNode content, PathAddress... serverGroupAddressses) { ModelNode composite = createEmptyOperation(COMPOSITE, PathAddress.EMPTY_ADDRESS); ModelNode steps = composite.get(STEPS); ModelNode step1 = steps.add(); step1.set(createAddOperation(ROOT_REPLACEMENT_ADDRESS)); step1.get(RUNTIME_NAME).set(TEST); step1.get(CONTENT).add(content); for (PathAddress serverGroup : serverGroupAddressses) { ModelNode sgr = steps.add(); sgr.set(createEmptyOperation(REPLACE_DEPLOYMENT, serverGroup)); sgr.get(ENABLED).set(true); sgr.get(NAME).set(REPLACEMENT); sgr.get(TO_REPLACE).set(TEST); } return composite; } private List<ModelNode> getDeploymentList(PathAddress address) throws IOException { ModelNode op = createEmptyOperation("read-children-names", address); op.get("child-type").set("deployment"); ModelNode response = testSupport.getDomainPrimaryLifecycleUtil().getDomainClient().execute(op); ModelNode result = validateResponse(response); return result.isDefined() ? result.asList() : Collections.<ModelNode>emptyList(); } private void performHttpCall(String host, int port) throws IOException { performHttpCall(host, port, "test/index.html", "Hello World"); } private void performHttpCall(String host, int port, String path, String expected) throws IOException { URLConnection conn = null; InputStream in = null; StringWriter writer = new StringWriter(); try { URL url = new URL("http://" + TestSuiteEnvironment.formatPossibleIpv6Address(host) + ":" + port + "/" + path); //System.out.println("Reading response from " + url + ":"); conn = url.openConnection(); conn.setDoInput(true); in = new BufferedInputStream(conn.getInputStream()); int i = in.read(); while (i != -1) { writer.write((char) i); i = in.read(); } assertTrue((writer.toString().indexOf(expected) > -1)); //System.out.println("OK"); } finally { safeClose(in); safeClose(writer); } } private void removeDeployment(String deploymentName, PathAddress address) throws IOException { ModelNode op = createRemoveOperation(address.append(DEPLOYMENT, deploymentName)); ModelNode response = testSupport.getDomainPrimaryLifecycleUtil().getDomainClient().execute(op); validateResponse(response); } }
19,398
40.628755
142
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/LegacySubsystemConfigurationUtil.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, 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.test.integration.domain.mixed; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.stream.XMLStreamException; import org.jboss.as.controller.Extension; import org.jboss.as.controller.PathAddress; import org.jboss.dmr.ModelNode; import org.wildfly.build.configassembly.ConfigurationAssembler; import org.wildfly.build.configassembly.SubsystemConfig; import org.wildfly.build.configassembly.SubsystemInputStreamSources; import org.wildfly.build.util.FileInputStreamSource; import org.wildfly.build.util.InputStreamSource; import org.wildfly.test.mixed.domain.TestParserUtils; /** * Used by the domain adjuster to generate subsystem.xml files from existing templates for large/complex susbsystems. * Any extensions and socket binding groups must still be added manually. * * * @author Kabir Khan */ public class LegacySubsystemConfigurationUtil { private static final String SUBSYSTEM_OPEN = "<subsystem"; private static final String SUBSYSTEM_CLOSE = "</subsystem>"; private static final String TEST_NAMESPACE = "urn.org.jboss.test:1.0"; final Extension extension; final String subsystemName; final String supplement; final String resourceName; final PathAddress profile; public LegacySubsystemConfigurationUtil(Extension extension, PathAddress profile, String subsystemName, String supplement, String resourceName) { this.extension = extension; this.subsystemName = subsystemName; this.supplement = supplement; this.resourceName = resourceName; this.profile = profile; } public List<ModelNode> getSubsystemOperations() throws Exception { File file = createAssembly(); String subsystemXml = extractSubsystemXml(file); List<ModelNode> list = parseSubsystemXml(subsystemXml); for (ModelNode op : list) { PathAddress address = PathAddress.pathAddress(op.get(OP_ADDR)); op.get(OP_ADDR).set(profile.append(address).toModelNode()); } return list; } private List<ModelNode> parseSubsystemXml(String subsystemXml) throws XMLStreamException { return new TestParserUtils.Builder(extension, subsystemName, subsystemXml) .build() .parseOperations(); } private String extractSubsystemXml(File file) throws IOException { StringBuilder sb = new StringBuilder(); List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); boolean inSusbsystem = false; for (String line : lines) { if (!inSusbsystem) { if (line.contains(SUBSYSTEM_OPEN)) { inSusbsystem = true; //This does not take into account things like <subsystem xmlns="..."/> but for simple subsystems //like that this class should not be used anyway. sb.append(line.substring(line.indexOf(SUBSYSTEM_OPEN))); } } else { if (!line.contains(SUBSYSTEM_CLOSE)) { sb.append(line); } else { sb.append(line, 0, line.indexOf(SUBSYSTEM_CLOSE) + SUBSYSTEM_CLOSE.length()); break; } } } return sb.toString(); } private File createAssembly() throws IOException, XMLStreamException, URISyntaxException { final Map<String, Map<String, SubsystemConfig>> subsystemConfigs = new HashMap<>(); final SubsystemInputStreamSources subsystemSources = createSubsystemInputStreamSources(subsystemConfigs); final File outputFile = createOutputFile(); outputFile.delete(); final URL url = this.getClass().getClassLoader().getResource("legacy-templates/test-template.xml"); if (url == null) { throw new IllegalStateException("Can't find the template file"); } final InputStreamSource template = new FileInputStreamSource(new File(url.toURI())); final ConfigurationAssembler assembler = new ConfigurationAssembler(subsystemSources, template, "server", subsystemConfigs, outputFile); assembler.assemble(); return outputFile; } private SubsystemInputStreamSources createSubsystemInputStreamSources(Map<String, Map<String, SubsystemConfig>> subsystemConfigs) { final Map<String, URL> urls = new HashMap<>(); addSubsystem(urls, subsystemConfigs, "messaging", "ha", "subsystem-templates/messaging.xml"); return new SubsystemInputStreamSources() { @Override public InputStreamSource getInputStreamSource(String subsystem) { URL url = urls.get(subsystem); if (url == null) { throw new IllegalArgumentException("No stream for " + subsystem); } return new InputStreamSource() { @Override public InputStream getInputStream() throws IOException { return new BufferedInputStream(url.openStream()); } }; } }; } private void addSubsystem(Map<String, URL> urls, Map<String, Map<String, SubsystemConfig>> subsystemConfigs, String subsystem, String supplement, String resourceName) { URL url = this.getClass().getClassLoader().getResource(resourceName); if (url == null) { throw new IllegalArgumentException("Could not find " + resourceName); } urls.put(subsystem, url); Map<String, SubsystemConfig> config = Collections.singletonMap(subsystem, new SubsystemConfig(subsystem, supplement)); subsystemConfigs.put("", config); } private File createOutputFile() throws IOException, URISyntaxException { final URL url = this.getClass().getProtectionDomain().getCodeSource().getLocation(); final File target = new File(url.toURI()).getParentFile(); final File output = new File(target, subsystemName + "-legacy-xml"); if (!output.exists()) { Files.createDirectories(Paths.get(output.getAbsolutePath())); } return new File(output, "test.xml"); }}
7,677
41.41989
172
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/WildcardReadsTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.domain.mixed; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADDRESS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ATTRIBUTES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.AUTO_START; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.GROUP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_RUNTIME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INET_ADDRESS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INTERFACE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PRIMARY; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PORT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.QUERY; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_DESCRIPTION_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RUNNING_SERVER; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SELECT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_CONFIG; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_GROUP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING_GROUP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WHERE; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Locale; import java.util.Set; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.dmr.ValueExpression; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; /** * Tests for cross-process wildcard reads in a mixed domain. See https://issues.jboss.org/browse/WFCORE-621. * * @author Brian Stansberry */ public class WildcardReadsTestCase { private static final PathElement HOST_WILD = PathElement.pathElement(HOST); private static final PathElement HOST_PRIMARY = PathElement.pathElement(HOST, "primary"); private static final PathElement HOST_SECONDARY = PathElement.pathElement(HOST, "secondary"); private static final PathElement SERVER_WILD = PathElement.pathElement(RUNNING_SERVER); private static final PathElement SERVER_ONE = PathElement.pathElement(RUNNING_SERVER, "server-one"); private static final PathElement INTERFACE_WILD = PathElement.pathElement(INTERFACE); private static final PathElement INTERFACE_PUBLIC = PathElement.pathElement(INTERFACE, "public"); private static final PathElement SERVER_CONFIG_WILD = PathElement.pathElement(SERVER_CONFIG); private static final PathElement SERVER_CONFIG_ONE = PathElement.pathElement(SERVER_CONFIG, "server-one"); private static final PathAddress SOCKET_BINDING_HTTP = PathAddress.pathAddress(PathElement.pathElement(SOCKET_BINDING_GROUP, "standard-sockets"), PathElement.pathElement(SOCKET_BINDING, "http")); private static final ValueExpression PRIMARY_ADDRESS = new ValueExpression("${jboss.test.host.primary.address}"); private static final ValueExpression SECONDARY_ADDRESS = new ValueExpression("${jboss.test.host.secondary.address}"); private static final Set<String> VALID_STATES = new HashSet<>(Arrays.asList("running", "stopped")); private static DomainTestSupport support; private static Boolean primaryServerOneStarted; @Before public void init() throws Exception { support = KernelBehaviorTestSuite.getSupport(this.getClass()); if (primaryServerOneStarted == null) { String state = readPrimaryServerOneState(); primaryServerOneStarted = "running".equalsIgnoreCase(state); } if (!primaryServerOneStarted) { ModelNode op = Util.createEmptyOperation("start", PathAddress.pathAddress(HOST_PRIMARY, SERVER_CONFIG_ONE)); executeForResult(op, ModelType.STRING); String state; long timeout = System.currentTimeMillis() + TimeoutUtil.adjust(30000); while (!"running".equalsIgnoreCase(state = readPrimaryServerOneState()) && System.currentTimeMillis() < timeout) { Thread.sleep(25); } assertNotNull("Could not start primary/server-one", state); assertEquals("Could not start primary/server-one", "running", state.toLowerCase(Locale.ENGLISH)); } } private static String readPrimaryServerOneState() throws IOException { ModelNode op = Util.getReadAttributeOperation(PathAddress.pathAddress(HOST_PRIMARY, SERVER_ONE), "server-state"); ModelNode response = support.getDomainPrimaryLifecycleUtil().getDomainClient().execute(op); if (SUCCESS.equals(response.get(OUTCOME).asString())) { return response.get(RESULT).asString(); } return null; } @AfterClass public static synchronized void afterClass() { if (primaryServerOneStarted == Boolean.FALSE) { ModelNode op = Util.createEmptyOperation("stop", PathAddress.pathAddress(HOST_PRIMARY, SERVER_CONFIG_ONE)); executeForResult(op, ModelType.STRING); } KernelBehaviorTestSuite.afterClass(); } @Test public void testAllHostsAllServersReadInterfaceResources() { ModelNode op = Util.createEmptyOperation(READ_RESOURCE_OPERATION, PathAddress.pathAddress(HOST_WILD, SERVER_WILD, INTERFACE_WILD)); ModelNode resp = executeForResult(op); assertEquals(resp.toString(), 6, resp.asInt()); int primaryCount = 0; for (ModelNode item : resp.asList()) { if (isPrimaryItem(item, 3)) { primaryCount++; } assertEquals(item.toString(), ModelType.EXPRESSION, item.get(RESULT, INET_ADDRESS).getType()); } assertEquals(resp.toString(), 3, primaryCount); } @Test public void testSecondaryAllServersReadInterfaceResources() { ModelNode op = Util.createEmptyOperation(READ_RESOURCE_OPERATION, PathAddress.pathAddress(HOST_SECONDARY, SERVER_WILD, INTERFACE_WILD)); ModelNode resp = executeForResult(op); assertEquals(resp.toString(), 3, resp.asInt()); int primaryCount = 0; for (ModelNode item : resp.asList()) { if (isPrimaryItem(item, 3)) { primaryCount++; } assertEquals(item.toString(), ModelType.EXPRESSION, item.get(RESULT, INET_ADDRESS).getType()); } assertEquals(resp.toString(), 0, primaryCount); } @Test public void testAllHostsAllServersReadRootResource() { ModelNode op = Util.createEmptyOperation(READ_RESOURCE_OPERATION, PathAddress.pathAddress(HOST_WILD, SERVER_WILD)); op.get(INCLUDE_RUNTIME).set(true); ModelNode resp = executeForResult(op); assertEquals(resp.toString(), expectUnstartedServerResource() ? 4 : 3, resp.asInt()); int primaryCount = 0; for (ModelNode item : resp.asList()) { if (isPrimaryItem(item, 2)) { primaryCount++; } assertTrue(item.toString(), VALID_STATES.contains(item.get(RESULT, "server-state").asString().toLowerCase(Locale.ENGLISH))); } assertEquals(resp.toString(), 2, primaryCount); } @Test public void testSecondaryAllServersReadRootResource() { ModelNode op = Util.createEmptyOperation(READ_RESOURCE_OPERATION, PathAddress.pathAddress(HOST_SECONDARY, SERVER_WILD)); op.get(INCLUDE_RUNTIME).set(true); ModelNode resp = executeForResult(op); assertEquals(resp.toString(), expectUnstartedServerResource() ? 2 : 1, resp.asInt()); int primaryCount = 0; for (ModelNode item : resp.asList()) { if (isPrimaryItem(item, 2)) { primaryCount++; } assertTrue(item.toString(), VALID_STATES.contains(item.get(RESULT, "server-state").asString().toLowerCase(Locale.ENGLISH))); } assertEquals(resp.toString(), 0, primaryCount); } @Test public void testAllHostsAllServersReadInterfaceAttribute() { ModelNode op = Util.createEmptyOperation(READ_ATTRIBUTE_OPERATION, PathAddress.pathAddress(HOST_WILD, SERVER_WILD, INTERFACE_PUBLIC)); op.get(NAME).set("inet-address"); ModelNode resp = executeForResult(op); assertEquals(resp.toString(), 2, resp.asInt()); int primaryCount = 0; for (ModelNode item : resp.asList()) { if (isPrimaryItem(item, 3)) { primaryCount++; } assertEquals(item.toString(), ModelType.EXPRESSION, item.get(RESULT).getType()); } assertEquals(resp.toString(), 1, primaryCount); } @Test public void testSecondaryAllServersReadInterfaceAttribute() { ModelNode op = Util.createEmptyOperation(READ_ATTRIBUTE_OPERATION, PathAddress.pathAddress(HOST_SECONDARY, SERVER_WILD, INTERFACE_PUBLIC)); op.get(NAME).set("inet-address"); ModelNode resp = executeForResult(op); assertEquals(resp.toString(), 1, resp.asInt()); int primaryCount = 0; for (ModelNode item : resp.asList()) { if (isPrimaryItem(item, 3)) { primaryCount++; } assertEquals(item.toString(), ModelType.EXPRESSION, item.get(RESULT).getType()); } assertEquals(resp.toString(), 0, primaryCount); } @Test public void testAllHostsAllServersReadRootAttribute() { ModelNode op = Util.createEmptyOperation(READ_ATTRIBUTE_OPERATION, PathAddress.pathAddress(HOST_WILD, SERVER_WILD)); op.get(NAME).set("server-state"); ModelNode resp = executeForResult(op); assertEquals(resp.toString(), expectUnstartedServerResource() ? 4 : 3, resp.asInt()); int primaryCount = 0; for (ModelNode item : resp.asList()) { if (isPrimaryItem(item, 2)) { primaryCount++; } assertTrue(item.toString(), VALID_STATES.contains(item.get(RESULT).asString().toLowerCase(Locale.ENGLISH))); } assertEquals(resp.toString(), 2, primaryCount); } @Test public void testSecondaryAllServersReadRootAttribute() { ModelNode op = Util.createEmptyOperation(READ_ATTRIBUTE_OPERATION, PathAddress.pathAddress(HOST_SECONDARY, SERVER_WILD)); op.get(NAME).set("server-state"); ModelNode resp = executeForResult(op); assertEquals(resp.toString(), expectUnstartedServerResource() ? 2 : 1, resp.asInt()); int primaryCount = 0; for (ModelNode item : resp.asList()) { if (isPrimaryItem(item, 2)) { primaryCount++; } assertTrue(item.toString(), VALID_STATES.contains(item.get(RESULT).asString().toLowerCase(Locale.ENGLISH))); } assertEquals(resp.toString(), 0, primaryCount); } @Test public void testAllHostsAllServersReadInterfaceDescription() { ModelNode op = Util.createEmptyOperation(READ_RESOURCE_DESCRIPTION_OPERATION, PathAddress.pathAddress(HOST_WILD, SERVER_WILD, INTERFACE_PUBLIC)); ModelNode resp = executeForResult(op); assertEquals(resp.toString(), 2, resp.asInt()); int primaryCount = 0; for (ModelNode item : resp.asList()) { if (isPrimaryItem(item, 3)) { primaryCount++; } assertTrue(item.toString(), item.hasDefined(RESULT, ATTRIBUTES, INET_ADDRESS)); } assertEquals(resp.toString(), 1, primaryCount); } @Test public void testSecondaryAllServersReadInterfaceDescription() { ModelNode op = Util.createEmptyOperation(READ_RESOURCE_DESCRIPTION_OPERATION, PathAddress.pathAddress(HOST_SECONDARY, SERVER_WILD, INTERFACE_PUBLIC)); ModelNode resp = executeForResult(op); assertEquals(resp.toString(), 1, resp.asInt()); int primaryCount = 0; for (ModelNode item : resp.asList()) { if (isPrimaryItem(item, 3)) { primaryCount++; } assertTrue(item.toString(), item.hasDefined(RESULT, ATTRIBUTES, INET_ADDRESS)); } assertEquals(resp.toString(), 0, primaryCount); } @Test public void testAllHostsAllServersReadRootDescription() { ModelNode op = Util.createEmptyOperation(READ_RESOURCE_DESCRIPTION_OPERATION, PathAddress.pathAddress(HOST_WILD, SERVER_WILD)); ModelNode resp = executeForResult(op); assertEquals(resp.toString(), expectUnstartedServerResource() ? 4 : 3, resp.asInt()); int primaryCount = 0; for (ModelNode item : resp.asList()) { if (isPrimaryItem(item, 2)) { primaryCount++; } assertTrue(item.toString(), item.hasDefined(RESULT, ATTRIBUTES, "server-state")); } assertEquals(resp.toString(), 2, primaryCount); } @Test public void testSecondaryAllServersReadRootDescription() { ModelNode op = Util.createEmptyOperation(READ_RESOURCE_DESCRIPTION_OPERATION, PathAddress.pathAddress(HOST_SECONDARY, SERVER_WILD)); ModelNode resp = executeForResult(op); assertEquals(resp.toString(), expectUnstartedServerResource() ? 2 : 1, resp.asInt()); int primaryCount = 0; for (ModelNode item : resp.asList()) { if (isPrimaryItem(item, 2)) { primaryCount++; } assertTrue(item.toString(), item.hasDefined(RESULT, ATTRIBUTES, "server-state")); } assertEquals(resp.toString(), 0, primaryCount); } @Test public void testWildcardHostRootQuery() { // Basic /host=*:query ModelNode op = Util.createEmptyOperation(QUERY, PathAddress.pathAddress(HOST_WILD)); ModelNode resp = executeForResult(op); assertEquals(resp.toString(), 2, resp.asInt()); ModelNode secondaryResult = null; int primaryCount = 0; for (ModelNode item : resp.asList()) { if (isPrimaryItem(item, 1)) { primaryCount++; } else { secondaryResult = item.get(RESULT); } assertTrue(item.toString(), item.hasDefined(RESULT, "host-state")); } assertEquals(resp.toString(), 1, primaryCount); assertNotNull(resp.toString(), secondaryResult); // Now limit the result to secondary hosts op.get(WHERE, PRIMARY).set(false); resp = executeForResult(op); assertEquals(resp.toString(), 0, resp.asInt()); op = Util.createEmptyOperation(QUERY, PathAddress.pathAddress(HOST_WILD)); op.get(WHERE, "master").set(false); resp = executeForResult(op); assertEquals(resp.toString(), 1, resp.asInt()); assertEquals(resp.toString(), secondaryResult, resp.get(0).get(RESULT)); // Now slim down the output op.get(SELECT).add(NAME); resp = executeForResult(op); assertEquals(resp.toString(), 1, resp.asInt()); assertEquals(resp.toString(), 1, resp.get(0).get(RESULT).keys().size()); assertEquals(resp.toString(), "secondary", resp.get(0).get(RESULT, NAME).asString()); } @Test public void testSpecificHostRootQuery() { // /host=secondary:query ModelNode op = Util.createEmptyOperation(QUERY, PathAddress.pathAddress(HOST_SECONDARY)); ModelNode result = executeForResult(op, ModelType.OBJECT); assertTrue(result.toString(), result.hasDefined("host-state")); assertEquals(result.toString(), "secondary", result.get(NAME).asString()); // Now cause the filter to exclude the secondary op.get(WHERE, "master").set(true); executeForResult(op, ModelType.UNDEFINED); // Correct the filter, slim down the input op.get(WHERE, "master").set(false); op.get(SELECT).add(NAME); result = executeForResult(op, ModelType.OBJECT); assertEquals(result.toString(), 1, result.keys().size()); assertEquals(result.toString(), "secondary", result.get(NAME).asString()); } @Test public void testWildcardHostServerConfigQuery() { // Basic /host=*/server-config=*:query ModelNode op = Util.createEmptyOperation(QUERY, PathAddress.pathAddress(HOST_WILD, SERVER_CONFIG_WILD)); ModelNode resp = executeForResult(op); assertEquals(resp.toString(), 4, resp.asInt()); Set<ModelNode> autoStarts = new HashSet<>(); int primaryCount = 0; for (ModelNode item : resp.asList()) { if (isPrimaryItem(item, 2)) { primaryCount++; } ModelNode result = item.get(RESULT); assertTrue(item.toString(), result.has(AUTO_START)); if (result.hasDefined(AUTO_START) && !result.get(AUTO_START).asBoolean()) { autoStarts.add(result); } assertTrue(item.toString(), result.hasDefined(GROUP)); assertTrue(item.toString(), result.hasDefined("status")); } assertEquals(resp.toString(), 2, primaryCount); // Now limit the result to non-auto-start op.get(WHERE, AUTO_START).set(false); resp = executeForResult(op); assertEquals(resp.toString(), 3, resp.asInt()); for (ModelNode item : resp.asList()) { assertTrue(resp.toString(), autoStarts.contains(item.get(RESULT))); } // Now slim down the output op.get(SELECT).add(GROUP); resp = executeForResult(op); assertEquals(resp.toString(), 3, resp.asInt()); for (ModelNode item : resp.asList()) { ModelNode result = item.get(RESULT); assertEquals(resp.toString(), 1, result.keys().size()); assertEquals(resp.toString(), "other-server-group", result.get(GROUP).asString()); } } @Test public void testSpecificHostServerConfigQuery() { // Basic /host=secondary/server-config=*:query ModelNode op = Util.createEmptyOperation(QUERY, PathAddress.pathAddress(HOST_SECONDARY, SERVER_CONFIG_WILD)); ModelNode resp = executeForResult(op); assertEquals(resp.toString(), 2, resp.asInt()); Set<ModelNode> autoStarts = new HashSet<>(); for (ModelNode item : resp.asList()) { assertFalse(resp.toString(), isPrimaryItem(item, 2)); ModelNode result = item.get(RESULT); assertTrue(item.toString(), result.has(AUTO_START)); if (result.hasDefined(AUTO_START) && !result.get(AUTO_START).asBoolean()) { autoStarts.add(result); } assertTrue(item.toString(), result.hasDefined(GROUP)); assertTrue(item.toString(), result.hasDefined("status")); } // Now limit the result to auto-start=false servers op.get(WHERE, AUTO_START).set(false); resp = executeForResult(op); assertEquals(resp.toString(), 1, resp.asInt()); for (ModelNode item : resp.asList()) { assertTrue(resp.toString(), autoStarts.contains(item.get(RESULT))); } // Now slim down the output op.get(SELECT).add(GROUP); resp = executeForResult(op); assertEquals(resp.toString(), 1, resp.asInt()); for (ModelNode item : resp.asList()) { ModelNode result = item.get(RESULT); assertEquals(resp.toString(), 1, result.keys().size()); assertEquals(resp.toString(), "other-server-group", result.get(GROUP).asString()); } } @Test public void testWildcardServerRootQuery() { // Basic /host=*/server=*:query ModelNode op = Util.createEmptyOperation(QUERY, PathAddress.pathAddress(HOST_WILD, SERVER_WILD)); ModelNode resp = executeForResult(op); assertEquals(resp.toString(), expectUnstartedServerResource() ? 4 : 3, resp.asInt()); Set<ModelNode> running = new HashSet<>(); int primaryCount = 0; for (ModelNode item : resp.asList()) { String expectedHost; if (isPrimaryItem(item, 2)) { primaryCount++; expectedHost = "primary"; } else { expectedHost = "secondary"; } ModelNode result = item.get(RESULT); assertTrue(item.toString(), result.hasDefined("server-state")); if (result.get("server-state").asString().toLowerCase(Locale.ENGLISH).equals("running")) { assertEquals(resp.toString(), expectedHost, result.get(HOST).asString()); running.add(result); } } assertEquals(resp.toString(), 2, primaryCount); assertEquals(resp.toString(), 2, running.size()); // Now limit the result to running servers op.get(WHERE, "server-state").set("running"); resp = executeForResult(op); assertEquals(resp.toString(), 2, resp.asInt()); for (ModelNode item : resp.asList()) { assertTrue(resp.toString(), running.contains(item.get(RESULT))); } // Now slim down the output op.get(SELECT).add(SERVER_GROUP); resp = executeForResult(op); assertEquals(resp.toString(), 2, resp.asInt()); for (ModelNode item : resp.asList()) { ModelNode result = item.get(RESULT); assertEquals(resp.toString(), 1, result.keys().size()); assertEquals(resp.toString(), "other-server-group", result.get(SERVER_GROUP).asString()); } } @Test public void testSpecificHostServerRootQuery() { // Basic /host=secondary/server=*:query ModelNode op = Util.createEmptyOperation(QUERY, PathAddress.pathAddress(HOST_SECONDARY, SERVER_WILD)); ModelNode resp = executeForResult(op); assertEquals(resp.toString(), expectUnstartedServerResource() ? 2 : 1, resp.asInt()); Set<ModelNode> running = new HashSet<>(); for (ModelNode item : resp.asList()) { assertFalse(resp.toString(), isPrimaryItem(item, 2)); ModelNode result = item.get(RESULT); assertTrue(item.toString(), result.hasDefined("server-state")); if (result.get("server-state").asString().toLowerCase(Locale.ENGLISH).equals("running")) { assertEquals(resp.toString(), "secondary", result.get(HOST).asString()); running.add(result); } } assertEquals(resp.toString(), 1, running.size()); // Now limit the result to running servers op.get(WHERE, "server-state").set("running"); resp = executeForResult(op); assertEquals(resp.toString(), 1, resp.asInt()); for (ModelNode item : resp.asList()) { assertTrue(resp.toString(), running.contains(item.get(RESULT))); } // Now slim down the output op.get(SELECT).add(SERVER_GROUP); resp = executeForResult(op); assertEquals(resp.toString(), 1, resp.asInt()); for (ModelNode item : resp.asList()) { ModelNode result = item.get(RESULT); assertEquals(resp.toString(), 1, result.keys().size()); assertEquals(resp.toString(), "other-server-group", result.get(SERVER_GROUP).asString()); } } @Test public void testSpecificServerRootQuery() { // /host=secondary/server=server-one:query ModelNode op = Util.createEmptyOperation(QUERY, PathAddress.pathAddress(HOST_SECONDARY, SERVER_ONE)); ModelNode result = executeForResult(op, ModelType.OBJECT); assertEquals(result.toString(), "running", result.get("server-state").asString()); assertEquals(result.toString(), "secondary", result.get(HOST).asString()); // Now cause the filter to exclude the server op.get(WHERE, HOST).set("primary"); executeForResult(op, ModelType.UNDEFINED); // Correct the filter, slim down the input op.get(WHERE, HOST).set("secondary"); op.get(SELECT).add(NAME); result = executeForResult(op, ModelType.OBJECT); assertEquals(result.toString(), 1, result.keys().size()); assertEquals(result.toString(), "server-one", result.get(NAME).asString()); } @Test public void testWildcardServerWildcardInterfaceQuery() { // Basic /host=*/server=*/interface=*:query ModelNode op = Util.createEmptyOperation(QUERY, PathAddress.pathAddress(HOST_WILD, SERVER_WILD, INTERFACE_WILD)); ModelNode resp = executeForResult(op); assertEquals(resp.toString(), 2 * 3, resp.asInt()); int primaryCount = 0; for (ModelNode item : resp.asList()) { ValueExpression expectedAddress; if (isPrimaryItem(item, 3)) { primaryCount++; expectedAddress = PRIMARY_ADDRESS; } else { expectedAddress = SECONDARY_ADDRESS; } ModelNode result = item.get(RESULT); assertEquals(resp.toString(), expectedAddress, result.get(INET_ADDRESS).asExpression()); } assertEquals(resp.toString(), 3, primaryCount); // Now limit the result to secondary servers op.get(WHERE, INET_ADDRESS).set(SECONDARY_ADDRESS); resp = executeForResult(op); assertEquals(resp.toString(), 3, resp.asInt()); // Now slim down the output op.get(SELECT).add(INET_ADDRESS); resp = executeForResult(op); assertEquals(resp.toString(), 3, resp.asInt()); for (ModelNode item : resp.asList()) { ModelNode result = item.get(RESULT); assertEquals(resp.toString(), 1, result.keys().size()); assertEquals(resp.toString(), SECONDARY_ADDRESS, result.get(INET_ADDRESS).asExpression()); } } @Test public void testSpecificServerWildcardInterfaceQuery() { // Basic /host=secondary/server=server-one/interface=*:query ModelNode op = Util.createEmptyOperation(QUERY, PathAddress.pathAddress(HOST_SECONDARY, SERVER_ONE, INTERFACE_WILD)); ModelNode resp = executeForResult(op); assertEquals(resp.toString(), 3, resp.asInt()); for (ModelNode item : resp.asList()) { ModelNode result = item.get(RESULT); assertEquals(resp.toString(), SECONDARY_ADDRESS, result.get(INET_ADDRESS).asExpression()); } // Now limit the result to primary servers // This is a wildcard request, so the result should be an empty list op.get(WHERE, INET_ADDRESS).set(PRIMARY_ADDRESS); resp = executeForResult(op); assertEquals(resp.toString(), 0, resp.asInt()); // Now correct the filter and slim down the output op.get(WHERE, INET_ADDRESS).set(SECONDARY_ADDRESS); op.get(SELECT).add(INET_ADDRESS); resp = executeForResult(op); assertEquals(resp.toString(), 3, resp.asInt()); for (ModelNode item : resp.asList()) { ModelNode result = item.get(RESULT); assertEquals(resp.toString(), 1, result.keys().size()); assertEquals(resp.toString(), SECONDARY_ADDRESS, result.get(INET_ADDRESS).asExpression()); } } @Test public void testSpecificServerSpecificSocketBindingQuery() { // /host=secondary/server=server-one/socket-binding-group=standard-sockets/socket-binding=*:query ModelNode op = Util.createEmptyOperation(QUERY, PathAddress.pathAddress(HOST_SECONDARY, SERVER_ONE).append(SOCKET_BINDING_HTTP)); ModelNode result = executeForResult(op, ModelType.OBJECT); assertEquals(result.toString(), 8080, result.get(PORT).asInt()); assertFalse(result.toString(), result.hasDefined(INTERFACE)); // Now cause the filter to exclude the server op.get(WHERE, INTERFACE).set("bogus"); executeForResult(op, ModelType.UNDEFINED); // Correct the filter, slim down the input op.get(WHERE, INTERFACE).set("undefined"); op.get(SELECT).add(PORT); result = executeForResult(op, ModelType.OBJECT); assertEquals(result.toString(), 1, result.keys().size()); assertEquals(result.toString(), 8080, result.get(PORT).asInt()); } protected boolean expectUnstartedServerResource() { return true; } private ModelNode executeForResult(ModelNode op) { return executeForResult(op, ModelType.LIST); } private static ModelNode executeForResult(ModelNode op, ModelType expectedType) { try { ModelNode response = support.getDomainPrimaryLifecycleUtil().getDomainClient().execute(op); assertEquals(response.toString(), SUCCESS, response.get(OUTCOME).asString()); ModelNode result = response.get(RESULT); assertEquals(result.toString(), expectedType, result.getType()); return result; } catch (IOException e) { throw new RuntimeException(e); } } private boolean isPrimaryItem(ModelNode item, int itemSize) { assertTrue(item.toString(), item.hasDefined(ADDRESS)); PathAddress pa = PathAddress.pathAddress(item.get(ADDRESS)); assertEquals(item.toString(), itemSize, pa.size()); return pa.getElement(0).getValue().equals("primary"); } }
31,775
44.264957
199
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/DomainHostExcludesTest.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.test.integration.domain.mixed; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CHILD_TYPE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CLONE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DOMAIN_CONTROLLER; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXTENSION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.IGNORE_UNUSED_CONFIG; 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.PORT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROFILE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_CHILDREN_NAMES_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RUNNING_SERVER; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_CONFIG; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SHUTDOWN; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING_GROUP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.TO_PROFILE; import static org.jboss.as.controller.operations.common.Util.createRemoveOperation; import static org.jboss.as.test.integration.domain.management.util.DomainTestUtils.executeForResult; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.jboss.as.controller.ExpressionResolverImpl; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.domain.management.util.DomainLifecycleUtil; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.integration.domain.management.util.DomainTestUtils; import org.jboss.as.test.integration.domain.management.util.WildFlyManagedConfiguration; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.junit.AfterClass; import org.junit.Assert; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; /** * Base class for tests of the ability of a DC to exclude resources from visibility to a secondary. * * @author Brian Stansberry */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public abstract class DomainHostExcludesTest { private static final String[] EXCLUDED_EXTENSIONS_7X = { "org.jboss.as.web", "org.jboss.as.messaging", "org.jboss.as.threads" }; public static final Set<String> EXTENSIONS_SET_7X = new HashSet<>(Arrays.asList(EXCLUDED_EXTENSIONS_7X)); private static final PathElement HOST = PathElement.pathElement("host", "secondary"); private static final PathAddress HOST_EXCLUDE = PathAddress.pathAddress("host-exclude", "test"); private static final PathElement SOCKET = PathElement.pathElement(SOCKET_BINDING, "http"); private static final PathAddress CLONE_PROFILE = PathAddress.pathAddress(PROFILE, CLONE); private static DomainTestSupport testSupport; private static Version.AsVersion version; /** Subclasses call from a @BeforeClass method */ protected static void setup(Class<?> clazz, String hostRelease, ModelVersion secondaryApiVersion) throws IOException, MgmtOperationException, TimeoutException, InterruptedException { version = clazz.getAnnotation(Version.class).value(); testSupport = MixedDomainTestSuite.getSupport(clazz); // note that some of these 7+ specific changes may warrant creating a newer version of testing-host.xml for the newer secondary hosts // at some point (the currently used host.xml is quite an old version). If these exceptions become more complicated than this, we should // probably do that. //Unset the ignore-unused-configuration flag ModelNode dc = DomainTestUtils.executeForResult( Util.getReadAttributeOperation(PathAddress.pathAddress(HOST), DOMAIN_CONTROLLER), testSupport.getDomainSecondaryLifecycleUtil().getDomainClient()); dc = dc.get("remote"); dc.get(IGNORE_UNUSED_CONFIG).set(false); dc.get(OP).set("write-remote-domain-controller"); dc.get(OP_ADDR).set(PathAddress.pathAddress(HOST).toModelNode()); DomainTestUtils.executeForResult(dc, testSupport.getDomainSecondaryLifecycleUtil().getDomainClient()); stopSecondary(); // restarting the secondary will recopy the testing-host.xml file over the top, clobbering the ignore-unused-configuration above, // so use setRewriteConfigFiles(false) to prevent this. WildFlyManagedConfiguration secondaryCfg = testSupport.getDomainSecondaryConfiguration(); secondaryCfg.setRewriteConfigFiles(false); // Setup a host exclude for the secondary ignoring some extensions ModelControllerClient client = testSupport.getDomainPrimaryLifecycleUtil().getDomainClient(); setupExclude(client, hostRelease, secondaryApiVersion); // Now, add some ignored extensions to verify they are ignored due to the host-excluded configured before addExtensions(true, client); startSecondary(); } private static void stopSecondary() throws IOException, MgmtOperationException, InterruptedException { ModelControllerClient client = testSupport.getDomainPrimaryLifecycleUtil().getDomainClient(); executeForResult(Util.createEmptyOperation(SHUTDOWN, PathAddress.pathAddress(HOST)), client); boolean gone = false; long timeout = TimeoutUtil.adjust(30000); long deadline = System.currentTimeMillis() + timeout; do { ModelNode hosts = readChildrenNames(client, PathAddress.EMPTY_ADDRESS, HOST.getKey()); gone = true; for (ModelNode host : hosts.asList()) { if (HOST.getValue().equals(host.asString())) { gone = false; Thread.sleep(100); break; } } } while (!gone && System.currentTimeMillis() < deadline); Assert.assertTrue("Secondary was not removed within " + timeout + " ms", gone); testSupport.getDomainSecondaryLifecycleUtil().stop(); } private static void setupExclude(ModelControllerClient client, String hostRelease, ModelVersion hostVersion) throws IOException, MgmtOperationException { ModelNode addOp = Util.createAddOperation(HOST_EXCLUDE); if (hostRelease != null) { addOp.get("host-release").set(hostRelease); } else { addOp.get("management-major-version").set(hostVersion.getMajor()); addOp.get("management-minor-version").set(hostVersion.getMinor()); if (hostVersion.getMicro() != 0) { addOp.get("management-micro-version").set(hostVersion.getMicro()); } } addOp.get("active-server-groups").add("other-server-group"); ModelNode asbgs = addOp.get("active-socket-binding-groups"); asbgs.add("full-sockets"); asbgs.add("full-ha-sockets"); ModelNode extensions = addOp.get("excluded-extensions"); for (String ext : getExcludedExtensions()) { extensions.add(ext); } executeForResult(addOp, client); } private static void addExtensions(boolean evens, ModelControllerClient client) throws IOException, MgmtOperationException { for (int i = 0; i < getExcludedExtensions().length; i++) { if ((i % 2 == 0) == evens) { executeForResult(Util.createAddOperation(PathAddress.pathAddress(EXTENSION, getExcludedExtensions()[i])), client); } } } private static void startSecondary() throws TimeoutException, InterruptedException { DomainLifecycleUtil legacyUtil = testSupport.getDomainSecondaryLifecycleUtil(); long start = System.currentTimeMillis(); legacyUtil.start(); legacyUtil.awaitServers(start); } @AfterClass public static void tearDown() throws IOException, MgmtOperationException, TimeoutException, InterruptedException { try { executeForResult(createRemoveOperation(HOST_EXCLUDE), testSupport.getDomainPrimaryLifecycleUtil().getDomainClient()); } finally { restoreSecondary(); } } @Test public void test001SecondaryBoot() throws Exception { ModelControllerClient secondaryClient = testSupport.getDomainSecondaryLifecycleUtil().getDomainClient(); checkExtensions(secondaryClient); checkProfiles(secondaryClient); checkSocketBindingGroups(secondaryClient); checkSockets(secondaryClient, PathAddress.pathAddress(SOCKET_BINDING_GROUP, "full-sockets")); checkSockets(secondaryClient, PathAddress.pathAddress(SOCKET_BINDING_GROUP, "full-ha-sockets")); } @Test public void test002ServerBoot() throws IOException, MgmtOperationException, InterruptedException, OperationFailedException { ModelControllerClient primaryClient = testSupport.getDomainPrimaryLifecycleUtil().getDomainClient(); PathAddress serverCfgAddr = PathAddress.pathAddress(HOST, PathElement.pathElement(SERVER_CONFIG, "server-one")); ModelNode op = Util.createEmptyOperation("start", serverCfgAddr); executeForResult(op, primaryClient); PathAddress serverAddr = PathAddress.pathAddress(HOST, PathElement.pathElement(RUNNING_SERVER, "server-one")); awaitServerLaunch(primaryClient, serverAddr); checkSockets(primaryClient, serverAddr.append(PathElement.pathElement(SOCKET_BINDING_GROUP, "full-ha-sockets"))); } private void awaitServerLaunch(ModelControllerClient client, PathAddress serverAddr) throws InterruptedException { long timeout = TimeoutUtil.adjust(20000); long expired = System.currentTimeMillis() + timeout; ModelNode op = Util.getReadAttributeOperation(serverAddr, "server-state"); do { try { ModelNode state = DomainTestUtils.executeForResult(op, client); if ("running".equalsIgnoreCase(state.asString())) { return; } } catch (IOException | MgmtOperationException e) { // ignore and try again } TimeUnit.MILLISECONDS.sleep(250L); } while (System.currentTimeMillis() < expired); Assert.fail("Server did not start in " + timeout + " ms"); } @Test public void test003PostBootUpdates() throws IOException, MgmtOperationException { ModelControllerClient primaryClient = testSupport.getDomainPrimaryLifecycleUtil().getDomainClient(); ModelControllerClient secondaryClient = testSupport.getDomainSecondaryLifecycleUtil().getDomainClient(); // Tweak an ignored profile and socket-binding-group to prove secondary doesn't see it updateExcludedProfile(primaryClient); updateExcludedSocketBindingGroup(primaryClient); // Verify profile cloning is ignored when the cloned profile is excluded testProfileCloning(primaryClient, secondaryClient); // Add more ignored extensions to verify secondary doesn't see the ops addExtensions(false, primaryClient); checkExtensions(secondaryClient); } private void checkExtensions(ModelControllerClient client) throws IOException, MgmtOperationException { ModelNode op = Util.createEmptyOperation(READ_CHILDREN_NAMES_OPERATION, PathAddress.EMPTY_ADDRESS); op.get(CHILD_TYPE).set(EXTENSION); ModelNode result = executeForResult(op, client); Assert.assertTrue(result.isDefined()); Assert.assertTrue(result.asInt() > 0); for (ModelNode ext : result.asList()) { Assert.assertFalse(ext.asString(), getExtensionsSet().contains(ext.asString())); } } private void checkProfiles(ModelControllerClient client) throws IOException, MgmtOperationException { ModelNode result = readChildrenNames(client, PathAddress.EMPTY_ADDRESS, PROFILE); Assert.assertTrue(result.isDefined()); Assert.assertEquals(result.toString(), 1, result.asInt()); Assert.assertEquals(result.toString(), "full-ha", result.get(0).asString()); } private void checkSocketBindingGroups(ModelControllerClient client) throws IOException, MgmtOperationException { ModelNode result = readChildrenNames(client, PathAddress.EMPTY_ADDRESS, SOCKET_BINDING_GROUP); Assert.assertTrue(result.isDefined()); Assert.assertEquals(result.toString(), 2, result.asInt()); Set<String> expected = new HashSet<>(Arrays.asList("full-sockets", "full-ha-sockets")); for (ModelNode sbg : result.asList()) { expected.remove(sbg.asString()); } Assert.assertTrue(result.toString(), expected.isEmpty()); } private void checkSockets(ModelControllerClient client, PathAddress baseAddress) throws IOException, MgmtOperationException, OperationFailedException { ModelNode result = readChildrenNames(client, baseAddress, SOCKET_BINDING); Assert.assertTrue(result.isDefined()); Assert.assertTrue(result.toString(), result.asInt() > 1); ModelNode op = Util.getReadAttributeOperation(baseAddress.append(SOCKET), PORT); result = executeForResult(op, client); Assert.assertTrue(result.isDefined()); result = new TestExpressionResolver().resolveExpressions(result); Assert.assertEquals(result.toString(), 8080, result.asInt()); } private void updateExcludedProfile(ModelControllerClient client) throws IOException, MgmtOperationException { ModelNode op = Util.getWriteAttributeOperation(PathAddress.pathAddress(PathElement.pathElement(PROFILE, "default"), PathElement.pathElement(SUBSYSTEM, "jmx")), "non-core-mbean-sensitivity", false); executeForResult(op, client); } private void updateExcludedSocketBindingGroup(ModelControllerClient client) throws IOException, MgmtOperationException { ModelNode op = Util.getWriteAttributeOperation(PathAddress.pathAddress(PathElement.pathElement(SOCKET_BINDING_GROUP, "standard-sockets"), PathElement.pathElement(SOCKET_BINDING, "http")), PORT, 8080); executeForResult(op, client); } private static ModelNode readChildrenNames(ModelControllerClient client, PathAddress pathAddress, String childType) throws IOException, MgmtOperationException { ModelNode op = Util.createEmptyOperation(READ_CHILDREN_NAMES_OPERATION, pathAddress); op.get(CHILD_TYPE).set(childType); return executeForResult(op, client); } private void testProfileCloning(ModelControllerClient primaryClient, ModelControllerClient secondaryClient) throws IOException, MgmtOperationException { ModelNode profiles = readChildrenNames(primaryClient, PathAddress.EMPTY_ADDRESS, PROFILE); Assert.assertTrue(profiles.isDefined()); Assert.assertTrue(profiles.toString(), profiles.asInt() > 0); for (ModelNode mn : profiles.asList()) { String profile = mn.asString(); cloneProfile(primaryClient, profile); try { checkProfiles(secondaryClient); } finally { executeForResult(Util.createRemoveOperation(CLONE_PROFILE), primaryClient); } } } private void cloneProfile(ModelControllerClient client, String toClone) throws IOException, MgmtOperationException { ModelNode op = Util.createEmptyOperation(CLONE, PathAddress.pathAddress(PROFILE, toClone)); op.get(TO_PROFILE).set(CLONE); executeForResult(op, client); } private static void restoreSecondary() throws TimeoutException, InterruptedException { DomainLifecycleUtil secondaryUtil = testSupport.getDomainSecondaryLifecycleUtil(); if (!secondaryUtil.isHostControllerStarted()) { startSecondary(); } } private Set<String> getExtensionsSet() { if (version.getMajor() >= 7) { return EXTENSIONS_SET_7X; } throw new IllegalStateException("Unknown version " + version); } private static String[] getExcludedExtensions() { if (version.getMajor() >= 7) { return EXCLUDED_EXTENSIONS_7X; } throw new IllegalStateException("Unknown version " + version); } private static class TestExpressionResolver extends ExpressionResolverImpl { public TestExpressionResolver() { } } }
18,116
46.302872
186
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/eap740/PatchRemoteHost740TestCase.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.test.integration.domain.mixed.eap740; import static org.jboss.as.test.integration.domain.mixed.Version.AsVersion.EAP_7_4_0; import java.io.IOException; import org.jboss.as.test.integration.domain.mixed.PatchRemoteHostTest; import org.jboss.as.test.integration.domain.mixed.Version; import org.junit.BeforeClass; @Version(EAP_7_4_0) public class PatchRemoteHost740TestCase extends PatchRemoteHostTest { @BeforeClass public static void beforeClass() throws IOException { MixedDomain740TestSuite.initializeDomain(); PatchRemoteHostTest.setup(PatchRemoteHost740TestCase.class); } }
1,656
38.452381
85
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/eap740/MixedDomain740TestSuite.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.test.integration.domain.mixed.eap740; import org.jboss.as.test.integration.domain.mixed.MixedDomainTestSuite; import org.jboss.as.test.integration.domain.mixed.Version; import org.jboss.as.test.integration.domain.mixed.Version.AsVersion; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; /** * Test suite for the standard mixed domain tests. * * @author <a href="[email protected]">Kabir Khan</a> */ @RunWith(Suite.class) @SuiteClasses(value= {SimpleMixedDomain740TestCase.class, MixedDomainDeployment740TestCase.class, PatchRemoteHost740TestCase.class}) @Version(AsVersion.EAP_7_4_0) public class MixedDomain740TestSuite extends MixedDomainTestSuite { @BeforeClass public static void initializeDomain() { MixedDomainTestSuite.getSupport(MixedDomain740TestSuite.class); } }
1,939
39.416667
132
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/eap740/LegacyConfig740TestCase.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.test.integration.domain.mixed.eap740; import org.jboss.as.test.integration.domain.mixed.LegacyConfigTest; import org.jboss.as.test.integration.domain.mixed.Version; import org.junit.BeforeClass; /** * EAP 7.4 variant of the superclass. * * @author Brian Stansberry */ @Version(Version.AsVersion.EAP_7_4_0) public class LegacyConfig740TestCase extends LegacyConfigTest { @BeforeClass public static void beforeClass() { LegacyConfig740TestSuite.initializeDomain(); } }
1,539
35.666667
70
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/eap740/MixedDomainDeploymentOverlay740TestCase.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.test.integration.domain.mixed.eap740; import org.jboss.as.test.integration.domain.mixed.MixedDeploymentOverlayTestCase; import org.jboss.as.test.integration.domain.mixed.Version; import org.jboss.as.test.integration.domain.mixed.Version.AsVersion; import org.junit.BeforeClass; /** * @author Emmanuel Hugonnet (c) 2017 Red Hat, inc. */ @Version(AsVersion.EAP_7_4_0) public class MixedDomainDeploymentOverlay740TestCase extends MixedDeploymentOverlayTestCase { @BeforeClass public static void beforeClass() { MixedDomainOverlay740TestSuite.initializeDomain(); MixedDeploymentOverlayTestCase.setupDomain(); } }
1,686
40.146341
93
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/eap740/RBACConfig740TestCase.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.test.integration.domain.mixed.eap740; import org.jboss.as.test.integration.domain.mixed.RBACConfigTestCase; import org.jboss.as.test.integration.domain.mixed.Version; import org.junit.BeforeClass; /** * EAP 7.4 variant of RBACConfigTestCase. * * @author Brian Stansberry */ @Version(Version.AsVersion.EAP_7_4_0) public class RBACConfig740TestCase extends RBACConfigTestCase { @BeforeClass public static void beforeClass() { KernelBehavior740TestSuite.initializeDomain(); } }
1,547
35.857143
70
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/eap740/KernelBehavior740TestSuite.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.test.integration.domain.mixed.eap740; import org.jboss.as.test.integration.domain.mixed.KernelBehaviorTestSuite; import org.jboss.as.test.integration.domain.mixed.Version; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; /** * * @author Brian Stansberry */ @RunWith(Suite.class) @Suite.SuiteClasses(value= {RBACConfig740TestCase.class, WildcardReads740TestCase.class}) @Version(Version.AsVersion.EAP_7_4_0) public class KernelBehavior740TestSuite extends KernelBehaviorTestSuite { @BeforeClass public static void initializeDomain() { KernelBehaviorTestSuite.getSupport(KernelBehavior740TestSuite.class); } }
1,725
37.355556
89
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/eap740/DomainAdjuster740.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.test.integration.domain.mixed.eap740; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXTENSION; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.helpers.domain.DomainClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.domain.mixed.DomainAdjuster; import org.jboss.dmr.ModelNode; /** * Does adjustments to the domain model for 7.4.0 legacy secondary hosts. * * @author <a href="mailto:[email protected]">Darran Lofthouse</a> */ public class DomainAdjuster740 extends DomainAdjuster { @Override protected List<ModelNode> adjustForVersion(final DomainClient client, PathAddress profileAddress, boolean withPrimaryServers) { final List<ModelNode> ops = new ArrayList<>(); adjustRemoting(ops, profileAddress.append(SUBSYSTEM, "remoting")); adjustUndertow(ops, profileAddress.append(SUBSYSTEM, "undertow")); adjustEjb3(ops, profileAddress.append(SUBSYSTEM, "ejb3")); removeDistributableEjb(ops, profileAddress.append(SUBSYSTEM, "distributable-ejb")); if (profileAddress.getElement(0).getValue().equals("full-ha")) { adjustJGroups(ops, profileAddress.append(SUBSYSTEM, "jgroups")); } return ops; } private static void adjustRemoting(final List<ModelNode> ops, final PathAddress subsystem) { // This adjusts the configuration to reflect the configuration that was used in EAP 7.4, // this could equally be moved all the way back and only adjusted for EAP 7.0.0 as we remove // the Elytron subsystem. final PathAddress httpRemotingConnector = subsystem .append("http-connector", "http-remoting-connector"); ops.add(Util.getUndefineAttributeOperation(httpRemotingConnector, "sasl-authentication-factory")); } private static void adjustUndertow(final List<ModelNode> ops, final PathAddress subsystem) { // This adjusts the configuration to reflect the configuration that was used in EAP 7.4, // this could equally be moved all the way back and only adjusted for EAP 7.0.0 as we remove // the Elytron subsystem. final PathAddress httpInvoker = subsystem .append("server", "default-server") .append("host", "default-host") .append("setting", "http-invoker"); ops.add(Util.getUndefineAttributeOperation(httpInvoker, "http-authentication-factory")); ops.add(Util.getWriteAttributeOperation(httpInvoker, "security-realm", "ApplicationRealm")); } private static void adjustEjb3(List<ModelNode> operations, PathAddress subsystemAddress) { PathAddress timerServiceAddress = subsystemAddress.append("service", "timer-service"); operations.add(Util.createCompositeOperation(Arrays.asList(Util.getUndefineAttributeOperation(timerServiceAddress, "default-transient-timer-management"), Util.getWriteAttributeOperation(timerServiceAddress, "thread-pool-name", "default")))); operations.add(Util.createCompositeOperation(Arrays.asList(Util.getUndefineAttributeOperation(timerServiceAddress, "default-persistent-timer-management"), Util.getWriteAttributeOperation(timerServiceAddress, "default-data-store", "default-file-store")))); } private static void adjustJGroups(List<ModelNode> operations, PathAddress subsystemAddress) { for (String stack : Arrays.asList("tcp", "udp")) { // Remove protocols that do not exist in EAP 7.4, but don't bother replacing for (String protocol : Arrays.asList("RED", "FD_SOCK2", "FD_ALL3", "FRAG4", "VERIFY_SUSPECT2")) { operations.add(Util.createRemoveOperation(subsystemAddress.append("stack", stack).append("protocol", protocol))); } } } /** * Remove the distributable-ejb subsystem from the domain model for EAP 7.4.0 secondary hosts as they * do not support this subsystem or its associated module org.wildfly.clustering.ejb. * * @param ops list of operations used to adjust the domain model for EAP 7.4.0 * @param subsystem the root of the subsystem to be adjusted/removed */ private static void removeDistributableEjb(final List<ModelNode> ops, final PathAddress subsystem) { // remove the distributable-ejb subsystem in its entirety from the domain model ops.add(Util.createRemoveOperation(subsystem)); // remove its extension from the list of extensions ops.add(Util.createRemoveOperation(PathAddress.pathAddress(EXTENSION, "org.wildfly.extension.clustering.ejb"))); } }
5,873
51.918919
263
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/eap740/LegacyConfig740TestSuite.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.test.integration.domain.mixed.eap740; import org.jboss.as.test.integration.domain.mixed.MixedDomainTestSuite; import org.jboss.as.test.integration.domain.mixed.Version; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.runner.RunWith; import org.junit.runners.Suite; /** * Tests of using EAP 7.4 domain.xml with a current DC and a 7.4 secondary. * * @author Brian Stansberry */ @RunWith(Suite.class) @Suite.SuiteClasses(value= { LegacyConfig740TestCase.class, DomainHostExcludes740TestCase.class }) @Version(Version.AsVersion.EAP_7_4_0) @Ignore("https://issues.redhat.com/browse/WFLY-16644") public class LegacyConfig740TestSuite extends MixedDomainTestSuite { @BeforeClass public static void initializeDomain() { MixedDomainTestSuite.getSupportForLegacyConfig(LegacyConfig740TestSuite.class, Version.AsVersion.EAP_7_4_0); } }
1,937
37
116
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/eap740/MixedDomainDeployment740TestCase.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.test.integration.domain.mixed.eap740; import org.jboss.as.test.integration.domain.mixed.MixedDomainDeploymentTest; import org.jboss.as.test.integration.domain.mixed.Version; import org.jboss.as.test.integration.domain.mixed.Version.AsVersion; import org.junit.BeforeClass; /** * * @author <a href="[email protected]">Kabir Khan</a> */ @Version(AsVersion.EAP_7_4_0) public class MixedDomainDeployment740TestCase extends MixedDomainDeploymentTest { @BeforeClass public static void beforeClass() { MixedDomain740TestSuite.initializeDomain(); } @Override protected boolean supportManagedExplodedDeployment() { return true; } }
1,717
36.347826
81
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/eap740/DomainHostExcludes740TestCase.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.test.integration.domain.mixed.eap740; import static org.jboss.as.test.integration.domain.mixed.Version.AsVersion.EAP_7_4_0; import java.io.IOException; import java.util.concurrent.TimeoutException; import org.jboss.as.test.integration.domain.mixed.DomainHostExcludesTest; import org.jboss.as.test.integration.domain.mixed.Version; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.junit.BeforeClass; /** * Tests of the ability of a DC to exclude resources from visibility to an EAP 7.4.0 secondary. * * @author Brian Stansberry */ @Version(EAP_7_4_0) public class DomainHostExcludes740TestCase extends DomainHostExcludesTest { @BeforeClass public static void beforeClass() throws InterruptedException, TimeoutException, MgmtOperationException, IOException { LegacyConfig740TestSuite.initializeDomain(); setup(DomainHostExcludes740TestCase.class, EAP_7_4_0.getHostExclude(), EAP_7_4_0.getModelVersion()); } }
2,028
40.408163
121
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/eap740/ElytronOnlyPrimarySmoke740TestCase.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.test.integration.domain.mixed.eap740; import org.jboss.as.test.integration.domain.mixed.ElytronOnlyPrimarySmokeTestCase; import org.jboss.as.test.integration.domain.mixed.Version; import org.junit.BeforeClass; /** * @author Martin Simka */ @Version(Version.AsVersion.EAP_7_4_0) public class ElytronOnlyPrimarySmoke740TestCase extends ElytronOnlyPrimarySmokeTestCase { @BeforeClass public static void beforeClass() { ElytronOnlyPrimary740TestSuite.initializeDomain(); } }
1,541
37.55
89
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/eap740/MixedDomainOverlay740TestSuite.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.test.integration.domain.mixed.eap740; import org.jboss.as.test.integration.domain.mixed.MixedDomainTestSuite; import org.jboss.as.test.integration.domain.mixed.Version; import org.jboss.as.test.integration.domain.mixed.Version.AsVersion; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; /** * @author Emmanuel Hugonnet (c) 2017 Red Hat, inc. */ @RunWith(Suite.class) @SuiteClasses(value= {MixedDomainDeploymentOverlay740TestCase.class}) @Version(AsVersion.EAP_7_4_0) public class MixedDomainOverlay740TestSuite extends MixedDomainTestSuite { @BeforeClass public static void initializeDomain() { MixedDomainTestSuite.getSupport(MixedDomainOverlay740TestSuite.class, "primary-config/host.xml", "secondary-config/host-secondary-overlay.xml", Profile.DEFAULT, true, false, true); } }
1,941
41.217391
188
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/eap740/WildcardReads740TestCase.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.test.integration.domain.mixed.eap740; import org.jboss.as.test.integration.domain.mixed.Version; import org.jboss.as.test.integration.domain.mixed.WildcardReadsTestCase; import org.junit.BeforeClass; /** * * @author Brian Stansberry */ @Version(Version.AsVersion.EAP_7_4_0) public class WildcardReads740TestCase extends WildcardReadsTestCase { @BeforeClass public static void beforeClass() { KernelBehavior740TestSuite.initializeDomain(); } }
1,515
35.095238
72
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/eap740/SimpleMixedDomain740TestCase.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.test.integration.domain.mixed.eap740; import org.jboss.as.test.integration.domain.mixed.SimpleMixedDomainTest; import org.jboss.as.test.integration.domain.mixed.Version; import org.jboss.as.test.integration.domain.mixed.Version.AsVersion; import org.junit.BeforeClass; /** * * @author <a href="[email protected]">Kabir Khan</a> */ @Version(AsVersion.EAP_7_4_0) public class SimpleMixedDomain740TestCase extends SimpleMixedDomainTest { @BeforeClass public static void beforeClass() { MixedDomain740TestSuite.initializeDomain(); } }
1,605
37.238095
73
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/eap740/ElytronOnlyPrimary740TestSuite.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.test.integration.domain.mixed.eap740; import org.jboss.as.test.integration.domain.mixed.ElytronOnlyPrimaryTestSuite; import org.jboss.as.test.integration.domain.mixed.Version; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; /** * @author Martin Simka */ @RunWith(Suite.class) @Suite.SuiteClasses(value= {ElytronOnlyPrimarySmoke740TestCase.class}) @Version(Version.AsVersion.EAP_7_4_0) public class ElytronOnlyPrimary740TestSuite extends ElytronOnlyPrimaryTestSuite { @BeforeClass public static void initializeDomain() { ElytronOnlyPrimaryTestSuite.getSupport(ElytronOnlyPrimary740TestSuite.class); } }
1,719
38.090909
85
java
null
wildfly-main/testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/patching/PatchingTestUtil.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.test.integration.domain.mixed.patching; import static org.jboss.as.patching.IoUtils.safeClose; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import org.jboss.as.patching.IoUtils; import org.jboss.as.patching.ZipUtils; import org.jboss.as.patching.metadata.Patch; import org.jboss.as.patching.metadata.PatchXml; /** * @author Jan Martiska, Jeff Mesnil */ public class PatchingTestUtil { public static File touch(File baseDir, String... segments) throws IOException { File f = baseDir; for (String segment : segments) { f = new File(f, segment); } f.getParentFile().mkdirs(); f.createNewFile(); return f; } public static void dump(File f, String content) throws IOException { final OutputStream os = new FileOutputStream(f); try { os.write(content.getBytes(StandardCharsets.UTF_8)); os.close(); } finally { IoUtils.safeClose(os); } } public static void dump(File f, byte[] content) throws IOException { final OutputStream os = new FileOutputStream(f); try { os.write(content); os.close(); } finally { IoUtils.safeClose(os); } } public static void createPatchXMLFile(File dir, Patch patch) throws Exception { File patchXMLfile = new File(dir, "patch.xml"); FileOutputStream fos = new FileOutputStream(patchXMLfile); try { PatchXml.marshal(fos, patch); } finally { safeClose(fos); } } public static File createZippedPatchFile(File sourceDir, String zipFileName) { return createZippedPatchFile(sourceDir, zipFileName, null); } public static File createZippedPatchFile(File sourceDir, String zipFileName, File targetDir) { if (targetDir == null) { targetDir = sourceDir.getParentFile(); } File zipFile = new File(targetDir, zipFileName + ".zip"); ZipUtils.zip(sourceDir, zipFile); return zipFile; } }
3,218
32.53125
98
java
null
wildfly-main/batch-jberet/src/test/java/org/wildfly/extension/batch/jberet/JBeretSubsystemParsingTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.PathAddress; import org.jboss.as.model.test.FailedOperationTransformationConfig; import org.jboss.as.model.test.ModelTestControllerVersion; import org.jboss.as.model.test.ModelTestUtils; import org.jboss.as.subsystem.test.AdditionalInitialization; import org.jboss.as.subsystem.test.KernelServices; import org.jboss.as.subsystem.test.KernelServicesBuilder; import org.jboss.as.subsystem.test.LegacyKernelServicesInitializer; import org.jboss.dmr.ModelNode; import org.junit.Test; import org.wildfly.extension.batch.jberet.job.repository.CommonAttributes; import org.wildfly.extension.batch.jberet.job.repository.InMemoryJobRepositoryDefinition; import org.wildfly.extension.batch.jberet.job.repository.JdbcJobRepositoryDefinition; import org.wildfly.security.manager.WildFlySecurityManager; /** * Basic subsystem test. Tests parsing various batch configurations */ @SuppressWarnings("deprecation") public class JBeretSubsystemParsingTestCase extends AbstractBatchTestCase { public JBeretSubsystemParsingTestCase() { super(BatchSubsystemDefinition.NAME, new BatchSubsystemExtension()); } @Override protected String getSubsystemXml() throws IOException { return readResource("/default-subsystem.xml"); } @Override protected String getSubsystemXsdPath() { return "schema/wildfly-batch-jberet_3_0.xsd"; } @Test public void testMinimalSubsystem() throws Exception { standardSubsystemTest("/minimal-subsystem.xml"); } @Test public void testMultiThreadFactory() throws Exception { standardSubsystemTest("/multi-thread-factory-subsystem.xml"); } @Test public void testJdbcSubsystem() throws Exception { standardSubsystemTest("/jdbc-default-subsystem.xml"); } @Test public void testSecurityDomainSubsystem() throws Exception { standardSubsystemTest("/security-domain-subsystem.xml"); } /** * Verifies that attributes with expression are handled properly. * * @throws Exception for any test failure */ @Test public void testExpressionInAttributeValue() throws Exception { final KernelServices kernelServices = boot(getSubsystemXml("/with-expression-subsystem.xml")); final ModelNode batchModel = kernelServices.readWholeModel().get("subsystem", getMainSubsystemName()); final boolean expectedRestartOnResume = false; final boolean restartOnResume = batchModel.get("restart-jobs-on-resume").resolve().asBoolean(); assertEquals("Expecting restart-jobs-on-resume " + expectedRestartOnResume + ", but got " + restartOnResume, expectedRestartOnResume, restartOnResume); final ModelNode threadPool = batchModel.get("thread-pool").asProperty().getValue(); final int expectedMaxThreads = 10; final int maxThreads = threadPool.get("max-threads").resolve().asInt(); assertEquals("Expecting max-threads " + expectedMaxThreads + ", but got " + maxThreads, expectedMaxThreads, maxThreads); final ModelNode threadFactory = batchModel.get("thread-factory").asProperty().getValue(); final String expectedGroupName = "batch"; final String groupName = threadFactory.get("group-name").resolve().asString(); assertEquals("Expecting thread-factory group-name " + expectedGroupName + ", but got " + groupName, expectedGroupName, groupName); final int expectedPriority = 5; final int priority = threadFactory.get("priority").resolve().asInt(); assertEquals("Expecting thread-factory priority " + expectedPriority + ", but got " + priority, expectedPriority, priority); final String expectedThreadNamePattern = "%i-%g"; final String threadNamePattern = threadFactory.get("thread-name-pattern").resolve().asString(); assertEquals("Expecting thread-factory thread-name-pattern " + expectedThreadNamePattern + ", but got " + threadNamePattern, expectedThreadNamePattern, threadNamePattern); } @Test public void testLegacySubsystems() throws Exception { // Get a list of all the logging_x_x.xml files final Pattern pattern = Pattern.compile("(.*-subsystem)_\\d+_\\d+\\.xml"); // Using the CP as that's the standardSubsystemTest will use to find the config file final String cp = WildFlySecurityManager.getPropertyPrivileged("java.class.path", "."); final String[] entries = cp.split(Pattern.quote(File.pathSeparator)); final List<String> configs = new ArrayList<>(); for (String entry : entries) { final Path path = Paths.get(entry); if (Files.isDirectory(path)) { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) { final String name = file.getFileName().toString(); if (pattern.matcher(name).matches()) { configs.add("/" + name); } return FileVisitResult.CONTINUE; } }); } } // The paths shouldn't be empty assertFalse("No configs were found", configs.isEmpty()); for (String configId : configs) { // Run the standard subsystem test, but don't compare the XML as it should never match standardSubsystemTest(configId, false); } } @Test public void testRejectingTransformersEAP74() throws Exception { FailedOperationTransformationConfig transformationConfig = new FailedOperationTransformationConfig(); PathAddress repositoryAddress = PathAddress.pathAddress(BatchSubsystemDefinition.SUBSYSTEM_PATH, InMemoryJobRepositoryDefinition.PATH); transformationConfig.addFailedAttribute(repositoryAddress, new FailedOperationTransformationConfig.NewAttributesConfig(CommonAttributes.EXECUTION_RECORDS_LIMIT)); PathAddress jdbcRepositoryAddress = PathAddress.pathAddress(BatchSubsystemDefinition.SUBSYSTEM_PATH, JdbcJobRepositoryDefinition.PATH); transformationConfig.addFailedAttribute(jdbcRepositoryAddress, new FailedOperationTransformationConfig.NewAttributesConfig(CommonAttributes.EXECUTION_RECORDS_LIMIT)); testRejectingTransformers(transformationConfig, ModelTestControllerVersion.EAP_7_4_0); } private void testRejectingTransformers(FailedOperationTransformationConfig transformationConfig, ModelTestControllerVersion controllerVersion) throws Exception { ModelVersion subsystemModelVersion = controllerVersion.getSubsystemModelVersion(BatchSubsystemDefinition.NAME); KernelServicesBuilder builder = createKernelServicesBuilder(createAdditionalInitialization()); LegacyKernelServicesInitializer kernelServicesInitializer = builder.createLegacyKernelServicesBuilder(createAdditionalInitialization(), controllerVersion, subsystemModelVersion) .addMavenResourceURL("org.wildfly.core:wildfly-threads:" + controllerVersion.getCoreVersion()) .dontPersistXml(); try { BatchSubsystemExtension.class.getClassLoader().loadClass("javax" + ".batch.operations.JobStartException"); kernelServicesInitializer.addMavenResourceURL("org.jboss.eap:wildfly-batch-jberet:" + controllerVersion.getMavenGavVersion()); } catch (ClassNotFoundException e) { kernelServicesInitializer.addMavenResourceURL("org.wildfly:wildfly-batch-jberet-jakarta:26.0.0.Final"); } KernelServices kernelServices = builder.build(); assertTrue(kernelServices.isSuccessfulBoot()); assertTrue(kernelServices.getLegacyServices(subsystemModelVersion).isSuccessfulBoot()); List<ModelNode> operations = builder.parseXmlResource("/default-subsystem.xml"); ModelTestUtils.checkFailedTransformedBootOperations(kernelServices, subsystemModelVersion, operations, transformationConfig); } @Override protected AdditionalInitialization createAdditionalInitialization() { return AdditionalInitialization.withCapabilities( "org.wildfly.data-source.ExampleDS", "org.wildfly.security.security-domain.ApplicationDomain", "org.wildfly.transactions.global-default-local-provider"); } }
10,143
47.075829
185
java
null
wildfly-main/batch-jberet/src/test/java/org/wildfly/extension/batch/jberet/AbstractBatchTestCase.java
package org.wildfly.extension.batch.jberet; import org.jboss.as.controller.Extension; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.client.Operation; import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest; import org.jboss.as.subsystem.test.KernelServices; import org.jboss.as.subsystem.test.SubsystemOperations; import org.jboss.dmr.ModelNode; import org.junit.Assert; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ abstract class AbstractBatchTestCase extends AbstractSubsystemBaseTest { public AbstractBatchTestCase(final String mainSubsystemName, final Extension mainExtension) { super(mainSubsystemName, mainExtension); } protected KernelServices boot() throws Exception { return boot(getSubsystemXml()); } protected KernelServices boot(final String subsystemXml) throws Exception { final KernelServices result; if (subsystemXml == null) { result = createKernelServicesBuilder(createAdditionalInitialization()).build(); } else { result = createKernelServicesBuilder(createAdditionalInitialization()).setSubsystemXml(subsystemXml).build(); } Assert.assertTrue(result.isSuccessfulBoot()); return result; } protected static ModelNode executeOperation(final KernelServices kernelServices, final Operation op) { return executeOperation(kernelServices, op.getOperation()); } protected static ModelNode executeOperation(final KernelServices kernelServices, final ModelNode op) { final ModelNode result = kernelServices.executeOperation(op); Assert.assertTrue(SubsystemOperations.getFailureDescriptionAsString(result), SubsystemOperations.isSuccessfulOutcome(result)); return result; } protected static ModelNode createAddress(final PathElement pathElement) { if (pathElement == null) { return PathAddress.pathAddress(BatchSubsystemDefinition.SUBSYSTEM_PATH).toModelNode(); } return PathAddress.pathAddress(BatchSubsystemDefinition.SUBSYSTEM_PATH, pathElement).toModelNode(); } protected static ModelNode createAddress(final String resourceKey, final String resourceValue) { return createAddress(PathElement.pathElement(resourceKey, resourceValue)); } }
2,388
40.912281
134
java
null
wildfly-main/batch-jberet/src/test/java/org/wildfly/extension/batch/jberet/SubsystemOperationsTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.jboss.as.controller.capability.registry.RuntimeCapabilityRegistry; import org.jboss.as.controller.client.Operation; import org.jboss.as.controller.client.helpers.Operations.CompositeOperationBuilder; import org.jboss.as.controller.extension.ExtensionRegistry; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.Resource; import org.jboss.as.subsystem.test.AdditionalInitialization; import org.jboss.as.subsystem.test.KernelServices; import org.jboss.as.subsystem.test.SubsystemOperations; import org.jboss.dmr.ModelNode; import org.junit.Assert; import org.junit.Test; import org.wildfly.extension.batch.jberet.job.repository.CommonAttributes; import org.wildfly.extension.batch.jberet.job.repository.InMemoryJobRepositoryDefinition; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; public class SubsystemOperationsTestCase extends AbstractBatchTestCase { public SubsystemOperationsTestCase() { super(BatchSubsystemDefinition.NAME, new BatchSubsystemExtension()); } @Override protected void standardSubsystemTest(final String configId) { // do nothing as this is not a subsystem parsing test } @Override protected String getSubsystemXml() throws IOException { return readResource("/default-subsystem.xml"); } @Override protected AdditionalInitialization createAdditionalInitialization() { return new AdditionalInitialization() { @Override protected void initializeExtraSubystemsAndModel(ExtensionRegistry extensionRegistry, Resource rootResource, ManagementResourceRegistration rootRegistration, RuntimeCapabilityRegistry capabilityRegistry) { super.initializeExtraSubystemsAndModel(extensionRegistry, rootResource, rootRegistration, capabilityRegistry); registerCapabilities(capabilityRegistry, "org.wildfly.batch.thread.pool.new-job-repo", "org.wildfly.transactions.global-default-local-provider", "org.wildfly.data-source.ExampleDS"); } }; } @Test public void testThreadPoolChange() throws Exception { final KernelServices kernelServices = boot(); final CompositeOperationBuilder compositeOp = CompositeOperationBuilder.create(); // Add a new thread-pool final ModelNode address = createAddress("thread-pool", "test-pool"); final ModelNode addOp = SubsystemOperations.createAddOperation(address); addOp.get("max-threads").set(10L); final ModelNode keepAlive = addOp.get("keepalive-time"); keepAlive.get("time").set(100L); keepAlive.get("unit").set(TimeUnit.MILLISECONDS.toString()); compositeOp.addStep(addOp); // Write the new default compositeOp.addStep(SubsystemOperations.createWriteAttributeOperation(createAddress(null), "default-thread-pool", "test-pool")); executeOperation(kernelServices, compositeOp.build()); } @Test public void testJobRepositoryChange() throws Exception { final KernelServices kernelServices = boot(); final CompositeOperationBuilder compositeOp = CompositeOperationBuilder.create(); // Add a new thread-pool final ModelNode address = createAddress(InMemoryJobRepositoryDefinition.NAME, "new-job-repo"); compositeOp.addStep(SubsystemOperations.createAddOperation(address)); // Write the new default compositeOp.addStep(SubsystemOperations.createWriteAttributeOperation(createAddress(null), "default-thread-pool", "new-job-repo")); executeOperation(kernelServices, compositeOp.build()); } @Test public void testAddRemoveThreadPool() throws Exception { final KernelServices kernelServices = boot(getSubsystemXml("/minimal-subsystem.xml")); final ModelNode address = createAddress("thread-pool", "test-pool"); final ModelNode addOp = SubsystemOperations.createAddOperation(address); addOp.get("max-threads").set(10L); final ModelNode keepAlive = addOp.get("keepalive-time"); keepAlive.get("time").set(100L); keepAlive.get("unit").set(TimeUnit.MILLISECONDS.toString()); executeOperation(kernelServices, addOp); final ModelNode removeOp = SubsystemOperations.createRemoveOperation(address); executeOperation(kernelServices, removeOp); // Add one more time to test a composite operation executeOperation(kernelServices, addOp); // Remove and add in a composite operation final Operation compositeOp = CompositeOperationBuilder.create() .addStep(removeOp) .addStep(addOp) .build(); executeOperation(kernelServices, compositeOp); } @Test public void testAddSubsystem() throws Exception { // Boot with no subsystem final KernelServices kernelServices = boot(null); final CompositeOperationBuilder operationBuilder = CompositeOperationBuilder.create(); // Create the base subsystem address final ModelNode subsystemAddress = createAddress(null); final ModelNode subsystemAddOp = SubsystemOperations.createAddOperation(subsystemAddress); subsystemAddOp.get("default-job-repository").set("in-memory"); subsystemAddOp.get("default-thread-pool").set("batch"); operationBuilder.addStep(subsystemAddOp); // Add a job repository operationBuilder.addStep(SubsystemOperations.createAddOperation(createAddress(InMemoryJobRepositoryDefinition.NAME, "in-memory"))); final ModelNode threadPool = SubsystemOperations.createAddOperation(createAddress("thread-pool", "batch")); threadPool.get("max-threads").set(10); final ModelNode keepAlive = threadPool.get("keepalive-time"); keepAlive.get("time").set(100L); keepAlive.get("unit").set(TimeUnit.MILLISECONDS.toString()); operationBuilder.addStep(threadPool); // Execute the add operation executeOperation(kernelServices, operationBuilder.build()); } @Test public void testRemoveSubsystem() throws Exception { final KernelServices kernelServices = boot(); final ModelNode removeSubsystemOp = SubsystemOperations.createRemoveOperation(createAddress(null)); executeOperation(kernelServices, removeSubsystemOp); } @Test public void testEnums() { for (Element e : Element.values()) { assertEquals(e, Element.forName(e.getLocalName())); } assertEquals(Element.UNKNOWN, Element.forName("zzz")); for (Attribute e : Attribute.values()) { assertEquals(e, Attribute.forName(e.getLocalName())); } assertEquals(Attribute.UNKNOWN, Attribute.forName("xxx")); for (Namespace e : Namespace.values()) { assertEquals(e, Namespace.forUri(e.getUriString())); } assertEquals(Namespace.UNKNOWN, Namespace.forUri("yyy")); } @Test public void testWriteExecutionRecordsLimit() throws Exception { String[] resourcePath = new String[] {SUBSYSTEM, BatchSubsystemDefinition.NAME, InMemoryJobRepositoryDefinition.NAME, "in-memory"}; final KernelServices kernelServices = boot(); Assert.assertEquals(200, kernelServices.readWholeModel().get(resourcePath).get("execution-records-limit").asInt()); final ModelNode address = createAddress(InMemoryJobRepositoryDefinition.NAME, "in-memory"); ModelNode operation = SubsystemOperations.createWriteAttributeOperation(address, CommonAttributes.EXECUTION_RECORDS_LIMIT, 250); executeOperation(kernelServices, operation); Assert.assertEquals(250, kernelServices.readWholeModel().get(resourcePath).get("execution-records-limit").asInt()); } }
9,122
42.650718
216
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/AttributeParsers.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.wildfly.extension.batch.jberet; import java.util.EnumMap; import java.util.EnumSet; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import javax.xml.stream.XMLStreamException; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.AttributeParser; import org.jboss.as.controller.parsing.ParseUtils; import org.jboss.dmr.ModelNode; import org.jboss.staxmapper.XMLExtendedStreamReader; /** * Attribute parsing utilities. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ class AttributeParsers { /** * An attribute parser for elements with a single {@code value} that don't allow any content within the element. */ static final AttributeParser VALUE = new AttributeParser() { @Override public void parseElement(final AttributeDefinition attribute, final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException { final ModelNode valueNode = ParseUtils.parseAttributeValue(readValueAttribute(reader), attribute.isAllowExpression(), attribute.getType()); operation.get(attribute.getName()).set(valueNode); ParseUtils.requireNoContent(reader); } @Override public boolean isParseAsElement() { return true; } }; /** * Reads a {@code name} attribute on an element. * * @param reader the reader used to read the attribute with * * @return the name attribute or {@code null} if the name attribute was not defined * * @throws XMLStreamException if an XML processing error occurs */ static String readNameAttribute(final XMLExtendedStreamReader reader) throws XMLStreamException { return readRequiredAttributes(reader, EnumSet.of(Attribute.NAME)).get(Attribute.NAME); } /** * Reads a {@code value} attribute on an element. * * @param reader the reader used to read the attribute with * * @return the value attribute or {@code null} if the value attribute was not defined * * @throws XMLStreamException if an XML processing error occurs */ static String readValueAttribute(final XMLExtendedStreamReader reader) throws XMLStreamException { return readRequiredAttributes(reader, EnumSet.of(Attribute.VALUE)).get(Attribute.VALUE); } /** * Reads the required attributes from an XML configuration. * <p> * The reader must be on an element with attributes. * </p> * * @param reader the reader for the attributes * @param attributes the required attributes * * @return a map of the required attributes with the key being the attribute and the value being the value of the * attribute * * @throws XMLStreamException if an XML processing error occurs */ static Map<Attribute, String> readRequiredAttributes(final XMLExtendedStreamReader reader, final Set<Attribute> attributes) throws XMLStreamException { final int attributeCount = reader.getAttributeCount(); final Map<Attribute, String> result = new EnumMap<>(Attribute.class); for (int i = 0; i < attributeCount; i++) { final Attribute current = Attribute.forName(reader.getAttributeLocalName(i)); if (attributes.contains(current)) { if (result.put(current, reader.getAttributeValue(i)) != null) { throw ParseUtils.duplicateAttribute(reader, current.getLocalName()); } } else { throw ParseUtils.unexpectedAttribute(reader, i, attributes.stream().map(Attribute::getLocalName).collect(Collectors.toSet())); } } if (result.isEmpty()) { throw ParseUtils.missingRequired(reader, attributes.stream().map(Attribute::getLocalName).collect(Collectors.toSet())); } return result; } static Map<Attribute, String> readAttributes(final XMLExtendedStreamReader reader, final Set<Attribute> attributes) { final Map<Attribute, String> result = new EnumMap<>(Attribute.class); for (int i = 0; i < reader.getAttributeCount(); i++) { final Attribute current = Attribute.forName(reader.getAttributeLocalName(i)); if (attributes.contains(current)) { result.put(current, reader.getAttributeValue(i)); } } return result; } }
5,060
39.488
162
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/Element.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.wildfly.extension.batch.jberet; import java.util.HashMap; import java.util.Map; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public enum Element { UNKNOWN(null), DEFAULT_JOB_REPOSITORY("default-job-repository"), DEFAULT_THREAD_POOL("default-thread-pool"), JOB_REPOSITORY("job-repository"), JDBC("jdbc"), IN_MEMORY("in-memory"), NAMED("named"), RESTART_JOBS_ON_RESUME("restart-jobs-on-resume"), SECURITY_DOMAIN("security-domain"), THREAD_FACTORY("thread-factory"), THREAD_POOL("thread-pool"), ; private final String name; Element(final String name) { this.name = name; } /** * Get the local name of this element. * * @return the local name */ public String getLocalName() { return name; } @Override public String toString() { return name; } private static final Map<String, Element> MAP; static { final Map<String, Element> map = new HashMap<>(); for (Element element : values()) { final String name = element.getLocalName(); if (name != null) map.put(name, element); } MAP = map; } public static Element forName(String localName) { final Element element = MAP.get(localName); return element == null ? UNKNOWN : element; } }
2,422
28.54878
70
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/BatchConfigurationService.java
/* * Copyright 2015 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.batch.jberet; import org.jberet.repository.JobRepository; import org.jberet.spi.JobExecutor; import org.jboss.msc.service.Service; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.wildfly.security.auth.server.SecurityDomain; import java.util.function.Consumer; import java.util.function.Supplier; /** * A default batch configuration service. * * @author <a href="mailto:[email protected]">James R. Perkins</a> * @author <a href="mailto:[email protected]">Richard Opalka</a> */ class BatchConfigurationService implements BatchConfiguration, Service<BatchConfiguration> { private final Consumer<BatchConfiguration> batchConfigurationConsumer; private final Supplier<JobRepository> jobRepositorySupplier; private final Supplier<JobExecutor> jobExecutorSupplier; private final Supplier<SecurityDomain> securityDomainSupplier; private volatile boolean restartOnResume; BatchConfigurationService(final Consumer<BatchConfiguration> batchConfigurationConsumer, final Supplier<JobRepository> jobRepositorySupplier, final Supplier<JobExecutor> jobExecutorSupplier, final Supplier<SecurityDomain> securityDomainSupplier) { this.batchConfigurationConsumer = batchConfigurationConsumer; this.jobRepositorySupplier = jobRepositorySupplier; this.jobExecutorSupplier = jobExecutorSupplier; this.securityDomainSupplier = securityDomainSupplier; } @Override public boolean isRestartOnResume() { return restartOnResume; } protected void setRestartOnResume(final boolean restartOnResume) { this.restartOnResume = restartOnResume; } @Override public JobRepository getDefaultJobRepository() { return jobRepositorySupplier.get(); } @Override public JobExecutor getDefaultJobExecutor() { return jobExecutorSupplier.get(); } @Override public SecurityDomain getSecurityDomain() { return securityDomainSupplier != null ? securityDomainSupplier.get() : null; } @Override public void start(final StartContext context) throws StartException { batchConfigurationConsumer.accept(this); } @Override public void stop(final StopContext context) { batchConfigurationConsumer.accept(null); } @Override public BatchConfiguration getValue() throws IllegalStateException, IllegalArgumentException { return this; } }
3,220
34.01087
97
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/BatchServiceNames.java
package org.wildfly.extension.batch.jberet; import org.jboss.as.controller.capability.CapabilityServiceSupport; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.Services; import org.jboss.as.threads.ThreadsServices; import org.jboss.msc.service.ServiceName; /** * Service names for the batch subsystem. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public class BatchServiceNames { /** * The default service name fo the thread-pool */ public static final ServiceName BASE_BATCH_THREAD_POOL_NAME = ThreadsServices.EXECUTOR.append("batch"); /** * Creates a service name for the batch environment service. * * @param deploymentUnit the deployment unit to create the service name for * * @return the service name */ public static ServiceName batchEnvironmentServiceName(final DeploymentUnit deploymentUnit) { return deploymentUnit.getServiceName().append("batch").append("environment"); } /** * Creates a service name for the {@linkplain org.jberet.spi.ArtifactFactory artifact factory} service. * * @param deploymentUnit the deployment unit to create the service name for * * @return the service name */ public static ServiceName batchArtifactFactoryServiceName(final DeploymentUnit deploymentUnit) { return deploymentUnit.getServiceName().append("batch").append("artifact").append("factory"); } /** * Creates the service name used for the bean manager on the deployment. * * @param deploymentUnit the deployment unit to create the service name for * * @return the service name */ public static ServiceName beanManagerServiceName(final DeploymentUnit deploymentUnit) { return deploymentUnit.getServiceName().append("beanmanager"); } /** * Creates the service name used for the job operator registered for the deployment. * * @param deploymentUnit the deployment unit where the operator is to be registered * * @return the service name */ public static ServiceName jobOperatorServiceName(final DeploymentUnit deploymentUnit) { return deploymentUnit.getServiceName().append("batch").append("job-operator"); } /** * Creates the service name used for the job operator registered for the deployment. * * @param deploymentRuntimeName the runtime name for the deployment * * @return the service name */ public static ServiceName jobOperatorServiceName(final String deploymentRuntimeName) { return Services.deploymentUnitName(deploymentRuntimeName).append("batch").append("job-operator"); } /** * Creates the service name used for the job operator registered for the deployment. * * @param deploymentRuntimeName the runtime name for the deployment * @param subdeploymentName the name of the subdeployment * * @return the service name */ public static ServiceName jobOperatorServiceName(final String deploymentRuntimeName, final String subdeploymentName) { return Services.deploymentUnitName(deploymentRuntimeName, subdeploymentName).append("batch").append("job-operator"); } public static final String REQUEST_CONTROLLER_CAPABILITY = "org.wildfly.request-controller"; public static ServiceName requestControllerServiceName(CapabilityServiceSupport serviceSupport) { return serviceSupport.getCapabilityServiceName(REQUEST_CONTROLLER_CAPABILITY); } }
3,570
36.989362
124
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/BatchSubsystemDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import java.util.function.Consumer; import java.util.function.Supplier; import org.jberet.repository.JobRepository; import org.jberet.spi.ContextClassLoaderJobOperatorContextSelector; import org.jberet.spi.JobExecutor; import org.jberet.spi.JobOperatorContext; import org.jboss.as.controller.AbstractBoottimeAddStepHandler; import org.jboss.as.controller.AbstractWriteAttributeHandler; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.OperationStepHandler; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.ReloadRequiredRemoveStepHandler; import org.jboss.as.controller.ReloadRequiredWriteAttributeHandler; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition; import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler; import org.jboss.as.controller.registry.AttributeAccess; import org.jboss.as.controller.registry.ManagementResourceRegistration; 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.as.threads.ThreadFactoryResourceDefinition; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.wildfly.extension.batch.jberet._private.Capabilities; import org.wildfly.extension.batch.jberet.deployment.BatchAttachments; import org.wildfly.extension.batch.jberet.deployment.BatchCleanupProcessor; import org.wildfly.extension.batch.jberet.deployment.BatchDependencyProcessor; import org.wildfly.extension.batch.jberet.deployment.BatchDeploymentDescriptorParser_1_0; import org.wildfly.extension.batch.jberet.deployment.BatchDeploymentDescriptorParser_2_0; import org.wildfly.extension.batch.jberet.deployment.BatchDeploymentDescriptorParser_3_0; import org.wildfly.extension.batch.jberet.deployment.BatchDeploymentResourceProcessor; import org.wildfly.extension.batch.jberet.deployment.BatchEnvironmentProcessor; import org.wildfly.extension.batch.jberet.job.repository.InMemoryJobRepositoryDefinition; import org.wildfly.extension.batch.jberet.job.repository.JdbcJobRepositoryDefinition; import org.wildfly.extension.batch.jberet.thread.pool.BatchThreadPoolResourceDefinition; import org.wildfly.security.auth.server.SecurityDomain; public class BatchSubsystemDefinition extends SimpleResourceDefinition { /** * The name of our subsystem within the model. */ public static final String NAME = "batch-jberet"; public static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(SUBSYSTEM, NAME); static final String THREAD_FACTORY = "thread-factory"; static final SimpleAttributeDefinition DEFAULT_JOB_REPOSITORY = SimpleAttributeDefinitionBuilder.create("default-job-repository", ModelType.STRING, false) .setAllowExpression(false) .setAttributeGroup("environment") .setAttributeMarshaller(AttributeMarshallers.NAMED) .setCapabilityReference(Capabilities.JOB_REPOSITORY_CAPABILITY.getName(), Capabilities.BATCH_CONFIGURATION_CAPABILITY) .setRestartAllServices() .build(); static final SimpleAttributeDefinition DEFAULT_THREAD_POOL = SimpleAttributeDefinitionBuilder.create("default-thread-pool", ModelType.STRING, false) .setAllowExpression(false) .setAttributeGroup("environment") .setAttributeMarshaller(AttributeMarshallers.NAMED) .setCapabilityReference(Capabilities.THREAD_POOL_CAPABILITY.getName(), Capabilities.BATCH_CONFIGURATION_CAPABILITY) .setRestartAllServices() .build(); static final SimpleAttributeDefinition RESTART_JOBS_ON_RESUME = SimpleAttributeDefinitionBuilder.create("restart-jobs-on-resume", ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.TRUE) .setAttributeParser(AttributeParsers.VALUE) .setAttributeMarshaller(AttributeMarshallers.VALUE) .build(); static final SimpleAttributeDefinition SECURITY_DOMAIN = SimpleAttributeDefinitionBuilder.create("security-domain", ModelType.STRING, true) .setAttributeMarshaller(AttributeMarshallers.NAMED) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setCapabilityReference(Capabilities.SECURITY_DOMAIN_CAPABILITY, Capabilities.BATCH_CONFIGURATION_CAPABILITY) .setAccessConstraints(SensitiveTargetAccessConstraintDefinition.ELYTRON_SECURITY_DOMAIN_REF) .build(); private final boolean registerRuntimeOnly; BatchSubsystemDefinition(final boolean registerRuntimeOnly) { super(new SimpleResourceDefinition.Parameters(SUBSYSTEM_PATH, BatchResourceDescriptionResolver.getResourceDescriptionResolver()) .setAddHandler(BatchSubsystemAdd.INSTANCE) .setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE) .addCapabilities(Capabilities.BATCH_CONFIGURATION_CAPABILITY)); this.registerRuntimeOnly = registerRuntimeOnly; } @Override public void registerOperations(final ManagementResourceRegistration resourceRegistration) { super.registerOperations(resourceRegistration); resourceRegistration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE); } @Override public void registerChildren(final ManagementResourceRegistration resourceRegistration) { super.registerChildren(resourceRegistration); resourceRegistration.registerSubModel(new InMemoryJobRepositoryDefinition()); resourceRegistration.registerSubModel(new JdbcJobRepositoryDefinition()); // thread-pool resource resourceRegistration.registerSubModel(new BatchThreadPoolResourceDefinition(registerRuntimeOnly)); // thread-factory resource final ThreadFactoryResourceDefinition threadFactoryResource = new ThreadFactoryResourceDefinition(); resourceRegistration.registerSubModel(threadFactoryResource); } @Override public void registerAttributes(final ManagementResourceRegistration resourceRegistration) { super.registerAttributes(resourceRegistration); final OperationStepHandler writeHandler = new ReloadRequiredWriteAttributeHandler(DEFAULT_JOB_REPOSITORY, DEFAULT_THREAD_POOL, SECURITY_DOMAIN); resourceRegistration.registerReadWriteAttribute(DEFAULT_JOB_REPOSITORY, null, writeHandler); resourceRegistration.registerReadWriteAttribute(DEFAULT_THREAD_POOL, null, writeHandler); resourceRegistration.registerReadWriteAttribute(SECURITY_DOMAIN, null, writeHandler); resourceRegistration.registerReadWriteAttribute(RESTART_JOBS_ON_RESUME, null, new AbstractWriteAttributeHandler<Boolean>(RESTART_JOBS_ON_RESUME) { @Override protected boolean applyUpdateToRuntime(final OperationContext context, final ModelNode operation, final String attributeName, final ModelNode resolvedValue, final ModelNode currentValue, final HandbackHolder<Boolean> handbackHolder) throws OperationFailedException { setValue(context, resolvedValue); return false; } @Override protected void revertUpdateToRuntime(final OperationContext context, final ModelNode operation, final String attributeName, final ModelNode valueToRestore, final ModelNode valueToRevert, final Boolean handback) throws OperationFailedException { setValue(context, valueToRestore); } private void setValue(final OperationContext context, final ModelNode value) { final BatchConfigurationService service = (BatchConfigurationService) context.getServiceRegistry(true) .getService(context.getCapabilityServiceName(Capabilities.BATCH_CONFIGURATION_CAPABILITY.getName(), BatchConfiguration.class)).getService(); service.setRestartOnResume(value.asBoolean()); } }); } /** * Handler responsible for adding the subsystem resource to the model. */ static class BatchSubsystemAdd extends AbstractBoottimeAddStepHandler { static final BatchSubsystemAdd INSTANCE = new BatchSubsystemAdd(); private final ContextClassLoaderJobOperatorContextSelector selector; private BatchSubsystemAdd() { super(DEFAULT_JOB_REPOSITORY, DEFAULT_THREAD_POOL, RESTART_JOBS_ON_RESUME, SECURITY_DOMAIN); selector = new ContextClassLoaderJobOperatorContextSelector(() -> JobOperatorContext.create(DefaultBatchEnvironment.INSTANCE)); JobOperatorContext.setJobOperatorContextSelector(selector); } @Override protected void performBoottime(final OperationContext context, final ModelNode operation, final ModelNode model) throws OperationFailedException { // Check if the request-controller subsystem exists final boolean rcPresent = context.hasOptionalCapability(BatchServiceNames.REQUEST_CONTROLLER_CAPABILITY, null, null); context.addStep(new AbstractDeploymentChainStep() { public void execute(DeploymentProcessorTarget processorTarget) { final JBossAllXmlParserRegisteringProcessor<Object> jbossAllProcessor = JBossAllXmlParserRegisteringProcessor.builder() .addParser(BatchDeploymentDescriptorParser_1_0.ROOT_ELEMENT, BatchAttachments.BATCH_ENVIRONMENT_META_DATA, new BatchDeploymentDescriptorParser_1_0()) .addParser(BatchDeploymentDescriptorParser_2_0.ROOT_ELEMENT, BatchAttachments.BATCH_ENVIRONMENT_META_DATA, new BatchDeploymentDescriptorParser_2_0()) .addParser(BatchDeploymentDescriptorParser_3_0.ROOT_ELEMENT, BatchAttachments.BATCH_ENVIRONMENT_META_DATA, new BatchDeploymentDescriptorParser_3_0()) .build(); processorTarget.addDeploymentProcessor(BatchSubsystemDefinition.NAME, Phase.STRUCTURE, Phase.STRUCTURE_REGISTER_JBOSS_ALL_BATCH, jbossAllProcessor); processorTarget.addDeploymentProcessor(NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_BATCH, new BatchDependencyProcessor()); processorTarget.addDeploymentProcessor(NAME, Phase.POST_MODULE, Phase.POST_MODULE_BATCH_ENVIRONMENT, new BatchEnvironmentProcessor(rcPresent, selector)); processorTarget.addDeploymentProcessor(NAME, Phase.INSTALL, Phase.INSTALL_BATCH_RESOURCES, new BatchDeploymentResourceProcessor(NAME)); processorTarget.addDeploymentProcessor(NAME, Phase.CLEANUP, Phase.CLEANUP_BATCH, new BatchCleanupProcessor()); } }, OperationContext.Stage.RUNTIME); final ModelNode defaultJobRepository = DEFAULT_JOB_REPOSITORY.resolveModelAttribute(context, model); final ModelNode defaultThreadPool = DEFAULT_THREAD_POOL.resolveModelAttribute(context, model); final ModelNode securityDomain = SECURITY_DOMAIN.resolveModelAttribute(context, model); final boolean restartOnResume = RESTART_JOBS_ON_RESUME.resolveModelAttribute(context, model).asBoolean(); final ServiceTarget target = context.getServiceTarget(); final ServiceName sn = context.getCapabilityServiceName(Capabilities.BATCH_CONFIGURATION_CAPABILITY.getName(), BatchConfiguration.class); final ServiceBuilder<?> serviceBuilder = target.addService(sn); final Consumer<BatchConfiguration> batchConfigurationConsumer = serviceBuilder.provides(sn); final Supplier<JobRepository> jobRepositorySupplier = serviceBuilder.requires( context.getCapabilityServiceName(Capabilities.JOB_REPOSITORY_CAPABILITY.getName(), defaultJobRepository.asString(), JobRepository.class)); final Supplier<JobExecutor> jobExecutorSupplier = serviceBuilder.requires( context.getCapabilityServiceName(Capabilities.THREAD_POOL_CAPABILITY.getName(), defaultThreadPool.asString(), JobExecutor.class)); final Supplier<SecurityDomain> securityDomainSupplier = securityDomain.isDefined() ? serviceBuilder.requires(context.getCapabilityServiceName(Capabilities.SECURITY_DOMAIN_CAPABILITY, securityDomain.asString(), SecurityDomain.class)) : null; // Only start this service if there are deployments present, allow it to be stopped as deployments // are removed. serviceBuilder.setInitialMode(ServiceController.Mode.ON_DEMAND); final BatchConfigurationService service = new BatchConfigurationService(batchConfigurationConsumer, jobRepositorySupplier, jobExecutorSupplier, securityDomainSupplier); service.setRestartOnResume(restartOnResume); serviceBuilder.setInstance(service); serviceBuilder.install(); } } }
14,811
61.49789
278
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/BatchSubsystemParser_2_0.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.wildfly.extension.batch.jberet; import java.util.Collections; import java.util.List; import javax.xml.stream.XMLStreamConstants; import org.jboss.dmr.ModelNode; import org.jboss.staxmapper.XMLElementReader; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ class BatchSubsystemParser_2_0 extends BatchSubsystemParser_1_0 implements XMLStreamConstants, XMLElementReader<List<ModelNode>> { public BatchSubsystemParser_2_0() { super(Collections.singletonMap(Element.SECURITY_DOMAIN, BatchSubsystemDefinition.SECURITY_DOMAIN)); } }
1,182
33.794118
130
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/BatchExtensionTransformerRegistration.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.transform.ExtensionTransformerRegistration; import org.jboss.as.controller.transform.SubsystemTransformerRegistration; import org.jboss.as.controller.transform.description.ChainedTransformationDescriptionBuilder; import org.jboss.as.controller.transform.description.DiscardAttributeChecker; import org.jboss.as.controller.transform.description.RejectAttributeChecker; import org.jboss.as.controller.transform.description.ResourceTransformationDescriptionBuilder; import org.jboss.as.controller.transform.description.TransformationDescriptionBuilder; import org.kohsuke.MetaInfServices; import org.wildfly.extension.batch.jberet.job.repository.CommonAttributes; import org.wildfly.extension.batch.jberet.job.repository.InMemoryJobRepositoryDefinition; import org.wildfly.extension.batch.jberet.job.repository.JdbcJobRepositoryDefinition; @MetaInfServices public class BatchExtensionTransformerRegistration implements ExtensionTransformerRegistration { @Override public String getSubsystemName() { return BatchSubsystemDefinition.NAME; } @Override public void registerTransformers(SubsystemTransformerRegistration registration) { ChainedTransformationDescriptionBuilder builder = TransformationDescriptionBuilder.Factory.createChainedSubystemInstance(registration.getCurrentSubsystemVersion()); registerV3Transformers(builder.createBuilder(BatchSubsystemExtension.VERSION_3_0_0, BatchSubsystemExtension.VERSION_2_0_0)); builder.buildAndRegister(registration, new ModelVersion[] {BatchSubsystemExtension.VERSION_1_0_0, BatchSubsystemExtension.VERSION_2_0_0, BatchSubsystemExtension.VERSION_3_0_0}); } private static void registerV3Transformers(ResourceTransformationDescriptionBuilder subsystem) { ResourceTransformationDescriptionBuilder inMemoryJobRepository = subsystem.addChildResource(InMemoryJobRepositoryDefinition.PATH); rejectAttribute(inMemoryJobRepository, CommonAttributes.EXECUTION_RECORDS_LIMIT); ResourceTransformationDescriptionBuilder jdbcJobRepository = subsystem.addChildResource(JdbcJobRepositoryDefinition.PATH); rejectAttribute(jdbcJobRepository, CommonAttributes.EXECUTION_RECORDS_LIMIT); } /** * Rejects attribute if it's defined or discard if it has the default value. */ private static void rejectAttribute(ResourceTransformationDescriptionBuilder resource, AttributeDefinition attribute) { resource.getAttributeBuilder() .setDiscard(DiscardAttributeChecker.DEFAULT_VALUE, attribute) .addRejectCheck(RejectAttributeChecker.DEFINED, attribute); } }
3,833
52.25
185
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/AttributeMarshallers.java
/* * Copyright 2015 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.batch.jberet; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.AttributeMarshaller; import org.jboss.dmr.ModelNode; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ class AttributeMarshallers { public static final AttributeMarshaller NAMED = new AttributeMarshaller() { @Override public void marshallAsElement(final AttributeDefinition attribute, final ModelNode resourceModel, final boolean marshallDefault, final XMLStreamWriter writer) throws XMLStreamException { if (resourceModel.hasDefined(attribute.getName())) { writer.writeStartElement(attribute.getName()); writer.writeAttribute(Attribute.NAME.getLocalName(), resourceModel.get(attribute.getName()).asString()); writer.writeEndElement(); } } }; public static final AttributeMarshaller VALUE = new AttributeMarshaller() { @Override public void marshallAsElement(final AttributeDefinition attribute, final ModelNode resourceModel, final boolean marshallDefault, final XMLStreamWriter writer) throws XMLStreamException { if (resourceModel.hasDefined(attribute.getName())) { writer.writeStartElement(attribute.getName()); writer.writeAttribute(Attribute.VALUE.getLocalName(), resourceModel.get(attribute.getName()).asString()); writer.writeEndElement(); } } }; }
2,206
39.87037
194
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/DefaultBatchEnvironment.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.wildfly.extension.batch.jberet; import java.util.Properties; import jakarta.transaction.TransactionManager; import org.jberet.repository.JobRepository; import org.jberet.spi.ArtifactFactory; import org.jberet.spi.BatchEnvironment; import org.jberet.spi.JobTask; import org.jberet.spi.JobXmlResolver; import org.wildfly.extension.batch.jberet._private.BatchLogger; import org.wildfly.security.manager.WildFlySecurityManager; /** * An environment to act as a default batch environment for deployments. This environment throws an * {@link jakarta.batch.operations.BatchRuntimeException} for each method. Deployments should not end up with this * environment. This is used as a fallback in cases where the {@link org.jberet.spi.JobOperatorContextSelector} cannot * find an appropriate environment. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public class DefaultBatchEnvironment implements BatchEnvironment { public static final DefaultBatchEnvironment INSTANCE = new DefaultBatchEnvironment(); private DefaultBatchEnvironment() { } @Override public ClassLoader getClassLoader() { throw BatchLogger.LOGGER.noBatchEnvironmentFound(WildFlySecurityManager.getCurrentContextClassLoaderPrivileged()); } @Override public ArtifactFactory getArtifactFactory() { throw BatchLogger.LOGGER.noBatchEnvironmentFound(WildFlySecurityManager.getCurrentContextClassLoaderPrivileged()); } @Override public void submitTask(final JobTask jobTask) { throw BatchLogger.LOGGER.noBatchEnvironmentFound(WildFlySecurityManager.getCurrentContextClassLoaderPrivileged()); } @Override public TransactionManager getTransactionManager() { throw BatchLogger.LOGGER.noBatchEnvironmentFound(WildFlySecurityManager.getCurrentContextClassLoaderPrivileged()); } @Override public JobRepository getJobRepository() { throw BatchLogger.LOGGER.noBatchEnvironmentFound(WildFlySecurityManager.getCurrentContextClassLoaderPrivileged()); } @Override public JobXmlResolver getJobXmlResolver() { throw BatchLogger.LOGGER.noBatchEnvironmentFound(WildFlySecurityManager.getCurrentContextClassLoaderPrivileged()); } @Override public Properties getBatchConfigurationProperties() { throw BatchLogger.LOGGER.noBatchEnvironmentFound(WildFlySecurityManager.getCurrentContextClassLoaderPrivileged()); } @Override public String getApplicationName() { throw BatchLogger.LOGGER.noBatchEnvironmentFound(WildFlySecurityManager.getCurrentContextClassLoaderPrivileged()); } }
3,237
37.094118
122
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/BatchSubsystemWriter.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet; import javax.xml.stream.XMLStreamException; import java.util.List; import org.jboss.as.controller.persistence.SubsystemMarshallingContext; import org.jboss.as.threads.ThreadsParser; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; import org.jboss.staxmapper.XMLElementWriter; import org.jboss.staxmapper.XMLExtendedStreamWriter; import org.wildfly.extension.batch.jberet.job.repository.CommonAttributes; import org.wildfly.extension.batch.jberet.job.repository.InMemoryJobRepositoryDefinition; import org.wildfly.extension.batch.jberet.job.repository.JdbcJobRepositoryDefinition; import org.wildfly.extension.batch.jberet.thread.pool.BatchThreadPoolResourceDefinition; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public class BatchSubsystemWriter implements XMLElementWriter<SubsystemMarshallingContext> { @Override public void writeContent(final XMLExtendedStreamWriter writer, final SubsystemMarshallingContext context) throws XMLStreamException { final ThreadsParser threadsParser = ThreadsParser.getInstance(); context.startSubsystemElement(Namespace.CURRENT.getUriString(), false); final ModelNode model = context.getModelNode(); BatchSubsystemDefinition.DEFAULT_JOB_REPOSITORY.marshallAsElement(model, writer); BatchSubsystemDefinition.DEFAULT_THREAD_POOL.marshallAsElement(model, writer); BatchSubsystemDefinition.RESTART_JOBS_ON_RESUME.marshallAsElement(model, writer); BatchSubsystemDefinition.SECURITY_DOMAIN.marshallAsElement(model, writer); // Write the in-memory job repositories if (model.hasDefined(InMemoryJobRepositoryDefinition.NAME)) { final List<Property> repositories = model.get(InMemoryJobRepositoryDefinition.NAME).asPropertyList(); for (Property property : repositories) { writer.writeStartElement(Element.JOB_REPOSITORY.getLocalName()); writeNameAttribute(writer, property.getName()); CommonAttributes.EXECUTION_RECORDS_LIMIT.marshallAsAttribute(property.getValue(), writer); writer.writeEmptyElement(Element.IN_MEMORY.getLocalName()); writer.writeEndElement(); // end job-repository } } // Write the JDBC job repositories if (model.hasDefined(JdbcJobRepositoryDefinition.NAME)) { final List<Property> repositories = model.get(JdbcJobRepositoryDefinition.NAME).asPropertyList(); for (Property property : repositories) { writer.writeStartElement(Element.JOB_REPOSITORY.getLocalName()); writeNameAttribute(writer, property.getName()); CommonAttributes.EXECUTION_RECORDS_LIMIT.marshallAsAttribute(property.getValue(), writer); writer.writeStartElement(Element.JDBC.getLocalName()); JdbcJobRepositoryDefinition.DATA_SOURCE.marshallAsAttribute(property.getValue(), writer); writer.writeEndElement(); writer.writeEndElement(); // end job-repository } } // Write the thread pool if (model.hasDefined(BatchThreadPoolResourceDefinition.NAME)) { final List<Property> threadPools = model.get(BatchThreadPoolResourceDefinition.NAME).asPropertyList(); for (Property threadPool : threadPools) { threadsParser.writeUnboundedQueueThreadPool(writer, threadPool, Element.THREAD_POOL.getLocalName(), true); } } // Write out the thread factory if (model.hasDefined(BatchSubsystemDefinition.THREAD_FACTORY)) { final List<Property> threadFactories = model.get(BatchSubsystemDefinition.THREAD_FACTORY).asPropertyList(); for (Property threadFactory : threadFactories) { threadsParser.writeThreadFactory(writer, threadFactory); } } writer.writeEndElement(); } private static void writeNameAttribute(final XMLExtendedStreamWriter writer, final String name) throws XMLStreamException { writer.writeAttribute(Attribute.NAME.getLocalName(), name); } }
5,231
49.796117
137
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/BatchSubsystemParser_1_0.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet; import static org.jboss.as.threads.Namespace.THREADS_1_1; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import org.jboss.as.controller.AttributeParser; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.controller.parsing.ParseUtils; import org.jboss.as.threads.ThreadsParser; import org.jboss.dmr.ModelNode; import org.jboss.staxmapper.XMLElementReader; import org.jboss.staxmapper.XMLExtendedStreamReader; import org.wildfly.extension.batch.jberet.job.repository.InMemoryJobRepositoryDefinition; import org.wildfly.extension.batch.jberet.job.repository.JdbcJobRepositoryDefinition; import org.wildfly.extension.batch.jberet.thread.pool.BatchThreadPoolResourceDefinition; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public class BatchSubsystemParser_1_0 implements XMLStreamConstants, XMLElementReader<List<ModelNode>> { private final Map<Element, SimpleAttributeDefinition> attributeElements; public BatchSubsystemParser_1_0() { this(Collections.emptyMap()); } BatchSubsystemParser_1_0(final Map<Element, SimpleAttributeDefinition> additionalElements) { attributeElements = new HashMap<>(additionalElements); attributeElements.put(Element.DEFAULT_JOB_REPOSITORY, BatchSubsystemDefinition.DEFAULT_JOB_REPOSITORY); attributeElements.put(Element.DEFAULT_THREAD_POOL, BatchSubsystemDefinition.DEFAULT_THREAD_POOL); attributeElements.put(Element.RESTART_JOBS_ON_RESUME, BatchSubsystemDefinition.RESTART_JOBS_ON_RESUME); } @Override public void readElement(final XMLExtendedStreamReader reader, final List<ModelNode> ops) throws XMLStreamException { final ThreadsParser threadsParser = ThreadsParser.getInstance(); final PathAddress subsystemAddress = PathAddress.pathAddress(BatchSubsystemDefinition.SUBSYSTEM_PATH); // Add the subsystem final ModelNode subsystemAddOp = Util.createAddOperation(subsystemAddress); ops.add(subsystemAddOp); // Find the required elements final Set<Element> requiredElements = EnumSet.of(Element.JOB_REPOSITORY, Element.THREAD_POOL); attributeElements.forEach((element, attribute) -> { if (!attribute.isNillable() && attribute.getDefaultValue() == null) { requiredElements.add(element); } }); final Namespace namespace = Namespace.forUri(reader.getNamespaceURI()); while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { final String localName = reader.getLocalName(); final Element element = Element.forName(localName); final SimpleAttributeDefinition attribute = attributeElements.get(element); if (attribute != null) { final AttributeParser parser = attribute.getParser(); if (parser.isParseAsElement()) { parser.parseElement(attribute, reader, subsystemAddOp); } else { // Assume this is an element with a single name attribute parser.parseAndSetParameter(attribute, AttributeParsers.readNameAttribute(reader), subsystemAddOp, reader); ParseUtils.requireNoContent(reader); } requiredElements.remove(element); } else if (element == Element.JOB_REPOSITORY) { parseJobRepository(reader, subsystemAddress, ops); requiredElements.remove(Element.JOB_REPOSITORY); } else if (element == Element.THREAD_POOL) { threadsParser.parseUnboundedQueueThreadPool(reader, namespace.getUriString(), THREADS_1_1, subsystemAddress.toModelNode(), ops, BatchThreadPoolResourceDefinition.NAME, null); requiredElements.remove(Element.THREAD_POOL); } else if (element == Element.THREAD_FACTORY) { threadsParser.parseThreadFactory(reader, namespace.getUriString(), THREADS_1_1, subsystemAddress.toModelNode(), ops, BatchSubsystemDefinition.THREAD_FACTORY, null); } else { throw ParseUtils.unexpectedElement(reader); } } if (!requiredElements.isEmpty()) { throw ParseUtils.missingRequired(reader, requiredElements); } ParseUtils.requireNoContent(reader); } protected void parseJobRepository(final XMLExtendedStreamReader reader, final PathAddress subsystemAddress, final List<ModelNode> ops) throws XMLStreamException { final String name = AttributeParsers.readRequiredAttributes(reader, EnumSet.of(Attribute.NAME)).get(Attribute.NAME); while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { final String localName = reader.getLocalName(); final Element element = Element.forName(localName); if (element == Element.IN_MEMORY) { ops.add(Util.createAddOperation(subsystemAddress.append(InMemoryJobRepositoryDefinition.NAME, name))); ParseUtils.requireNoContent(reader); } else if (element == Element.JDBC) { final Map<Attribute, String> attributes = AttributeParsers.readRequiredAttributes(reader, EnumSet.of(Attribute.DATA_SOURCE)); final ModelNode op = Util.createAddOperation(subsystemAddress.append(JdbcJobRepositoryDefinition.NAME, name)); JdbcJobRepositoryDefinition.DATA_SOURCE.parseAndSetParameter(attributes.get(Attribute.DATA_SOURCE), op, reader); ops.add(op); ParseUtils.requireNoContent(reader); } else { throw ParseUtils.unexpectedElement(reader); } } } }
7,149
49.70922
166
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/Attribute.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.wildfly.extension.batch.jberet; import java.util.Map; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public enum Attribute { UNKNOWN(null), DATA_SOURCE("data-source"), NAME("name"), VALUE("value"), EXECUTION_RECORDS_LIMIT("execution-records-limit"); private static final Map<String, Attribute> MAP = Map.of( DATA_SOURCE.name, DATA_SOURCE, NAME.name, NAME, VALUE.name, VALUE, EXECUTION_RECORDS_LIMIT.name, EXECUTION_RECORDS_LIMIT); private final String name; Attribute(final String name) { this.name = name; } /** * Get the local name of this attribute. * * @return the local name */ public String getLocalName() { return name; } public static Attribute forName(String localName) { if (localName == null) { return UNKNOWN; } final Attribute element = MAP.get(localName); return element == null ? UNKNOWN : element; } }
2,075
30.454545
70
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/BatchSubsystemParser_3_0.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.wildfly.extension.batch.jberet; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.controller.parsing.ParseUtils; import org.jboss.dmr.ModelNode; import org.jboss.staxmapper.XMLElementReader; import org.jboss.staxmapper.XMLExtendedStreamReader; import org.wildfly.extension.batch.jberet.job.repository.CommonAttributes; import org.wildfly.extension.batch.jberet.job.repository.InMemoryJobRepositoryDefinition; import org.wildfly.extension.batch.jberet.job.repository.JdbcJobRepositoryDefinition; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import java.util.EnumSet; import java.util.List; import java.util.Map; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ class BatchSubsystemParser_3_0 extends BatchSubsystemParser_2_0 implements XMLStreamConstants, XMLElementReader<List<ModelNode>> { public BatchSubsystemParser_3_0() { super(); } protected void parseJobRepository(final XMLExtendedStreamReader reader, final PathAddress subsystemAddress, final List<ModelNode> ops) throws XMLStreamException { Map<Attribute, String> topLevelAttributes = AttributeParsers.readAttributes(reader, EnumSet.of(Attribute.NAME, Attribute.EXECUTION_RECORDS_LIMIT)); String name = topLevelAttributes.get(Attribute.NAME); String executionRecordsLimit = topLevelAttributes.get(Attribute.EXECUTION_RECORDS_LIMIT); if (name == null) { throw ParseUtils.missingRequired(reader, Attribute.NAME.getLocalName()); } while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { final String localName = reader.getLocalName(); final Element element = Element.forName(localName); if (element == Element.IN_MEMORY) { ModelNode op = Util.createAddOperation(subsystemAddress.append(InMemoryJobRepositoryDefinition.NAME, name)); if (executionRecordsLimit != null) { CommonAttributes.EXECUTION_RECORDS_LIMIT.parseAndSetParameter(executionRecordsLimit, op, reader); } ops.add(op); ParseUtils.requireNoContent(reader); } else if (element == Element.JDBC) { final Map<Attribute, String> attributes = AttributeParsers.readRequiredAttributes(reader, EnumSet.of(Attribute.DATA_SOURCE)); final ModelNode op = Util.createAddOperation(subsystemAddress.append(JdbcJobRepositoryDefinition.NAME, name)); JdbcJobRepositoryDefinition.DATA_SOURCE.parseAndSetParameter(attributes.get(Attribute.DATA_SOURCE), op, reader); if (executionRecordsLimit != null) { CommonAttributes.EXECUTION_RECORDS_LIMIT.parseAndSetParameter(executionRecordsLimit, op, reader); } ops.add(op); ParseUtils.requireNoContent(reader); } else { throw ParseUtils.unexpectedElement(reader); } } } }
3,700
46.448718
166
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/BatchSubsystemExtension.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.wildfly.extension.batch.jberet; import org.jboss.as.controller.Extension; import org.jboss.as.controller.ExtensionContext; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.SubsystemRegistration; import org.jboss.as.controller.parsing.ExtensionParsingContext; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.wildfly.extension.batch.jberet.deployment.BatchDeploymentResourceDefinition; import org.wildfly.extension.batch.jberet.deployment.BatchJobExecutionResourceDefinition; import org.wildfly.extension.batch.jberet.deployment.BatchJobResourceDefinition; public class BatchSubsystemExtension implements Extension { /** * Version numbers for batch subsystem management interface. */ static final ModelVersion VERSION_3_0_0 = ModelVersion.create(3, 0, 0); static final ModelVersion VERSION_2_0_0 = ModelVersion.create(2, 0, 0); static final ModelVersion VERSION_1_0_0 = ModelVersion.create(1, 0, 0); static final ModelVersion CURRENT_MODEL_VERSION = VERSION_3_0_0; @Override public void initializeParsers(final ExtensionParsingContext context) { context.setSubsystemXmlMapping(BatchSubsystemDefinition.NAME, Namespace.BATCH_1_0.getUriString(), BatchSubsystemParser_1_0::new); context.setSubsystemXmlMapping(BatchSubsystemDefinition.NAME, Namespace.BATCH_2_0.getUriString(), BatchSubsystemParser_2_0::new); context.setSubsystemXmlMapping(BatchSubsystemDefinition.NAME, Namespace.BATCH_3_0.getUriString(), BatchSubsystemParser_3_0::new); } @Override public void initialize(final ExtensionContext context) { final SubsystemRegistration subsystem = context.registerSubsystem(BatchSubsystemDefinition.NAME, CURRENT_MODEL_VERSION); subsystem.registerSubsystemModel(new BatchSubsystemDefinition(context.isRuntimeOnlyRegistrationValid())); subsystem.registerXMLElementWriter(new BatchSubsystemWriter()); // Register the deployment resources if (context.isRuntimeOnlyRegistrationValid()) { final ManagementResourceRegistration deployments = subsystem.registerDeploymentModel(new BatchDeploymentResourceDefinition()); final ManagementResourceRegistration jobRegistration = deployments.registerSubModel(new BatchJobResourceDefinition()); jobRegistration.registerSubModel(new BatchJobExecutionResourceDefinition()); } } }
3,474
51.651515
138
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/Namespace.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.wildfly.extension.batch.jberet; import java.util.Map; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ enum Namespace { // must be first UNKNOWN(null), BATCH_1_0("urn:jboss:domain:batch-jberet:1.0"), BATCH_2_0("urn:jboss:domain:batch-jberet:2.0"), BATCH_3_0("urn:jboss:domain:batch-jberet:3.0"), ; private static final Map<String, Namespace> MAP = Map.of( BATCH_1_0.name, BATCH_1_0, BATCH_2_0.name, BATCH_2_0, BATCH_3_0.name, BATCH_3_0 ); /** * The current namespace version. */ public static final Namespace CURRENT = BATCH_3_0; private final String name; Namespace(final String name) { this.name = name; } /** * Get the URI of this namespace. * * @return the URI */ public String getUriString() { return name; } public static Namespace forUri(String uri) { if (uri == null) { return UNKNOWN; } final Namespace element = MAP.get(uri); return element == null ? UNKNOWN : element; } }
2,155
28.534247
70
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/BatchResourceDescriptionResolver.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet; import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver; /** * A description resolver for the batch subsystem. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public class BatchResourceDescriptionResolver { public static final String RESOURCE_NAME = BatchResourceDescriptionResolver.class.getPackage().getName() + ".LocalDescriptions"; public static final String BASE = "batch.jberet"; public static StandardResourceDescriptionResolver getResourceDescriptionResolver() { return new StandardResourceDescriptionResolver(BASE, RESOURCE_NAME, BatchSubsystemExtension.class.getClassLoader(), true, false); } public static StandardResourceDescriptionResolver getResourceDescriptionResolver(final String keyPrefix) { String prefix = BASE + (keyPrefix == null ? "" : "." + keyPrefix); return new StandardResourceDescriptionResolver(prefix, RESOURCE_NAME, BatchSubsystemExtension.class.getClassLoader(), true, false); } public static StandardResourceDescriptionResolver getResourceDescriptionResolver(final String... prefixes) { final StringBuilder prefix = new StringBuilder(BASE); for (String p : prefixes) { prefix.append('.').append(p); } return new StandardResourceDescriptionResolver(prefix.toString(), RESOURCE_NAME, BatchSubsystemExtension.class.getClassLoader(), true, false); } }
2,507
46.320755
150
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/BatchConfiguration.java
/* * Copyright 2015 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.batch.jberet; import org.jberet.repository.JobRepository; import org.jberet.spi.JobExecutor; import org.wildfly.security.auth.server.SecurityDomain; /** * A configuration for the {@link org.jberet.spi.BatchEnvironment} behavior. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public interface BatchConfiguration { /** * Indicates whether or no batch jobs should be restarted on a resume operation if they were stopped during a * suspend. * * @return {@code true} to restart jobs on resume otherwise {@code false} to leave the jobs in a stopped state */ boolean isRestartOnResume(); /** * Returns the default job repository to use. * * @return the default job repository */ JobRepository getDefaultJobRepository(); /** * Returns the default job executor to use. * * @return the default job executor */ JobExecutor getDefaultJobExecutor(); /** * Returns the security domain if defined. * * @return the security domain or {@code null} if not defined */ SecurityDomain getSecurityDomain(); }
1,766
29.465517
114
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/_private/Capabilities.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet._private; import org.jberet.repository.JobRepository; import org.jberet.spi.JobExecutor; import org.jboss.as.controller.capability.RuntimeCapability; import org.wildfly.extension.batch.jberet.BatchConfiguration; /** * Capabilities for the batch extension. This is not to be used outside of this extension. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public class Capabilities { /** * Represents the data source capability */ public static final String DATA_SOURCE_CAPABILITY = "org.wildfly.data-source"; /** * Name of the capability that ensures a local provider of transactions is present. * Once its service is started, calls to the getInstance() methods of ContextTransactionManager, * ContextTransactionSynchronizationRegistry and LocalUserTransaction can be made knowing * that the global default TM, TSR and UT will be from that provider. */ public static final String LOCAL_TRANSACTION_PROVIDER_CAPABILITY = "org.wildfly.transactions.global-default-local-provider"; /** * A capability for the current batch configuration. */ public static final RuntimeCapability<Void> BATCH_CONFIGURATION_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.batch.configuration", false, BatchConfiguration.class) // BatchConfiguration itself doesn't require a TM, but any effective use of it does (BatchEnvironment) .addRequirements(LOCAL_TRANSACTION_PROVIDER_CAPABILITY) .build(); /** * A capability for thread-pools. */ public static final RuntimeCapability<Void> THREAD_POOL_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.batch.thread.pool", true, JobExecutor.class) .build(); /** * A capability for all job repositories. All job repositories should use this capability regardless of the * implementation of the repository. */ public static final RuntimeCapability<Void> JOB_REPOSITORY_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.batch.job.repository", true, JobRepository.class) .build(); /** * The capability name for the Elytron security domain. */ public static final String SECURITY_DOMAIN_CAPABILITY = "org.wildfly.security.security-domain"; /** * The capability name for the kernel SuspendController */ public static final String SUSPEND_CONTROLLER_CAPABILITY = "org.wildfly.server.suspend-controller"; /** * The capability name for the kernel ProcessStateNotifier. */ public static final String PROCESS_STATE_NOTIFIER_CAPABILITY = "org.wildfly.management.process-state-notifier"; }
3,739
42.488372
177
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/_private/BatchLogger.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.wildfly.extension.batch.jberet._private; import java.security.Permission; import jakarta.batch.operations.BatchRuntimeException; import jakarta.batch.operations.JobSecurityException; import jakarta.batch.operations.JobStartException; import jakarta.batch.operations.NoSuchJobException; import org.jboss.as.controller.PathElement; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.Logger.Level; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; import org.jboss.msc.service.StartException; /** * Log messages for WildFly batch module */ @MessageLogger(projectCode = "WFLYBATCH") public interface BatchLogger extends BasicLogger { /** * A logger with the category {@code org.wildfly.extension.batch}. */ BatchLogger LOGGER = Logger.getMessageLogger(BatchLogger.class, "org.wildfly.extension.batch"); /** * Creates an exception indicating there was an error processing the batch jobs directory. * * @param cause the cause of the error * * @return a {@link org.jboss.as.server.deployment.DeploymentUnitProcessingException} for the error */ @Message(id = 1, value = "Error processing META-INF/batch-jobs directory.") DeploymentUnitProcessingException errorProcessingBatchJobsDir(@Cause Throwable cause); /** * Creates an exception indicating that the resource of given type can not be removed. * * @return an {@link UnsupportedOperationException} for the error */ @Message(id = 2, value = "Resources of type %s cannot be removed") UnsupportedOperationException cannotRemoveResourceOfType(String childType); /** * Creates an exception indicating the deployment name could not be found on the address. * * @return an {@link java.lang.IllegalArgumentException} for the error */ @Message(id = 3, value = "Could not find deployment name: %s") IllegalArgumentException couldNotFindDeploymentName(String address); /** * Creates an exception indicating the {@link org.wildfly.extension.batch.jberet.deployment.JobOperatorService * JobOperatorService} has stopped. * * @return an {@link java.lang.IllegalStateException} for the error */ @Message(id = 4, value = "The service JobOperatorService has been stopped and cannot execute operations.") IllegalStateException jobOperatorServiceStopped(); /** * Creates an exception indicating the job name was not found for the deployment. * * @param jobName the invalid job name * * @return a {@link jakarta.batch.operations.NoSuchJobException} for the error */ @Message(id = 5, value = "The job name '%s' was not found for the deployment.") NoSuchJobException noSuchJobException(String jobName); /** * Creates an exception indicating the job XML file could not be found in the deployment. * * @param xmlFile the invalid XML file * * @return a {@link jakarta.batch.operations.JobStartException} for the error */ @Message(id = 6, value = "Could not find the job XML file in the deployment: %s") JobStartException couldNotFindJobXml(String xmlFile); /** * Logs a warning message indicating the job XML file failed to be processed and attempting the run the job may * result in errors. * * @param jobXmlFile the invalid job XML file name */ @LogMessage(level = Level.WARN) @Message(id = 7, value = "Failed processing the job XML file %s. Attempting to execute this job may result in errors.") void invalidJobXmlFile(String jobXmlFile); /** * Logs an warning message indicating en empty job-repository element was found in the deployment descriptor. * * @param deploymentName the name of the deployment */ @LogMessage(level = Level.WARN) @Message(id = 8, value = "Empty job-repository element found in deployment descriptor. Using the default job repository for deployment %s.") void emptyJobRepositoryElement(String deploymentName); @Message(id = 9, value = "Indexed child resources can only be registered if the parent resource supports ordered children. The parent of '%s' is not indexed") IllegalStateException indexedChildResourceRegistrationNotAvailable(PathElement address); /** * Creates an exception indicating the failure to create a job repository. * * @param cause the cause of the error * @param type the type of the job repository * * @return a {@link StartException} for the error */ @Message(id = 11, value = "Failed to create %s job repository.") StartException failedToCreateJobRepository(@Cause Throwable cause, String type); /** * Logs an error message indicating only one job repository can be defined in the {@code jboss-all.xml} deployment * descriptor. */ @LogMessage(level = Level.ERROR) @Message(id = 13, value = "Only one job repository can be defined in the jboss-all.xml deployment descriptor. The first job repository will be used.") void multipleJobRepositoriesFound(); /** * Logs a warning message indicating a job is stopping. * * @param executionId the execution id of the job * @param jobName the name of the job * @param deploymentName the name of the deployment stopping the job */ @LogMessage(level = Level.WARN) @Message(id = 14, value = "Stopping execution %d of %s for deployment %s") void stoppingJob(long executionId, String jobName, String deploymentName); /** * Logs an error message indicating a job failed to stop. * * @param cause the cause of the error * @param executionId the execution id of the job * @param jobName the name of the job * @param deploymentName the name of the deployment */ @LogMessage(level = Level.ERROR) @Message(id = 15, value = "Failed to stop execution %d for job %s on deployment %s") void stoppingJobFailed(@Cause Throwable cause, long executionId, String jobName, String deploymentName); /** * Logs an error message indicating a job failed to restart. * * @param cause the cause of the error * @param executionId the execution id of the job * @param jobName the name of the job * @param deploymentName the name of the deployment */ @LogMessage(level = Level.ERROR) @Message(id = 16, value = "Failed to restart execution %d for job %s on deployment %s") void failedRestartingJob(@Cause Throwable cause, long executionId, String jobName, String deploymentName); /** * Logs an info message indicating a job is restarting due to a previous stop issued by a suspend operation. * * @param jobName the name of the job * @param previousId the previous execution id * @param newId the new execution id */ @LogMessage(level = Level.INFO) @Message(id = 17, value = "Restarting previously stopped batch job %s. Previous execution id %d. New execution id %d.") void restartingJob(String jobName, long previousId, long newId); // /** // * Creates an exception indicating the job repository has been shutdown and job operations can no longer be // * executed. // */ // @Message(id = 18, value = "The job repository has been shutdown. Job operations can no longer be executed.") // IllegalStateException jobRepositoryShutdown(); /** * Creates an exception indicating the batch environment was not found for the {@linkplain ClassLoader class loader}. * * @return an {@link BatchRuntimeException} for the error */ @Message(id = 19, value = "No batch environment was found for class loader: %s") BatchRuntimeException noBatchEnvironmentFound(ClassLoader cl); /** * Creates an exception indicating the user is not authorized for the batch operation. * @param user the user name * @param permission the missing permission * @return * Operation requires %s permissions. User %s is not authorized for this operation. */ @Message(id = 20, value = "Permission denied. User %s does not have %s permissions.") JobSecurityException unauthorized(String user, Permission permission); }
9,529
42.515982
162
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/BatchDependencyProcessor.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.wildfly.extension.batch.jberet.deployment; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.module.ModuleDependency; import org.jboss.as.server.deployment.module.ModuleSpecification; import org.jboss.modules.Module; import org.jboss.modules.ModuleLoader; /** * Adds required batch dependencies to deployments. */ public class BatchDependencyProcessor implements DeploymentUnitProcessor { @Override public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); final ModuleLoader moduleLoader = Module.getBootModuleLoader(); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, "jakarta.batch.api", false, false, false, false)); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, "org.jberet.jberet-core", false, false, true, false)); } }
2,397
46.96
137
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/DiagnosticContextHandle.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.deployment; import java.util.Map; import org.jboss.logging.MDC; import org.jboss.logging.NDC; /** * A {@code ContextHandle} to propagate and clear mapped diagnostic context (MDC) * and nested diagnostic context (NDC) data used in logging. */ class DiagnosticContextHandle implements ContextHandle { private final Map<String, Object> mdcMap; private final String ndcTop; DiagnosticContextHandle(final Map<String, Object> mdcMap, final String ndcTop) { this.mdcMap = mdcMap; this.ndcTop = ndcTop; } @Override public Handle setup() { for (Map.Entry<String, Object> e : mdcMap.entrySet()) { MDC.put(e.getKey(), e.getValue()); } if (ndcTop != null) { NDC.clear(); NDC.push(ndcTop); } return new Handle() { @Override public void tearDown() { MDC.clear(); NDC.clear(); } }; } }
2,044
31.460317
84
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/BatchEnvironmentMetaData.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.deployment; import org.jberet.repository.JobRepository; /** * Represents environment objects created via a deployment descriptor. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ class BatchEnvironmentMetaData { private final JobRepository jobRepository; private final String jobRepositoryName; private final String dataSourceName; private final String executorName; private final Boolean restartJobsOnResume; private final Integer executionRecordsLimit; protected BatchEnvironmentMetaData(final JobRepository jobRepository, final String jobRepositoryName, final String dataSourceName, final String executorName, final Boolean restartJobsOnResume, final Integer executionRecordsLimit) { this.jobRepository = jobRepository; this.jobRepositoryName = jobRepositoryName; this.dataSourceName = dataSourceName; this.executorName = executorName; this.restartJobsOnResume = restartJobsOnResume; this.executionRecordsLimit = executionRecordsLimit; } public JobRepository getJobRepository() { return jobRepository; } public String getJobRepositoryName() { return jobRepositoryName; } public String getDataSourceName() { return dataSourceName; } public String getExecutorName() { return executorName; } public Boolean getRestartJobsOnResume() { return restartJobsOnResume; } public Integer getExecutionRecordsLimit() { return executionRecordsLimit; } }
2,817
35.128205
77
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/BatchDeploymentResourceProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.deployment; import org.jboss.as.controller.PathAddress; import org.jboss.as.ee.structure.DeploymentType; import org.jboss.as.ee.structure.DeploymentTypeMarker; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentResourceSupport; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.wildfly.extension.batch.jberet._private.BatchLogger; /** * Process deployments to add runtime deployment resources for the batch-jberet subsystem * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public class BatchDeploymentResourceProcessor implements DeploymentUnitProcessor { private final String subsystemName; public BatchDeploymentResourceProcessor(final String subsystemName) { this.subsystemName = subsystemName; } @Override public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (deploymentUnit.hasAttachment(Attachments.MODULE) && !DeploymentTypeMarker.isType(DeploymentType.EAR, deploymentUnit) && deploymentUnit.hasAttachment(Attachments.DEPLOYMENT_ROOT)) { BatchLogger.LOGGER.tracef("Processing deployment '%s' for the batch deployment resources.", deploymentUnit.getName()); final DeploymentResourceSupport deploymentResourceSupport = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_RESOURCE_SUPPORT); // Add the job operator service used interact with a deployments batch job final WildFlyJobOperator jobOperator = deploymentUnit.getAttachment(BatchAttachments.JOB_OPERATOR); // Process each job XML file for (String jobName : jobOperator.getAllJobNames()) { try { // Add the job information to the service BatchLogger.LOGGER.debugf("Added job %s to allowed jobs for deployment %s", jobName, deploymentUnit.getName()); // Register the a resource for each job found final PathAddress jobAddress = PathAddress.pathAddress(BatchJobResourceDefinition.JOB, jobName); if (!deploymentResourceSupport.hasDeploymentSubModel(subsystemName, jobAddress)) { deploymentResourceSupport.registerDeploymentSubResource(subsystemName, jobAddress, new BatchJobExecutionResource(jobOperator, jobName)); } } catch (Exception e) { // The deployment shouldn't fail in this case, just the specific resource registration should be skipped // Log a debug message so the error is not lost BatchLogger.LOGGER.debugf(e, "Batch jobs as an error occurred will not be registered for runtime views on the deployment (%s).", jobName, deploymentUnit.getName()); } } } } }
4,242
54.103896
192
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/BatchJobExecutionResourceDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.deployment; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Properties; import java.util.function.Function; import jakarta.batch.operations.JobExecutionAlreadyCompleteException; import jakarta.batch.operations.JobExecutionNotMostRecentException; import jakarta.batch.operations.JobExecutionNotRunningException; import jakarta.batch.operations.JobRestartException; import jakarta.batch.operations.JobSecurityException; import jakarta.batch.operations.NoSuchJobExecutionException; import jakarta.batch.runtime.BatchStatus; import jakarta.batch.runtime.JobExecution; import jakarta.batch.runtime.JobInstance; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleMapAttributeDefinition; import org.jboss.as.controller.SimpleOperationDefinition; import org.jboss.as.controller.SimpleOperationDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.descriptions.ResourceDescriptionResolver; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.wildfly.extension.batch.jberet.BatchResourceDescriptionResolver; /** * A definition representing a job execution resource. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public class BatchJobExecutionResourceDefinition extends SimpleResourceDefinition { static final String EXECUTION = "execution"; static final SimpleAttributeDefinition INSTANCE_ID = SimpleAttributeDefinitionBuilder.create("instance-id", ModelType.LONG) .setStorageRuntime() .build(); static final SimpleAttributeDefinition BATCH_STATUS = SimpleAttributeDefinitionBuilder.create("batch-status", ModelType.STRING) .setStorageRuntime() .build(); static final SimpleAttributeDefinition EXIT_STATUS = SimpleAttributeDefinitionBuilder.create("exit-status", ModelType.STRING) .setStorageRuntime() .build(); static final SimpleAttributeDefinition CREATE_TIME = SimpleAttributeDefinitionBuilder.create("create-time", ModelType.STRING) .setStorageRuntime() .build(); static final SimpleAttributeDefinition START_TIME = SimpleAttributeDefinitionBuilder.create("start-time", ModelType.STRING) .setStorageRuntime() .build(); static final SimpleAttributeDefinition LAST_UPDATED_TIME = SimpleAttributeDefinitionBuilder.create("last-updated-time", ModelType.STRING) .setStorageRuntime() .build(); static final SimpleAttributeDefinition END_TIME = SimpleAttributeDefinitionBuilder.create("end-time", ModelType.STRING) .setStorageRuntime() .build(); private static final ZoneId DEFAULT_ZONE_ID = ZoneId.systemDefault(); private static final ResourceDescriptionResolver DEFAULT_RESOLVER = BatchResourceDescriptionResolver.getResourceDescriptionResolver("deployment", "job", "execution"); private static final SimpleMapAttributeDefinition PROPERTIES = new SimpleMapAttributeDefinition.Builder("properties", ModelType.STRING, true) .build(); private static final SimpleOperationDefinition RESTART_JOB = new SimpleOperationDefinitionBuilder("restart-job", DEFAULT_RESOLVER) .setParameters(PROPERTIES) .setReplyType(ModelType.LONG) .setRuntimeOnly() .build(); private static final SimpleOperationDefinition STOP_JOB = new SimpleOperationDefinitionBuilder("stop-job", DEFAULT_RESOLVER) .setRuntimeOnly() .build(); public BatchJobExecutionResourceDefinition() { super(new Parameters(PathElement.pathElement(EXECUTION), DEFAULT_RESOLVER).setRuntime()); } @Override public void registerAttributes(final ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerReadOnlyAttribute(INSTANCE_ID, new JobOperationReadOnlyStepHandler() { @Override protected void updateModel(final OperationContext context, final ModelNode model, final WildFlyJobOperator jobOperator, final String jobName) throws OperationFailedException { final JobInstance jobInstance = jobOperator.getJobInstance(Long.parseLong(context.getCurrentAddressValue())); model.set(jobInstance.getInstanceId()); } }); resourceRegistration.registerReadOnlyAttribute(BATCH_STATUS, new JobExecutionOperationStepHandler() { @Override protected void updateModel(final ModelNode model, final JobExecution jobExecution) throws OperationFailedException { final BatchStatus status = jobExecution.getBatchStatus(); if (status != null) { model.set(status.toString()); } } }); resourceRegistration.registerReadOnlyAttribute(EXIT_STATUS, new JobExecutionOperationStepHandler() { @Override protected void updateModel(final ModelNode model, final JobExecution jobExecution) throws OperationFailedException { final String exitStatus = jobExecution.getExitStatus(); if (exitStatus != null) { model.set(exitStatus); } } }); resourceRegistration.registerReadOnlyAttribute(CREATE_TIME, new DateTimeFormatterOperationStepHandler(JobExecution::getCreateTime)); resourceRegistration.registerReadOnlyAttribute(START_TIME, new DateTimeFormatterOperationStepHandler(JobExecution::getStartTime)); resourceRegistration.registerReadOnlyAttribute(LAST_UPDATED_TIME, new DateTimeFormatterOperationStepHandler(JobExecution::getLastUpdatedTime)); resourceRegistration.registerReadOnlyAttribute(END_TIME, new DateTimeFormatterOperationStepHandler(JobExecution::getEndTime)); } @Override public void registerOperations(final ManagementResourceRegistration resourceRegistration) { super.registerOperations(resourceRegistration); resourceRegistration.registerOperationHandler(STOP_JOB, new JobOperationStepHandler() { @Override protected void execute(final OperationContext context, final ModelNode operation, final WildFlyJobOperator jobOperator) throws OperationFailedException { // Resolve the execution id final long executionId = Long.parseLong(context.getCurrentAddressValue()); try { jobOperator.stop(executionId); } catch (NoSuchJobExecutionException | JobExecutionNotRunningException | JobSecurityException e) { throw createOperationFailure(e); } } }); resourceRegistration.registerOperationHandler(RESTART_JOB, new JobOperationStepHandler() { @Override protected void execute(final OperationContext context, final ModelNode operation, final WildFlyJobOperator jobOperator) throws OperationFailedException { // Resolve the execution id final long executionId = Long.parseLong(context.getCurrentAddressValue()); // Get the properties final Properties properties = resolvePropertyValue(context, operation, PROPERTIES); try { final long newExecutionId = jobOperator.restart(executionId, properties); context.getResult().set(newExecutionId); } catch (JobExecutionAlreadyCompleteException | NoSuchJobExecutionException | JobExecutionNotMostRecentException | JobRestartException | JobSecurityException e) { throw createOperationFailure(e); } } }); } abstract static class JobExecutionOperationStepHandler extends JobOperationReadOnlyStepHandler { @Override protected void updateModel(final OperationContext context, final ModelNode model, final WildFlyJobOperator jobOperator, final String jobName) throws OperationFailedException { final JobExecution jobExecution = jobOperator.getJobExecution(Long.parseLong(context.getCurrentAddressValue())); updateModel(model, jobExecution); } protected abstract void updateModel(ModelNode model, JobExecution jobExecution) throws OperationFailedException; } static class DateTimeFormatterOperationStepHandler extends JobExecutionOperationStepHandler { private final Function<JobExecution, Date> dateGetter; public DateTimeFormatterOperationStepHandler(final Function<JobExecution, Date> dateGetter) { this.dateGetter = dateGetter; } protected void updateModel(final ModelNode model, final JobExecution jobExecution) throws OperationFailedException { final Date date = dateGetter.apply(jobExecution); if (date != null) { // use OffsetDateTime and ISO_OFFSET_DATE_TIME if we want to include offset in the formatting output model.set(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format( LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), DEFAULT_ZONE_ID))); } } } }
10,698
50.191388
187
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/SecurityAwareBatchEnvironment.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.wildfly.extension.batch.jberet.deployment; import org.jberet.spi.BatchEnvironment; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.auth.server.SecurityIdentity; /** * A batch environment which can provide various security options. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public interface SecurityAwareBatchEnvironment extends BatchEnvironment { /** * Returns the security domain if defined or {@code null} if not defined. * * @return the security domain or {@code null} if not defined */ SecurityDomain getSecurityDomain(); /** * If the {@linkplain #getSecurityDomain() security domain} is not {@code null} the current user is returned. * otherwise {@code null} is returned. * <p> * Note that if the current identity is anonymous {@code null} will be returned. * </p> * * @return the current user name or {@code null} */ default String getCurrentUserName() { final SecurityIdentity securityIdentity = getIdentity(); if (securityIdentity != null && !securityIdentity.isAnonymous()) { return securityIdentity.getPrincipal().getName(); } return null; } /** * If the {@linkplain #getSecurityDomain() security domain} is not {@code null} the current identity is returned. * otherwise {@code null} is returned. * * @return the current identity or {@code null} */ default SecurityIdentity getIdentity() { final SecurityDomain securityDomain = getSecurityDomain(); if (securityDomain != null) { return securityDomain.getCurrentSecurityIdentity(); } return null; } }
2,349
33.558824
117
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/BatchPermission.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.wildfly.extension.batch.jberet.deployment; import org.wildfly.common.Assert; import org.wildfly.security.permission.AbstractNameSetOnlyPermission; import org.wildfly.security.util.StringEnumeration; import org.wildfly.security.util.StringMapping; /** * A general batch permission. The permission {@code name} must be one of the following: * <ul> * <li>{@code start}</li> * <li>{@code stop}</li> * <li>{@code restart}</li> * <li>{@code abandon}</li> * <li>{@code read}</li> * </ul> * The {@code actions} are not used and should be empty or {@code null}. * * @author <a href="mailto:[email protected]">David M. Lloyd</a> * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public final class BatchPermission extends AbstractNameSetOnlyPermission<BatchPermission> { private static final long serialVersionUID = 6124294238228442419L; private static final StringEnumeration strings = StringEnumeration.of( "start", "stop", "restart", "abandon", "read" ); private static final StringMapping<BatchPermission> mapping = new StringMapping<>(strings, BatchPermission::new); private static final BatchPermission allPermission = new BatchPermission("*"); /** * Construct a new instance. * * @param name the name of the permission */ public BatchPermission(final String name) { this(name, null); } /** * Construct a new instance. * * @param name the name of the permission * @param actions the actions (should be empty) */ public BatchPermission(final String name, final String actions) { super(name, strings); requireEmptyActions(actions); } public BatchPermission withName(final String name) { return forName(name); } /** * Get the permission with the given name. * * @param name the name (must not be {@code null}) * * @return the permission (not {@code null}) * * @throws IllegalArgumentException if the name is not valid */ public static BatchPermission forName(final String name) { Assert.checkNotNullParam("name", name); return "*".equals(name) ? allPermission : mapping.getItemByString(name); } }
2,907
30.956044
117
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/BatchEnvironmentService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.deployment; import java.util.Properties; import java.util.function.Consumer; import java.util.function.Supplier; import jakarta.transaction.TransactionManager; import org.jberet.repository.JobRepository; import org.jberet.spi.ArtifactFactory; import org.jberet.spi.BatchEnvironment; import org.jberet.spi.JobExecutor; import org.jberet.spi.JobTask; import org.jberet.spi.JobXmlResolver; import org.jboss.as.naming.context.NamespaceContextSelector; import org.jboss.logging.MDC; import org.jboss.logging.NDC; import org.jboss.msc.Service; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.wildfly.extension.batch.jberet.BatchConfiguration; import org.wildfly.extension.batch.jberet._private.BatchLogger; import org.wildfly.extension.requestcontroller.ControlPoint; import org.wildfly.extension.requestcontroller.RequestController; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.auth.server.SecurityIdentity; import org.wildfly.security.manager.WildFlySecurityManager; import org.wildfly.transaction.client.ContextTransactionManager; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class BatchEnvironmentService implements Service { private static final Properties PROPS = new Properties(); private final Consumer<SecurityAwareBatchEnvironment> batchEnvironmentConsumer; private final Supplier<WildFlyArtifactFactory> artifactFactorySupplier; private final Supplier<JobExecutor> jobExecutorSupplier; private final Supplier<RequestController> requestControllerSupplier; private final Supplier<JobRepository> jobRepositorySupplier; private final Supplier<BatchConfiguration> batchConfigurationSupplier; private final ClassLoader classLoader; private final JobXmlResolver jobXmlResolver; private final String deploymentName; private final NamespaceContextSelector namespaceContextSelector; private SecurityAwareBatchEnvironment batchEnvironment = null; private volatile ControlPoint controlPoint; public BatchEnvironmentService(final Consumer<SecurityAwareBatchEnvironment> batchEnvironmentConsumer, final Supplier<WildFlyArtifactFactory> artifactFactorySupplier, final Supplier<JobExecutor> jobExecutorSupplier, final Supplier<RequestController> requestControllerSupplier, final Supplier<JobRepository> jobRepositorySupplier, final Supplier<BatchConfiguration> batchConfigurationSupplier, final ClassLoader classLoader, final JobXmlResolver jobXmlResolver, final String deploymentName, final NamespaceContextSelector namespaceContextSelector) { this.batchEnvironmentConsumer = batchEnvironmentConsumer; this.artifactFactorySupplier = artifactFactorySupplier; this.jobExecutorSupplier = jobExecutorSupplier; this.requestControllerSupplier = requestControllerSupplier; this.jobRepositorySupplier = jobRepositorySupplier; this.batchConfigurationSupplier = batchConfigurationSupplier; this.classLoader = classLoader; this.jobXmlResolver = jobXmlResolver; this.deploymentName = deploymentName; this.namespaceContextSelector = namespaceContextSelector; } @Override public synchronized void start(final StartContext context) throws StartException { BatchLogger.LOGGER.debugf("Creating batch environment; %s", classLoader); final BatchConfiguration batchConfiguration = batchConfigurationSupplier.get(); // Find the job executor to use JobExecutor jobExecutor = jobExecutorSupplier != null ? jobExecutorSupplier.get() : null; if (jobExecutor == null) { jobExecutor = batchConfiguration.getDefaultJobExecutor(); } // Find the job repository to use JobRepository jobRepository = jobRepositorySupplier != null ? jobRepositorySupplier.get() : null; if (jobRepository == null) { jobRepository = batchConfiguration.getDefaultJobRepository(); } this.batchEnvironment = new WildFlyBatchEnvironment(artifactFactorySupplier.get(), jobExecutor, ContextTransactionManager.getInstance(), jobRepository, jobXmlResolver); final RequestController requestController = requestControllerSupplier != null ? requestControllerSupplier.get() : null; if (requestController != null) { // Create the entry point controlPoint = requestController.getControlPoint(deploymentName, "batch-executor-service"); } else { controlPoint = null; } batchEnvironmentConsumer.accept(batchEnvironment); } @Override public synchronized void stop(final StopContext context) { batchEnvironmentConsumer.accept(null); BatchLogger.LOGGER.debugf("Removing batch environment; %s", classLoader); batchEnvironment = null; if (controlPoint != null) { requestControllerSupplier.get().removeControlPoint(controlPoint); } } private class WildFlyBatchEnvironment implements BatchEnvironment, SecurityAwareBatchEnvironment { private final WildFlyArtifactFactory artifactFactory; private final JobExecutor jobExecutor; private final TransactionManager transactionManager; private final JobRepository jobRepository; private final JobXmlResolver jobXmlResolver; WildFlyBatchEnvironment(final WildFlyArtifactFactory artifactFactory, final JobExecutor jobExecutor, final TransactionManager transactionManager, final JobRepository jobRepository, final JobXmlResolver jobXmlResolver) { this.jobXmlResolver = jobXmlResolver; this.artifactFactory = artifactFactory; this.jobExecutor = jobExecutor; this.transactionManager = transactionManager; this.jobRepository = jobRepository; } @Override public ClassLoader getClassLoader() { return classLoader; } @Override public ArtifactFactory getArtifactFactory() { return artifactFactory; } @Override public void submitTask(final JobTask jobTask) { final SecurityIdentity identity = getIdentity(); final ContextHandle contextHandle = createContextHandle(); final JobTask task = new JobTask() { @Override public int getRequiredRemainingPermits() { return jobTask.getRequiredRemainingPermits(); } @Override public void run() { final ContextHandle.Handle handle = contextHandle.setup(); try { if (identity == null) { jobTask.run(); } else { identity.runAs(jobTask); } } finally { handle.tearDown(); } } }; if (controlPoint == null) { jobExecutor.execute(task); } else { // Queue the task to run in the control point, if resume is executed the queued tasks will run controlPoint.queueTask(task, jobExecutor, -1, null, false); } } @Override public TransactionManager getTransactionManager() { return transactionManager; } @Override public JobRepository getJobRepository() { return jobRepository; } @Override public JobXmlResolver getJobXmlResolver() { return jobXmlResolver; } @Override public Properties getBatchConfigurationProperties() { return PROPS; } @Override public String getApplicationName() { return deploymentName; } @Override public SecurityDomain getSecurityDomain() { return batchConfigurationSupplier.get().getSecurityDomain(); } private ContextHandle createContextHandle() { final ClassLoader tccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); // If the TCCL is null, use the deployments ModuleClassLoader final ClassLoaderContextHandle classLoaderContextHandle = (tccl == null ? new ClassLoaderContextHandle(classLoader) : new ClassLoaderContextHandle(tccl)); // Class loader handle must be first so the TCCL is set before the other handles execute return new ContextHandle.ChainedContextHandle(classLoaderContextHandle, new NamespaceContextHandle(namespaceContextSelector), artifactFactory.createContextHandle(), new ConcurrentContextHandle(), new DiagnosticContextHandle(MDC.getMap(), NDC.get())); } } }
10,537
43.464135
166
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/BatchJobResourceDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.deployment; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleListAttributeDefinition; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.wildfly.extension.batch.jberet.BatchResourceDescriptionResolver; /** * A definition representing a job resource. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public class BatchJobResourceDefinition extends SimpleResourceDefinition { static final String JOB = "job"; private static final SimpleAttributeDefinition RUNNING_EXECUTIONS = SimpleAttributeDefinitionBuilder.create("running-executions", ModelType.INT) .setStorageRuntime() .build(); private static final SimpleAttributeDefinition INSTANCE_COUNT = SimpleAttributeDefinitionBuilder.create("instance-count", ModelType.INT) .setStorageRuntime() .build(); private static final SimpleAttributeDefinition JOB_XML_NAME = SimpleAttributeDefinitionBuilder.create("job-xml-name", ModelType.STRING) .setStorageRuntime() .build(); private static final SimpleListAttributeDefinition JOB_XML_NAMES = SimpleListAttributeDefinition.Builder.of("job-xml-names", JOB_XML_NAME) .setStorageRuntime() .build(); public BatchJobResourceDefinition() { super(new Parameters(PathElement.pathElement(JOB), BatchResourceDescriptionResolver.getResourceDescriptionResolver("deployment", "job")).setRuntime()); } @Override public void registerAttributes(final ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerReadOnlyAttribute(RUNNING_EXECUTIONS, new JobOperationReadOnlyStepHandler() { @Override protected void updateModel(final OperationContext context, final ModelNode model, final WildFlyJobOperator jobOperator, final String jobName) throws OperationFailedException { model.set(jobOperator.allowMissingJob(() -> jobOperator.getRunningExecutions(jobName).size(), 0)); } }); resourceRegistration.registerReadOnlyAttribute(INSTANCE_COUNT, new JobOperationReadOnlyStepHandler() { @Override protected void updateModel(final OperationContext context, final ModelNode model, final WildFlyJobOperator jobOperator, final String jobName) throws OperationFailedException { model.set(jobOperator.allowMissingJob(() -> jobOperator.getJobInstanceCount(jobName), 0)); } }); resourceRegistration.registerReadOnlyAttribute(JOB_XML_NAMES, new JobOperationReadOnlyStepHandler() { @Override protected void updateModel(final OperationContext context, final ModelNode model, final WildFlyJobOperator jobOperator, final String jobName) throws OperationFailedException { final ModelNode list = model.setEmptyList(); for (String jobXmlName : jobOperator.getJobXmlNames(jobName)) { list.add(jobXmlName); } } }); } }
4,515
48.626374
187
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/BatchDeploymentDescriptorParser_2_0.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.batch.jberet.deployment; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import org.jboss.as.controller.parsing.ParseUtils; import org.jboss.staxmapper.XMLExtendedStreamReader; import org.wildfly.extension.batch.jberet.Attribute; /** * A parser for batch deployment descriptors ({@code batch-jberet:2.0}) in {@code jboss-all.xml}. */ public class BatchDeploymentDescriptorParser_2_0 extends BatchDeploymentDescriptorParser_1_0 { public static final String NAMESPACE = "urn:jboss:domain:batch-jberet:2.0"; public static final QName ROOT_ELEMENT = new QName(NAMESPACE, "batch"); @Override String parseJdbcJobRepository(final XMLExtendedStreamReader reader) throws XMLStreamException { final String dataSourceName = readRequiredAttribute(reader, Attribute.DATA_SOURCE); ParseUtils.requireNoContent(reader); return dataSourceName; } }
1,966
40.851064
99
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/BatchEnvironmentProcessor.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.wildfly.extension.batch.jberet.deployment; import static org.jboss.as.server.deployment.Attachments.DEPLOYMENT_COMPLETE_SERVICES; import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME; import static org.wildfly.extension.batch.jberet.BatchServiceNames.requestControllerServiceName; import java.util.concurrent.ExecutorService; import java.util.function.Consumer; import java.util.function.Supplier; import javax.sql.DataSource; import jakarta.batch.operations.JobOperator; import jakarta.enterprise.inject.spi.BeanManager; import org.jberet.repository.JobRepository; import org.jberet.spi.ArtifactFactory; import org.jberet.spi.ContextClassLoaderJobOperatorContextSelector; import org.jberet.spi.JobExecutor; import org.jberet.spi.JobOperatorContext; import org.jboss.as.controller.ProcessStateNotifier; import org.jboss.as.controller.capability.CapabilityServiceSupport; import org.jboss.as.ee.component.EEModuleDescription; import org.jboss.as.ee.structure.DeploymentType; import org.jboss.as.ee.structure.DeploymentTypeMarker; import org.jboss.as.naming.context.NamespaceContextSelector; import org.jboss.as.server.Services; 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.suspend.SuspendController; import org.jboss.as.weld.WeldCapability; import org.jboss.modules.Module; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.wildfly.extension.batch.jberet.BatchConfiguration; import org.wildfly.extension.batch.jberet.BatchServiceNames; import org.wildfly.extension.batch.jberet._private.BatchLogger; import org.wildfly.extension.batch.jberet._private.Capabilities; import org.wildfly.extension.batch.jberet.job.repository.JdbcJobRepositoryService; import org.wildfly.extension.requestcontroller.RequestController; /** * Deployment unit processor for jakarta.batch integration. * <p> * Installs the {@link BatchEnvironmentService} and {@link JobOperatorService}. * </p> * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class BatchEnvironmentProcessor implements DeploymentUnitProcessor { private final boolean rcPresent; private final ContextClassLoaderJobOperatorContextSelector selector; public BatchEnvironmentProcessor(final boolean rcPresent, final ContextClassLoaderJobOperatorContextSelector selector) { this.rcPresent = rcPresent; this.selector = selector; } @Override public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (deploymentUnit.hasAttachment(Attachments.MODULE)) { BatchLogger.LOGGER.tracef("Processing deployment '%s' for the batch environment.", deploymentUnit.getName()); // Configure and attach the job resolver for all deployments final WildFlyJobXmlResolver jobXmlResolver = WildFlyJobXmlResolver.forDeployment(deploymentUnit); // Skip the rest of the processing for EAR's, only sub-deployments need an environment configured if (DeploymentTypeMarker.isType(DeploymentType.EAR, deploymentUnit)) return; // Get the class loader final Module module = deploymentUnit.getAttachment(Attachments.MODULE); final ClassLoader moduleClassLoader = module.getClassLoader(); final ServiceTarget serviceTarget = phaseContext.getServiceTarget(); // Check for a deployment descriptor BatchEnvironmentMetaData metaData = deploymentUnit.getAttachment(BatchAttachments.BATCH_ENVIRONMENT_META_DATA); if (metaData == null) { // Check the parent final DeploymentUnit parent = deploymentUnit.getParent(); if (parent != null) { metaData = parent.getAttachment(BatchAttachments.BATCH_ENVIRONMENT_META_DATA); } } final JobRepository jobRepository = metaData != null ? metaData.getJobRepository() : null; final String jobRepositoryName = metaData != null ? metaData.getJobRepositoryName() : null; final String dataSourceName = metaData != null ? metaData.getDataSourceName() : null; final String jobExecutorName = metaData != null ? metaData.getExecutorName() : null; final Boolean restartJobsOnResume = metaData != null ? metaData.getRestartJobsOnResume() : null; final Integer executionRecordsLimit = metaData != null ? metaData.getExecutionRecordsLimit() : null; final CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT); final String deploymentName = deploymentUnit.getName(); // Create the batch environment final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION); final NamespaceContextSelector namespaceContextSelector = eeModuleDescription == null ? null : eeModuleDescription.getNamespaceContextSelector(); final ServiceName batchEnvSN = BatchServiceNames.batchEnvironmentServiceName(deploymentUnit); final ServiceBuilder<?> serviceBuilder = serviceTarget.addService(batchEnvSN); final Consumer<SecurityAwareBatchEnvironment> batchEnvironmentConsumer = serviceBuilder.provides(batchEnvSN); // Add a dependency to the thread-pool final Supplier<JobExecutor> jobExecutorSupplier = jobExecutorName != null ? serviceBuilder.requires(Capabilities.THREAD_POOL_CAPABILITY.getCapabilityServiceName(jobExecutorName)) : null; // Register the required services final Supplier<BatchConfiguration> batchConfigurationSupplier = serviceBuilder.requires(Capabilities.BATCH_CONFIGURATION_CAPABILITY.getCapabilityServiceName()); // Ensure local transaction support is started serviceBuilder.requires(support.getCapabilityServiceName(Capabilities.LOCAL_TRANSACTION_PROVIDER_CAPABILITY)); final ServiceName artifactFactoryServiceName = BatchServiceNames.batchArtifactFactoryServiceName(deploymentUnit); final ServiceBuilder<?> artifactFactoryServiceBuilder = serviceTarget.addService(artifactFactoryServiceName); final Consumer<ArtifactFactory> artifactFactoryConsumer = artifactFactoryServiceBuilder.provides(artifactFactoryServiceName); Supplier<BeanManager> beanManagerSupplier = null; // Register the bean manager if this is a Jakarta Contexts and Dependency Injection deployment if (support.hasCapability(WELD_CAPABILITY_NAME)) { final WeldCapability api = support.getOptionalCapabilityRuntimeAPI(WELD_CAPABILITY_NAME, WeldCapability.class).get(); if (api.isPartOfWeldDeployment(deploymentUnit)) { BatchLogger.LOGGER.tracef("Adding BeanManager service dependency for deployment %s", deploymentUnit.getName()); beanManagerSupplier = api.addBeanManagerService(deploymentUnit, artifactFactoryServiceBuilder); } } final ArtifactFactoryService artifactFactoryService = new ArtifactFactoryService(artifactFactoryConsumer, beanManagerSupplier); artifactFactoryServiceBuilder.setInstance(artifactFactoryService); artifactFactoryServiceBuilder.install(); final Supplier<WildFlyArtifactFactory> artifactFactorySupplier = serviceBuilder.requires(artifactFactoryServiceName); Supplier<JobRepository> jobRepositorySupplier = null; if (jobRepositoryName != null) { // Register a named job repository jobRepositorySupplier = serviceBuilder.requires(support.getCapabilityServiceName(Capabilities.JOB_REPOSITORY_CAPABILITY.getName(), jobRepositoryName)); } else if (dataSourceName != null) { // Register a jdbc job repository with data-source final ServiceName jobRepositoryServiceName = support.getCapabilityServiceName(Capabilities.JOB_REPOSITORY_CAPABILITY.getName(), deploymentName); final ServiceBuilder<?> jobRepositoryServiceBuilder = serviceTarget.addService(jobRepositoryServiceName); final Consumer<JobRepository> jobRepositoryConsumer = jobRepositoryServiceBuilder.provides(jobRepositoryServiceName); final Supplier<ExecutorService> executorSupplier = Services.requireServerExecutor(jobRepositoryServiceBuilder); final Supplier<DataSource> dataSourceSupplier = jobRepositoryServiceBuilder.requires(support.getCapabilityServiceName(Capabilities.DATA_SOURCE_CAPABILITY, dataSourceName)); final JdbcJobRepositoryService jdbcJobRepositoryService = new JdbcJobRepositoryService(jobRepositoryConsumer, dataSourceSupplier, executorSupplier, executionRecordsLimit); jobRepositoryServiceBuilder.setInstance(jdbcJobRepositoryService); jobRepositoryServiceBuilder.install(); jobRepositorySupplier = serviceBuilder.requires(jobRepositoryServiceName); } else if (jobRepository != null) { // Use the job repository as defined in the deployment descriptor jobRepositorySupplier = () -> jobRepository; } final Supplier<RequestController> requestControllerSupplier = rcPresent ? serviceBuilder.requires(requestControllerServiceName(support)) : null; // Install the batch environment service final BatchEnvironmentService service = new BatchEnvironmentService(batchEnvironmentConsumer, artifactFactorySupplier, jobExecutorSupplier, requestControllerSupplier, jobRepositorySupplier, batchConfigurationSupplier, moduleClassLoader, jobXmlResolver, deploymentName, namespaceContextSelector); serviceBuilder.setInstance(service); serviceBuilder.install(); // Install the JobOperatorService final ServiceName jobOperatorServiceName = BatchServiceNames.jobOperatorServiceName(deploymentUnit); final ServiceBuilder<?> jobOperatorServiceSB = serviceTarget.addService(jobOperatorServiceName); final Consumer<JobOperator> jobOperatorConsumer = jobOperatorServiceSB.provides(jobOperatorServiceName); final Supplier<ExecutorService> executorSupplier = Services.requireServerExecutor(jobOperatorServiceSB); final Supplier<BatchConfiguration> batchConfigSupplier = jobOperatorServiceSB.requires(support.getCapabilityServiceName(Capabilities.BATCH_CONFIGURATION_CAPABILITY.getName())); final Supplier<SuspendController> suspendControllerSupplier = jobOperatorServiceSB.requires(support.getCapabilityServiceName(Capabilities.SUSPEND_CONTROLLER_CAPABILITY)); final Supplier<ProcessStateNotifier> processStateSupplier = jobOperatorServiceSB.requires(support.getCapabilityServiceName(Capabilities.PROCESS_STATE_NOTIFIER_CAPABILITY)); final Supplier<SecurityAwareBatchEnvironment> batchEnvironmentSupplier = jobOperatorServiceSB.requires(BatchServiceNames.batchEnvironmentServiceName(deploymentUnit)); final JobOperatorService jobOperatorService = new JobOperatorService(jobOperatorConsumer, batchConfigSupplier, batchEnvironmentSupplier, executorSupplier, suspendControllerSupplier, processStateSupplier, restartJobsOnResume, deploymentName, jobXmlResolver); jobOperatorServiceSB.setInstance(jobOperatorService); jobOperatorServiceSB.install(); // Add the JobOperatorService to the deployment unit deploymentUnit.putAttachment(BatchAttachments.JOB_OPERATOR, jobOperatorService); deploymentUnit.addToAttachmentList(DEPLOYMENT_COMPLETE_SERVICES, jobOperatorServiceName); // Add the JobOperator to the context selector selector.registerContext(moduleClassLoader, JobOperatorContext.create(jobOperatorService)); } } @Override public void undeploy(DeploymentUnit context) { if (context.hasAttachment(Attachments.MODULE)) { selector.unregisterContext(context.getAttachment(Attachments.MODULE).getClassLoader()); } } }
13,655
64.971014
307
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/BatchDeploymentResourceDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.deployment; import java.util.Properties; import jakarta.batch.operations.JobExecutionAlreadyCompleteException; import jakarta.batch.operations.JobExecutionNotMostRecentException; import jakarta.batch.operations.JobExecutionNotRunningException; import jakarta.batch.operations.JobRestartException; import jakarta.batch.operations.JobSecurityException; import jakarta.batch.operations.JobStartException; import jakarta.batch.operations.NoSuchJobExecutionException; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleListAttributeDefinition; import org.jboss.as.controller.SimpleMapAttributeDefinition; import org.jboss.as.controller.SimpleOperationDefinition; import org.jboss.as.controller.SimpleOperationDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.descriptions.ResourceDescriptionResolver; import org.jboss.as.controller.operations.validation.LongRangeValidator; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.wildfly.extension.batch.jberet.BatchResourceDescriptionResolver; import org.wildfly.extension.batch.jberet.BatchSubsystemDefinition; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public class BatchDeploymentResourceDefinition extends SimpleResourceDefinition { private static final ResourceDescriptionResolver DEFAULT_RESOLVER = BatchResourceDescriptionResolver.getResourceDescriptionResolver("deployment"); private static final SimpleAttributeDefinition EXECUTION_ID = SimpleAttributeDefinitionBuilder.create("execution-id", ModelType.LONG, false) .setValidator(new LongRangeValidator(1L, false)) .build(); private static final SimpleAttributeDefinition JOB_XML_NAME = SimpleAttributeDefinitionBuilder.create("job-xml-name", ModelType.STRING, false) .build(); private static final SimpleMapAttributeDefinition PROPERTIES = new SimpleMapAttributeDefinition.Builder("properties", ModelType.STRING, true) .build(); private static final SimpleListAttributeDefinition JOB_XML_NAMES = SimpleListAttributeDefinition.Builder.of("job-xml-names", JOB_XML_NAME) .setStorageRuntime() .build(); private static final SimpleOperationDefinition START_JOB = new SimpleOperationDefinitionBuilder("start-job", DEFAULT_RESOLVER) .setParameters(JOB_XML_NAME, PROPERTIES) .setReplyType(ModelType.LONG) .setRuntimeOnly() .build(); private static final SimpleOperationDefinition RESTART_JOB = new SimpleOperationDefinitionBuilder("restart-job", DEFAULT_RESOLVER) .setParameters(EXECUTION_ID, PROPERTIES) .setReplyType(ModelType.LONG) .setRuntimeOnly() .build(); private static final SimpleOperationDefinition STOP_JOB = new SimpleOperationDefinitionBuilder("stop-job", DEFAULT_RESOLVER) .setParameters(EXECUTION_ID) .setRuntimeOnly() .build(); public BatchDeploymentResourceDefinition() { super(new Parameters(BatchSubsystemDefinition.SUBSYSTEM_PATH, DEFAULT_RESOLVER) .setRuntime() .setFeature(false)); } @Override public void registerOperations(final ManagementResourceRegistration resourceRegistration) { super.registerOperations(resourceRegistration); resourceRegistration.registerOperationHandler(START_JOB, new JobOperationStepHandler() { @Override protected void execute(final OperationContext context, final ModelNode operation, final WildFlyJobOperator jobOperator) throws OperationFailedException { // Resolve the job XML name final String jobName = resolveValue(context, operation, JOB_XML_NAME).asString(); final Properties properties = resolvePropertyValue(context, operation, PROPERTIES); try { final long executionId = jobOperator.start(jobName, properties); context.getResult().set(executionId); } catch (JobStartException | JobSecurityException e) { throw createOperationFailure(e); } } }); resourceRegistration.registerOperationHandler(STOP_JOB, new JobOperationStepHandler() { @Override protected void execute(final OperationContext context, final ModelNode operation, final WildFlyJobOperator jobOperator) throws OperationFailedException { // Resolve the execution id final long executionId = resolveValue(context, operation, EXECUTION_ID).asLong(); try { jobOperator.stop(executionId); } catch (NoSuchJobExecutionException | JobExecutionNotRunningException | JobSecurityException e) { throw createOperationFailure(e); } } }); resourceRegistration.registerOperationHandler(RESTART_JOB, new JobOperationStepHandler() { @Override protected void execute(final OperationContext context, final ModelNode operation, final WildFlyJobOperator jobOperator) throws OperationFailedException { // Resolve the execution id final long executionId = resolveValue(context, operation, EXECUTION_ID).asLong(); final Properties properties = resolvePropertyValue(context, operation, PROPERTIES); try { final long newExecutionId = jobOperator.restart(executionId, properties); context.getResult().set(newExecutionId); } catch (JobExecutionAlreadyCompleteException | NoSuchJobExecutionException | JobExecutionNotMostRecentException | JobRestartException | JobSecurityException e) { throw createOperationFailure(e); } } }); } @Override public void registerAttributes(final ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerReadOnlyAttribute(JOB_XML_NAMES, new JobOperationStepHandler(false) { @Override protected void execute(final OperationContext context, final ModelNode operation, final WildFlyJobOperator jobOperator) throws OperationFailedException { final ModelNode list = context.getResult().setEmptyList(); for (String jobXmlName : jobOperator.getJobXmlNames()) { list.add(jobXmlName); } } }); } }
7,941
50.23871
178
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/ClassLoaderContextHandle.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.deployment; import org.wildfly.security.manager.WildFlySecurityManager; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ class ClassLoaderContextHandle implements ContextHandle { private final ClassLoader classLoader; ClassLoaderContextHandle(final ClassLoader classLoader) { this.classLoader = classLoader; } @Override public Handle setup() { final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader); return new Handle() { @Override public void tearDown() { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current); } }; } }
1,866
37.102041
100
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/WildFlyJobOperator.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.wildfly.extension.batch.jberet.deployment; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.function.Supplier; import jakarta.batch.operations.JobOperator; import jakarta.batch.operations.NoSuchJobException; /** * An extended version of a {@link JobOperator} for WildFly. Allows access to the job XML descriptors. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ interface WildFlyJobOperator extends JobOperator { /** * Returns all the job XML descriptors associated with this deployment. * * @return the job XML descriptors */ Collection<String> getJobXmlNames(); /** * Returns the job XML descriptors associated with a job. * * @param jobName the job name to find the XML descriptors for * * @return the set of job XML descriptors the job can be run from */ Collection<String> getJobXmlNames(String jobName); /** * Returns all the jobs this operator has access to. Some of these jobs may not be found with {@link #getJobNames()} * as they may not exist in the {@linkplain org.jberet.repository.JobRepository job repository}. * * @return a collection of all the jobs this operator has access to */ Set<String> getAllJobNames(); /** * Gets job execution ids belonging to the job identified by the {@code jobName}. * @param jobName the job name identifying the job * @return job execution ids belonging to the job * @since 25.0.0.Beta1 */ List<Long> getJobExecutionsByJob(final String jobName); /** * Allows safe execution of a method catching any {@link NoSuchJobException} thrown. If the exception is thrown the * default value is returned, otherwise the value from the supplier is returned. * * @param supplier the supplier for the value * @param defaultValue the default value if a {@link NoSuchJobException} is thrown * @param <T> the return type * * @return the value from the supplier or the default value if a {@link NoSuchJobException} was thrown */ default <T> T allowMissingJob(final Supplier<T> supplier, final T defaultValue) { try { return supplier.get(); } catch (NoSuchJobException ignore) { } return defaultValue; } }
2,965
34.73494
120
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/BatchDeploymentDescriptorParser_3_0.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.batch.jberet.deployment; import org.jboss.as.controller.parsing.ParseUtils; import org.jboss.staxmapper.XMLExtendedStreamReader; import org.wildfly.extension.batch.jberet.Attribute; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; /** * A parser for batch deployment descriptors ({@code batch-jberet:3.0}) in {@code jboss-all.xml}. */ public class BatchDeploymentDescriptorParser_3_0 extends BatchDeploymentDescriptorParser_2_0 { public static final String NAMESPACE = "urn:jboss:domain:batch-jberet:3.0"; public static final QName ROOT_ELEMENT = new QName(NAMESPACE, "batch"); @Override Integer parseExecutionRecordsLimit(final XMLExtendedStreamReader reader) throws XMLStreamException { Integer executionRecordsLimit = null; for (int i = 0; i < reader.getAttributeCount(); i++) { if (Attribute.EXECUTION_RECORDS_LIMIT.getLocalName().equals(reader.getAttributeLocalName(0))) { try { executionRecordsLimit = Integer.valueOf(reader.getAttributeValue(0)); } catch (NumberFormatException e) { throw ParseUtils.invalidAttributeValue(reader, 0); } } else { throw ParseUtils.unexpectedAttribute(reader, 0); } } return executionRecordsLimit; } }
2,421
41.491228
107
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/WildFlyJobXmlResolver.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.deployment; import java.io.IOException; import java.io.InputStream; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.ServiceLoader; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArraySet; import javax.xml.stream.XMLResolver; import javax.xml.stream.XMLStreamException; import org.jberet.job.model.Job; import org.jberet.job.model.JobParser; import org.jberet.spi.JobXmlResolver; 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.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.SubDeploymentMarker; import org.jboss.as.server.deployment.module.ResourceRoot; import org.jboss.modules.Module; import org.jboss.vfs.VirtualFile; import org.jboss.vfs.VirtualFileFilter; import org.wildfly.extension.batch.jberet._private.BatchLogger; import org.wildfly.security.manager.WildFlySecurityManager; /** * A {@linkplain JobXmlResolver job XML resolver} for WildFly. A deployments resolvers are loaded via a * {@link ServiceLoader} and processed before XML found in the deployment itself. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public class WildFlyJobXmlResolver implements JobXmlResolver { private final CopyOnWriteArraySet<JobXmlResolver> jobXmlResolvers; private final ConcurrentMap<String, String> jobXmlNames; private final ConcurrentMap<String, VirtualFile> jobXmlFiles; private final ConcurrentMap<String, Set<String>> jobNames; private WildFlyJobXmlResolver(final ConcurrentMap<String, VirtualFile> jobXmlFiles) { jobXmlNames = new ConcurrentHashMap<>(); jobXmlResolvers = new CopyOnWriteArraySet<>(); jobNames = new ConcurrentHashMap<>(); this.jobXmlFiles = jobXmlFiles; } /** * Creates the {@linkplain JobXmlResolver resolver} for the deployment inheriting any visible resolvers and job XML * files from dependencies. * * @param deploymentUnit the deployment to process * * @return the resolve * * @throws DeploymentUnitProcessingException if an error occurs processing the deployment */ public static WildFlyJobXmlResolver forDeployment(final DeploymentUnit deploymentUnit) throws DeploymentUnitProcessingException { // If this deployment unit already has a resolver, just use it if (deploymentUnit.hasAttachment(BatchAttachments.JOB_XML_RESOLVER)) { return deploymentUnit.getAttachment(BatchAttachments.JOB_XML_RESOLVER); } // Get the module for it's class loader final Module module = deploymentUnit.getAttachment(Attachments.MODULE); final ClassLoader classLoader = module.getClassLoader(); WildFlyJobXmlResolver resolver; // If we're an EAR we need to skip sub-deployments as they'll be process later, however all sub-deployments have // access to the EAR/lib directory so those resources need to be processed if (DeploymentTypeMarker.isType(DeploymentType.EAR, deploymentUnit)) { // Create a new WildFlyJobXmlResolver without jobs from sub-deployments as they'll be processed later final List<ResourceRoot> resources = new ArrayList<>(); for (ResourceRoot r : deploymentUnit.getAttachmentList(Attachments.RESOURCE_ROOTS)) { if (! SubDeploymentMarker.isSubDeployment(r)) { resources.add(r); } } resolver = create(classLoader, resources); deploymentUnit.putAttachment(BatchAttachments.JOB_XML_RESOLVER, resolver); } else { // Create a new resolver for this deployment if (deploymentUnit.hasAttachment(Attachments.RESOURCE_ROOTS)) { resolver = create(classLoader, deploymentUnit.getAttachmentList(Attachments.RESOURCE_ROOTS)); } else { resolver = create(classLoader, Collections.singletonList(deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT))); } deploymentUnit.putAttachment(BatchAttachments.JOB_XML_RESOLVER, resolver); // Process all accessible sub-deployments final List<DeploymentUnit> accessibleDeployments = deploymentUnit.getAttachmentList(Attachments.ACCESSIBLE_SUB_DEPLOYMENTS); for (DeploymentUnit subDeployment : accessibleDeployments) { // Skip our self if (deploymentUnit.equals(subDeployment)) { continue; } if (subDeployment.hasAttachment(BatchAttachments.JOB_XML_RESOLVER)) { final WildFlyJobXmlResolver toCopy = subDeployment.getAttachment(BatchAttachments.JOB_XML_RESOLVER); WildFlyJobXmlResolver.merge(resolver, toCopy); } else { // We need to create a resolver for the sub-deployment and merge the two final WildFlyJobXmlResolver toCopy = forDeployment(subDeployment); subDeployment.putAttachment(BatchAttachments.JOB_XML_RESOLVER, toCopy); WildFlyJobXmlResolver.merge(resolver, toCopy); } } } return resolver; } @Override public InputStream resolveJobXml(final String jobXml, final ClassLoader classLoader) throws IOException { if (jobXmlFiles.isEmpty() && jobXmlResolvers.isEmpty()) { return null; } for (JobXmlResolver resolver : jobXmlResolvers) { final InputStream in = resolver.resolveJobXml(jobXml, classLoader); if (in != null) { return in; } } final VirtualFile file = jobXmlFiles.get(jobXml); if (file == null) { return null; } if (WildFlySecurityManager.isChecking()) { return AccessController.doPrivileged((PrivilegedAction<InputStream>) () -> { try { return file.openStream(); } catch (IOException e) { throw new RuntimeException(e); } }); } return file.openStream(); } @Override public Collection<String> getJobXmlNames(final ClassLoader classLoader) { return new ArrayList<>(jobXmlNames.keySet()); } @Override public String resolveJobName(final String jobXml, final ClassLoader classLoader) { return jobXmlNames.get(jobXml); } /** * Validates whether or not the job name exists for this deployment. * * @param jobName the job name to check * * @return {@code true} if the job exists, otherwise {@code false} */ boolean isValidJobName(final String jobName) { return jobNames.containsKey(jobName); } /** * Returns the job XML file names which contain the job name. * * @param jobName the job name to find the job XML files for * * @return the set of job XML files the job can be run from */ Set<String> getJobXmlNames(final String jobName) { if (jobNames.containsKey(jobName)) { return Collections.unmodifiableSet(jobNames.get(jobName)); } return Collections.emptySet(); } /** * Returns all the job names available from this resolver. * * @return the job names available from this resolver */ Set<String> getJobNames() { return new LinkedHashSet<>(jobNames.keySet()); } /** * Validates whether or not the job XML descriptor exists for this deployment. * * @param jobXmlName the job XML descriptor name * * @return {@code true} if the job XML descriptor exists for this deployment, otherwise {@code false} */ boolean isValidJobXmlName(final String jobXmlName) { return jobXmlNames.containsKey(jobXmlName); } private static WildFlyJobXmlResolver create(final ClassLoader classLoader, final List<ResourceRoot> resources) throws DeploymentUnitProcessingException { final ConcurrentMap<String, VirtualFile> foundJobXmlFiles = new ConcurrentHashMap<>(); for (ResourceRoot r : resources) { final VirtualFile root = r.getRoot(); try { addJobXmlFiles(foundJobXmlFiles, root.getChild(DEFAULT_PATH)); } catch (IOException e) { throw BatchLogger.LOGGER.errorProcessingBatchJobsDir(e); } } final WildFlyJobXmlResolver jobXmlResolver = new WildFlyJobXmlResolver(foundJobXmlFiles); // Initialize this instance jobXmlResolver.init(classLoader); return jobXmlResolver; } private static void addJobXmlFiles(final ConcurrentMap<String, VirtualFile> foundJobXmlFiles, final VirtualFile jobsDir) throws IOException { if (jobsDir != null && jobsDir.exists()) { // We may have some job XML files final Map<String, VirtualFile> xmlFiles = new HashMap<>(); for (VirtualFile f : jobsDir.getChildren(JobXmlFilter.INSTANCE)) { if (xmlFiles.put(f.getName(), f) != null) { throw new IllegalStateException("Duplicate key"); } } foundJobXmlFiles.putAll(xmlFiles); } } private static void merge(final WildFlyJobXmlResolver target, final WildFlyJobXmlResolver toCopy) { for (Map.Entry<String, Set<String>> entry : toCopy.jobNames.entrySet()) { if (target.jobNames.containsKey(entry.getKey())) { target.jobNames.get(entry.getKey()).addAll(entry.getValue()); } else { target.jobNames.put(entry.getKey(), entry.getValue()); } } toCopy.jobXmlNames.forEach(target.jobXmlNames::putIfAbsent); toCopy.jobXmlFiles.forEach(target.jobXmlFiles::putIfAbsent); target.jobXmlResolvers.addAll(toCopy.jobXmlResolvers); } /** * Initializes the state of an instance */ private void init(final ClassLoader classLoader) { // Load the user defined resolvers for (JobXmlResolver resolver : ServiceLoader.load(JobXmlResolver.class, classLoader)) { jobXmlResolvers.add(resolver); for (String jobXml : resolver.getJobXmlNames(classLoader)) { addJob(jobXml, resolver.resolveJobName(jobXml, classLoader)); } } // Load the default names for (Map.Entry<String, VirtualFile> entry : jobXmlFiles.entrySet()) { try { // Parsing the entire job XML seems excessive to just get the job name. There are two reasons for this: // 1) If an error occurs during parsing there's no real need to consider this a valid job // 2) Using the implementation parser seems less error prone for future-proofing final Job job = JobParser.parseJob(entry.getValue().openStream(), classLoader, new XMLResolver() { // this is essentially what JBeret does, but it's ugly. JBeret might need an API to handle this @Override public Object resolveEntity(final String publicID, final String systemID, final String baseURI, final String namespace) throws XMLStreamException { try { return (jobXmlFiles.containsKey(systemID) ? jobXmlFiles.get(systemID).openStream() : null); } catch (IOException e) { throw new XMLStreamException(e); } } }); addJob(entry.getKey(), job.getId()); } catch (XMLStreamException | IOException e) { // Report the possible error as we don't want to fail the deployment. The job may never be run. BatchLogger.LOGGER.invalidJobXmlFile(entry.getKey()); } } } private void addJob(final String jobXmlName, final String jobName) { jobXmlNames.put(jobXmlName, jobName); final Set<String> xmlDescriptors = jobNames.computeIfAbsent(jobName, s -> new LinkedHashSet<>()); xmlDescriptors.add(jobXmlName); } private static class JobXmlFilter implements VirtualFileFilter { static final JobXmlFilter INSTANCE = new JobXmlFilter(); @Override public boolean accepts(final VirtualFile file) { return file.isFile() && file.getName().endsWith(".xml"); } } }
14,044
43.166667
167
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/WildFlyArtifactFactory.java
/* * Copyright 2017 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.batch.jberet.deployment; import org.jberet.spi.ArtifactFactory; /** * ArtifactFactory for Jakarta EE runtime environment. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public interface WildFlyArtifactFactory extends ArtifactFactory { /** * Creates a {@linkplain ContextHandle context handle} required for setting up the Jakarta Contexts and Dependency Injection context. * * @return the newly create context handle */ ContextHandle createContextHandle(); }
1,145
31.742857
137
java