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/transactions/src/main/java/org/jboss/as/txn/subsystem/ProcessIdType.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
/**
* Enums for the known com.arjuna.ats.arjuna.utils.Process implementation types
* @author Scott stark (sstark@redhat.com) (C) 2011 Red Hat Inc.
* @version $Revision:$
*/
public enum ProcessIdType {
UUID("uuid", "com.arjuna.ats.internal.arjuna.utils.UuidProcessId"),
FILE("file", "com.arjuna.ats.internal.arjuna.utils.FileProcessId"),
MBEAN("mbean", "com.arjuna.ats.internal.arjuna.utils.MBeanProcessId"),
SOCKET("socket", "com.arjuna.ats.internal.arjuna.utils.SocketProcessId")
;
private final String name;
private final String clazz;
ProcessIdType(final String name, final String clazz) {
this.name = name;
this.clazz = clazz;
}
public String getClazz() {
return clazz;
}
public String getName() {
return name;
}
}
| 1,870
| 35.686275
| 79
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/LogStoreTransactionParticipantDefinition.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleOperationDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
/**
* @author <a href="mailto:tomaz.cerar@redhat.com">Tomaz Cerar</a>
*/
public class LogStoreTransactionParticipantDefinition extends SimpleResourceDefinition {
static final SimpleAttributeDefinition[] PARTICIPANT_ATTRIBUTES = new SimpleAttributeDefinition[]{
LogStoreConstants.JMX_NAME, LogStoreConstants.PARTICIPANT_JNDI_NAME,
LogStoreConstants.PARTICIPANT_STATUS, LogStoreConstants.RECORD_TYPE,
LogStoreConstants.EIS_NAME, LogStoreConstants.EIS_VERSION};
LogStoreTransactionParticipantDefinition() {
super(new Parameters(TransactionExtension.PARTICIPANT_PATH,
TransactionExtension.getResourceDescriptionResolver(LogStoreConstants.LOG_STORE, CommonAttributes.TRANSACTION, CommonAttributes.PARTICIPANT))
.setRuntime()
);
}
@Override
public void registerOperations(ManagementResourceRegistration resourceRegistration) {
super.registerOperations(resourceRegistration);
final LogStoreParticipantRefreshHandler refreshHandler = LogStoreParticipantRefreshHandler.INSTANCE;
final LogStoreProbeHandler probeHandler = LogStoreProbeHandler.INSTANCE;
resourceRegistration.registerOperationHandler(new SimpleOperationDefinitionBuilder(LogStoreConstants.REFRESH, getResourceDescriptionResolver()).build(), refreshHandler);
resourceRegistration.registerOperationHandler(new SimpleOperationDefinitionBuilder(LogStoreConstants.RECOVER, getResourceDescriptionResolver()).build(), new LogStoreParticipantRecoveryHandler(refreshHandler));
resourceRegistration.registerOperationHandler(new SimpleOperationDefinitionBuilder(LogStoreConstants.DELETE, getResourceDescriptionResolver()).build(), new LogStoreParticipantDeleteHandler(probeHandler));
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
for (final SimpleAttributeDefinition attribute : PARTICIPANT_ATTRIBUTES) {
resourceRegistration.registerReadOnlyAttribute(attribute, null);
}
}
}
| 3,390
| 50.378788
| 217
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/TransactionSubsystem14Parser.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.txn.logging.TransactionLogger;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLExtendedStreamReader;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.parsing.ParseUtils.duplicateNamedElement;
import static org.jboss.as.controller.parsing.ParseUtils.missingOneOf;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequired;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequiredElement;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoContent;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoNamespaceAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
/**
* The {@link XMLElementReader} that handles the Transaction subsystem.
*
* @author <a href="mailto:istudens@redhat.com">Ivo Studensky</a>
*/
class TransactionSubsystem14Parser implements XMLStreamConstants, XMLElementReader<List<ModelNode>> {
private final Namespace validNamespace;
protected TransactionSubsystem14Parser(Namespace validNamespace) {
this.validNamespace = validNamespace;
this.relativeToHasDefaultValue = true;
}
TransactionSubsystem14Parser(){
this(Namespace.TRANSACTIONS_1_4);
}
protected boolean choiceObjectStoreEncountered;
protected boolean needsDefaultRelativeTo;
protected boolean relativeToHasDefaultValue;
protected Namespace getExpectedNamespace() {
return validNamespace;
}
/**
* {@inheritDoc}
*/
@Override
public void readElement(XMLExtendedStreamReader reader, List<ModelNode> list) throws XMLStreamException {
// no attributes
if (reader.getAttributeCount() > 0) {
throw unexpectedAttribute(reader, 0);
}
final ModelNode address = new ModelNode();
address.add(ModelDescriptionConstants.SUBSYSTEM, TransactionExtension.SUBSYSTEM_NAME);
address.protect();
final ModelNode subsystem = new ModelNode();
subsystem.get(OP).set(ADD);
subsystem.get(OP_ADDR).set(address);
list.add(subsystem);
final ModelNode logStoreAddress = address.clone();
final ModelNode logStoreOperation = new ModelNode();
logStoreOperation.get(OP).set(ADD);
logStoreAddress.add(LogStoreConstants.LOG_STORE, LogStoreConstants.LOG_STORE);
logStoreAddress.protect();
logStoreOperation.get(OP_ADDR).set(logStoreAddress);
list.add(logStoreOperation);
// elements
final EnumSet<Element> required = EnumSet.of(Element.RECOVERY_ENVIRONMENT, Element.CORE_ENVIRONMENT);
final EnumSet<Element> encountered = EnumSet.noneOf(Element.class);
choiceObjectStoreEncountered = false;
needsDefaultRelativeTo = true;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
if (Namespace.forUri(reader.getNamespaceURI()) != getExpectedNamespace()) {
throw unexpectedElement(reader);
}
final Element element = Element.forName(reader.getLocalName());
required.remove(element);
if (!encountered.add(element)) {
throw unexpectedElement(reader);
}
readElement(reader, element, list, subsystem, logStoreOperation);
}
if(needsDefaultRelativeTo && relativeToHasDefaultValue) {
TransactionSubsystemRootResourceDefinition.OBJECT_STORE_RELATIVE_TO.parseAndSetParameter("jboss.server.data.dir", subsystem, reader);
}
if (!required.isEmpty()) {
throw missingRequiredElement(reader, required);
}
}
protected void readElement(final XMLExtendedStreamReader reader, final Element element, final List<ModelNode> operations, final ModelNode subsystemOperation, final ModelNode logStoreOperation) throws XMLStreamException {
switch (element) {
case RECOVERY_ENVIRONMENT: {
parseRecoveryEnvironmentElement(reader, subsystemOperation);
break;
}
case CORE_ENVIRONMENT: {
parseCoreEnvironmentElement(reader, subsystemOperation);
break;
}
case COORDINATOR_ENVIRONMENT: {
parseCoordinatorEnvironmentElement(reader, subsystemOperation);
break;
}
case OBJECT_STORE: {
parseObjectStoreEnvironmentElementAndEnrichOperation(reader, subsystemOperation);
break;
}
case JTS: {
parseJts(reader, subsystemOperation);
break;
}
case USE_HORNETQ_STORE: {
if (choiceObjectStoreEncountered) {
throw unexpectedElement(reader);
}
choiceObjectStoreEncountered = true;
parseUseJournalstore(reader, logStoreOperation, subsystemOperation);
subsystemOperation.get(CommonAttributes.USE_JOURNAL_STORE).set(true);
break;
}
case JDBC_STORE: {
if (choiceObjectStoreEncountered) {
throw unexpectedElement(reader);
}
choiceObjectStoreEncountered = true;
parseJdbcStoreElementAndEnrichOperation(reader, logStoreOperation, subsystemOperation);
subsystemOperation.get(CommonAttributes.USE_JDBC_STORE).set(true);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
protected void parseJts(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
// no attributes
if (reader.getAttributeCount() > 0) {
throw unexpectedAttribute(reader, 0);
}
operation.get(CommonAttributes.JTS).set(true);
requireNoContent(reader);
}
protected void parseUseJournalstore(final XMLExtendedStreamReader reader, final ModelNode logStoreOperation, final ModelNode operation) throws XMLStreamException {
logStoreOperation.get(LogStoreConstants.LOG_STORE_TYPE.getName()).set("journal");
// Handle attributes
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case ENABLE_ASYNC_IO:
TransactionSubsystemRootResourceDefinition.JOURNAL_STORE_ENABLE_ASYNC_IO.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
// Handle elements
requireNoContent(reader);
}
protected void parseObjectStoreEnvironmentElementAndEnrichOperation(final XMLExtendedStreamReader reader, ModelNode operation) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case RELATIVE_TO:
TransactionSubsystemRootResourceDefinition.OBJECT_STORE_RELATIVE_TO.parseAndSetParameter(value, operation, reader);
needsDefaultRelativeTo = false;
break;
case PATH:
TransactionSubsystemRootResourceDefinition.OBJECT_STORE_PATH.parseAndSetParameter(value, operation, reader);
if (!value.equals(TransactionSubsystemRootResourceDefinition.OBJECT_STORE_PATH.getDefaultValue().asString())) {
needsDefaultRelativeTo = false;
}
break;
default:
throw unexpectedAttribute(reader, i);
}
}
// Handle elements
requireNoContent(reader);
}
protected void parseJdbcStoreElementAndEnrichOperation(final XMLExtendedStreamReader reader, final ModelNode logStoreOperation, ModelNode operation) throws XMLStreamException {
logStoreOperation.get(LogStoreConstants.LOG_STORE_TYPE.getName()).set("jdbc");
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case DATASOURCE_JNDI_NAME:
TransactionSubsystemRootResourceDefinition.JDBC_STORE_DATASOURCE.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case JDBC_ACTION_STORE: {
parseJdbcStoreConfigElementAndEnrichOperation(reader, operation, TransactionSubsystemRootResourceDefinition.JDBC_ACTION_STORE_TABLE_PREFIX, TransactionSubsystemRootResourceDefinition.JDBC_ACTION_STORE_DROP_TABLE);
break;
}
case JDBC_STATE_STORE: {
parseJdbcStoreConfigElementAndEnrichOperation(reader, operation, TransactionSubsystemRootResourceDefinition.JDBC_STATE_STORE_TABLE_PREFIX, TransactionSubsystemRootResourceDefinition.JDBC_STATE_STORE_DROP_TABLE);
break;
}
case JDBC_COMMUNICATION_STORE: {
parseJdbcStoreConfigElementAndEnrichOperation(reader, operation, TransactionSubsystemRootResourceDefinition.JDBC_COMMUNICATION_STORE_TABLE_PREFIX, TransactionSubsystemRootResourceDefinition.JDBC_COMMUNICATION_STORE_DROP_TABLE);
break;
}
}
}
}
protected void parseJdbcStoreConfigElementAndEnrichOperation(final XMLExtendedStreamReader reader, final ModelNode operation, final SimpleAttributeDefinition tablePrefix, final SimpleAttributeDefinition dropTable) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case TABLE_PREFIX:
tablePrefix.parseAndSetParameter(value, operation, reader);
break;
case DROP_TABLE:
dropTable.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
// Handle elements
requireNoContent(reader);
}
protected void parseCoordinatorEnvironmentElement(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case ENABLE_STATISTICS:
TransactionSubsystemRootResourceDefinition.ENABLE_STATISTICS.parseAndSetParameter(value, operation, reader);
break;
case ENABLE_TSM_STATUS:
TransactionSubsystemRootResourceDefinition.ENABLE_TSM_STATUS.parseAndSetParameter(value, operation, reader);
break;
case DEFAULT_TIMEOUT:
TransactionSubsystemRootResourceDefinition.DEFAULT_TIMEOUT.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
// Handle elements
requireNoContent(reader);
}
/**
* Handle the core-environment element and children
*
* @param reader
* @return ModelNode for the core-environment
* @throws XMLStreamException
*
*/
protected void parseCoreEnvironmentElement(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NODE_IDENTIFIER:
TransactionSubsystemRootResourceDefinition.NODE_IDENTIFIER.parseAndSetParameter(value, operation, reader);
break;
case PATH:
case RELATIVE_TO:
throw TransactionLogger.ROOT_LOGGER.unsupportedAttribute(attribute.getLocalName(), reader.getLocation());
default:
throw unexpectedAttribute(reader, i);
}
}
// elements
final EnumSet<Element> required = EnumSet.of(Element.PROCESS_ID);
final EnumSet<Element> encountered = EnumSet.noneOf(Element.class);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
required.remove(element);
switch (element) {
case PROCESS_ID: {
if (!encountered.add(element)) {
throw duplicateNamedElement(reader, reader.getLocalName());
}
parseProcessIdEnvironmentElement(reader, operation);
break;
}
default:
throw unexpectedElement(reader);
}
}
if (!required.isEmpty()) {
throw missingRequiredElement(reader, required);
}
}
/**
* Handle the process-id child elements
*
* @param reader
* @param coreEnvironmentAdd
* @return
* @throws XMLStreamException
*
*/
protected void parseProcessIdEnvironmentElement(XMLExtendedStreamReader reader, ModelNode coreEnvironmentAdd) throws XMLStreamException {
// no attributes
if (reader.getAttributeCount() > 0) {
throw unexpectedAttribute(reader, 0);
}
// elements
boolean encountered = false;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case UUID:
if (encountered) {
throw unexpectedElement(reader);
}
encountered = true;
if (reader.getAttributeCount() > 0) {
throw unexpectedAttribute(reader, 0);
}
coreEnvironmentAdd.get(TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.getName()).set(true);
requireNoContent(reader);
break;
case SOCKET: {
if (encountered) {
throw unexpectedElement(reader);
}
encountered = true;
parseSocketProcessIdElement(reader, coreEnvironmentAdd);
break;
}
default:
throw unexpectedElement(reader);
}
}
if (!encountered) {
throw missingOneOf(reader, EnumSet.of(Element.UUID, Element.SOCKET));
}
}
protected void parseSocketProcessIdElement(XMLExtendedStreamReader reader, ModelNode coreEnvironmentAdd) throws XMLStreamException {
final int count = reader.getAttributeCount();
final EnumSet<Attribute> required = EnumSet.of(Attribute.BINDING);
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case BINDING:
TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING.parseAndSetParameter(value, coreEnvironmentAdd, reader);
break;
case SOCKET_PROCESS_ID_MAX_PORTS:
TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_MAX_PORTS.parseAndSetParameter(value, coreEnvironmentAdd, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
// Handle elements
requireNoContent(reader);
}
protected void parseRecoveryEnvironmentElement(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
Set<Attribute> required = EnumSet.of(Attribute.BINDING, Attribute.STATUS_BINDING);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case BINDING:
TransactionSubsystemRootResourceDefinition.BINDING.parseAndSetParameter(value, operation, reader);
break;
case STATUS_BINDING:
TransactionSubsystemRootResourceDefinition.STATUS_BINDING.parseAndSetParameter(value, operation, reader);
break;
case RECOVERY_LISTENER:
TransactionSubsystemRootResourceDefinition.RECOVERY_LISTENER.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
// Handle elements
requireNoContent(reader);
}
}
| 20,928
| 42.602083
| 247
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/LogStoreAddHandler.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.dmr.ModelNode;
/**
*
* @author <a href="stefano.maestri@redhat.com">Stefano Maestri</a>
*/
class LogStoreAddHandler implements OperationStepHandler {
private LogStoreResource resource = null;
LogStoreAddHandler(LogStoreResource resource) {
this.resource = resource;
}
@Override
public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException {
// Add the log store resource
final ModelNode model = resource.getModel();
LogStoreConstants.LOG_STORE_TYPE.validateAndSet(operation, model);
context.addResource(PathAddress.EMPTY_ADDRESS, resource);
}
}
| 1,948
| 36.480769
| 116
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/TransactionSubsystem15Parser.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequired;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
import java.util.List;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* The {@link XMLExtendedStreamReader} that handles the version 3.0 of Transaction subsystem xml.
*/
class TransactionSubsystem15Parser extends TransactionSubsystem14Parser {
TransactionSubsystem15Parser() {
super(Namespace.TRANSACTIONS_1_5);
}
@Override
protected void readElement(final XMLExtendedStreamReader reader, final Element element, final List<ModelNode> operations, final ModelNode subsystemOperation, final ModelNode logStoreOperation) throws XMLStreamException {
switch (element) {
case RECOVERY_ENVIRONMENT: {
parseRecoveryEnvironmentElement(reader, subsystemOperation);
break;
}
case CORE_ENVIRONMENT: {
parseCoreEnvironmentElement(reader, subsystemOperation);
break;
}
case COORDINATOR_ENVIRONMENT: {
parseCoordinatorEnvironmentElement(reader, subsystemOperation);
break;
}
case OBJECT_STORE: {
parseObjectStoreEnvironmentElementAndEnrichOperation(reader, subsystemOperation);
break;
}
case JTS: {
parseJts(reader, subsystemOperation);
break;
}
case USE_HORNETQ_STORE: {
if (choiceObjectStoreEncountered) {
throw unexpectedElement(reader);
}
choiceObjectStoreEncountered = true;
parseUseJournalstore(reader, logStoreOperation, subsystemOperation);
subsystemOperation.get(CommonAttributes.USE_JOURNAL_STORE).set(true);
break;
}
case JDBC_STORE: {
if (choiceObjectStoreEncountered) {
throw unexpectedElement(reader);
}
choiceObjectStoreEncountered = true;
parseJdbcStoreElementAndEnrichOperation(reader, logStoreOperation, subsystemOperation);
subsystemOperation.get(CommonAttributes.USE_JDBC_STORE).set(true);
break;
}
case CM_RESOURCES:
parseCMs(reader, operations);
break;
default: {
throw unexpectedElement(reader);
}
}
}
private void parseCMs(XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case CM_RESPOURCE:
parseCM(reader, operations);
break;
default: {
throw unexpectedElement(reader);
}
}
}
}
private void parseCM(XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
final ModelNode address = new ModelNode();
address.add(ModelDescriptionConstants.SUBSYSTEM, TransactionExtension.SUBSYSTEM_NAME);
address.protect();
final ModelNode cmrAddress = address.clone();
final ModelNode cmrOperation = new ModelNode();
cmrOperation.get(OP).set(ADD);
String jndiName = null;
for (Attribute attribute : Attribute.values()) {
switch (attribute) {
case JNDI_NAME: {
jndiName = rawAttributeText(reader, CMResourceResourceDefinition.JNDI_NAME.getXmlName(), null);
break;
}
default:
break;
}
}
if (jndiName == null) {
throw missingRequired(reader, CMResourceResourceDefinition.JNDI_NAME.getXmlName());
}
cmrAddress.add(CommonAttributes.CM_RESOURCE, jndiName);
while (reader.hasNext()) {
switch (reader.nextTag()) {
case END_ELEMENT: {
if (Element.forName(reader.getLocalName()) == Element.CM_RESPOURCE) {
cmrAddress.protect();
cmrOperation.get(OP_ADDR).set(cmrAddress);
operations.add(cmrOperation);
return;
} else {
if (Element.forName(reader.getLocalName()) == Element.UNKNOWN) {
throw unexpectedElement(reader);
}
}
break;
}
case START_ELEMENT: {
switch (Element.forName(reader.getLocalName())) {
case CM_TABLE: {
addAttribute(reader, cmrOperation, CMResourceResourceDefinition.CM_TABLE_NAME);
addAttribute(reader, cmrOperation, CMResourceResourceDefinition.CM_TABLE_BATCH_SIZE);
addAttribute(reader, cmrOperation, CMResourceResourceDefinition.CM_TABLE_IMMEDIATE_CLEANUP);
break;
}
}
}
}
}
}
private void addAttribute(XMLExtendedStreamReader reader, ModelNode operation, SimpleAttributeDefinition attributeDefinition) throws XMLStreamException {
String value = rawAttributeText(reader, attributeDefinition.getXmlName(), null);
if (value != null) {
attributeDefinition.parseAndSetParameter(value, operation, reader);
}
}
/**
* Reads and trims the text for the given attribute and returns it or {@code defaultValue} if there is no
* value for the attribute
*
* @param reader source for the attribute text
* @param attributeName the name of the attribute
* @param defaultValue value to return if there is no value for the attribute
* @return the string representing raw attribute text or {@code defaultValue} if there is none
*/
private String rawAttributeText(XMLStreamReader reader, String attributeName, String defaultValue) {
return reader.getAttributeValue("", attributeName) == null
? defaultValue :
reader.getAttributeValue("", attributeName).trim();
}
}
| 8,097
| 40.958549
| 224
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/TransactionSubsystem30Parser.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequired;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
import java.util.List;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* The {@link org.jboss.staxmapper.XMLElementReader} that handles the version 3.0 of Transaction subsystem xml.
*/
class TransactionSubsystem30Parser extends TransactionSubsystem20Parser {
TransactionSubsystem30Parser() {
super(Namespace.TRANSACTIONS_3_0);
}
TransactionSubsystem30Parser(Namespace namespace) {
super(namespace);
}
@Override
protected void readElement(final XMLExtendedStreamReader reader, final Element element, final List<ModelNode> operations, final ModelNode subsystemOperation, final ModelNode logStoreOperation) throws XMLStreamException {
switch (element) {
case RECOVERY_ENVIRONMENT: {
parseRecoveryEnvironmentElement(reader, subsystemOperation);
break;
}
case CORE_ENVIRONMENT: {
parseCoreEnvironmentElement(reader, subsystemOperation);
break;
}
case COORDINATOR_ENVIRONMENT: {
parseCoordinatorEnvironmentElement(reader, subsystemOperation);
break;
}
case OBJECT_STORE: {
parseObjectStoreEnvironmentElementAndEnrichOperation(reader, subsystemOperation);
break;
}
case JTS: {
parseJts(reader, subsystemOperation);
break;
}
case USE_JOURNAL_STORE: {
if (choiceObjectStoreEncountered) {
throw unexpectedElement(reader);
}
choiceObjectStoreEncountered = true;
parseUseJournalstore(reader, logStoreOperation, subsystemOperation);
subsystemOperation.get(CommonAttributes.USE_JOURNAL_STORE).set(true);
break;
}
case JDBC_STORE: {
if (choiceObjectStoreEncountered) {
throw unexpectedElement(reader);
}
choiceObjectStoreEncountered = true;
parseJdbcStoreElementAndEnrichOperation(reader, logStoreOperation, subsystemOperation);
subsystemOperation.get(CommonAttributes.USE_JDBC_STORE).set(true);
break;
}
case CM_RESOURCES:
parseCMs(reader, operations);
break;
default: {
throw unexpectedElement(reader);
}
}
}
protected void parseCMs(XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case CM_RESPOURCE:
parseCM(reader, operations);
break;
default: {
throw unexpectedElement(reader);
}
}
}
}
private void parseCM(XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
final ModelNode address = new ModelNode();
address.add(ModelDescriptionConstants.SUBSYSTEM, TransactionExtension.SUBSYSTEM_NAME);
address.protect();
final ModelNode cmrAddress = address.clone();
final ModelNode cmrOperation = new ModelNode();
cmrOperation.get(OP).set(ADD);
String jndiName = null;
for (Attribute attribute : Attribute.values()) {
switch (attribute) {
case JNDI_NAME: {
jndiName = rawAttributeText(reader, CMResourceResourceDefinition.JNDI_NAME.getXmlName(), null);
break;
}
default:
break;
}
}
if (jndiName == null) {
throw missingRequired(reader, CMResourceResourceDefinition.JNDI_NAME.getXmlName());
}
cmrAddress.add(CommonAttributes.CM_RESOURCE, jndiName);
while (reader.hasNext()) {
switch (reader.nextTag()) {
case END_ELEMENT: {
if (Element.forName(reader.getLocalName()) == Element.CM_RESPOURCE) {
cmrAddress.protect();
cmrOperation.get(OP_ADDR).set(cmrAddress);
operations.add(cmrOperation);
return;
} else {
if (Element.forName(reader.getLocalName()) == Element.UNKNOWN) {
throw unexpectedElement(reader);
}
}
break;
}
case START_ELEMENT: {
switch (Element.forName(reader.getLocalName())) {
case CM_TABLE: {
addAttribute(reader, cmrOperation, CMResourceResourceDefinition.CM_TABLE_NAME);
addAttribute(reader, cmrOperation, CMResourceResourceDefinition.CM_TABLE_BATCH_SIZE);
addAttribute(reader, cmrOperation, CMResourceResourceDefinition.CM_TABLE_IMMEDIATE_CLEANUP);
break;
}
}
}
}
}
}
private void addAttribute(XMLExtendedStreamReader reader, ModelNode operation, SimpleAttributeDefinition attributeDefinition) throws XMLStreamException {
String value = rawAttributeText(reader, attributeDefinition.getXmlName(), null);
if (value != null) {
attributeDefinition.parseAndSetParameter(value, operation, reader);
}
}
/**
* Reads and trims the text for the given attribute and returns it or {@code defaultValue} if there is no
* value for the attribute
*
* @param reader source for the attribute text
* @param attributeName the name of the attribute
* @param defaultValue value to return if there is no value for the attribute
* @return the string representing raw attribute text or {@code defaultValue} if there is none
*/
private String rawAttributeText(XMLStreamReader reader, String attributeName, String defaultValue) {
return reader.getAttributeValue("", attributeName) == null
? defaultValue :
reader.getAttributeValue("", attributeName).trim();
}
}
| 8,202
| 40.639594
| 224
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/TransactionSubsystem13Parser.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.parsing.ParseUtils.duplicateNamedElement;
import static org.jboss.as.controller.parsing.ParseUtils.missingOneOf;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequired;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequiredElement;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoContent;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoNamespaceAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.txn.logging.TransactionLogger;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
*/
class TransactionSubsystem13Parser implements XMLStreamConstants, XMLElementReader<List<ModelNode>> {
TransactionSubsystem13Parser() {
}
/**
* {@inheritDoc}
*/
@Override
public void readElement(XMLExtendedStreamReader reader, List<ModelNode> list) throws XMLStreamException {
// no attributes
if (reader.getAttributeCount() > 0) {
throw unexpectedAttribute(reader, 0);
}
final ModelNode address = new ModelNode();
address.add(ModelDescriptionConstants.SUBSYSTEM, TransactionExtension.SUBSYSTEM_NAME);
address.protect();
final ModelNode subsystem = new ModelNode();
subsystem.get(OP).set(ADD);
subsystem.get(OP_ADDR).set(address);
list.add(subsystem);
final ModelNode logStoreAddress = address.clone();
final ModelNode logStoreOperation = new ModelNode();
logStoreOperation.get(OP).set(ADD);
logStoreAddress.add(LogStoreConstants.LOG_STORE, LogStoreConstants.LOG_STORE);
logStoreAddress.protect();
logStoreOperation.get(OP_ADDR).set(logStoreAddress);
list.add(logStoreOperation);
// elements
final EnumSet<Element> required = EnumSet.of(Element.RECOVERY_ENVIRONMENT, Element.CORE_ENVIRONMENT);
final EnumSet<Element> encountered = EnumSet.noneOf(Element.class);
boolean choiceElementEncountered = false;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
switch (Namespace.forUri(reader.getNamespaceURI())) {
case TRANSACTIONS_1_3: {
final Element element = Element.forName(reader.getLocalName());
required.remove(element);
if (!encountered.add(element)) {
throw unexpectedElement(reader);
}
switch (element) {
case RECOVERY_ENVIRONMENT: {
parseRecoveryEnvironmentElement(reader, subsystem);
break;
}
case CORE_ENVIRONMENT: {
parseCoreEnvironmentElement(reader, subsystem);
break;
}
case COORDINATOR_ENVIRONMENT: {
parseCoordinatorEnvironmentElement(reader, subsystem);
break;
}
case OBJECT_STORE: {
parseObjectStoreEnvironmentElementAndEnrichOperation(reader, subsystem);
break;
}
case JTS: {
parseJts(reader, subsystem);
break;
}
case USE_HORNETQ_STORE: {
if (choiceElementEncountered) {
throw unexpectedElement(reader);
}
choiceElementEncountered = true;
parseUseJournalstore(reader, logStoreOperation);
subsystem.get(CommonAttributes.USE_JOURNAL_STORE).set(true);
break;
}
case JDBC_STORE: {
if (choiceElementEncountered) {
throw unexpectedElement(reader);
}
choiceElementEncountered = true;
parseJdbcStoreElementAndEnrichOperation(reader, subsystem);
subsystem.get(CommonAttributes.USE_JDBC_STORE).set(true);
break;
}
default: {
throw unexpectedElement(reader);
}
}
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
if (!required.isEmpty()) {
throw missingRequiredElement(reader, required);
}
}
private void parseJts(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
// no attributes
if (reader.getAttributeCount() > 0) {
throw unexpectedAttribute(reader, 0);
}
operation.get(CommonAttributes.JTS).set(true);
requireNoContent(reader);
}
private void parseUseJournalstore(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
operation.get(LogStoreConstants.LOG_STORE_TYPE.getName()).set("journal");
requireNoContent(reader);
}
static void parseObjectStoreEnvironmentElementAndEnrichOperation(final XMLExtendedStreamReader reader, ModelNode operation) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case RELATIVE_TO:
TransactionSubsystemRootResourceDefinition.OBJECT_STORE_RELATIVE_TO.parseAndSetParameter(value, operation, reader);
break;
case PATH:
TransactionSubsystemRootResourceDefinition.OBJECT_STORE_PATH.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
// Handle elements
requireNoContent(reader);
}
static void parseJdbcStoreElementAndEnrichOperation(final XMLExtendedStreamReader reader, ModelNode operation) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case DATASOURCE_JNDI_NAME:
TransactionSubsystemRootResourceDefinition.JDBC_STORE_DATASOURCE.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case JDBC_ACTION_STORE: {
parseJdbcStoreConfigElementAndEnrichOperation(reader, operation, TransactionSubsystemRootResourceDefinition.JDBC_ACTION_STORE_TABLE_PREFIX, TransactionSubsystemRootResourceDefinition.JDBC_ACTION_STORE_DROP_TABLE);
break;
}
case JDBC_STATE_STORE: {
parseJdbcStoreConfigElementAndEnrichOperation(reader, operation, TransactionSubsystemRootResourceDefinition.JDBC_STATE_STORE_TABLE_PREFIX, TransactionSubsystemRootResourceDefinition.JDBC_STATE_STORE_DROP_TABLE);
break;
}
case JDBC_COMMUNICATION_STORE: {
parseJdbcStoreConfigElementAndEnrichOperation(reader, operation, TransactionSubsystemRootResourceDefinition.JDBC_COMMUNICATION_STORE_TABLE_PREFIX, TransactionSubsystemRootResourceDefinition.JDBC_COMMUNICATION_STORE_DROP_TABLE);
break;
}
}
}
}
static void parseJdbcStoreConfigElementAndEnrichOperation(final XMLExtendedStreamReader reader, final ModelNode operation, final SimpleAttributeDefinition tablePrefix, final SimpleAttributeDefinition dropTable) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case TABLE_PREFIX:
tablePrefix.parseAndSetParameter(value, operation, reader);
break;
case DROP_TABLE:
dropTable.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
// Handle elements
requireNoContent(reader);
}
static void parseCoordinatorEnvironmentElement(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case ENABLE_STATISTICS:
TransactionSubsystemRootResourceDefinition.ENABLE_STATISTICS.parseAndSetParameter(value, operation, reader);
break;
case ENABLE_TSM_STATUS:
TransactionSubsystemRootResourceDefinition.ENABLE_TSM_STATUS.parseAndSetParameter(value, operation, reader);
break;
case DEFAULT_TIMEOUT:
TransactionSubsystemRootResourceDefinition.DEFAULT_TIMEOUT.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
// Handle elements
requireNoContent(reader);
}
/**
* Handle the core-environment element and children
*
* @param reader the stream reader
* @param operation ModelNode for the core-environment add operation
* @throws XMLStreamException
*
*/
static void parseCoreEnvironmentElement(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NODE_IDENTIFIER:
TransactionSubsystemRootResourceDefinition.NODE_IDENTIFIER.parseAndSetParameter(value, operation, reader);
break;
case PATH:
case RELATIVE_TO:
throw TransactionLogger.ROOT_LOGGER.unsupportedAttribute(attribute.getLocalName(), reader.getLocation());
default:
throw unexpectedAttribute(reader, i);
}
}
// elements
final EnumSet<Element> required = EnumSet.of(Element.PROCESS_ID);
final EnumSet<Element> encountered = EnumSet.noneOf(Element.class);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
required.remove(element);
switch (element) {
case PROCESS_ID: {
if (!encountered.add(element)) {
throw duplicateNamedElement(reader, reader.getLocalName());
}
parseProcessIdEnvironmentElement(reader, operation);
break;
}
default:
throw unexpectedElement(reader);
}
}
if (!required.isEmpty()) {
throw missingRequiredElement(reader, required);
}
}
/**
* Handle the process-id child elements
*
* @param reader the stream reader
* @param coreEnvironmentAdd the add operation
*
* @throws XMLStreamException
*
*/
static void parseProcessIdEnvironmentElement(XMLExtendedStreamReader reader, ModelNode coreEnvironmentAdd) throws XMLStreamException {
// no attributes
if (reader.getAttributeCount() > 0) {
throw unexpectedAttribute(reader, 0);
}
// elements
boolean encountered = false;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case UUID:
if (encountered) {
throw unexpectedElement(reader);
}
encountered = true;
if (reader.getAttributeCount() > 0) {
throw unexpectedAttribute(reader, 0);
}
coreEnvironmentAdd.get(TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.getName()).set(true);
requireNoContent(reader);
break;
case SOCKET: {
if (encountered) {
throw unexpectedElement(reader);
}
encountered = true;
parseSocketProcessIdElement(reader, coreEnvironmentAdd);
break;
}
default:
throw unexpectedElement(reader);
}
}
if (!encountered) {
throw missingOneOf(reader, EnumSet.of(Element.UUID, Element.SOCKET));
}
}
static void parseSocketProcessIdElement(XMLExtendedStreamReader reader, ModelNode coreEnvironmentAdd) throws XMLStreamException {
final int count = reader.getAttributeCount();
final EnumSet<Attribute> required = EnumSet.of(Attribute.BINDING);
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case BINDING:
TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING.parseAndSetParameter(value, coreEnvironmentAdd, reader);
break;
case SOCKET_PROCESS_ID_MAX_PORTS:
TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_MAX_PORTS.parseAndSetParameter(value, coreEnvironmentAdd, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
// Handle elements
requireNoContent(reader);
}
static void parseRecoveryEnvironmentElement(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
Set<Attribute> required = EnumSet.of(Attribute.BINDING, Attribute.STATUS_BINDING);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case BINDING:
TransactionSubsystemRootResourceDefinition.BINDING.parseAndSetParameter(value, operation, reader);
break;
case STATUS_BINDING:
TransactionSubsystemRootResourceDefinition.STATUS_BINDING.parseAndSetParameter(value, operation, reader);
break;
case RECOVERY_LISTENER:
TransactionSubsystemRootResourceDefinition.RECOVERY_LISTENER.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
// Handle elements
requireNoContent(reader);
}
}
| 19,177
| 43.087356
| 247
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/LogStoreConstants.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.client.helpers.MeasurementUnit;
import org.jboss.as.controller.operations.validation.EnumValidator;
import org.jboss.as.controller.operations.validation.StringLengthValidator;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author @author <a href="stefano.maestri@redhat.com">Stefano Maestri</a> 2011 Red Hat Inc.
*/
class LogStoreConstants {
static final String PROBE = "probe";
static final String RECOVER = "recover";
static final String DELETE = "delete";
static final String REFRESH = "refresh";
public static final String LOG_STORE = "log-store";
public static final String TRANSACTIONS = "transactions";
public static final String PARTICIPANTS = "participants";
static enum ParticipantStatus {
PENDING,
PREPARED,
FAILED,
HEURISTIC,
READONLY
}
static final String JMX_ON_ATTRIBUTE = "jmx-name";
static final String JNDI_ATTRIBUTE = "jndi-name";
static final String LOG_STORE_TYPE_ATTRIBUTE = "type";
static final String EXPOSE_ALL_LOGS_ATTRIBUTE = "expose-all-logs";
static final Map<String, String> MODEL_TO_JMX_TXN_NAMES =
Collections.unmodifiableMap(new HashMap<String, String>() {
private static final long serialVersionUID = 1L;
{
put(JMX_ON_ATTRIBUTE, null);
put("id", "Id");
put("age-in-seconds", "AgeInSeconds");
put("type", "Type");
}});
static final Map<String, String> MODEL_TO_JMX_PARTICIPANT_NAMES =
Collections.unmodifiableMap(new HashMap<String, String>() {
private static final long serialVersionUID = 1L;
{
put(JMX_ON_ATTRIBUTE, null);
put("type", "Type");
put("status", "Status");
put(JNDI_ATTRIBUTE, "JndiName");
put("eis-product-name", "EisProductName");
put("eis-product-version", "EisProductVersion");
}});
static final String[] TXN_JMX_NAMES = MODEL_TO_JMX_TXN_NAMES.values().toArray(new String[MODEL_TO_JMX_TXN_NAMES.size()]);
static final String[] PARTICIPANT_JMX_NAMES = MODEL_TO_JMX_PARTICIPANT_NAMES.values().toArray(new String[MODEL_TO_JMX_PARTICIPANT_NAMES.size()]);
static SimpleAttributeDefinition LOG_STORE_TYPE = (new SimpleAttributeDefinitionBuilder(LOG_STORE_TYPE_ATTRIBUTE, ModelType.STRING))
.setAllowExpression(false)
.setRequired(false)
.setDefaultValue(new ModelNode("default"))
.setMeasurementUnit(MeasurementUnit.NONE)
.build();
static final SimpleAttributeDefinition EXPOSE_ALL_LOGS = new SimpleAttributeDefinitionBuilder(EXPOSE_ALL_LOGS_ATTRIBUTE, ModelType.BOOLEAN)
.setAllowExpression(true)
.setRequired(false)
.setDefaultValue(ModelNode.FALSE)
.setMeasurementUnit(MeasurementUnit.NONE)
.setStorageRuntime()
.build();
static SimpleAttributeDefinition JMX_NAME = (new SimpleAttributeDefinitionBuilder(JMX_ON_ATTRIBUTE, ModelType.STRING))
.setAllowExpression(false)
.setRequired(false)
.setDefaultValue(new ModelNode())
.setMeasurementUnit(MeasurementUnit.NONE)
.setValidator(new StringLengthValidator(0, true))
.build();
static SimpleAttributeDefinition TRANSACTION_AGE = (new SimpleAttributeDefinitionBuilder("age-in-seconds", ModelType.LONG))
.setAllowExpression(false)
.setRequired(false)
.setDefaultValue(new ModelNode())
.setMeasurementUnit(MeasurementUnit.SECONDS)
.build();
static SimpleAttributeDefinition TRANSACTION_ID = (new SimpleAttributeDefinitionBuilder("id", ModelType.STRING))
.setAllowExpression(false)
.setRequired(false)
.setDefaultValue(new ModelNode())
.setMeasurementUnit(MeasurementUnit.NONE)
.build();
static SimpleAttributeDefinition PARTICIPANT_STATUS = (new SimpleAttributeDefinitionBuilder("status", ModelType.STRING))
.setAllowExpression(false)
.setRequired(false)
.setDefaultValue(new ModelNode())
.setMeasurementUnit(MeasurementUnit.NONE)
.setValidator(EnumValidator.create(ParticipantStatus.class))
.build();
static SimpleAttributeDefinition PARTICIPANT_JNDI_NAME = (new SimpleAttributeDefinitionBuilder(JNDI_ATTRIBUTE, ModelType.STRING))
.setAllowExpression(false)
.setRequired(false)
.setDefaultValue(new ModelNode())
.setMeasurementUnit(MeasurementUnit.NONE)
.build();
static SimpleAttributeDefinition EIS_NAME = (new SimpleAttributeDefinitionBuilder("eis-product-name", ModelType.STRING))
.setAllowExpression(false)
.setRequired(false)
.setDefaultValue(new ModelNode())
.setMeasurementUnit(MeasurementUnit.NONE)
.setValidator(new StringLengthValidator(0, true))
.build();
static SimpleAttributeDefinition EIS_VERSION = (new SimpleAttributeDefinitionBuilder("eis-product-version", ModelType.STRING))
.setAllowExpression(false)
.setRequired(false)
.setDefaultValue(new ModelNode())
.setMeasurementUnit(MeasurementUnit.NONE)
.setValidator(new StringLengthValidator(0, true))
.build();
static SimpleAttributeDefinition RECORD_TYPE = (new SimpleAttributeDefinitionBuilder("type", ModelType.STRING))
.setAllowExpression(false)
.setRequired(false)
.setDefaultValue(new ModelNode())
.setMeasurementUnit(MeasurementUnit.NONE)
.build();
static String jmxNameToModelName(Map<String, String> map, String jmxName) {
for(Map.Entry<String, String> e : map.entrySet()) {
if (jmxName.equals(e.getValue()))
return e.getKey();
}
return null;
}
}
| 7,396
| 40.094444
| 149
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/TransactionSubsystem50Parser.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
*/
package org.jboss.as.txn.subsystem;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLExtendedStreamReader;
import javax.xml.stream.XMLStreamException;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoContent;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoNamespaceAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute;
/**
* The {@link org.jboss.staxmapper.XMLElementReader} that handles the version 5.1 of Transaction subsystem xml.
*/
class TransactionSubsystem50Parser extends TransactionSubsystem40Parser {
TransactionSubsystem50Parser() {
super(Namespace.TRANSACTIONS_5_0);
}
TransactionSubsystem50Parser(Namespace namespace) {
super(namespace);
}
protected void parseCoordinatorEnvironmentElement(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case STATISTICS_ENABLED:
TransactionSubsystemRootResourceDefinition.STATISTICS_ENABLED.parseAndSetParameter(value, operation, reader);
break;
case ENABLE_STATISTICS:
TransactionSubsystemRootResourceDefinition.ENABLE_STATISTICS.parseAndSetParameter(value, operation, reader);
break;
case ENABLE_TSM_STATUS:
TransactionSubsystemRootResourceDefinition.ENABLE_TSM_STATUS.parseAndSetParameter(value, operation, reader);
break;
case DEFAULT_TIMEOUT:
TransactionSubsystemRootResourceDefinition.DEFAULT_TIMEOUT.parseAndSetParameter(value, operation, reader);
break;
case MAXIMUM_TIMEOUT:
TransactionSubsystemRootResourceDefinition.MAXIMUM_TIMEOUT.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
// Handle elements
requireNoContent(reader);
}
}
| 3,447
| 43.205128
| 146
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/TransactionSubsystem10Parser.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.txn.logging.TransactionLogger;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLExtendedStreamReader;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.parsing.ParseUtils.duplicateNamedElement;
import static org.jboss.as.controller.parsing.ParseUtils.missingOneOf;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequired;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequiredElement;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoContent;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoNamespaceAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
/**
*/
class TransactionSubsystem10Parser implements XMLStreamConstants, XMLElementReader<List<ModelNode>> {
TransactionSubsystem10Parser() {
}
/**
* {@inheritDoc}
*/
@Override
public void readElement(XMLExtendedStreamReader reader, List<ModelNode> list) throws XMLStreamException {
// no attributes
if (reader.getAttributeCount() > 0) {
throw unexpectedAttribute(reader, 0);
}
final ModelNode address = new ModelNode();
address.add(ModelDescriptionConstants.SUBSYSTEM, TransactionExtension.SUBSYSTEM_NAME);
address.protect();
final ModelNode subsystem = new ModelNode();
subsystem.get(OP).set(ADD);
subsystem.get(OP_ADDR).set(address);
list.add(subsystem);
// elements
final EnumSet<Element> required = EnumSet.of(Element.RECOVERY_ENVIRONMENT, Element.CORE_ENVIRONMENT);
final EnumSet<Element> encountered = EnumSet.noneOf(Element.class);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
switch (Namespace.forUri(reader.getNamespaceURI())) {
case TRANSACTIONS_1_0: {
final Element element = Element.forName(reader.getLocalName());
required.remove(element);
if (!encountered.add(element)) {
throw unexpectedElement(reader);
}
switch (element) {
case RECOVERY_ENVIRONMENT: {
parseRecoveryEnvironmentElement(reader, subsystem);
break;
}
case CORE_ENVIRONMENT: {
parseCoreEnvironmentElement(reader, subsystem);
break;
}
case COORDINATOR_ENVIRONMENT: {
parseCoordinatorEnvironmentElement(reader, subsystem);
break;
}
case OBJECT_STORE: {
parseObjectStoreEnvironmentElementAndEnrichOperation(reader, subsystem);
break;
}
default: {
throw unexpectedElement(reader);
}
}
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
if (!required.isEmpty()) {
throw missingRequiredElement(reader, required);
}
final ModelNode logStoreAddress = address.clone();
final ModelNode operation = new ModelNode();
operation.get(OP).set(ADD);
logStoreAddress.add(LogStoreConstants.LOG_STORE, LogStoreConstants.LOG_STORE);
logStoreAddress.protect();
operation.get(OP_ADDR).set(logStoreAddress);
list.add(operation);
}
static void parseObjectStoreEnvironmentElementAndEnrichOperation(final XMLExtendedStreamReader reader, ModelNode operation) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case RELATIVE_TO:
TransactionSubsystemRootResourceDefinition.OBJECT_STORE_RELATIVE_TO.parseAndSetParameter(value, operation, reader);
break;
case PATH:
TransactionSubsystemRootResourceDefinition.OBJECT_STORE_PATH.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
// Handle elements
requireNoContent(reader);
}
static void parseCoordinatorEnvironmentElement(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case ENABLE_STATISTICS:
TransactionSubsystemRootResourceDefinition.STATISTICS_ENABLED.parseAndSetParameter(value, operation, reader);
break;
case ENABLE_TSM_STATUS:
TransactionSubsystemRootResourceDefinition.ENABLE_TSM_STATUS.parseAndSetParameter(value, operation, reader);
break;
case DEFAULT_TIMEOUT:
TransactionSubsystemRootResourceDefinition.DEFAULT_TIMEOUT.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
// Handle elements
requireNoContent(reader);
}
/**
* Handle the core-environment element and children
*
* @param reader
* @return ModelNode for the core-environment
* @throws XMLStreamException
*
*/
static void parseCoreEnvironmentElement(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NODE_IDENTIFIER:
TransactionSubsystemRootResourceDefinition.NODE_IDENTIFIER.parseAndSetParameter(value, operation, reader);
break;
case PATH:
case RELATIVE_TO:
throw TransactionLogger.ROOT_LOGGER.unsupportedAttribute(attribute.getLocalName(), reader.getLocation());
default:
throw unexpectedAttribute(reader, i);
}
}
// elements
final EnumSet<Element> required = EnumSet.of(Element.PROCESS_ID);
final EnumSet<Element> encountered = EnumSet.noneOf(Element.class);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
required.remove(element);
switch (element) {
case PROCESS_ID: {
if (!encountered.add(element)) {
throw duplicateNamedElement(reader, reader.getLocalName());
}
parseProcessIdEnvironmentElement(reader, operation);
break;
}
default:
throw unexpectedElement(reader);
}
}
if (!required.isEmpty()) {
throw missingRequiredElement(reader, required);
}
}
/**
* Handle the process-id child elements
*
* @param reader
* @param coreEnvironmentAdd
* @return
* @throws XMLStreamException
*
*/
static void parseProcessIdEnvironmentElement(XMLExtendedStreamReader reader, ModelNode coreEnvironmentAdd) throws XMLStreamException {
// no attributes
if (reader.getAttributeCount() > 0) {
throw unexpectedAttribute(reader, 0);
}
// elements
boolean encountered = false;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case UUID:
if (encountered) {
throw unexpectedElement(reader);
}
encountered = true;
if (reader.getAttributeCount() > 0) {
throw unexpectedAttribute(reader, 0);
}
coreEnvironmentAdd.get(TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.getName()).set(true);
requireNoContent(reader);
break;
case SOCKET: {
if (encountered) {
throw unexpectedElement(reader);
}
encountered = true;
parseSocketProcessIdElement(reader, coreEnvironmentAdd);
break;
}
default:
throw unexpectedElement(reader);
}
}
if (!encountered) {
throw missingOneOf(reader, EnumSet.of(Element.UUID, Element.SOCKET));
}
}
static void parseSocketProcessIdElement(XMLExtendedStreamReader reader, ModelNode coreEnvironmentAdd) throws XMLStreamException {
final int count = reader.getAttributeCount();
final EnumSet<Attribute> required = EnumSet.of(Attribute.BINDING);
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case BINDING:
TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING.parseAndSetParameter(value, coreEnvironmentAdd, reader);
break;
case SOCKET_PROCESS_ID_MAX_PORTS:
TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_MAX_PORTS.parseAndSetParameter(value, coreEnvironmentAdd, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
// Handle elements
requireNoContent(reader);
}
static void parseRecoveryEnvironmentElement(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
Set<Attribute> required = EnumSet.of(Attribute.BINDING, Attribute.STATUS_BINDING);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case BINDING:
TransactionSubsystemRootResourceDefinition.BINDING.parseAndSetParameter(value, operation, reader);
break;
case STATUS_BINDING:
TransactionSubsystemRootResourceDefinition.STATUS_BINDING.parseAndSetParameter(value, operation, reader);
break;
case RECOVERY_LISTENER:
TransactionSubsystemRootResourceDefinition.RECOVERY_LISTENER.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
// Handle elements
requireNoContent(reader);
}
}
| 14,213
| 41.053254
| 155
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/CommonAttributes.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
/**
* @author Emanuel Muckenhuber
* @author Scott Stark (sstark@redhat.com) (C) 2011 Red Hat Inc.
*/
interface CommonAttributes {
String BINDING= "socket-binding";
String CORE_ENVIRONMENT = "core-environment";
String COORDINATOR_ENVIRONMENT = "coordinator-environment";
String DEFAULT_TIMEOUT = "default-timeout";
String MAXIMUM_TIMEOUT = "maximum-timeout";
String ENABLE_STATISTICS = "enable-statistics";
/** transaction status manager (TSM) service, needed for out of process recovery, should be provided or not */
String ENABLE_TSM_STATUS = "enable-tsm-status";
String NODE_IDENTIFIER = "node-identifier";
String OBJECT_STORE = "object-store";
String OBJECT_STORE_PATH = "object-store-path";
String OBJECT_STORE_RELATIVE_TO = "object-store-relative-to";
String STATE_STORE = "state";
String COMMUNICATION_STORE = "communication";
String ACTION_STORE = "action";
String JTS = "jts";
String USE_HORNETQ_STORE = "use-hornetq-store";
String USE_JOURNAL_STORE = "use-journal-store";
String HORNETQ_STORE_ENABLE_ASYNC_IO = "hornetq-store-enable-async-io";
String JOURNAL_STORE_ENABLE_ASYNC_IO = "journal-store-enable-async-io";
String JDBC_STORE = "jdbc-store";
String USE_JDBC_STORE = "use-jdbc-store";
String JDBC_STORE_DATASOURCE = "jdbc-store-datasource";
String JDBC_ACTION_STORE_TABLE_PREFIX = "jdbc-action-store-table-prefix";
String JDBC_ACTION_STORE_DROP_TABLE = "jdbc-action-store-drop-table";
String JDBC_COMMUNICATION_STORE_TABLE_PREFIX = "jdbc-communication-store-table-prefix";
String JDBC_COMMUNICATION_STORE_DROP_TABLE = "jdbc-communication-store-drop-table";
String JDBC_STATE_STORE_TABLE_PREFIX = "jdbc-state-store-table-prefix";
String JDBC_STATE_STORE_DROP_TABLE = "jdbc-state-store-drop-table";
/** The com.arjuna.ats.arjuna.utils.Process implementation type */
String PROCESS_ID = "process-id";
String CONFIGURATION = "configuration";
String LOG_STORE = "log-store";
String RECOVERY_ENVIRONMENT = "recovery-environment";
String RECOVERY_LISTENER = "recovery-listener";
/** The process-id/socket element */
String SOCKET = "socket";
/** The process-id/socket attribute for max ports */
String SOCKET_PROCESS_ID_MAX_PORTS = "max-ports";
String STATISTICS_ENABLED = "statistics-enabled";
String STATUS_BINDING = "status-socket-binding";
/** The process-id/uuid element */
String UUID = "uuid";
// TxStats
String STATISTICS = "statistics";
String NUMBER_OF_TRANSACTIONS = "number-of-transactions";
String NUMBER_OF_NESTED_TRANSACTIONS = "number-of-nested-transactions";
String NUMBER_OF_HEURISTICS = "number-of-heuristics";
String NUMBER_OF_COMMITTED_TRANSACTIONS = "number-of-committed-transactions";
String NUMBER_OF_ABORTED_TRANSACTIONS = "number-of-aborted-transactions";
String NUMBER_OF_INFLIGHT_TRANSACTIONS = "number-of-inflight-transactions";
String NUMBER_OF_TIMED_OUT_TRANSACTIONS = "number-of-timed-out-transactions";
String NUMBER_OF_APPLICATION_ROLLBACKS = "number-of-application-rollbacks";
String NUMBER_OF_RESOURCE_ROLLBACKS = "number-of-resource-rollbacks";
String NUMBER_OF_SYSTEM_ROLLBACKS = "number-of-system-rollbacks";
String AVERAGE_COMMIT_TIME = "average-commit-time";
String PARTICIPANT = "participant";
String TRANSACTION = "transaction";
// TODO, process-id/mbean, process-id/file
String CM_RESOURCES ="commit-markable-resources";
String CM_RESOURCE ="commit-markable-resource";
String CM_LOCATION ="xid-location";
String CM_JNDI_NAME = "jndi-name";
String CM_BATCH_SIZE = "batch-size";
String CM_IMMEDIATE_CLEANUP = "immediate-cleanup";
String CM_LOCATION_NAME = "name";
Integer CM_BATCH_SIZE_DEF_VAL = 100;
Boolean CM_IMMEDIATE_CLEANUP_DEF_VAL = true;
String CM_LOCATION_NAME_DEF_VAL = "xids";
String CLIENT = "client";
String STALE_TRANSACTION_TIME = "stale-transaction-time";
}
| 5,084
| 44
| 114
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/Attribute.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
import java.util.HashMap;
import java.util.Map;
/**
* Enumeration of attributes used in the transactions subsystem.
*
* @author John E. Bailey
* @author Scott Stark (sstark@redhat.com) (C) 2011 Red Hat Inc.
*/
enum Attribute {
UNKNOWN(null),
BINDING("socket-binding"),
STATUS_BINDING("status-socket-binding"),
NODE_IDENTIFIER("node-identifier"),
SOCKET_PROCESS_ID_MAX_PORTS("socket-process-id-max-ports"),
ENABLE_STATISTICS("enable-statistics"),
ENABLE_TSM_STATUS("enable-tsm-status"),
DEFAULT_TIMEOUT("default-timeout"),
MAXIMUM_TIMEOUT("maximum-timeout"),
RECOVERY_LISTENER("recovery-listener"),
RELATIVE_TO("relative-to"),
STATISTICS_ENABLED("statistics-enabled"),
PATH("path"),
DATASOURCE_JNDI_NAME("datasource-jndi-name"),
TABLE_PREFIX("table-prefix"),
DROP_TABLE("drop-table"),
ENABLE_ASYNC_IO("enable-async-io"),
JNDI_NAME(CommonAttributes.CM_JNDI_NAME),
CM_TABLE_IMMEDIATE_CLEANUP(CommonAttributes.CM_IMMEDIATE_CLEANUP),
CM_TABLE_BATCH_SIZE(CommonAttributes.CM_BATCH_SIZE),
NAME(CommonAttributes.CM_LOCATION_NAME),
STALE_TRANSACTION_TIME(CommonAttributes.STALE_TRANSACTION_TIME)
;
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;
}
private static final Map<String, Attribute> MAP;
static {
final Map<String, Attribute> map = new HashMap<String, Attribute>();
for (Attribute element : values()) {
final String name = element.getLocalName();
if (name != null) map.put(name, element);
}
MAP = map;
}
public static Attribute forName(String localName) {
final Attribute element = MAP.get(localName);
return element == null ? UNKNOWN : element;
}
public String toString() {
return getLocalName();
}
}
| 3,083
| 32.16129
| 76
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/LogStoreTransactionDefinition.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleOperationDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
/**
* @author <a href="mailto:tomaz.cerar@redhat.com">Tomaz Cerar</a>
*/
class LogStoreTransactionDefinition extends SimpleResourceDefinition {
private final LogStoreResource resource;
static final SimpleAttributeDefinition[] TRANSACTION_ATTRIBUTE = new SimpleAttributeDefinition[]{
LogStoreConstants.JMX_NAME, LogStoreConstants.TRANSACTION_ID,
LogStoreConstants.TRANSACTION_AGE, LogStoreConstants.RECORD_TYPE};
public LogStoreTransactionDefinition(final LogStoreResource resource) {
super(new Parameters(TransactionExtension.TRANSACTION_PATH,
TransactionExtension.getResourceDescriptionResolver(LogStoreConstants.LOG_STORE, CommonAttributes.TRANSACTION))
.setRuntime()
);
this.resource = resource;
}
@Override
public void registerOperations(ManagementResourceRegistration resourceRegistration) {
super.registerOperations(resourceRegistration);
resourceRegistration.registerOperationHandler(new SimpleOperationDefinitionBuilder(LogStoreConstants.DELETE, getResourceDescriptionResolver()).build(), new LogStoreTransactionDeleteHandler(resource));
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
for (SimpleAttributeDefinition def : TRANSACTION_ATTRIBUTE) {
resourceRegistration.registerReadOnlyAttribute(def, null);
}
}
}
| 2,756
| 43.467742
| 208
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/TransactionSubsystem40Parser.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
*/
package org.jboss.as.txn.subsystem;
/**
* The {@link org.jboss.staxmapper.XMLElementReader} that handles the version 4.0 of Transaction subsystem xml.
*/
class TransactionSubsystem40Parser extends TransactionSubsystem30Parser {
TransactionSubsystem40Parser() {
super(Namespace.TRANSACTIONS_4_0);
this.relativeToHasDefaultValue = false;
}
TransactionSubsystem40Parser(Namespace namespace) {
super(namespace);
this.relativeToHasDefaultValue = false;
}
}
| 1,540
| 37.525
| 111
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/LogStoreParticipantDeleteHandler.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.dmr.ModelNode;
public class LogStoreParticipantDeleteHandler extends LogStoreParticipantOperationHandler {
private LogStoreProbeHandler probeHandler = null;
public LogStoreParticipantDeleteHandler(LogStoreProbeHandler probeHandler) {
super("remove");
this.probeHandler = probeHandler;
}
void refreshParticipant(OperationContext context) {
final ModelNode operation = Util.createEmptyOperation("refresh-log-store", context.getCurrentAddress().getParent().getParent());
context.addStep(operation, new OperationStepHandler() {
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
probeHandler.execute(context, operation);
}
}, OperationContext.Stage.MODEL);
}
}
| 2,126
| 40.705882
| 136
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/CMResourceAdd.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.txn.logging.TransactionLogger.ROOT_LOGGER;
import com.arjuna.ats.jta.common.JTAEnvironmentBean;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.txn.service.CMResourceService;
import org.jboss.as.txn.service.TxnServices;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceController;
/**
* the {@link AbstractAddStepHandler} implementations that add CM managed resource.
*
* @author Stefano Maestri (c) 2011 Red Hat Inc.
*/
class CMResourceAdd extends AbstractAddStepHandler {
static CMResourceAdd INSTANCE = new CMResourceAdd();
/**
* {@inheritDoc}
*/
@Override
protected void populateModel(ModelNode operation, ModelNode model) throws OperationFailedException {
String str = PathAddress.pathAddress(operation.get(OP_ADDR)).getLastElement().getValue();
if (!str.startsWith("java:/") && !str.startsWith("java:jboss/")) {
throw ROOT_LOGGER.jndiNameInvalidFormat();
}
CMResourceResourceDefinition.CM_TABLE_NAME.validateAndSet(operation, model);
CMResourceResourceDefinition.CM_TABLE_BATCH_SIZE.validateAndSet(operation, model);
CMResourceResourceDefinition.CM_TABLE_IMMEDIATE_CLEANUP.validateAndSet(operation, model);
}
/**
* {@inheritDoc}
*/
@Override
protected void performRuntime(final OperationContext context, final ModelNode operation, final ModelNode model) throws OperationFailedException {
if (!context.isBooting()) {
context.restartRequired();
return;
}
PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR));
final String jndiName = address.getLastElement().getValue();
final String tableName = CMResourceResourceDefinition.CM_TABLE_NAME.resolveModelAttribute(context, model).asString();
final int batchSize = CMResourceResourceDefinition.CM_TABLE_BATCH_SIZE.resolveModelAttribute(context, model).asInt();
final boolean immediateCleanup = CMResourceResourceDefinition.CM_TABLE_IMMEDIATE_CLEANUP.resolveModelAttribute(context, model).asBoolean();
ROOT_LOGGER.debugf("adding commit-markable-resource: jndi-name=%s, table-name=%s, batch-size=%d, immediate-cleanup=%b", jndiName, tableName, batchSize, immediateCleanup);
CMResourceService service = new CMResourceService(jndiName, tableName, immediateCleanup, batchSize);
context.getServiceTarget().addService(TxnServices.JBOSS_TXN_CMR.append(jndiName), service)
.addDependency(TxnServices.JBOSS_TXN_JTA_ENVIRONMENT, JTAEnvironmentBean.class, service.getJTAEnvironmentBeanInjector())
.setInitialMode(ServiceController.Mode.ACTIVE)
.install();
}
}
| 4,064
| 46.823529
| 178
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/TransactionSubsystem60Parser.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
*/
package org.jboss.as.txn.subsystem;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLExtendedStreamReader;
import javax.xml.stream.XMLStreamException;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import static org.jboss.as.controller.parsing.ParseUtils.*;
/**
* The {@link org.jboss.staxmapper.XMLElementReader} that handles the version 6.0 of Transaction subsystem xml.
*
* @author <a href="mailto:tadamski@redhat.com">Tomasz Adamski</a>
*/
class TransactionSubsystem60Parser extends TransactionSubsystem50Parser {
TransactionSubsystem60Parser() {
super(Namespace.TRANSACTIONS_6_0);
}
TransactionSubsystem60Parser(Namespace namespace) {
super(namespace);
}
@Override
protected void readElement(final XMLExtendedStreamReader reader, final Element element, final List<ModelNode> operations, final ModelNode subsystemOperation, final ModelNode logStoreOperation) throws XMLStreamException {
switch (element) {
case RECOVERY_ENVIRONMENT: {
parseRecoveryEnvironmentElement(reader, subsystemOperation);
break;
}
case CORE_ENVIRONMENT: {
parseCoreEnvironmentElement(reader, subsystemOperation);
break;
}
case COORDINATOR_ENVIRONMENT: {
parseCoordinatorEnvironmentElement(reader, subsystemOperation);
break;
}
case OBJECT_STORE: {
parseObjectStoreEnvironmentElementAndEnrichOperation(reader, subsystemOperation);
break;
}
case JTS: {
parseJts(reader, subsystemOperation);
break;
}
case USE_JOURNAL_STORE: {
if (choiceObjectStoreEncountered) {
throw unexpectedElement(reader);
}
choiceObjectStoreEncountered = true;
parseUseJournalstore(reader, logStoreOperation, subsystemOperation);
subsystemOperation.get(CommonAttributes.USE_JOURNAL_STORE).set(true);
break;
}
case JDBC_STORE: {
if (choiceObjectStoreEncountered) {
throw unexpectedElement(reader);
}
choiceObjectStoreEncountered = true;
parseJdbcStoreElementAndEnrichOperation(reader, logStoreOperation, subsystemOperation);
subsystemOperation.get(CommonAttributes.USE_JDBC_STORE).set(true);
break;
}
case CM_RESOURCES:
parseCMs(reader, operations);
break;
case CLIENT:
parseClient(reader, subsystemOperation);
break;
default: {
throw unexpectedElement(reader);
}
}
}
protected void parseClient(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
Set<Attribute> required = EnumSet.of(Attribute.STALE_TRANSACTION_TIME);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case STALE_TRANSACTION_TIME:
TransactionSubsystemRootResourceDefinition.STALE_TRANSACTION_TIME.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
// Handle elements
requireNoContent(reader);
}
}
| 5,014
| 36.992424
| 224
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/TransactionSubsystem11Parser.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.parsing.ParseUtils.duplicateNamedElement;
import static org.jboss.as.controller.parsing.ParseUtils.missingOneOf;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequired;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequiredElement;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoContent;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoNamespaceAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.txn.logging.TransactionLogger;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
*/
class TransactionSubsystem11Parser implements XMLStreamConstants, XMLElementReader<List<ModelNode>> {
TransactionSubsystem11Parser() {
}
/**
* {@inheritDoc}
*/
@Override
public void readElement(XMLExtendedStreamReader reader, List<ModelNode> list) throws XMLStreamException {
// no attributes
if (reader.getAttributeCount() > 0) {
throw unexpectedAttribute(reader, 0);
}
final ModelNode address = new ModelNode();
address.add(ModelDescriptionConstants.SUBSYSTEM, TransactionExtension.SUBSYSTEM_NAME);
address.protect();
final ModelNode subsystem = new ModelNode();
subsystem.get(OP).set(ADD);
subsystem.get(OP_ADDR).set(address);
list.add(subsystem);
// elements
final EnumSet<Element> required = EnumSet.of(Element.RECOVERY_ENVIRONMENT, Element.CORE_ENVIRONMENT);
final EnumSet<Element> encountered = EnumSet.noneOf(Element.class);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
switch (Namespace.forUri(reader.getNamespaceURI())) {
case TRANSACTIONS_1_1: {
final Element element = Element.forName(reader.getLocalName());
required.remove(element);
if (!encountered.add(element)) {
throw unexpectedElement(reader);
}
switch (element) {
case RECOVERY_ENVIRONMENT: {
parseRecoveryEnvironmentElement(reader, subsystem);
break;
}
case CORE_ENVIRONMENT: {
parseCoreEnvironmentElement(reader, subsystem);
break;
}
case COORDINATOR_ENVIRONMENT: {
parseCoordinatorEnvironmentElement(reader, subsystem);
break;
}
case OBJECT_STORE: {
parseObjectStoreEnvironmentElementAndEnrichOperation(reader, subsystem);
break;
}
case JTS: {
parseJts(reader, subsystem);
break;
}
default: {
throw unexpectedElement(reader);
}
}
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
if (!required.isEmpty()) {
throw missingRequiredElement(reader, required);
}
final ModelNode logStoreAddress = address.clone();
final ModelNode operation = new ModelNode();
operation.get(OP).set(ADD);
logStoreAddress.add(LogStoreConstants.LOG_STORE, LogStoreConstants.LOG_STORE);
logStoreAddress.protect();
operation.get(OP_ADDR).set(logStoreAddress);
list.add(operation);
}
private void parseJts(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
// no attributes
if (reader.getAttributeCount() > 0) {
throw unexpectedAttribute(reader, 0);
}
operation.get(CommonAttributes.JTS).set(true);
requireNoContent(reader);
}
static void parseObjectStoreEnvironmentElementAndEnrichOperation(final XMLExtendedStreamReader reader, ModelNode operation) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case RELATIVE_TO:
TransactionSubsystemRootResourceDefinition.OBJECT_STORE_RELATIVE_TO.parseAndSetParameter(value, operation, reader);
break;
case PATH:
TransactionSubsystemRootResourceDefinition.OBJECT_STORE_PATH.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
// Handle elements
requireNoContent(reader);
}
static void parseCoordinatorEnvironmentElement(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case ENABLE_STATISTICS:
TransactionSubsystemRootResourceDefinition.ENABLE_STATISTICS.parseAndSetParameter(value, operation, reader);
break;
case ENABLE_TSM_STATUS:
TransactionSubsystemRootResourceDefinition.ENABLE_TSM_STATUS.parseAndSetParameter(value, operation, reader);
break;
case DEFAULT_TIMEOUT:
TransactionSubsystemRootResourceDefinition.DEFAULT_TIMEOUT.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
// Handle elements
requireNoContent(reader);
}
/**
* Handle the core-environment element and children
*
* @param reader the stream reader
* @param operation ModelNode for the core-environment add operation
* @throws XMLStreamException
*
*/
static void parseCoreEnvironmentElement(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NODE_IDENTIFIER:
TransactionSubsystemRootResourceDefinition.NODE_IDENTIFIER.parseAndSetParameter(value, operation, reader);
break;
case PATH:
case RELATIVE_TO:
throw TransactionLogger.ROOT_LOGGER.unsupportedAttribute(attribute.getLocalName(), reader.getLocation());
default:
throw unexpectedAttribute(reader, i);
}
}
// elements
final EnumSet<Element> required = EnumSet.of(Element.PROCESS_ID);
final EnumSet<Element> encountered = EnumSet.noneOf(Element.class);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
required.remove(element);
switch (element) {
case PROCESS_ID: {
if (!encountered.add(element)) {
throw duplicateNamedElement(reader, reader.getLocalName());
}
parseProcessIdEnvironmentElement(reader, operation);
break;
}
default:
throw unexpectedElement(reader);
}
}
if (!required.isEmpty()) {
throw missingRequiredElement(reader, required);
}
}
/**
* Handle the process-id child elements
*
* @param reader the stream reader
* @param coreEnvironmentAdd the add operation model node
*
* @throws XMLStreamException
*
*/
static void parseProcessIdEnvironmentElement(XMLExtendedStreamReader reader, ModelNode coreEnvironmentAdd) throws XMLStreamException {
// no attributes
if (reader.getAttributeCount() > 0) {
throw unexpectedAttribute(reader, 0);
}
// elements
boolean encountered = false;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case UUID:
if (encountered) {
throw unexpectedElement(reader);
}
encountered = true;
if (reader.getAttributeCount() > 0) {
throw unexpectedAttribute(reader, 0);
}
coreEnvironmentAdd.get(TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.getName()).set(true);
requireNoContent(reader);
break;
case SOCKET: {
if (encountered) {
throw unexpectedElement(reader);
}
encountered = true;
parseSocketProcessIdElement(reader, coreEnvironmentAdd);
break;
}
default:
throw unexpectedElement(reader);
}
}
if (!encountered) {
throw missingOneOf(reader, EnumSet.of(Element.UUID, Element.SOCKET));
}
}
static void parseSocketProcessIdElement(XMLExtendedStreamReader reader, ModelNode coreEnvironmentAdd) throws XMLStreamException {
final int count = reader.getAttributeCount();
final EnumSet<Attribute> required = EnumSet.of(Attribute.BINDING);
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case BINDING:
TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING.parseAndSetParameter(value, coreEnvironmentAdd, reader);
break;
case SOCKET_PROCESS_ID_MAX_PORTS:
TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_MAX_PORTS.parseAndSetParameter(value, coreEnvironmentAdd, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
// Handle elements
requireNoContent(reader);
}
static void parseRecoveryEnvironmentElement(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
Set<Attribute> required = EnumSet.of(Attribute.BINDING, Attribute.STATUS_BINDING);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case BINDING:
TransactionSubsystemRootResourceDefinition.BINDING.parseAndSetParameter(value, operation, reader);
break;
case STATUS_BINDING:
TransactionSubsystemRootResourceDefinition.STATUS_BINDING.parseAndSetParameter(value, operation, reader);
break;
case RECOVERY_LISTENER:
TransactionSubsystemRootResourceDefinition.RECOVERY_LISTENER.parseAndSetParameter(value, operation, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
// Handle elements
requireNoContent(reader);
}
}
| 14,793
| 41.148148
| 155
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/TxStatsHandler.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
import static org.jboss.as.controller.client.helpers.MeasurementUnit.NANOSECONDS;
import static org.jboss.as.controller.registry.AttributeAccess.Flag.COUNTER_METRIC;
import static org.jboss.as.controller.registry.AttributeAccess.Flag.GAUGE_METRIC;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import com.arjuna.ats.arjuna.coordinator.TxStats;
import org.jboss.as.controller.AbstractRuntimeOnlyHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.txn.logging.TransactionLogger;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
/**
* Handler for transaction manager metrics
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class TxStatsHandler extends AbstractRuntimeOnlyHandler {
public enum TxStat {
NUMBER_OF_TRANSACTIONS(SimpleAttributeDefinitionBuilder.create(CommonAttributes.NUMBER_OF_TRANSACTIONS, ModelType.LONG, true)
.setAttributeGroup(CommonAttributes.STATISTICS)
.setFlags(COUNTER_METRIC).build()),
NUMBER_OF_NESTED_TRANSACTIONS(SimpleAttributeDefinitionBuilder.create(CommonAttributes.NUMBER_OF_NESTED_TRANSACTIONS, ModelType.LONG, true)
.setAttributeGroup(CommonAttributes.STATISTICS)
.setFlags(COUNTER_METRIC).build()),
NUMBER_OF_HEURISTICS(SimpleAttributeDefinitionBuilder.create(CommonAttributes.NUMBER_OF_HEURISTICS, ModelType.LONG, true)
.setAttributeGroup(CommonAttributes.STATISTICS)
.setFlags(COUNTER_METRIC).build()),
NUMBER_OF_COMMITTED_TRANSACTIONS(SimpleAttributeDefinitionBuilder.create(CommonAttributes.NUMBER_OF_COMMITTED_TRANSACTIONS, ModelType.LONG, true)
.setAttributeGroup(CommonAttributes.STATISTICS)
.setFlags(COUNTER_METRIC).build()),
NUMBER_OF_ABORTED_TRANSACTIONS(SimpleAttributeDefinitionBuilder.create(CommonAttributes.NUMBER_OF_ABORTED_TRANSACTIONS, ModelType.LONG, true)
.setAttributeGroup(CommonAttributes.STATISTICS)
.setFlags(COUNTER_METRIC).build()),
NUMBER_OF_INFLIGHT_TRANSACTIONS(SimpleAttributeDefinitionBuilder.create(CommonAttributes.NUMBER_OF_INFLIGHT_TRANSACTIONS, ModelType.LONG, true)
.setAttributeGroup(CommonAttributes.STATISTICS)
.setFlags(GAUGE_METRIC).build()),
NUMBER_OF_TIMED_OUT_TRANSACTIONS(SimpleAttributeDefinitionBuilder.create(CommonAttributes.NUMBER_OF_TIMED_OUT_TRANSACTIONS, ModelType.LONG, true)
.setAttributeGroup(CommonAttributes.STATISTICS)
.setFlags(COUNTER_METRIC).build()),
NUMBER_OF_APPLICATION_ROLLBACKS(SimpleAttributeDefinitionBuilder.create(CommonAttributes.NUMBER_OF_APPLICATION_ROLLBACKS, ModelType.LONG, true)
.setAttributeGroup(CommonAttributes.STATISTICS)
.setFlags(COUNTER_METRIC).build()),
NUMBER_OF_RESOURCE_ROLLBACKS(SimpleAttributeDefinitionBuilder.create(CommonAttributes.NUMBER_OF_RESOURCE_ROLLBACKS, ModelType.LONG, true)
.setAttributeGroup(CommonAttributes.STATISTICS)
.setFlags(COUNTER_METRIC).build()),
NUMBER_OF_SYSTEM_ROLLBACKS(SimpleAttributeDefinitionBuilder.create(CommonAttributes.NUMBER_OF_SYSTEM_ROLLBACKS, ModelType.LONG, true)
.setAttributeGroup(CommonAttributes.STATISTICS)
.setFlags(COUNTER_METRIC).build()),
AVERAGE_COMMIT_TIME(SimpleAttributeDefinitionBuilder.create(CommonAttributes.AVERAGE_COMMIT_TIME, ModelType.LONG, true)
.setAttributeGroup(CommonAttributes.STATISTICS)
.setMeasurementUnit(NANOSECONDS)
.build());
private static final Map<String, TxStat> MAP = new HashMap<String, TxStat>();
static {
for (TxStat stat : EnumSet.allOf(TxStat.class)) {
MAP.put(stat.toString(), stat);
}
}
final AttributeDefinition definition;
private TxStat(final AttributeDefinition definition) {
this.definition = definition;
}
@Override
public final String toString() {
return definition.getName();
}
public static synchronized TxStat getStat(final String stringForm) {
return MAP.get(stringForm);
}
}
public static final TxStatsHandler INSTANCE = new TxStatsHandler();
private final TxStats txStats = TxStats.getInstance();
private TxStatsHandler() {
}
@Override
protected void executeRuntimeStep(OperationContext context, ModelNode operation) throws OperationFailedException {
TxStat stat = TxStat.getStat(operation.require(ModelDescriptionConstants.NAME).asString());
if (stat == null) {
context.getFailureDescription().set(TransactionLogger.ROOT_LOGGER.unknownMetric(operation.require(ModelDescriptionConstants.NAME).asString()));
}
else {
ModelNode result = new ModelNode();
switch (stat) {
case NUMBER_OF_TRANSACTIONS:
result.set(txStats.getNumberOfTransactions());
break;
case NUMBER_OF_NESTED_TRANSACTIONS:
result.set(txStats.getNumberOfNestedTransactions());
break;
case NUMBER_OF_HEURISTICS:
result.set(txStats.getNumberOfHeuristics());
break;
case NUMBER_OF_COMMITTED_TRANSACTIONS:
result.set(txStats.getNumberOfCommittedTransactions());
break;
case NUMBER_OF_ABORTED_TRANSACTIONS:
result.set(txStats.getNumberOfAbortedTransactions());
break;
case NUMBER_OF_INFLIGHT_TRANSACTIONS:
result.set(txStats.getNumberOfInflightTransactions());
break;
case NUMBER_OF_TIMED_OUT_TRANSACTIONS:
result.set(txStats.getNumberOfTimedOutTransactions());
break;
case NUMBER_OF_APPLICATION_ROLLBACKS:
result.set(txStats.getNumberOfApplicationRollbacks());
break;
case NUMBER_OF_RESOURCE_ROLLBACKS:
result.set(txStats.getNumberOfResourceRollbacks());
break;
case NUMBER_OF_SYSTEM_ROLLBACKS:
result.set(txStats.getNumberOfSystemRollbacks());
break;
case AVERAGE_COMMIT_TIME:
result.set(txStats.getAverageCommitTime());
break;
default:
throw new IllegalStateException(TransactionLogger.ROOT_LOGGER.unknownMetric(stat));
}
context.getResult().set(result);
}
}
void registerMetrics(final ManagementResourceRegistration resourceRegistration) {
for (TxStat stat : TxStat.values()) {
resourceRegistration.registerMetric(stat.definition, this);
}
}
}
| 8,460
| 47.907514
| 155
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/Namespace.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
import java.util.HashMap;
import java.util.Map;
/**
* The namespaces supported by the transactions extension.
*
* @author John E. Bailey
*/
enum Namespace {
// must be first
UNKNOWN(null),
TRANSACTIONS_1_0("urn:jboss:domain:transactions:1.0"),
TRANSACTIONS_1_1("urn:jboss:domain:transactions:1.1"),
TRANSACTIONS_1_2("urn:jboss:domain:transactions:1.2"),
TRANSACTIONS_1_3("urn:jboss:domain:transactions:1.3"),
TRANSACTIONS_1_4("urn:jboss:domain:transactions:1.4"),
TRANSACTIONS_1_5("urn:jboss:domain:transactions:1.5"),
TRANSACTIONS_2_0("urn:jboss:domain:transactions:2.0"),
TRANSACTIONS_3_0("urn:jboss:domain:transactions:3.0"),
TRANSACTIONS_4_0("urn:jboss:domain:transactions:4.0"),
TRANSACTIONS_5_0("urn:jboss:domain:transactions:5.0"),
TRANSACTIONS_6_0("urn:jboss:domain:transactions:6.0"),
;
/**
* The current namespace version.
*/
public static final Namespace CURRENT = TRANSACTIONS_6_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;
}
private static final Map<String, Namespace> MAP;
static {
final Map<String, Namespace> map = new HashMap<String, Namespace>();
for (Namespace namespace : values()) {
final String name = namespace.getUriString();
if (name != null) map.put(name, namespace);
}
MAP = map;
}
public static Namespace forUri(String uri) {
final Namespace element = MAP.get(uri);
return element == null ? UNKNOWN : element;
}
}
| 2,782
| 31.360465
| 76
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/LogStoreProbeHandler.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
import javax.management.AttributeList;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.JMException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Handler for exposing transaction logs
*
* @author <a href="stefano.maestri@redhat.com">Stefano Maestri</a> (c) 2011 Red Hat Inc.
* @author <a href="mmusgrove@redhat.com">Mike Musgrove</a> (c) 2012 Red Hat Inc.
*/
public class LogStoreProbeHandler implements OperationStepHandler {
static final LogStoreProbeHandler INSTANCE = new LogStoreProbeHandler();
static final String osMBeanName = "jboss.jta:type=ObjectStore";
static final String JNDI_PROPNAME =
LogStoreConstants.MODEL_TO_JMX_PARTICIPANT_NAMES.get(LogStoreConstants.JNDI_ATTRIBUTE);
private Map<String, String> getMBeanValues(MBeanServerConnection cnx, ObjectName on, String ... attributeNames)
throws InstanceNotFoundException, IOException, ReflectionException, IntrospectionException {
if (attributeNames == null) {
MBeanInfo info = cnx.getMBeanInfo( on );
MBeanAttributeInfo[] attributeArray = info.getAttributes();
int i = 0;
attributeNames = new String[attributeArray.length];
for (MBeanAttributeInfo ai : attributeArray)
attributeNames[i++] = ai.getName();
}
AttributeList attributes = cnx.getAttributes(on, attributeNames);
Map<String, String> values = new HashMap<String, String>();
for (javax.management.Attribute attribute : attributes.asList()) {
Object value = attribute.getValue();
values.put(attribute.getName(), value == null ? "" : value.toString());
}
return values;
}
private void addAttributes(ModelNode node, Map<String, String> model2JmxNames, Map<String, String> attributes) {
for (Map.Entry<String, String> e : model2JmxNames.entrySet()) {
String attributeValue = attributes.get(e.getValue());
if (attributeValue != null)
node.get(e.getKey()).set(attributeValue);
}
}
private void addParticipants(final Resource parent, Set<ObjectInstance> participants, MBeanServer mbs)
throws IntrospectionException, InstanceNotFoundException, IOException, ReflectionException {
int i = 1;
for (ObjectInstance participant : participants) {
final Resource resource = new LogStoreResource.LogStoreRuntimeResource(participant.getObjectName());
final ModelNode model = resource.getModel();
Map<String, String> pAttributes = getMBeanValues(mbs, participant.getObjectName(),
LogStoreConstants.PARTICIPANT_JMX_NAMES);
String pAddress = pAttributes.get(JNDI_PROPNAME);
if (pAddress == null || pAddress.length() == 0) {
pAttributes.put(JNDI_PROPNAME, String.valueOf(i++));
pAddress = pAttributes.get(JNDI_PROPNAME);
}
addAttributes(model, LogStoreConstants.MODEL_TO_JMX_PARTICIPANT_NAMES, pAttributes);
// model.get(LogStoreConstants.JMX_ON_ATTRIBUTE).set(participant.getObjectName().getCanonicalName());
final PathElement element = PathElement.pathElement(LogStoreConstants.PARTICIPANTS, pAddress);
parent.registerChild(element, resource);
}
}
private void addTransactions(final Resource parent, Set<ObjectInstance> transactions, MBeanServer mbs)
throws IntrospectionException, InstanceNotFoundException, IOException,
ReflectionException, MalformedObjectNameException {
for (ObjectInstance oi : transactions) {
String transactionId = oi.getObjectName().getCanonicalName();
if (!transactionId.contains("puid") && transactionId.contains("itype")) {
final Resource transaction = new LogStoreResource.LogStoreRuntimeResource(oi.getObjectName());
final ModelNode model = transaction.getModel();
Map<String, String> tAttributes = getMBeanValues(
mbs, oi.getObjectName(), LogStoreConstants.TXN_JMX_NAMES);
String txnId = tAttributes.get("Id");
addAttributes(model, LogStoreConstants.MODEL_TO_JMX_TXN_NAMES, tAttributes);
// model.get(LogStoreConstants.JMX_ON_ATTRIBUTE).set(transactionId);
String participantQuery = transactionId + ",puid=*";
Set<ObjectInstance> participants = mbs.queryMBeans(new ObjectName(participantQuery), null);
addParticipants(transaction, participants, mbs);
final PathElement element = PathElement.pathElement(LogStoreConstants.TRANSACTIONS, txnId);
parent.registerChild(element, transaction);
}
}
}
private Resource probeTransactions(MBeanServer mbs, boolean exposeAllLogs)
throws OperationFailedException {
try {
ObjectName on = new ObjectName(osMBeanName);
mbs.setAttribute(on, new javax.management.Attribute("ExposeAllRecordsAsMBeans", Boolean.valueOf(exposeAllLogs)));
mbs.invoke(on, "probe", null, null);
Set<ObjectInstance> transactions = mbs.queryMBeans(new ObjectName(osMBeanName + ",*"), null);
final Resource resource = Resource.Factory.create();
addTransactions(resource, transactions, mbs);
return resource;
} catch (JMException e) {
throw new OperationFailedException("Transaction discovery error: ", e);
} catch (IOException e) {
throw new OperationFailedException("Transaction discovery error: ", e);
}
}
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
if(! context.isNormalServer()) {
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
return;
}
final MBeanServer mbs = TransactionExtension.getMBeanServer(context);
if (mbs != null) {
// Get the log-store resource
final Resource resource = context.readResource(PathAddress.EMPTY_ADDRESS);
assert resource instanceof LogStoreResource;
final LogStoreResource logStore = (LogStoreResource) resource;
// Get the expose-all-logs parameter value
final ModelNode subModel = context.readResource(PathAddress.EMPTY_ADDRESS).getModel();
final boolean exposeAllLogs = LogStoreConstants.EXPOSE_ALL_LOGS.resolveModelAttribute(context, subModel).asBoolean();
final Resource storeModel = probeTransactions(mbs, exposeAllLogs);
// Replace the current model with an updated one
context.acquireControllerLock();
// WFLY-3020 -- don't drop the root model
storeModel.writeModel(logStore.getModel());
logStore.update(storeModel);
}
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
}
| 8,928
| 44.324873
| 129
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/CMResourceResourceDefinition.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
import org.jboss.as.controller.AbstractRemoveStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.ReadResourceNameOperationStepHandler;
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.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.OperationEntry;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
/**
* Implementation of {@link org.jboss.as.controller.ResourceDefinition} for commit-markable-resource.
*
* @author Stefano Maestri (c) 2011 Red Hat Inc.
*/
public class CMResourceResourceDefinition extends SimpleResourceDefinition {
public static final PathElement PATH_CM_RESOURCE = PathElement.pathElement(CommonAttributes.CM_RESOURCE);
static SimpleAttributeDefinition JNDI_NAME = new SimpleAttributeDefinitionBuilder(CommonAttributes.CM_JNDI_NAME, ModelType.STRING)
.setRequired(true)
.setResourceOnly()
.build();
static SimpleAttributeDefinition CM_TABLE_BATCH_SIZE = new SimpleAttributeDefinitionBuilder(CommonAttributes.CM_BATCH_SIZE, ModelType.INT)
.setAllowExpression(true)
.setRequired(false)
.setDefaultValue(new ModelNode(CommonAttributes.CM_BATCH_SIZE_DEF_VAL))
.setXmlName(CommonAttributes.CM_BATCH_SIZE)
.build();
static SimpleAttributeDefinition CM_TABLE_IMMEDIATE_CLEANUP = new SimpleAttributeDefinitionBuilder(CommonAttributes.CM_IMMEDIATE_CLEANUP, ModelType.BOOLEAN)
.setAllowExpression(true)
.setRequired(false)
.setDefaultValue(new ModelNode(CommonAttributes.CM_IMMEDIATE_CLEANUP_DEF_VAL))
.setXmlName(CommonAttributes.CM_IMMEDIATE_CLEANUP)
.build();
static SimpleAttributeDefinition CM_TABLE_NAME = new SimpleAttributeDefinitionBuilder(CommonAttributes.CM_LOCATION_NAME, ModelType.STRING)
.setAllowExpression(true)
.setRequired(false)
.setDefaultValue(new ModelNode(CommonAttributes.CM_LOCATION_NAME_DEF_VAL))
.setXmlName(CommonAttributes.CM_LOCATION_NAME)
.build();
/**
* Default constructure.
* It set {@link CMResourceAdd} as add handler
* and {@link org.jboss.as.controller.ReloadRequiredRemoveStepHandler} as remove handler
*/
public CMResourceResourceDefinition() {
super(new Parameters(PATH_CM_RESOURCE,
TransactionExtension.getResourceDescriptionResolver(CommonAttributes.CM_RESOURCE))
.setAddHandler(CMResourceAdd.INSTANCE)
.setAddRestartLevel(OperationEntry.Flag.RESTART_JVM)
.setRemoveHandler(new AbstractRemoveStepHandler() { // TODO consider adding a RestartRequiredRemoveStepHandler to WildFly Core
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
context.restartRequired();
}
@Override
protected void recoverServices(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
context.revertRestartRequired();
}
})
.setRemoveRestartLevel(OperationEntry.Flag.RESTART_JVM)
);
}
/**
* {@inheritDoc}
*/
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
ReloadRequiredWriteAttributeHandler reloadWrtiteHandler = new ReloadRequiredWriteAttributeHandler(JNDI_NAME, CM_TABLE_NAME, CM_TABLE_BATCH_SIZE, CM_TABLE_IMMEDIATE_CLEANUP);
resourceRegistration.registerReadWriteAttribute(CM_TABLE_NAME, null, reloadWrtiteHandler);
resourceRegistration.registerReadWriteAttribute(CM_TABLE_BATCH_SIZE, null, reloadWrtiteHandler);
resourceRegistration.registerReadWriteAttribute(CM_TABLE_IMMEDIATE_CLEANUP, null, reloadWrtiteHandler);
//This comes from the address
resourceRegistration.registerReadOnlyAttribute(JNDI_NAME, ReadResourceNameOperationStepHandler.INSTANCE);
}
}
| 5,586
| 47.582609
| 181
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/subsystem/TransactionSubsystemRemove.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.subsystem;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.ReloadRequiredRemoveStepHandler;
/**
* Removes the transaction subsystem root resource.
*
* @author Brian Stansberry
*/
class TransactionSubsystemRemove extends ReloadRequiredRemoveStepHandler {
static final TransactionSubsystemRemove INSTANCE = new TransactionSubsystemRemove();
private TransactionSubsystemRemove() {
}
/**
* Suppresses removal of the log-store=log-store child, as that remove op handler is a no-op.
*/
@Override
protected boolean removeChildRecursively(PathElement child) {
return !TransactionExtension.LOG_STORE_PATH.equals(child);
}
}
| 1,746
| 35.395833
| 97
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/integration/JBossContextXATerminator.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.integration;
import jakarta.resource.spi.XATerminator;
import jakarta.resource.spi.work.Work;
import jakarta.resource.spi.work.WorkCompletedException;
import jakarta.transaction.InvalidTransactionException;
import jakarta.transaction.SystemException;
import javax.transaction.xa.XAException;
import javax.transaction.xa.Xid;
import org.jboss.as.txn.logging.TransactionLogger;
import org.jboss.tm.JBossXATerminator;
import org.wildfly.transaction.client.ContextTransactionManager;
import org.wildfly.transaction.client.ImportResult;
import org.wildfly.transaction.client.LocalTransaction;
import org.wildfly.transaction.client.LocalTransactionContext;
import com.arjuna.ats.internal.jta.transaction.arjunacore.jca.SubordinationManager;
public class JBossContextXATerminator implements JBossXATerminator {
private final LocalTransactionContext localTransactionContext;
private final XATerminator contextXATerminator;
private final JBossXATerminator jbossXATerminator;
public JBossContextXATerminator(LocalTransactionContext transactionContext, JBossXATerminator jbossXATerminator) {
this.localTransactionContext = transactionContext;
this.contextXATerminator = transactionContext.getXATerminator();
this.jbossXATerminator = jbossXATerminator;
}
@Override
public void commit(Xid xid, boolean onePhase) throws XAException {
contextXATerminator.commit(xid, onePhase);
}
@Override
public void forget(Xid xid) throws XAException {
contextXATerminator.forget(xid);
}
@Override
public int prepare(Xid xid) throws XAException {
return contextXATerminator.prepare(xid);
}
@Override
public Xid[] recover(int flag) throws XAException {
return contextXATerminator.recover(flag);
}
@Override
public void rollback(Xid xid) throws XAException {
contextXATerminator.rollback(xid);
}
/**
* <p>
* Interception of register work call to get transaction being imported to wildfly transacton client.
* <p>
* For importing a transaction Wildfly transaction client eventually calls {@link SubordinationManager}
* as Narayana {@link XATerminator}s do. This wrapping then let wildfly transacton client to register the transaction
* for itself, wildfly transacton client then import transaction to Narayana too and finally this method
* uses Narayana's {@link XATerminator} to register all {@link Work}s binding.<br>
* Narayana's {@link XATerminator} tries to import transaction too but as transaction is already
* imported it just gets instance of transaction already imported via call of wildfly transacton client.
*/
@Override
public void registerWork(Work work, Xid xid, long timeout) throws WorkCompletedException {
try {
// Jakarta Connectors provides timeout in milliseconds, SubordinationManager expects seconds
int timeout_seconds = (int) timeout/1000;
// unlimited timeout for Jakarta Connectors means -1 which fails in wfly client
if(timeout_seconds <= 0) timeout_seconds = ContextTransactionManager.getGlobalDefaultTransactionTimeout();
localTransactionContext.findOrImportTransaction(xid, timeout_seconds);
} catch (XAException xae) {
throw TransactionLogger.ROOT_LOGGER.cannotFindOrImportInflowTransaction(xid, work, xae);
}
jbossXATerminator.registerWork(work, xid, timeout);
}
/**
* <p>
* Start work gets imported transaction and assign it to current thread.
* <p>
* This method mimics behavior of Narayana's {@link JBossXATerminator}.
*/
@Override
public void startWork(Work work, Xid xid) throws WorkCompletedException {
LocalTransaction transaction = null;
try {
ImportResult<LocalTransaction> transactionImportResult = localTransactionContext.findOrImportTransaction(xid, 0);
transaction = transactionImportResult.getTransaction();
ContextTransactionManager.getInstance().resume(transaction);
} catch (XAException xae) {
throw TransactionLogger.ROOT_LOGGER.cannotFindOrImportInflowTransaction(xid, work, xae);
} catch (InvalidTransactionException ite) {
throw TransactionLogger.ROOT_LOGGER.importedInflowTransactionIsInactive(xid, work, ite);
} catch (SystemException se) {
throw TransactionLogger.ROOT_LOGGER.cannotResumeInflowTransactionUnexpectedError(transaction, work, se);
}
}
/**
* <p>
* Suspending transaction and canceling the work.
* <p>
* Suspend transaction has to be called on the wildfly transaction manager
* and the we delegate work cancellation to {@link JBossXATerminator}.<br>
* First we have to cancel the work for jboss terminator would not work with
* suspended transaction.
*/
@Override
public void endWork(Work work, Xid xid) {
jbossXATerminator.cancelWork(work, xid);
try {
ContextTransactionManager.getInstance().suspend();
} catch (SystemException se) {
throw TransactionLogger.ROOT_LOGGER.cannotSuspendInflowTransactionUnexpectedError(work, se);
}
}
/**
* <p>
* Calling {@link JBossXATerminator} to cancel the work for us.
* <p>
* There should not be need any action to be processed by wildfly transaction client.
*/
@Override
public void cancelWork(Work work, Xid xid) {
jbossXATerminator.cancelWork(work, xid);
}
}
| 6,649
| 40.5625
| 125
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/integration/LocalUserTransactionOperationsProvider.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2017, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.integration;
import org.jboss.tm.usertx.UserTransactionOperationsProvider;
import org.wildfly.transaction.client.LocalUserTransaction;
/**
* Implementation of user transaction operations provider bound to
* {@link LocalUserTransaction}.
*
* @author Ondra Chaloupka <ochaloup@redhat.com>
*/
public class LocalUserTransactionOperationsProvider implements UserTransactionOperationsProvider {
@Override
public boolean getAvailability() {
return LocalUserTransaction.getInstance().isAvailable();
}
@Override
public void setAvailability(boolean available) {
LocalUserTransaction.getInstance().setAvailability(available);
}
}
| 1,711
| 35.425532
| 98
|
java
|
null |
wildfly-main/transactions/src/main/java/org/jboss/as/txn/suspend/RecoverySuspendController.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.txn.suspend;
import com.arjuna.ats.jbossatx.jta.RecoveryManagerService;
import org.jboss.as.controller.ControlledProcessState;
import org.jboss.as.server.suspend.ServerActivity;
import org.jboss.as.server.suspend.ServerActivityCallback;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Listens for notifications from a {@code SuspendController} and a {@code ProcessStateNotifier} and reacts
* to them by {@link RecoveryManagerService#suspend() suspending} or {@link RecoveryManagerService#resume() resuming}
* the {@link RecoveryManagerService}.
*
* @author <a href="mailto:gytis@redhat.com">Gytis Trikleris</a>
*/
public class RecoverySuspendController implements ServerActivity, PropertyChangeListener {
private final RecoveryManagerService recoveryManagerService;
private boolean suspended;
private boolean running;
public RecoverySuspendController(RecoveryManagerService recoveryManagerService) {
this.recoveryManagerService = recoveryManagerService;
}
/**
* {@link RecoveryManagerService#suspend() Suspends} the {@link RecoveryManagerService}.
*/
@Override
public void preSuspend(ServerActivityCallback serverActivityCallback) {
synchronized (this) {
suspended = true;
}
recoveryManagerService.suspend();
serverActivityCallback.done();
}
@Override
public void suspended(ServerActivityCallback serverActivityCallback) {
serverActivityCallback.done();
}
/**
* {@link RecoveryManagerService#resume() Resumes} the {@link RecoveryManagerService} if the current
* process state {@link ControlledProcessState.State#isRunning() is running}. Otherwise records that
* the service can be resumed once a {@link #propertyChange(PropertyChangeEvent) notification is received} that
* the process state is running.
*/
@Override
public void resume() {
boolean doResume;
synchronized (this) {
suspended = false;
doResume = running;
}
if (doResume) {
resumeRecovery();
}
}
/**
* Receives notifications from a {@code ProcessStateNotifier} to detect when the process has reached a
* {@link ControlledProcessState.State#isRunning()} running state}, reacting to them by
* {@link RecoveryManagerService#resume() resuming} the {@link RecoveryManagerService} if we haven't been
* {@link #preSuspend(ServerActivityCallback) suspended}.
*/
@Override
public void propertyChange(PropertyChangeEvent evt) {
boolean doResume;
synchronized (this) {
ControlledProcessState.State newState = (ControlledProcessState.State) evt.getNewValue();
running = newState.isRunning();
doResume = running && !suspended;
}
if (doResume) {
resumeRecovery();
}
}
private void resumeRecovery() {
recoveryManagerService.resume();
}
}
| 4,067
| 36.321101
| 117
|
java
|
null |
wildfly-main/security/subsystem/src/test/java/org/jboss/as/security/SecurityDomainModelv1UnitTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.security;
import org.jboss.as.subsystem.test.AbstractSubsystemTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.as.subsystem.test.KernelServicesBuilder;
import org.jboss.dmr.ModelNode;
import org.junit.Test;
public class SecurityDomainModelv1UnitTestCase extends AbstractSubsystemTest {
public SecurityDomainModelv1UnitTestCase() {
super(SecurityExtension.SUBSYSTEM_NAME, new SecurityExtension());
}
@Test
public void testParseAndMarshalModel() throws Exception {
//Parse the subsystem xml and install into the first controller
String subsystemXml = readResource("securitysubsystemv1.xml");
KernelServices servicesA = createKernelServicesBuilder(AdditionalInitialization.MANAGEMENT)
.setSubsystemXml(subsystemXml)
.build();
//Get the model and the persisted xml from the first controller
ModelNode modelA = servicesA.readWholeModel();
String marshalled = servicesA.getPersistedSubsystemXml();
servicesA.shutdown();
//Install the persisted xml from the first controller into a second controller
KernelServices servicesB = createKernelServicesBuilder(AdditionalInitialization.MANAGEMENT)
.setSubsystemXml(marshalled)
.build();
ModelNode modelB = servicesB.readWholeModel();
//Make sure the models from the two controllers are identical
super.compare(modelA, modelB);
}
@Test
public void testParseAndMarshalModelWithJASPI() throws Exception {
//Parse the subsystem xml and install into the first controller
String subsystemXml = readResource("securitysubsystemJASPIv1.xml");
KernelServices servicesA = createKernelServicesBuilder(AdditionalInitialization.MANAGEMENT)
.setSubsystemXml(subsystemXml)
.build();
//Get the model and the persisted xml from the first controller
ModelNode modelA = servicesA.readWholeModel();
String marshalled = servicesA.getPersistedSubsystemXml();
servicesA.shutdown();
//Install the persisted xml from the first controller into a second controller
KernelServices servicesB = createKernelServicesBuilder(AdditionalInitialization.MANAGEMENT)
.setSubsystemXml(marshalled)
.build();
ModelNode modelB = servicesB.readWholeModel();
//Make sure the models from the two controllers are identical
super.compare(modelA, modelB);
assertRemoveSubsystemResources(servicesB);
}
@Override
protected KernelServicesBuilder createKernelServicesBuilder(AdditionalInitialization additionalInit) {
return super.createKernelServicesBuilder(AdditionalInitialization.ADMIN_ONLY_HC);
}
}
| 3,921
| 42.098901
| 106
|
java
|
null |
wildfly-main/security/subsystem/src/test/java/org/jboss/as/security/JSSEExpressionsUnitTestCase.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.security;
import java.io.IOException;
import java.util.List;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.dmr.Property;
import org.junit.Assert;
/**
* TODO class javadoc.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class JSSEExpressionsUnitTestCase extends AbstractSubsystemBaseTest {
public JSSEExpressionsUnitTestCase() {
super(SecurityExtension.SUBSYSTEM_NAME, new SecurityExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource("securityExpressions.xml");
}
@Override
protected void validateModel(ModelNode model) {
super.validateModel(model);
ModelNode jsse = model.get("subsystem", "security", "security-domain", "other", "jsse", "classic");
Assert.assertEquals(ModelType.OBJECT, jsse.getType());
Assert.assertEquals(ModelType.EXPRESSION, jsse.get(Constants.CLIENT_ALIAS).getType());
Assert.assertEquals(ModelType.EXPRESSION, jsse.get(Constants.SERVER_ALIAS).getType());
Assert.assertEquals(ModelType.EXPRESSION, jsse.get(Constants.SERVICE_AUTH_TOKEN).getType());
Assert.assertEquals(ModelType.EXPRESSION, jsse.get(Constants.CLIENT_AUTH).getType());
Assert.assertEquals(ModelType.EXPRESSION, jsse.get(Constants.PROTOCOLS).getType());
Assert.assertEquals(ModelType.EXPRESSION, jsse.get(Constants.CLIENT_ALIAS).getType());
ModelNode keystore = jsse.get(Constants.KEYSTORE);
Assert.assertEquals(ModelType.OBJECT, keystore.getType());
Assert.assertEquals(ModelType.EXPRESSION, keystore.get(Constants.PASSWORD).getType());
Assert.assertEquals(ModelType.EXPRESSION, keystore.get(Constants.TYPE).getType());
Assert.assertEquals(ModelType.EXPRESSION, keystore.get(Constants.URL).getType());
Assert.assertEquals(ModelType.EXPRESSION, keystore.get(Constants.PROVIDER).getType());
Assert.assertEquals(ModelType.EXPRESSION, keystore.get(Constants.PROVIDER_ARGUMENT).getType());
ModelNode truststore = jsse.get(Constants.TRUSTSTORE);
Assert.assertEquals(ModelType.OBJECT, truststore.getType());
Assert.assertEquals(ModelType.EXPRESSION, truststore.get(Constants.PASSWORD).getType());
Assert.assertEquals(ModelType.EXPRESSION, truststore.get(Constants.TYPE).getType());
Assert.assertEquals(ModelType.EXPRESSION, truststore.get(Constants.URL).getType());
Assert.assertEquals(ModelType.EXPRESSION, truststore.get(Constants.PROVIDER).getType());
Assert.assertEquals(ModelType.EXPRESSION, truststore.get(Constants.PROVIDER_ARGUMENT).getType());
ModelNode keyManager = jsse.get(Constants.KEY_MANAGER);
Assert.assertEquals(ModelType.OBJECT, keyManager.getType());
Assert.assertEquals(ModelType.EXPRESSION, keyManager.get(Constants.ALGORITHM).getType());
Assert.assertEquals(ModelType.EXPRESSION, keyManager.get(Constants.PROVIDER).getType());
ModelNode trustManager = jsse.get(Constants.TRUST_MANAGER);
Assert.assertEquals(ModelType.OBJECT, trustManager.getType());
Assert.assertEquals(ModelType.EXPRESSION, trustManager.get(Constants.ALGORITHM).getType());
Assert.assertEquals(ModelType.EXPRESSION, trustManager.get(Constants.PROVIDER).getType());
// check if the module-option values have been created as expression nodes.
ModelNode auth = model.get("subsystem", "security", "security-domain", "other", "authentication", "classic");
Assert.assertEquals(ModelType.OBJECT, auth.getType());
List<Property> loginModules = auth.get(Constants.LOGIN_MODULE).asPropertyList();
//Assert.assertEquals(ModelType.LIST, loginModules.getType());
ModelNode loginModule = loginModules.get(0).getValue();
Assert.assertEquals(ModelType.OBJECT, auth.getType());
for (Property prop : loginModule.get(Constants.MODULE_OPTIONS).asPropertyList()){
Assert.assertEquals(ModelType.EXPRESSION, prop.getValue().getType());
}
ModelNode domain = model.get("subsystem", "security", "security-domain", "jboss-empty-jsse", "jsse", "classic");
Assert.assertEquals(ModelType.OBJECT, domain.getType());
}
@Override
protected AdditionalInitialization createAdditionalInitialization() {
return AdditionalInitialization.ADMIN_ONLY_HC;
}
}
| 5,589
| 49.818182
| 120
|
java
|
null |
wildfly-main/security/subsystem/src/test/java/org/jboss/as/security/JSSEParsingUnitTestCase.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.security;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.jboss.as.controller.Extension;
import org.jboss.as.controller.ProcessType;
import org.jboss.as.controller.RunningMode;
import org.jboss.as.controller.RunningModeControl;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.extension.ExtensionRegistry;
import org.jboss.as.model.test.ModelTestParser;
import org.jboss.as.model.test.ModelTestUtils;
import org.jboss.as.subsystem.test.TestParser;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLMapper;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* TODO class javadoc.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class JSSEParsingUnitTestCase {
private static final ModelNode SUCCESS;
static {
SUCCESS = new ModelNode();
SUCCESS.get(ModelDescriptionConstants.OUTCOME).set(ModelDescriptionConstants.SUCCESS);
SUCCESS.get(ModelDescriptionConstants.RESULT);
SUCCESS.protect();
}
private ExtensionRegistry extensionParsingRegistry;
private ModelTestParser testParser;
private XMLMapper xmlMapper;
private final String TEST_NAMESPACE = "urn.org.jboss.test:1.0";
protected final String mainSubsystemName = SecurityExtension.SUBSYSTEM_NAME;
private final Extension mainExtension = new SecurityExtension();
@Before
public void initializeParser() throws Exception {
//Initialize the parser
xmlMapper = XMLMapper.Factory.create();
extensionParsingRegistry = new ExtensionRegistry(ProcessType.EMBEDDED_SERVER, new RunningModeControl(RunningMode.NORMAL), null, null, null, null);
testParser = new TestParser(mainSubsystemName, extensionParsingRegistry);
xmlMapper.registerRootElement(new QName(TEST_NAMESPACE, "test"), testParser);
mainExtension.initializeParsers(extensionParsingRegistry.getExtensionParsingContext("Test", xmlMapper));
}
@After
public void cleanup() throws Exception {
xmlMapper = null;
extensionParsingRegistry = null;
testParser = null;
}
/**
* Parse the subsystem xml and create the operations that will be passed into the controller
*
* @param subsystemXml the subsystem xml to be parsed
* @return the created operations
* @throws XMLStreamException if there is a parsing problem
*/
List<ModelNode> parse(String subsystemXml) throws XMLStreamException, IOException {
String xml = "<test xmlns=\"" + TEST_NAMESPACE + "\">"
+ ModelTestUtils.readResource(getClass(), subsystemXml)
+ "</test>";
final XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(xml));
final List<ModelNode> operationList = new ArrayList<ModelNode>();
xmlMapper.parseDocument(operationList, reader);
return operationList;
}
@Test
public void testParseMissingPasswordJSSE() throws Exception {
try {
parse("securityErrorMissingPassword.xml");
Assert.fail("There should have been an error.");
} catch (XMLStreamException ex) {
Assert.assertTrue(ex.getMessage(), ex.getMessage().contains("WFLYSEC0023"));
}
}
@Test
public void testParseWrongJSSE() throws Exception {
try {
parse("securityParserError.xml");
Assert.fail("There should have been an error.");
} catch (XMLStreamException ex) {
Assert.assertTrue(ex.getMessage(), ex.getMessage().contains("WFLYSEC0023"));
}
}
@Test
public void testParseValidJSSE() throws Exception {
parse("securityParserValidJSSE.xml");
}
}
| 5,070
| 36.286765
| 154
|
java
|
null |
wildfly-main/security/subsystem/src/test/java/org/jboss/as/security/SecurityTransformersTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.security;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.ProcessType;
import org.jboss.as.controller.capability.registry.RuntimeCapabilityRegistry;
import org.jboss.as.controller.extension.ExtensionRegistry;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.model.test.FailedOperationTransformationConfig;
import org.jboss.as.model.test.ModelTestControllerVersion;
import org.jboss.as.model.test.ModelTestUtils;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.jboss.as.subsystem.test.AdditionalInitialization.ManagementAdditionalInitialization;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.as.subsystem.test.KernelServicesBuilder;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
/**
* @author Tomaz Cerar (c) 2017 Red Hat Inc.
*/
public class SecurityTransformersTestCase extends AbstractSubsystemBaseTest {
public SecurityTransformersTestCase() {
super(SecurityExtension.SUBSYSTEM_NAME, new SecurityExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource("securitysubsystemv20.xml");
}
@Override
protected AdditionalInitialization createAdditionalInitialization() {
String[] capabilities = new String[] {"org.wildfly.clustering.infinispan.cache-container.security",
"org.wildfly.clustering.infinispan.default-cache-configuration.security"};
return new ManagementAdditionalInitialization() {
@Override
protected ProcessType getProcessType() {
return ProcessType.HOST_CONTROLLER;
}
@Override
protected void initializeExtraSubystemsAndModel(ExtensionRegistry extensionRegistry, Resource rootResource, ManagementResourceRegistration rootRegistration, RuntimeCapabilityRegistry capabilityRegistry) {
super.initializeExtraSubystemsAndModel(extensionRegistry, rootResource, rootRegistration, capabilityRegistry);
registerCapabilities(capabilityRegistry, capabilities);
}
};
}
@Ignore("Figure out the set of deps needed by the legacy subsystem and add them")
@Test
public void testTransformersEAP74() throws Exception {
testTransformers(ModelTestControllerVersion.EAP_7_4_0);
}
private void testTransformers(ModelTestControllerVersion controllerVersion) throws Exception {
ModelVersion version = ModelVersion.create(2, 0, 0);
final String artifactId = "wildfly-security";
String mavenGav = String.format("%s:%s:%s", controllerVersion.getMavenGroupId(), artifactId, controllerVersion.getMavenGavVersion());
testTransformers(controllerVersion, version, mavenGav);
testReject(controllerVersion, version, mavenGav);
}
private void testReject(ModelTestControllerVersion controllerVersion, ModelVersion targetVersion, String mavenGAV) throws Exception {
KernelServicesBuilder builder = createKernelServicesBuilder(createAdditionalInitialization());
builder.createLegacyKernelServicesBuilder(null, controllerVersion, targetVersion)
.configureReverseControllerCheck(createAdditionalInitialization(), null)
//.skipReverseControllerCheck()
.addMavenResourceURL(mavenGAV)
.dontPersistXml();
KernelServices mainServices = builder.build();
Assert.assertTrue(mainServices.isSuccessfulBoot());
KernelServices legacyServices = mainServices.getLegacyServices(targetVersion);
Assert.assertTrue(legacyServices.isSuccessfulBoot());
Assert.assertNotNull(legacyServices);
// any elytron-related resources in the model should get rejected as those are not supported in model version 1.3.0.
PathAddress subsystemAddress = PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM, getMainSubsystemName()));
ModelTestUtils.checkFailedTransformedBootOperations(mainServices, targetVersion,
builder.parseXmlResource("security-transformers-reject_2.0.xml"),
new FailedOperationTransformationConfig()
.addFailedAttribute(PathAddress.pathAddress(subsystemAddress, PathElement.pathElement(Constants.ELYTRON_REALM)),
FailedOperationTransformationConfig.REJECTED_RESOURCE)
.addFailedAttribute(PathAddress.pathAddress(subsystemAddress, PathElement.pathElement(Constants.ELYTRON_KEY_STORE)),
FailedOperationTransformationConfig.REJECTED_RESOURCE)
.addFailedAttribute(PathAddress.pathAddress(subsystemAddress, PathElement.pathElement(Constants.ELYTRON_TRUST_STORE)),
FailedOperationTransformationConfig.REJECTED_RESOURCE)
.addFailedAttribute(PathAddress.pathAddress(subsystemAddress, PathElement.pathElement(Constants.ELYTRON_KEY_MANAGER)),
FailedOperationTransformationConfig.REJECTED_RESOURCE)
.addFailedAttribute(PathAddress.pathAddress(subsystemAddress, PathElement.pathElement(Constants.ELYTRON_TRUST_MANAGER)),
FailedOperationTransformationConfig.REJECTED_RESOURCE)
.addFailedAttribute(
PathAddress.pathAddress(subsystemAddress,
PathElement.pathElement(Constants.SECURITY_DOMAIN, "domain-with-custom-audit-provider"),
SecurityExtension.PATH_AUDIT_CLASSIC,
PathElement.pathElement(Constants.PROVIDER_MODULE,
"org.myorg.security.MyCustomLogAuditProvider")),
new FailedOperationTransformationConfig.NewAttributesConfig(Constants.MODULE))
.addFailedAttribute(PathAddress.pathAddress(subsystemAddress),
new FailedOperationTransformationConfig.NewAttributesConfig(Constants.INITIALIZE_JACC)));
legacyServices.shutdown();
mainServices.shutdown();
}
private void testTransformers(ModelTestControllerVersion controllerVersion, ModelVersion targetVersion, String mavenGAV) throws Exception {
//Boot up empty controllers with the resources needed for the ops coming from the xml to work
KernelServicesBuilder builder = createKernelServicesBuilder(createAdditionalInitialization())
.setSubsystemXmlResource("security-transformers_2.0.xml");
builder.createLegacyKernelServicesBuilder(null, controllerVersion, targetVersion)
.addMavenResourceURL(mavenGAV)
.configureReverseControllerCheck(createAdditionalInitialization(), null)
.dontPersistXml();
KernelServices mainServices = builder.build();
assertTrue(mainServices.isSuccessfulBoot());
assertTrue(mainServices.getLegacyServices(targetVersion).isSuccessfulBoot());
checkSubsystemModelTransformation(mainServices, targetVersion, null);
mainServices.shutdown();
}
@Override
public void testSchema() throws Exception {
}
}
| 8,763
| 51.166667
| 216
|
java
|
null |
wildfly-main/security/subsystem/src/test/java/org/jboss/as/security/SecurityDomainModelv11UnitTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.security;
import java.io.IOException;
import java.util.Properties;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.junit.Test;
public class SecurityDomainModelv11UnitTestCase extends AbstractSubsystemBaseTest {
public SecurityDomainModelv11UnitTestCase() {
super(SecurityExtension.SUBSYSTEM_NAME, new SecurityExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource("securitysubsystemv11.xml");
}
@Override
protected void compareXml(String configId, String original, String marshalled) throws Exception {
super.compareXml(configId, original, marshalled, true);
}
@Override
protected String getSubsystemXsdPath() throws Exception {
return "schema/jboss-as-security_1_1.xsd";
}
@Override
protected Properties getResolvedProperties() {
Properties p = new Properties();
p.setProperty("jboss.server.config.dir", "/some/path");
return p;
}
@Test
public void testParseAndMarshalModelWithJASPI() throws Exception {
super.standardSubsystemTest("securitysubsystemJASPIv11.xml", false);
}
@Override
protected AdditionalInitialization createAdditionalInitialization() {
return AdditionalInitialization.ADMIN_ONLY_HC;
}
}
| 2,447
| 33.971429
| 101
|
java
|
null |
wildfly-main/security/subsystem/src/test/java/org/jboss/as/security/SecurityDomainModelv20UnitTestCase.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.security;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.jboss.as.controller.ProcessType;
import org.jboss.as.controller.capability.registry.RuntimeCapabilityRegistry;
import org.jboss.as.controller.extension.ExtensionRegistry;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.jboss.as.subsystem.test.AdditionalInitialization.ManagementAdditionalInitialization;
import org.junit.AfterClass;
import org.junit.BeforeClass;
/**
* Security subsystem tests for the version 2.0 of the subsystem schema.
*
* @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a>
*/
public class SecurityDomainModelv20UnitTestCase extends AbstractSubsystemBaseTest {
public SecurityDomainModelv20UnitTestCase() {
super(SecurityExtension.SUBSYSTEM_NAME, new SecurityExtension());
}
private static String oldConfig;
@BeforeClass
public static void beforeClass() {
try {
File target = new File(SecurityDomainModelv20UnitTestCase.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParentFile();
File config = new File(target, "config");
config.mkdir();
oldConfig = System.setProperty("jboss.server.config.dir", config.getAbsolutePath());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@AfterClass
public static void afterClass() {
if (oldConfig != null) {
System.setProperty("jboss.server.config.dir", oldConfig);
} else {
System.clearProperty("jboss.server.config.dir");
}
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource("securitysubsystemv20.xml");
}
@Override
protected String getSubsystemXsdPath() throws Exception {
return "schema/wildfly-security_2_0.xsd";
}
@Override
protected Properties getResolvedProperties() {
Properties properties = new Properties();
properties.put("jboss.server.config.dir", System.getProperty("java.io.tmpdir"));
return properties;
}
@Override
protected AdditionalInitialization createAdditionalInitialization() {
String[] capabilities = new String[] { "org.wildfly.clustering.infinispan.default-cache-configuration.security" };
return new ManagementAdditionalInitialization() {
@Override
protected ProcessType getProcessType() {
return ProcessType.HOST_CONTROLLER;
}
@Override
protected void initializeExtraSubystemsAndModel(ExtensionRegistry extensionRegistry, Resource rootResource,
ManagementResourceRegistration rootRegistration, RuntimeCapabilityRegistry capabilityRegistry) {
super.initializeExtraSubystemsAndModel(extensionRegistry, rootResource, rootRegistration, capabilityRegistry);
registerCapabilities(capabilityRegistry, capabilities);
}
};
}
}
| 3,858
| 34.731481
| 153
|
java
|
null |
wildfly-main/security/subsystem/src/test/java/org/jboss/as/security/SecurityDomainModelv12UnitTestCase.java
|
/*
*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
* /
*/
package org.jboss.as.security;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.util.List;
import java.util.Properties;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.dmr.ModelNode;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* <p>
* Security subsystem tests for the version 1.2 of the subsystem schema.
* </p>
*/
public class SecurityDomainModelv12UnitTestCase extends AbstractSubsystemBaseTest {
private static String oldConfig;
private static final char[] KEYSTORE_PASSWORD = "changeit".toCharArray();
private static final char[] TRUSTSTORE_PASSWORD = "rmi+ssl".toCharArray();
private static final String WORKING_DIRECTORY_LOCATION = "./target/test-classes";
private static final String KEYSTORE_FILENAME = "clientcert.jks";
private static final String TRUSTSTORE_FILENAME = "keystore.jks";
private static final File KEY_STORE_FILE = new File(WORKING_DIRECTORY_LOCATION, KEYSTORE_FILENAME);
private static final File TRUST_STORE_FILE = new File(WORKING_DIRECTORY_LOCATION, TRUSTSTORE_FILENAME);
private static void createBlankKeyStores() throws Exception {
File workingDir = new File(WORKING_DIRECTORY_LOCATION);
if (workingDir.exists() == false) {
workingDir.mkdirs();
}
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null, null);
KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(null, null);
try (FileOutputStream fos = new FileOutputStream(KEY_STORE_FILE)){
keyStore.store(fos, KEYSTORE_PASSWORD);
}
try (FileOutputStream fos = new FileOutputStream(TRUST_STORE_FILE)){
trustStore.store(fos, TRUSTSTORE_PASSWORD);
}
}
private static void deleteKeyStoreFiles() {
File[] testFiles = {
KEY_STORE_FILE,
TRUST_STORE_FILE
};
for (File file : testFiles) {
if (file.exists()) {
file.delete();
}
}
}
@BeforeClass
public static void beforeClass() {
try {
createBlankKeyStores();
File target = new File(SecurityDomainModelv11UnitTestCase.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParentFile();
File config = new File(target, "config");
config.mkdir();
oldConfig = System.setProperty("jboss.server.config.dir", config.getAbsolutePath());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@AfterClass
public static void afterClass() {
deleteKeyStoreFiles();
if (oldConfig != null) {
System.setProperty("jboss.server.config.dir", oldConfig);
} else {
System.clearProperty("jboss.server.config.dir");
}
}
public SecurityDomainModelv12UnitTestCase() {
super(SecurityExtension.SUBSYSTEM_NAME, new SecurityExtension());
}
@Override
protected AdditionalInitialization createAdditionalInitialization() {
return AdditionalInitialization.ADMIN_ONLY_HC;
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource("securitysubsystemv12.xml");
}
@Override
protected String getSubsystemXsdPath() throws Exception {
return "schema/jboss-as-security_1_2.xsd";
}
@Override
protected void compareXml(String configId, String original, String marshalled) throws Exception {
super.compareXml(configId, original, marshalled, true);
}
@Override
protected Properties getResolvedProperties() {
Properties properties = new Properties();
properties.put("jboss.server.config.dir", System.getProperty("java.io.tmpdir"));
return properties;
}
@Test
public void testOrder() throws Exception {
KernelServices service = createKernelServicesBuilder(createAdditionalInitialization())
.setSubsystemXmlResource("securitysubsystemv12.xml")
.build();
PathAddress address = PathAddress.pathAddress().append("subsystem", "security").append("security-domain", "ordering");
address = address.append("authentication", "classic");
ModelNode writeOp = Util.createOperation("write-attribute", address);
writeOp.get("name").set("login-modules");
for (int i = 1; i <= 6; i++) {
ModelNode module = writeOp.get("value").add();
module.get("code").set("module-" + i);
module.get("flag").set("optional");
module.get("module-options");
}
service.executeOperation(writeOp);
ModelNode readOp = Util.createOperation("read-attribute", address);
readOp.get("name").set("login-modules");
ModelNode result = service.executeForResult(readOp);
List<ModelNode> modules = result.asList();
Assert.assertEquals("There should be exactly 6 modules but there are not", 6, modules.size());
for (int i = 1; i <= 6; i++) {
ModelNode module = modules.get(i - 1);
Assert.assertEquals(module.get("code").asString(), "module-" + i);
}
}
}
| 6,631
| 36.897143
| 153
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/JASPIMappingModuleDefinition.java
|
/*
*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
* /
*/
package org.jboss.as.security;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.operations.validation.EnumValidator;
import org.jboss.as.controller.operations.validation.StringLengthValidator;
import org.jboss.dmr.ModelType;
/**
* @author <a href="mailto:tomaz.cerar@redhat.com">Tomaz Cerar</a> (c) 2012 Red Hat Inc.
*/
class JASPIMappingModuleDefinition extends MappingModuleDefinition {
static final SimpleAttributeDefinition LOGIN_MODULE_STACK_REF = new SimpleAttributeDefinitionBuilder(Constants.LOGIN_MODULE_STACK_REF, ModelType.STRING)
.setRequired(false)
.setValidator(new StringLengthValidator(1, true))
.build();
private static final SimpleAttributeDefinition FLAG = new SimpleAttributeDefinitionBuilder(Constants.FLAG, ModelType.STRING)
.setRequired(false)
.setValidator(EnumValidator.create(ModuleFlag.class))
.setAllowExpression(true)
.build();
private static final AttributeDefinition[] ATTRIBUTES = {CODE, FLAG, LOGIN_MODULE_STACK_REF, MODULE_OPTIONS, LoginModuleResourceDefinition.MODULE};
JASPIMappingModuleDefinition() {
super(Constants.AUTH_MODULE);
}
@Override
public AttributeDefinition[] getAttributes() {
return ATTRIBUTES;
}
}
| 2,498
| 38.666667
| 156
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/Constants.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.security;
/**
* Attributes used by the security subsystem.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
public interface Constants {
String ACL = "acl";
String ACL_MODULE = "acl-module";
String ACL_MODULES = "acl-modules";
String ADDITIONAL_PROPERTIES = "additional-properties";
String ALGORITHM = "algorithm";
String AUDIT = "audit";
// String AUDIT_MANAGER_CLASS_NAME = "audit-manager-class-name";
String AUTH_MODULE = "auth-module";
String AUTH_MODULES = "auth-modules";
String AUTHENTICATION = "authentication";
// String AUTHENTICATION_JASPI = "authentication-jaspi";
// String AUTHENTICATION_MANAGER_CLASS_NAME = "authentication-manager-class-name";
String AUTHORIZATION = "authorization";
// String AUTHORIZATION_MANAGER_CLASS_NAME = "authorization-manager-class-name";
String CACHE_TYPE = "cache-type";
String CIPHER_SUITES = "cipher-suites";
String CLASSIC = "classic";
String CLIENT_ALIAS = "client-alias";
String CLIENT_AUTH = "client-auth";
String CODE = "code";
String DEEP_COPY_SUBJECT_MODE = "deep-copy-subject-mode";
// String DEFAULT_CALLBACK_HANDLER_CLASS_NAME = "default-callback-handler-class-name";
String EXTENDS = "extends";
String FLAG = "flag";
String IDENTITY_TRUST = "identity-trust";
// String IDENTITY_TRUST_MANAGER_CLASS_NAME = "identity-trust-manager-class-name";
String INITIALIZE_JACC = "initialize-jacc";
String JASPI = "jaspi";
String JSSE = "jsse";
String KEY_MANAGER = "key-manager";
// String KEY_MANAGER_FACTORY_ALGORITHM = "key-manager-factory-algorithm";
// String KEY_MANAGER_FACTORY_PROVIDER = "key-manager-factory-provider";
String KEYSTORE = "keystore";
String KEYSTORE_PASSWORD = "keystore-password";
// String KEYSTORE_PROVIDER = "keystore-provider";
// String KEYSTORE_PROVIDER_ARGUMENT = "keystore-provider-argument";
// String KEYSTORE_TYPE = "keystore-type";
// String KEYSTORE_URL = "keystore-url";
String LOGIN_MODULES = "login-modules";
String LOGIN_MODULE = "login-module";
String LOGIN_MODULE_STACK = "login-module-stack";
String LOGIN_MODULE_STACK_REF = "login-module-stack-ref";
String MAPPING = "mapping";
// String MAPPING_MANAGER_CLASS_NAME = "mapping-manager-class-name";
String MAPPING_MODULE = "mapping-module";
String MAPPING_MODULES = "mapping-modules";
String MODULE = "module";
String MODULE_OPTIONS = "module-options";
String NAME = "name";
String OPTIONAL = "optional";
String ORG_PICKETBOX = "org.picketbox";
String PASSWORD = "password";
String POLICY_MODULE = "policy-module";
String POLICY_MODULES = "policy-modules";
String PROTOCOLS = "protocols";
String PROPERTY= "property";
String PROVIDER = "provider";
String PROVIDER_ARGUMENT = "provider-argument";
String PROVIDER_MODULE = "provider-module";
String PROVIDER_MODULES = "provider-modules";
String REQUIRED = "required";
String REQUISITE = "requisite";
// String SECURITY_MANAGEMENT = "security-management";
String SECURITY_DOMAIN = "security-domain";
String SECURITY_PROPERTIES = "security-properties";
String SERVER_ALIAS = "server-alias";
String SERVICE_AUTH_TOKEN = "service-auth-token";
// String SUBJECT_FACTORY = "subject-factory";
// String SUBJECT_FACTORY_CLASS_NAME = "subject-factory-class-name";
String SUFFICIENT = "sufficient";
String TRUST_MANAGER = "trust-manager";
// String TRUST_MANAGER_FACTORY_ALGORITHM = "trust-manager-factory-algorithm";
// String TRUST_MANAGER_FACTORY_PROVIDER = "trust-manager-factory-provider";
String TRUST_MODULE = "trust-module";
String TRUST_MODULES = "trust-modules";
String TRUSTSTORE = "truststore";
// String TRUSTSTORE_PASSWORD = "truststore-password";
// String TRUSTSTORE_PROVIDER = "truststore-provider";
// String TRUSTSTORE_PROVIDER_ARGUMENT = "truststore-provider-argument";
// String TRUSTSTORE_TYPE = "truststore-type";
// String TRUSTSTORE_URL = "truststore-url";
String TYPE = "type";
String URL = "url";
String VALUE = "value";
String VAULT = "vault";
String VAULT_OPTION = "vault-option";
String VAULT_OPTIONS = "vault-options";
// String LIST_CACHED_PRINCIPALS = "list-cached-principals";
// String FLUSH_CACHE = "flush-cache";
// String PRINCIPAL_ARGUMENT = "principal";
// ELYTRON INTEGRATION CONSTANTS
String ELYTRON_INTEGRATION = "elytron-integration";
String SECURITY_REALMS = "security-realms";
String ELYTRON_REALM = "elytron-realm";
String LEGACY_JAAS_CONFIG = "legacy-jaas-config";
String TLS = "tls";
String ELYTRON_KEY_STORE = "elytron-key-store";
String ELYTRON_TRUST_STORE = "elytron-trust-store";
String ELYTRON_KEY_MANAGER = "elytron-key-manager";
String ELYTRON_TRUST_MANAGER = "elytron-trust-manager";
String LEGACY_JSSE_CONFIG = "legacy-jsse-config";
String APPLY_ROLE_MAPPERS = "apply-role-mappers";
String ELYTRON_SECURITY = "elytron-security";
}
| 6,134
| 44.110294
| 89
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/ClassicAuthenticationResourceDefinition.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.security;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.ModelOnlyRemoveStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
/**
* @author Jason T. Greene
*/
class ClassicAuthenticationResourceDefinition extends SimpleResourceDefinition {
public static final ClassicAuthenticationResourceDefinition INSTANCE = new ClassicAuthenticationResourceDefinition();
public static final LegacySupport.LoginModulesAttributeDefinition LOGIN_MODULES = new LegacySupport.LoginModulesAttributeDefinition(Constants.LOGIN_MODULES, Constants.LOGIN_MODULE);
private static final OperationStepHandler LEGACY_ADD_HANDLER = new LegacySupport.LegacyModulesConverter(Constants.LOGIN_MODULE, LOGIN_MODULES);
private ClassicAuthenticationResourceDefinition() {
super(SecurityExtension.PATH_CLASSIC_AUTHENTICATION,
SecurityExtension.getResourceDescriptionResolver(Constants.AUTHENTICATION + "." + Constants.CLASSIC),
new ClassicAuthenticationResourceDefinitionAdd(), ModelOnlyRemoveStepHandler.INSTANCE);
setDeprecated(SecurityExtension.DEPRECATED_SINCE);
}
@Override
public void registerAttributes(final ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerReadWriteAttribute(LOGIN_MODULES, new LegacySupport.LegacyModulesAttributeReader(Constants.LOGIN_MODULE), new LegacySupport.LegacyModulesAttributeWriter(Constants.LOGIN_MODULE));
}
@Override
public void registerChildren(ManagementResourceRegistration resourceRegistration) {
super.registerChildren(resourceRegistration);
resourceRegistration.registerSubModel(new LoginModuleResourceDefinition(Constants.LOGIN_MODULE));
}
static class ClassicAuthenticationResourceDefinitionAdd extends AbstractAddStepHandler {
@Override
protected void populateModel(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException {
if (operation.hasDefined(LOGIN_MODULES.getName())) {
context.addStep(new ModelNode(), operation, LEGACY_ADD_HANDLER, OperationContext.Stage.MODEL, true);
}
}
}
}
| 3,586
| 48.136986
| 215
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/Element.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.security;
import java.util.HashMap;
import java.util.Map;
/**
* Enum for the sub elements of the Security subsystem
*
* @author <a href="mailto:mmoyses@redhat.com">Marcus Moyses</a>
*/
enum Element {
// must be first
UNKNOWN(null),
ACL(Constants.ACL),
ACL_MODULE(Constants.ACL_MODULE),
ADDITIONAL_PROPERTIES(Constants.ADDITIONAL_PROPERTIES),
AUDIT(Constants.AUDIT),
AUTH_MODULE(Constants.AUTH_MODULE),
AUTHENTICATION("authentication"),
AUTHENTICATION_JASPI("authentication-jaspi"),
AUTHORIZATION("authorization"),
IDENTITY_TRUST("identity-trust"),
JSSE("jsse"),
LOGIN_MODULE("login-module"),
LOGIN_MODULE_STACK("login-module-stack"),
MAPPING("mapping"),
MAPPING_MODULE("mapping-module"),
MODULE_OPTION("module-option"),
POLICY_MODULE("policy-module"),
PROVIDER_MODULE("provider-module"),
PROPERTY("property"),
SECURITY_DOMAIN("security-domain"),
SECURITY_DOMAINS("security-domains"),
SECURITY_MANAGEMENT("security-management"),
SECURITY_PROPERTIES("security-properties"),
SUBJECT_FACTORY("subject-factory"),
TRUST_MODULE("trust-module"),
VAULT("vault"),
VAULT_OPTION("vault-option"),
// ELYTRON INTEGRATION ELEMENTS
ELYTRON_INTEGRATION(Constants.ELYTRON_INTEGRATION),
SECURITY_REALMS(Constants.SECURITY_REALMS),
ELYTRON_REALM(Constants.ELYTRON_REALM),
TLS(Constants.TLS),
ELYTRON_KEY_STORE(Constants.ELYTRON_KEY_STORE),
ELYTRON_TRUST_STORE(Constants.ELYTRON_TRUST_STORE),
ELYTRON_KEY_MANAGER(Constants.ELYTRON_KEY_MANAGER),
ELYTRON_TRUST_MANAGER(Constants.ELYTRON_TRUST_MANAGER);
private final String name;
Element(final String name) {
this.name = name;
}
/**
* Get the local name of this element.
*
* @return the local name
*/
public String getLocalName() {
return name;
}
private static final Map<String, Element> MAP;
static {
final Map<String, Element> map = new HashMap<String, Element>();
for (Element element : values()) {
final String name = element.getLocalName();
if (name != null)
map.put(name, element);
}
MAP = map;
}
public static Element forName(String localName) {
final Element element = MAP.get(localName);
return element == null ? UNKNOWN : element;
}
}
| 3,448
| 31.537736
| 72
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/MappingModuleDefinition.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.security;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.ModelOnlyAddStepHandler;
import org.jboss.as.controller.ModelOnlyRemoveStepHandler;
import org.jboss.as.controller.ModelOnlyWriteAttributeHandler;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.PropertiesAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.OperationEntry;
import org.jboss.dmr.ModelType;
/**
* @author <a href="mailto:tomaz.cerar@redhat.com">Tomaz Cerar</a> (c) 2012 Red Hat Inc.
*/
class MappingModuleDefinition extends SimpleResourceDefinition {
protected static final SimpleAttributeDefinition CODE = new SimpleAttributeDefinitionBuilder(ModelDescriptionConstants.CODE, ModelType.STRING)
.setRequired(true)
.build();
protected static final SimpleAttributeDefinition TYPE = new SimpleAttributeDefinitionBuilder(ModelDescriptionConstants.TYPE, ModelType.STRING)
.setRequired(true)
.setAllowExpression(true)
.build();
protected static final SimpleAttributeDefinition MODULE = LoginModuleResourceDefinition.MODULE;
protected static final PropertiesAttributeDefinition MODULE_OPTIONS = new PropertiesAttributeDefinition.Builder(Constants.MODULE_OPTIONS, true)
.setAllowExpression(true)
.build();
private static final AttributeDefinition[] ATTRIBUTES = {CODE, TYPE, MODULE, MODULE_OPTIONS};
MappingModuleDefinition(String key) {
super(PathElement.pathElement(key),
SecurityExtension.getResourceDescriptionResolver(Constants.MAPPING_MODULE),
null,
ModelOnlyRemoveStepHandler.INSTANCE
);
}
@Override
public void registerOperations(ManagementResourceRegistration resourceRegistration) {
super.registerOperations(resourceRegistration);
super.registerAddOperation(resourceRegistration, new ModelOnlyAddStepHandler(this.getAttributes()), OperationEntry.Flag.RESTART_NONE);
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
super.registerAttributes(resourceRegistration);
OperationStepHandler writeHandler = new ModelOnlyWriteAttributeHandler(getAttributes());
for (AttributeDefinition attr : getAttributes()) {
resourceRegistration.registerReadWriteAttribute(attr, null, writeHandler);
}
}
public AttributeDefinition[] getAttributes() {
return ATTRIBUTES;
}
}
| 3,979
| 42.736264
| 147
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/JASPIAuthenticationResourceDefinition.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.security;
import static org.jboss.as.security.Constants.AUTH_MODULE;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.ListAttributeDefinition;
import org.jboss.as.controller.ModelOnlyRemoveStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
/**
* @author Jason T. Greene
*/
class JASPIAuthenticationResourceDefinition extends SimpleResourceDefinition {
public static final JASPIAuthenticationResourceDefinition INSTANCE = new JASPIAuthenticationResourceDefinition();
public static final ListAttributeDefinition AUTH_MODULES = new LegacySupport.JASPIAuthenticationModulesAttributeDefinition();
private static final OperationStepHandler LEGACY_ADD_HANDLER = new LegacySupport.LegacyModulesConverter(Constants.AUTH_MODULE, AUTH_MODULES);
private JASPIAuthenticationResourceDefinition() {
super(SecurityExtension.PATH_JASPI_AUTH,
SecurityExtension.getResourceDescriptionResolver(Constants.AUTHENTICATION + "." + Constants.JASPI),
new JASPIAuthenticationResourceDefinitionAdd(), ModelOnlyRemoveStepHandler.INSTANCE);
setDeprecated(SecurityExtension.DEPRECATED_SINCE);
}
@Override
public void registerAttributes(final ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerReadWriteAttribute(AUTH_MODULES, new LegacySupport.LegacyModulesAttributeReader(Constants.AUTH_MODULE), new LegacySupport.LegacyModulesAttributeWriter(AUTH_MODULE));
}
@Override
public void registerChildren(ManagementResourceRegistration resourceRegistration) {
super.registerChildren(resourceRegistration);
resourceRegistration.registerSubModel(new JASPIMappingModuleDefinition());
resourceRegistration.registerSubModel(LoginModuleStackResourceDefinition.INSTANCE);
}
static class JASPIAuthenticationResourceDefinitionAdd extends AbstractAddStepHandler {
@Override
protected void populateModel(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException {
if (operation.hasDefined(AUTH_MODULES.getName())) {
context.addStep(new ModelNode(), operation, LEGACY_ADD_HANDLER, OperationContext.Stage.MODEL, true);
}
}
}
}
| 3,672
| 47.328947
| 202
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/SecuritySubsystemParser_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.jboss.as.security;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.parsing.ParseUtils.invalidAttributeValue;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequired;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoAttributes;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoContent;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoNamespaceAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
import static org.jboss.as.security.Constants.ELYTRON_KEY_MANAGER;
import static org.jboss.as.security.Constants.ELYTRON_KEY_STORE;
import static org.jboss.as.security.Constants.ELYTRON_REALM;
import static org.jboss.as.security.Constants.ELYTRON_TRUST_MANAGER;
import static org.jboss.as.security.Constants.ELYTRON_TRUST_STORE;
import static org.jboss.as.security.elytron.ElytronIntegrationResourceDefinitions.APPLY_ROLE_MAPPERS;
import static org.jboss.as.security.elytron.ElytronIntegrationResourceDefinitions.LEGACY_JAAS_CONFIG;
import static org.jboss.as.security.elytron.ElytronIntegrationResourceDefinitions.LEGACY_JSSE_CONFIG;
import java.util.EnumSet;
import java.util.List;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* This class implements a parser for the 2.0 version of legacy security subsystem. It extends the {@link SecuritySubsystemParser}
* and adds support for the {@code elytron-integration} section of the schema.
*
* @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a>
*/
class SecuritySubsystemParser_2_0 extends SecuritySubsystemParser {
protected SecuritySubsystemParser_2_0() {
}
@Override
protected void readElement(final XMLExtendedStreamReader reader, final Element element, final List<ModelNode> operations,
final PathAddress subsystemPath, final ModelNode subsystemNode) throws XMLStreamException {
switch(element) {
case ELYTRON_INTEGRATION: {
requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element innerElement = Element.forName(reader.getLocalName());
switch (innerElement) {
case SECURITY_REALMS: {
parseSecurityRealms(reader, operations, subsystemPath);
break;
}
case TLS: {
parseTLS(reader, operations, subsystemPath);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
break;
}
default: {
super.readElement(reader, element, operations, subsystemPath, subsystemNode);
}
}
}
protected void parseSecurityRealms(final XMLExtendedStreamReader reader, final List<ModelNode> operations,
final PathAddress subsystemPath) throws XMLStreamException {
requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case ELYTRON_REALM: {
parseElytronRealm(reader, operations, subsystemPath);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
protected void parseElytronRealm(final XMLExtendedStreamReader reader, final List<ModelNode> operations,
final PathAddress subsystemPath) throws XMLStreamException {
final ModelNode elytronRealmAddOperation = Util.createAddOperation();
PathElement elytronRealmPath = null;
final EnumSet<Attribute> required = EnumSet.of(Attribute.NAME, Attribute.LEGACY_JAAS_CONFIG);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME: {
if (value == null || value.length() == 0) {
throw invalidAttributeValue(reader, i);
}
elytronRealmPath = PathElement.pathElement(ELYTRON_REALM, value);
break;
}
case LEGACY_JAAS_CONFIG: {
LEGACY_JAAS_CONFIG.parseAndSetParameter(value, elytronRealmAddOperation, reader);
break;
}
case APPLY_ROLE_MAPPERS: {
APPLY_ROLE_MAPPERS.parseAndSetParameter(value, elytronRealmAddOperation, reader);
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
elytronRealmAddOperation.get(OP_ADDR).set(subsystemPath.append(elytronRealmPath).toModelNode());
operations.add(elytronRealmAddOperation);
requireNoContent(reader);
}
protected void parseTLS(final XMLExtendedStreamReader reader, final List<ModelNode> operations,
final PathAddress subsystemPath) throws XMLStreamException {
requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case ELYTRON_KEY_STORE: {
parseTLSEntity(reader, operations, subsystemPath, ELYTRON_KEY_STORE);
break;
}
case ELYTRON_TRUST_STORE: {
parseTLSEntity(reader, operations, subsystemPath, ELYTRON_TRUST_STORE);
break;
}
case ELYTRON_KEY_MANAGER: {
parseTLSEntity(reader, operations, subsystemPath, ELYTRON_KEY_MANAGER);
break;
}
case ELYTRON_TRUST_MANAGER: {
parseTLSEntity(reader, operations, subsystemPath, ELYTRON_TRUST_MANAGER);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
protected void parseTLSEntity(final XMLExtendedStreamReader reader, final List<ModelNode> operations,
final PathAddress subsystemPath, final String tlsEntityName) throws XMLStreamException {
final ModelNode elytronTLSEntityAddOperation = Util.createAddOperation();
PathElement elytronTLSEntityPath = null;
final EnumSet<Attribute> required = EnumSet.of(Attribute.NAME, Attribute.LEGACY_JSSE_CONFIG);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME: {
if (value == null || value.length() == 0) {
throw invalidAttributeValue(reader, i);
}
elytronTLSEntityPath = PathElement.pathElement(tlsEntityName, value);
break;
}
case LEGACY_JSSE_CONFIG: {
LEGACY_JSSE_CONFIG.parseAndSetParameter(value, elytronTLSEntityAddOperation, reader);
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
elytronTLSEntityAddOperation.get(OP_ADDR).set(subsystemPath.append(elytronTLSEntityPath).toModelNode());
operations.add(elytronTLSEntityAddOperation);
requireNoContent(reader);
}
}
| 9,559
| 43.0553
| 130
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/AuthorizationResourceDefinition.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.security;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.ListAttributeDefinition;
import org.jboss.as.controller.ModelOnlyRemoveStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
/**
* @author Jason T. Greene
*/
class AuthorizationResourceDefinition extends SimpleResourceDefinition {
public static final AuthorizationResourceDefinition INSTANCE = new AuthorizationResourceDefinition();
public static final ListAttributeDefinition POLICY_MODULES = new LegacySupport.LoginModulesAttributeDefinition(Constants.POLICY_MODULES, Constants.POLICY_MODULE);
private static final OperationStepHandler LEGACY_ADD_HANDLER = new LegacySupport.LegacyModulesConverter(Constants.POLICY_MODULE, POLICY_MODULES);
private AuthorizationResourceDefinition() {
super(SecurityExtension.PATH_AUTHORIZATION_CLASSIC,
SecurityExtension.getResourceDescriptionResolver(Constants.AUTHORIZATION),
new AuthorizationResourceDefinitionAdd(), ModelOnlyRemoveStepHandler.INSTANCE);
setDeprecated(SecurityExtension.DEPRECATED_SINCE);
}
@Override
public void registerAttributes(final ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerReadWriteAttribute(POLICY_MODULES, new LegacySupport.LegacyModulesAttributeReader(Constants.POLICY_MODULE), new LegacySupport.LegacyModulesAttributeWriter(Constants.POLICY_MODULE));
}
@Override
public void registerChildren(ManagementResourceRegistration resourceRegistration) {
super.registerChildren(resourceRegistration);
resourceRegistration.registerSubModel(new LoginModuleResourceDefinition(Constants.POLICY_MODULE));
}
static class AuthorizationResourceDefinitionAdd extends AbstractAddStepHandler {
@Override
protected void populateModel(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException {
if (operation.hasDefined(POLICY_MODULES.getName())) {
context.addStep(new ModelNode(), operation, LEGACY_ADD_HANDLER, OperationContext.Stage.MODEL, true);
}
}
}
}
| 3,554
| 47.040541
| 218
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/LoginModuleResourceDefinition.java
|
/*
*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
* /
*/
package org.jboss.as.security;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.ModelOnlyAddStepHandler;
import org.jboss.as.controller.ModelOnlyRemoveStepHandler;
import org.jboss.as.controller.ModelOnlyWriteAttributeHandler;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.PropertiesAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.operations.validation.EnumValidator;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelType;
/**
* @author <a href="mailto:tomaz.cerar@redhat.com">Tomaz Cerar</a> (c) 2012 Red Hat Inc.
*/
class LoginModuleResourceDefinition extends SimpleResourceDefinition {
static final SimpleAttributeDefinition CODE = new SimpleAttributeDefinitionBuilder(Constants.CODE, ModelType.STRING)
.setRequired(true)
.setMinSize(1)
.build();
static final SimpleAttributeDefinition FLAG = new SimpleAttributeDefinitionBuilder(Constants.FLAG, ModelType.STRING)
.setRequired(true)
.setAllowExpression(true)
.setValidator(EnumValidator.create(ModuleFlag.class))
.build();
static final SimpleAttributeDefinition MODULE = new SimpleAttributeDefinitionBuilder(Constants.MODULE, ModelType.STRING)
.setRequired(false)
.setAllowExpression(false)
.setMinSize(1)
.build();
static final PropertiesAttributeDefinition MODULE_OPTIONS = new PropertiesAttributeDefinition.Builder(Constants.MODULE_OPTIONS, true)
.setAllowExpression(true)
.build();
static final AttributeDefinition[] ATTRIBUTES = {CODE, FLAG, MODULE, MODULE_OPTIONS};
LoginModuleResourceDefinition(final String key) {
super(PathElement.pathElement(key),
SecurityExtension.getResourceDescriptionResolver(Constants.LOGIN_MODULE_STACK, Constants.LOGIN_MODULES),
new ModelOnlyAddStepHandler(ATTRIBUTES),
ModelOnlyRemoveStepHandler.INSTANCE
);
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
super.registerAttributes(resourceRegistration);
OperationStepHandler writeHandler = new ModelOnlyWriteAttributeHandler(ATTRIBUTES);
for (AttributeDefinition attribute : ATTRIBUTES) {
resourceRegistration.registerReadWriteAttribute(attribute, null, writeHandler);
}
}
}
| 3,773
| 43.928571
| 137
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/VaultResourceDefinition.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.security;
import org.jboss.as.controller.AbstractBoottimeAddStepHandler;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PropertiesAttributeDefinition;
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.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
/**
* @author Jason T. Greene
*/
class VaultResourceDefinition extends SimpleResourceDefinition {
public static final VaultResourceDefinition INSTANCE = new VaultResourceDefinition();
public static final SimpleAttributeDefinition CODE = new SimpleAttributeDefinitionBuilder(Constants.CODE, ModelType.STRING, true)
.build();
public static final PropertiesAttributeDefinition OPTIONS = new PropertiesAttributeDefinition.Builder(Constants.VAULT_OPTIONS, true)
.setXmlName(Constants.VAULT_OPTION)
.setAllowExpression(true)
.build();
private VaultResourceDefinition() {
super(SecurityExtension.VAULT_PATH,
SecurityExtension.getResourceDescriptionResolver(Constants.VAULT),
VaultResourceDefinitionAdd.INSTANCE, ReloadRequiredRemoveStepHandler.INSTANCE);
setDeprecated(SecurityExtension.DEPRECATED_SINCE);
}
public void registerAttributes(final ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerReadWriteAttribute(OPTIONS, null, new ReloadRequiredWriteAttributeHandler(OPTIONS));
resourceRegistration.registerReadWriteAttribute(CODE, null, new ReloadRequiredWriteAttributeHandler(CODE));
}
static class VaultResourceDefinitionAdd extends AbstractBoottimeAddStepHandler {
static final VaultResourceDefinitionAdd INSTANCE = new VaultResourceDefinitionAdd();
@Override
protected void populateModel(ModelNode operation, ModelNode model) throws OperationFailedException {
CODE.validateAndSet(operation, model);
OPTIONS.validateAndSet(operation, model);
}
}
}
| 3,391
| 43.631579
| 136
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/IdentityTrustResourceDefinition.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.security;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.ListAttributeDefinition;
import org.jboss.as.controller.ModelOnlyRemoveStepHandler;
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.SimpleResourceDefinition;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
/**
* @author Jason T. Greene
*/
class IdentityTrustResourceDefinition extends SimpleResourceDefinition {
public static final IdentityTrustResourceDefinition INSTANCE = new IdentityTrustResourceDefinition();
public static final ListAttributeDefinition TRUST_MODULES = new LegacySupport.LoginModulesAttributeDefinition(Constants.TRUST_MODULES, Constants.TRUST_MODULE);
private static final OperationStepHandler LEGACY_ADD_HANDLER = new LegacySupport.LegacyModulesConverter(Constants.TRUST_MODULE, TRUST_MODULES);
private IdentityTrustResourceDefinition() {
super(PathElement.pathElement(Constants.IDENTITY_TRUST, Constants.CLASSIC),
SecurityExtension.getResourceDescriptionResolver(Constants.IDENTITY_TRUST),
new IdentityTrustResourceDefinitionAdd(), ModelOnlyRemoveStepHandler.INSTANCE);
setDeprecated(SecurityExtension.DEPRECATED_SINCE);
}
@Override
public void registerAttributes(final ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerReadWriteAttribute(TRUST_MODULES, new LegacySupport.LegacyModulesAttributeReader(Constants.TRUST_MODULE), new LegacySupport.LegacyModulesAttributeWriter(Constants.TRUST_MODULE));
}
@Override
public void registerChildren(ManagementResourceRegistration resourceRegistration) {
super.registerChildren(resourceRegistration);
resourceRegistration.registerSubModel(new LoginModuleResourceDefinition(Constants.TRUST_MODULE));
}
static class IdentityTrustResourceDefinitionAdd extends AbstractAddStepHandler {
@Override
protected void populateModel(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException {
if (operation.hasDefined(TRUST_MODULES.getName())) {
context.addStep(new ModelNode(), operation, LEGACY_ADD_HANDLER, OperationContext.Stage.MODEL, true);
}
}
}
}
| 3,612
| 47.824324
| 215
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/AuditResourceDefinition.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.security;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.ListAttributeDefinition;
import org.jboss.as.controller.ModelOnlyRemoveStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
/**
* @author Jason T. Greene
*/
class AuditResourceDefinition extends SimpleResourceDefinition {
static final AuditResourceDefinition INSTANCE = new AuditResourceDefinition();
static final ListAttributeDefinition PROVIDER_MODULES = new LegacySupport.ProviderModulesAttributeDefinition(Constants.PROVIDER_MODULES, Constants.PROVIDER_MODULE);
private static final OperationStepHandler LEGACY_ADD_HANDLER = new LegacySupport.LegacyModulesConverter(Constants.PROVIDER_MODULE, PROVIDER_MODULES);
private AuditResourceDefinition() {
super(SecurityExtension.PATH_AUDIT_CLASSIC,
SecurityExtension.getResourceDescriptionResolver(Constants.AUDIT),
new AuditResourceDefinitionAdd(), ModelOnlyRemoveStepHandler.INSTANCE);
setDeprecated(SecurityExtension.DEPRECATED_SINCE);
}
@Override
public void registerAttributes(final ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerReadWriteAttribute(PROVIDER_MODULES, new LegacySupport.LegacyModulesAttributeReader(Constants.PROVIDER_MODULE), new LegacySupport.LegacyModulesAttributeWriter(Constants.PROVIDER_MODULE));
}
@Override
public void registerChildren(ManagementResourceRegistration resourceRegistration) {
super.registerChildren(resourceRegistration);
resourceRegistration.registerSubModel(new MappingProviderModuleDefinition(Constants.PROVIDER_MODULE));
}
static class AuditResourceDefinitionAdd extends AbstractAddStepHandler {
@Override
protected void populateModel(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException {
if (operation.hasDefined(PROVIDER_MODULES.getName())) {
context.addStep(new ModelNode(), operation, LEGACY_ADD_HANDLER, OperationContext.Stage.MODEL, true);
}
}
}
}
| 3,501
| 46.324324
| 224
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/SecurityExtension.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.security;
import java.util.Collections;
import java.util.Set;
import org.jboss.as.controller.ExtensionContext;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SubsystemRegistration;
import org.jboss.as.controller.descriptions.DeprecatedResourceDescriptionResolver;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver;
import org.jboss.as.controller.extension.AbstractLegacyExtension;
import org.jboss.as.controller.parsing.ExtensionParsingContext;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.security.elytron.ElytronIntegrationResourceDefinitions;
/**
* The security extension.
*
* @author <a href="mailto:mmoyses@redhat.com">Marcus Moyses</a>
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/public class SecurityExtension extends AbstractLegacyExtension {
public static final String SUBSYSTEM_NAME = "security";
static final PathElement PATH_SUBSYSTEM = PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, SUBSYSTEM_NAME);
private static final String RESOURCE_NAME = SecurityExtension.class.getPackage().getName() + ".LocalDescriptions";
private static final ModelVersion CURRENT_MODEL_VERSION = ModelVersion.create(2, 0, 0);
static final PathElement ACL_PATH = PathElement.pathElement(Constants.ACL, Constants.CLASSIC);
static final PathElement PATH_JASPI_AUTH = PathElement.pathElement(Constants.AUTHENTICATION, Constants.JASPI);
static final PathElement PATH_CLASSIC_AUTHENTICATION = PathElement.pathElement(Constants.AUTHENTICATION, Constants.CLASSIC);
static final PathElement SECURITY_DOMAIN_PATH = PathElement.pathElement(Constants.SECURITY_DOMAIN);
static final PathElement PATH_AUTHORIZATION_CLASSIC = PathElement.pathElement(Constants.AUTHORIZATION, Constants.CLASSIC);
static final PathElement PATH_MAPPING_CLASSIC = PathElement.pathElement(Constants.MAPPING, Constants.CLASSIC);
static final PathElement PATH_AUDIT_CLASSIC = PathElement.pathElement(Constants.AUDIT, Constants.CLASSIC);
static final PathElement PATH_LOGIN_MODULE_STACK = PathElement.pathElement(Constants.LOGIN_MODULE_STACK);
static final PathElement VAULT_PATH = PathElement.pathElement(Constants.VAULT, Constants.CLASSIC);
static final PathElement JSSE_PATH = PathElement.pathElement(Constants.JSSE, Constants.CLASSIC);
//deprecated in EAP 6.4
static final ModelVersion DEPRECATED_SINCE = ModelVersion.create(1,3,0);
public SecurityExtension() {
super("org.jboss.as.security.SecurityExtension", SUBSYSTEM_NAME);
}
public static StandardResourceDescriptionResolver getResourceDescriptionResolver(final String keyPrefix) {
return new DeprecatedResourceDescriptionResolver(SUBSYSTEM_NAME, keyPrefix, RESOURCE_NAME, SecurityExtension.class.getClassLoader(), true, true);
}
public static StandardResourceDescriptionResolver getResourceDescriptionResolver(final String... keyPrefix) {
StringBuilder prefix = new StringBuilder();
for (String kp : keyPrefix) {
if (prefix.length() > 0) {
prefix.append('.');
}
prefix.append(kp);
}
return new DeprecatedResourceDescriptionResolver(SUBSYSTEM_NAME, prefix.toString(), RESOURCE_NAME, SecurityExtension.class.getClassLoader(), true, false);
}
@Override
protected Set<ManagementResourceRegistration> initializeLegacyModel(ExtensionContext context) {
final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION, true);
final ManagementResourceRegistration registration = subsystem.registerSubsystemModel(SecuritySubsystemRootResourceDefinition.INSTANCE);
//registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE);
final ManagementResourceRegistration securityDomain = registration.registerSubModel(new SecurityDomainResourceDefinition());
securityDomain.registerSubModel(JASPIAuthenticationResourceDefinition.INSTANCE);
securityDomain.registerSubModel(ClassicAuthenticationResourceDefinition.INSTANCE);
securityDomain.registerSubModel(AuthorizationResourceDefinition.INSTANCE);
securityDomain.registerSubModel(MappingResourceDefinition.INSTANCE);
securityDomain.registerSubModel(ACLResourceDefinition.INSTANCE);
securityDomain.registerSubModel(AuditResourceDefinition.INSTANCE);
securityDomain.registerSubModel(IdentityTrustResourceDefinition.INSTANCE);
securityDomain.registerSubModel(JSSEResourceDefinition.INSTANCE);
registration.registerSubModel(VaultResourceDefinition.INSTANCE);
// register the elytron integration resources.
registration.registerSubModel(ElytronIntegrationResourceDefinitions.getElytronRealmResourceDefinition());
registration.registerSubModel(ElytronIntegrationResourceDefinitions.getElytronKeyStoreResourceDefinition());
registration.registerSubModel(ElytronIntegrationResourceDefinitions.getElytronTrustStoreResourceDefinition());
registration.registerSubModel(ElytronIntegrationResourceDefinitions.getElytronKeyManagersResourceDefinition());
registration.registerSubModel(ElytronIntegrationResourceDefinitions.getElytronTrustManagersResourceDefinition());
// register the subsystem XML persister.
subsystem.registerXMLElementWriter(SecuritySubsystemPersister.INSTANCE);
return Collections.singleton(registration);
}
@Override
protected void initializeLegacyParsers(ExtensionParsingContext context) {
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.SECURITY_1_0.getUriString(), SecuritySubsystemParser::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.SECURITY_1_1.getUriString(), SecuritySubsystemParser::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.SECURITY_1_2.getUriString(), SecuritySubsystemParser::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.SECURITY_2_0.getUriString(), SecuritySubsystemParser_2_0::new);
}
}
| 7,373
| 59.442623
| 162
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/ACLResourceDefinition.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.security;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.ListAttributeDefinition;
import org.jboss.as.controller.ModelOnlyRemoveStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.registry.AliasEntry;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
/**
* @author Jason T. Greene
*/
class ACLResourceDefinition extends SimpleResourceDefinition {
public static final ACLResourceDefinition INSTANCE = new ACLResourceDefinition();
public static final ListAttributeDefinition ACL_MODULES = new LegacySupport.LoginModulesAttributeDefinition(Constants.ACL_MODULES, Constants.ACL_MODULE);
private static final OperationStepHandler LEGACY_ADD_HANDLER = new LegacySupport.LegacyModulesConverter(Constants.ACL_MODULE, ACL_MODULES);
private ACLResourceDefinition() {
super(SecurityExtension.ACL_PATH,
SecurityExtension.getResourceDescriptionResolver(Constants.ACL),
new ACLResourceDefinitionAdd(),
ModelOnlyRemoveStepHandler.INSTANCE);
setDeprecated(SecurityExtension.DEPRECATED_SINCE);
}
@Override
public void registerAttributes(final ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerReadWriteAttribute(ACL_MODULES, new LegacySupport.LegacyModulesAttributeReader(Constants.ACL_MODULE), new LegacySupport.LegacyModulesAttributeWriter(Constants.ACL_MODULE));
}
@Override
public void registerChildren(ManagementResourceRegistration resourceRegistration) {
super.registerChildren(resourceRegistration);
ManagementResourceRegistration moduleReg = resourceRegistration.registerSubModel(new LoginModuleResourceDefinition(Constants.ACL_MODULE));
//https://issues.jboss.org/browse/WFLY-2474 acl-module was wrongly called login-module in 7.2.0
resourceRegistration.registerAlias(
PathElement.pathElement(Constants.LOGIN_MODULE),
new AliasEntry(moduleReg) {
@Override
public PathAddress convertToTargetAddress(PathAddress address, AliasContext aliasContext) {
PathElement element = address.getLastElement();
element = PathElement.pathElement(Constants.ACL_MODULE, element.getValue());
return address.subAddress(0, address.size() -1).append(element);
}
});
}
static class ACLResourceDefinitionAdd extends AbstractAddStepHandler {
@Override
protected void populateModel(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException {
if (operation.hasDefined(ACL_MODULES.getName())) {
context.addStep(new ModelNode(), operation, LEGACY_ADD_HANDLER, OperationContext.Stage.MODEL, true);
}
}
}
}
| 4,340
| 46.703297
| 209
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/JSSEResourceDefinition.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.security;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.AttributeMarshaller;
import org.jboss.as.controller.AttributeParser;
import org.jboss.as.controller.ModelOnlyAddStepHandler;
import org.jboss.as.controller.ModelOnlyRemoveStepHandler;
import org.jboss.as.controller.ModelOnlyWriteAttributeHandler;
import org.jboss.as.controller.ObjectTypeAttributeDefinition;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PropertiesAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelType;
/**
* @author Jason T. Greene
* @author Tomaz Cerar
*/
class JSSEResourceDefinition extends SimpleResourceDefinition {
static final ObjectTypeAttributeDefinition KEYSTORE = new ObjectTypeAttributeDefinition.Builder(Constants.KEYSTORE, ComplexAttributes.KEY_STORE_FIELDS)
.setValidator(new ComplexAttributes.KeyStoreAttributeValidator(Constants.KEYSTORE)).setAttributeMarshaller(new ComplexAttributes.KeyStoreAttributeMarshaller()).build();
static final ObjectTypeAttributeDefinition TRUSTSTORE = new ObjectTypeAttributeDefinition.Builder(Constants.TRUSTSTORE, ComplexAttributes.KEY_STORE_FIELDS)
.setValidator(new ComplexAttributes.KeyStoreAttributeValidator(Constants.TRUSTSTORE)).setAttributeMarshaller(new ComplexAttributes.KeyStoreAttributeMarshaller()).build();
static final ObjectTypeAttributeDefinition KEYMANAGER = new ObjectTypeAttributeDefinition.Builder(Constants.KEY_MANAGER, ComplexAttributes.KEY_MANAGER_FIELDS)
.setAttributeMarshaller(new ComplexAttributes.KeyManagerAttributeMarshaller())
.build();
static final ObjectTypeAttributeDefinition TRUSTMANAGER = new ObjectTypeAttributeDefinition.Builder(Constants.TRUST_MANAGER, ComplexAttributes.KEY_MANAGER_FIELDS)
.setAttributeMarshaller(new ComplexAttributes.KeyManagerAttributeMarshaller())
.build();
static final SimpleAttributeDefinition CLIENT_ALIAS = new SimpleAttributeDefinitionBuilder(Constants.CLIENT_ALIAS, ModelType.STRING, true)
.setAllowExpression(true)
.build();
static final SimpleAttributeDefinition SERVER_ALIAS = new SimpleAttributeDefinitionBuilder(Constants.SERVER_ALIAS, ModelType.STRING, true)
.setAllowExpression(true)
.build();
static final SimpleAttributeDefinition SERVICE_AUTH_TOKEN = new SimpleAttributeDefinitionBuilder(Constants.SERVICE_AUTH_TOKEN, ModelType.STRING, true)
.setAllowExpression(true)
.build();
static final SimpleAttributeDefinition CLIENT_AUTH = new SimpleAttributeDefinitionBuilder(Constants.CLIENT_AUTH, ModelType.BOOLEAN, true)
.setAllowExpression(true)
.build();
static final SimpleAttributeDefinition PROTOCOLS = new SimpleAttributeDefinitionBuilder(Constants.PROTOCOLS, ModelType.STRING, true)
.setAllowExpression(true)
.build();
static final SimpleAttributeDefinition CIPHER_SUITES = new SimpleAttributeDefinitionBuilder(Constants.CIPHER_SUITES, ModelType.STRING, true)
.setAllowExpression(true)
.build();
static final PropertiesAttributeDefinition ADDITIONAL_PROPERTIES = new PropertiesAttributeDefinition.Builder(Constants.ADDITIONAL_PROPERTIES, true)
.setAllowExpression(true)
.setAttributeMarshaller(AttributeMarshaller.PROPERTIES_MARSHALLER_UNWRAPPED)
.setAttributeParser(AttributeParser.PROPERTIES_PARSER_UNWRAPPED)
.build();
private static final AttributeDefinition[] ATTRIBUTES = {KEYSTORE, TRUSTSTORE, KEYMANAGER, TRUSTMANAGER, CLIENT_ALIAS, SERVER_ALIAS, SERVICE_AUTH_TOKEN,
CLIENT_AUTH, PROTOCOLS, CIPHER_SUITES, ADDITIONAL_PROPERTIES};
public static final JSSEResourceDefinition INSTANCE = new JSSEResourceDefinition();
private JSSEResourceDefinition() {
super(SecurityExtension.JSSE_PATH,
SecurityExtension.getResourceDescriptionResolver(Constants.JSSE),
new ModelOnlyAddStepHandler(ATTRIBUTES),
ModelOnlyRemoveStepHandler.INSTANCE);
setDeprecated(SecurityExtension.DEPRECATED_SINCE);
}
@Override
public void registerAttributes(final ManagementResourceRegistration resourceRegistration) {
OperationStepHandler writeHandler = new ModelOnlyWriteAttributeHandler(ATTRIBUTES);
for (AttributeDefinition attr : ATTRIBUTES) {
resourceRegistration.registerReadWriteAttribute(attr, null, writeHandler);
}
}
}
| 5,834
| 55.105769
| 182
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/MappingProviderModuleDefinition.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.security;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathElement;
/**
* This class should better be called {@code AuditProviderModuleDefinition} rather than {@code MappingProviderModuleDefinition},
* because it hangs under {@code AuditResourceDefinition} rather than {@code MappingResourceDefinition}.
*
* @author <a href="mailto:tomaz.cerar@redhat.com">Tomaz Cerar</a> (c) 2012 Red Hat Inc.
* @author <a href="https://github.com/ppalaga">Peter Palaga</a>
*/
class MappingProviderModuleDefinition extends MappingModuleDefinition {
protected static final PathElement PATH_PROVIDER_MODULE = PathElement.pathElement(Constants.PROVIDER_MODULE);
private static final AttributeDefinition[] ATTRIBUTES = { CODE, MODULE, MODULE_OPTIONS };
MappingProviderModuleDefinition(String key) {
super(key);
}
@Override
public AttributeDefinition[] getAttributes() {
return ATTRIBUTES;
}
}
| 2,036
| 38.173077
| 128
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/SecuritySubsystemParser.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.security;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CODE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.controller.parsing.ParseUtils.invalidAttributeValue;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequired;
import static org.jboss.as.controller.parsing.ParseUtils.requireAttributes;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoAttributes;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoContent;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoNamespaceAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
import static org.jboss.as.security.Constants.ACL;
import static org.jboss.as.security.Constants.ACL_MODULE;
import static org.jboss.as.security.Constants.AUDIT;
import static org.jboss.as.security.Constants.AUTHENTICATION;
import static org.jboss.as.security.Constants.AUTHORIZATION;
import static org.jboss.as.security.Constants.AUTH_MODULE;
import static org.jboss.as.security.Constants.CLASSIC;
import static org.jboss.as.security.Constants.IDENTITY_TRUST;
import static org.jboss.as.security.Constants.JASPI;
import static org.jboss.as.security.Constants.JSSE;
import static org.jboss.as.security.Constants.KEYSTORE;
import static org.jboss.as.security.Constants.KEY_MANAGER;
import static org.jboss.as.security.Constants.LOGIN_MODULE;
import static org.jboss.as.security.Constants.LOGIN_MODULE_STACK;
import static org.jboss.as.security.Constants.MAPPING;
import static org.jboss.as.security.Constants.MAPPING_MODULE;
import static org.jboss.as.security.Constants.POLICY_MODULE;
import static org.jboss.as.security.Constants.PROVIDER_MODULE;
import static org.jboss.as.security.Constants.SECURITY_DOMAIN;
import static org.jboss.as.security.Constants.TRUSTSTORE;
import static org.jboss.as.security.Constants.TRUST_MANAGER;
import static org.jboss.as.security.Constants.TRUST_MODULE;
import static org.jboss.as.security.Constants.VAULT;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.PropertiesAttributeDefinition;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.security.logging.SecurityLogger;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* The root element parser for the Security subsystem.
*
* @author Marcus Moyses
* @author Darran Lofthouse
* @author Brian Stansberry
* @author Jason T. Greene
* @author Anil Saldhana
* @author Tomaz Cerar
*/
class SecuritySubsystemParser implements XMLStreamConstants, XMLElementReader<List<ModelNode>> {
private Map<String, Integer> moduleNames;
protected SecuritySubsystemParser() {
}
@Override
public void readElement(XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
PathAddress address = PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM, SecurityExtension.SUBSYSTEM_NAME));
final ModelNode subsystemNode = Util.createAddOperation(address);
operations.add(subsystemNode);
requireNoAttributes(reader);
final EnumSet<Element> visited = EnumSet.noneOf(Element.class);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
if (!visited.add(element)) {
throw unexpectedElement(reader);
}
readElement(reader, element, operations, address, subsystemNode);
}
}
protected void readElement(final XMLExtendedStreamReader reader, final Element element, final List<ModelNode> operations,
final PathAddress subsystemPath, final ModelNode subsystemNode) throws XMLStreamException {
switch (element) {
case SECURITY_MANAGEMENT: {
parseSecurityManagement(reader, subsystemNode);
break;
}
case SECURITY_DOMAINS: {
final List<ModelNode> securityDomainsUpdates = parseSecurityDomains(reader, subsystemPath);
if (securityDomainsUpdates != null) {
operations.addAll(securityDomainsUpdates);
}
break;
}
case SECURITY_PROPERTIES:
reader.discardRemainder();
break;
case VAULT: {
final Namespace schemaVer = Namespace.forUri(reader.getNamespaceURI());
if (schemaVer == Namespace.SECURITY_1_0) {
throw unexpectedElement(reader);
}
final int count = reader.getAttributeCount();
ModelNode vault = createAddOperation(subsystemPath, VAULT, CLASSIC);
if (count > 1) {
throw unexpectedAttribute(reader, count);
}
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case CODE: {
vault.get(CODE).set(value);
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
parseProperties(Element.VAULT_OPTION.getLocalName(), reader, vault, VaultResourceDefinition.OPTIONS);
operations.add(vault);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
private void parseSecurityManagement(final XMLExtendedStreamReader reader, final ModelNode operation)
throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case DEEP_COPY_SUBJECT_MODE: {
SecuritySubsystemRootResourceDefinition.DEEP_COPY_SUBJECT_MODE.parseAndSetParameter(value, operation, reader);
break;
}
case INITIALIZE_JACC: {
SecuritySubsystemRootResourceDefinition.INITIALIZE_JACC.parseAndSetParameter(value, operation, reader);
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
requireNoContent(reader);
}
private List<ModelNode> parseSecurityDomains(final XMLExtendedStreamReader reader, final PathAddress parentAddress)
throws XMLStreamException {
requireNoAttributes(reader);
List<ModelNode> list = new ArrayList<ModelNode>();
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case SECURITY_DOMAIN: {
parseSecurityDomain(list, reader, parentAddress);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
return list;
}
private void parseSecurityDomain(List<ModelNode> list, XMLExtendedStreamReader reader, PathAddress parentAddress) throws XMLStreamException {
ModelNode op = Util.createAddOperation();
list.add(op);
PathElement secDomainPath = null;
EnumSet<Attribute> required = EnumSet.of(Attribute.NAME);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME: {
if (value == null || value.length() == 0) {
throw invalidAttributeValue(reader, i);
}
secDomainPath = PathElement.pathElement(SECURITY_DOMAIN, value);
break;
}
case CACHE_TYPE: {
SecurityDomainResourceDefinition.CACHE_TYPE.parseAndSetParameter(value, op, reader);
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
final PathAddress address = parentAddress.append(secDomainPath);
op.get(OP_ADDR).set(address.toModelNode());
final EnumSet<Element> visited = EnumSet.noneOf(Element.class);
moduleNames = new HashMap<String, Integer>();
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
if (!visited.add(element)) {
throw unexpectedElement(reader);
}
switch (element) {
case AUTHENTICATION: {
if (visited.contains(Element.AUTHENTICATION_JASPI)) {
throw SecurityLogger.ROOT_LOGGER.xmlStreamExceptionAuth(reader.getLocation());
}
parseAuthentication(list, address, reader);
break;
}
case AUTHORIZATION: {
parseAuthorization(list, address, reader);
break;
}
case ACL: {
parseACL(list, address, reader);
break;
}
case AUDIT: {
parseAudit(list, address, reader);
break;
}
case IDENTITY_TRUST: {
parseIdentityTrust(list, address, reader);
break;
}
case MAPPING: {
parseMapping(list, address, reader);
break;
}
case AUTHENTICATION_JASPI: {
if (visited.contains(Element.AUTHENTICATION)) { throw SecurityLogger.ROOT_LOGGER.xmlStreamExceptionAuth(reader.getLocation()); }
parseAuthenticationJaspi(list, address, reader);
break;
}
case JSSE: {
parseJSSE(list, address, reader);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
moduleNames.clear();
}
private void parseAuthentication(List<ModelNode> list, PathAddress parentAddress, XMLExtendedStreamReader reader)
throws XMLStreamException {
requireNoAttributes(reader);
PathAddress address = parentAddress.append(AUTHENTICATION, CLASSIC);
ModelNode op = Util.createAddOperation(address);
list.add(op);
parseLoginModules(reader, address, list);
}
private void parseLoginModules(XMLExtendedStreamReader reader, PathAddress parentAddress, List<ModelNode> list) throws XMLStreamException {
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case LOGIN_MODULE: {
EnumSet<Attribute> required = EnumSet.of(Attribute.CODE, Attribute.FLAG);
EnumSet<Attribute> notAllowed = EnumSet.of(Attribute.TYPE, Attribute.LOGIN_MODULE_STACK_REF);
parseCommonModule(reader, parentAddress, LOGIN_MODULE, required, notAllowed, list);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private ModelNode appendAddOperation(List<ModelNode> list, PathAddress parentAddress, String name, String value) {
ModelNode op = createAddOperation(parentAddress, name, value);
list.add(op);
return op;
}
private ModelNode createAddOperation(PathAddress parentAddress, String name, String value) {
return Util.createAddOperation(parentAddress.append(name, value));
}
private void parseAuthorization(List<ModelNode> list, PathAddress parentAddress, XMLExtendedStreamReader reader) throws XMLStreamException {
requireNoAttributes(reader);
PathAddress address = parentAddress.append(AUTHORIZATION, CLASSIC);
ModelNode op = Util.createAddOperation(address);
list.add(op);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case POLICY_MODULE: {
EnumSet<Attribute> required = EnumSet.of(Attribute.CODE, Attribute.FLAG);
EnumSet<Attribute> notAllowed = EnumSet.of(Attribute.TYPE, Attribute.LOGIN_MODULE_STACK_REF);
parseCommonModule(reader, address, POLICY_MODULE, required, notAllowed, list);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private void parseACL(List<ModelNode> list, PathAddress parentAddress, XMLExtendedStreamReader reader) throws XMLStreamException {
requireNoAttributes(reader);
PathAddress address = parentAddress.append(ACL, CLASSIC);
ModelNode op = Util.createAddOperation(address);
list.add(op);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case ACL_MODULE: {
EnumSet<Attribute> required = EnumSet.of(Attribute.CODE, Attribute.FLAG);
EnumSet<Attribute> notAllowed = EnumSet.of(Attribute.TYPE, Attribute.LOGIN_MODULE_STACK_REF);
parseCommonModule(reader, address, ACL_MODULE, required, notAllowed, list);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private void parseAudit(List<ModelNode> list, PathAddress parentAddress, XMLExtendedStreamReader reader) throws XMLStreamException {
requireNoAttributes(reader);
PathAddress address = parentAddress.append(AUDIT, CLASSIC);
ModelNode op = Util.createAddOperation(address);
list.add(op);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case PROVIDER_MODULE: {
EnumSet<Attribute> required = EnumSet.of(Attribute.CODE);
EnumSet<Attribute> notAllowed = EnumSet.of(Attribute.TYPE, Attribute.FLAG, Attribute.LOGIN_MODULE_STACK_REF);
parseCommonModule(reader, address, PROVIDER_MODULE, required, notAllowed, list);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private void parseIdentityTrust(List<ModelNode> list, PathAddress parentAddress, XMLExtendedStreamReader reader) throws XMLStreamException {
requireNoAttributes(reader);
PathAddress address = parentAddress.append(IDENTITY_TRUST, CLASSIC);
ModelNode op = Util.createAddOperation(address);
list.add(op);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case TRUST_MODULE: {
EnumSet<Attribute> required = EnumSet.of(Attribute.CODE, Attribute.FLAG);
EnumSet<Attribute> notAllowed = EnumSet.of(Attribute.TYPE, Attribute.LOGIN_MODULE_STACK_REF);
parseCommonModule(reader, address, TRUST_MODULE, required, notAllowed, list);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private void parseMapping(List<ModelNode> list, PathAddress parentAddress, XMLExtendedStreamReader reader) throws XMLStreamException {
requireNoAttributes(reader);
PathAddress address = parentAddress.append(MAPPING, CLASSIC);
ModelNode op = Util.createAddOperation(address);
list.add(op);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case MAPPING_MODULE: {
EnumSet<Attribute> required = EnumSet.of(Attribute.CODE);
EnumSet<Attribute> notAllowed = EnumSet.of(Attribute.FLAG, Attribute.LOGIN_MODULE_STACK_REF);
parseCommonModule(reader, address, MAPPING_MODULE, required, notAllowed, list);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private void parseCommonModule(XMLExtendedStreamReader reader, final PathAddress parentAddress, final String keyName, EnumSet<Attribute> required,
EnumSet<Attribute> notAllowed, List<ModelNode> list) throws XMLStreamException {
ModelNode node = Util.createAddOperation(parentAddress);
String code = null;
String name = null;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
if (notAllowed.contains(attribute)) { throw unexpectedAttribute(reader, i); }
required.remove(attribute);
switch (attribute) {
case CODE: {
code = value;
LoginModuleResourceDefinition.CODE.parseAndSetParameter(value, node, reader);
break;
}
case FLAG: {
LoginModuleResourceDefinition.FLAG.parseAndSetParameter(value, node, reader);
break;
}
case TYPE: {
MappingModuleDefinition.TYPE.parseAndSetParameter(value, node, reader);
break;
}
case MODULE: {
LoginModuleResourceDefinition.MODULE.parseAndSetParameter(value, node, reader);
break;
}
case LOGIN_MODULE_STACK_REF: {
JASPIMappingModuleDefinition.LOGIN_MODULE_STACK_REF.parseAndSetParameter(value, node, reader);
break;
}
case NAME: {
name = value;
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
if (name == null) {
name = code;
}
String key = keyName + "-" + name;
if (moduleNames.put(key, 1) != null) { //is case user configures duplicate login-module with same code, we generate name for him.
for (int i = 2; ; i++) {
name = code + "-" + i;
key = keyName + "-" + name;
if (!moduleNames.containsKey(key)) {
moduleNames.put(key, i);
break;
}
}
}
node.get(OP_ADDR).set(parentAddress.append(keyName, name).toModelNode());
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
parseProperties(Element.MODULE_OPTION.getLocalName(), reader, node, LoginModuleResourceDefinition.MODULE_OPTIONS);
list.add(node);
}
private void parseAuthenticationJaspi(List<ModelNode> list, PathAddress parentAddress, XMLExtendedStreamReader reader) throws XMLStreamException {
requireNoAttributes(reader);
PathAddress address = parentAddress.append(AUTHENTICATION, JASPI);
ModelNode op = Util.createAddOperation(address);
list.add(op);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case LOGIN_MODULE_STACK: {
parseLoginModuleStack(list, address, reader);
break;
}
case AUTH_MODULE: {
parseAuthModule(list, reader, address);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private void parseAuthModule(List<ModelNode> list, XMLExtendedStreamReader reader, PathAddress parentAddress) throws XMLStreamException {
Namespace schemaVer = Namespace.forUri(reader.getNamespaceURI());
EnumSet<Attribute> required = EnumSet.of(Attribute.CODE);
final EnumSet<Attribute> notAllowed;
// in version 1.2 of the schema the optional flag attribute has been included.
switch (schemaVer) {
case SECURITY_1_0:
case SECURITY_1_1:
notAllowed = EnumSet.of(Attribute.TYPE, Attribute.FLAG);
break;
default:
notAllowed = EnumSet.of(Attribute.TYPE);
}
parseCommonModule(reader, parentAddress, AUTH_MODULE, required, notAllowed, list);
}
private void parseLoginModuleStack(List<ModelNode> list, PathAddress parentAddress, XMLExtendedStreamReader reader) throws XMLStreamException {
EnumSet<Attribute> required = EnumSet.of(Attribute.NAME);
String name = null;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME: {
if (value == null) { throw invalidAttributeValue(reader, i); }
name = value;
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
PathAddress address = parentAddress.append(LOGIN_MODULE_STACK, name);
ModelNode op = Util.createAddOperation(address);
list.add(op);
parseLoginModules(reader, address, list);
}
private void parseProperties(String childElementName, XMLExtendedStreamReader reader, ModelNode node, PropertiesAttributeDefinition attribute) throws XMLStreamException {
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
if (childElementName.equals(element.getLocalName())) {
final String[] array = requireAttributes(reader, org.jboss.as.controller.parsing.Attribute.NAME.getLocalName(), org.jboss.as.controller.parsing.Attribute.VALUE.getLocalName());
attribute.parseAndAddParameterElement(array[0], array[1], node, reader);
} else {
throw unexpectedElement(reader);
}
requireNoContent(reader);
}
}
private void parseJSSE(List<ModelNode> list, PathAddress parentAddress, XMLExtendedStreamReader reader) throws XMLStreamException {
ModelNode op = appendAddOperation(list, parentAddress, JSSE, CLASSIC);
EnumSet<Attribute> visited = EnumSet.noneOf(Attribute.class);
EnumSet<Attribute> required = EnumSet.noneOf(Attribute.class);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
requireNoNamespaceAttribute(reader, i);
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case KEYSTORE_PASSWORD: {
ComplexAttributes.PASSWORD.parseAndSetParameter(value, op.get(KEYSTORE), reader);
visited.add(attribute);
break;
}
case KEYSTORE_TYPE: {
ComplexAttributes.TYPE.parseAndSetParameter(value, op.get(KEYSTORE), reader);
required.add(Attribute.KEYSTORE_PASSWORD);
break;
}
case KEYSTORE_URL: {
ComplexAttributes.URL.parseAndSetParameter(value, op.get(KEYSTORE), reader);
required.add(Attribute.KEYSTORE_PASSWORD);
break;
}
case KEYSTORE_PROVIDER: {
ComplexAttributes.PROVIDER.parseAndSetParameter(value, op.get(KEYSTORE), reader);
required.add(Attribute.KEYSTORE_PASSWORD);
break;
}
case KEYSTORE_PROVIDER_ARGUMENT: {
ComplexAttributes.PROVIDER_ARGUMENT.parseAndSetParameter(value, op.get(KEYSTORE), reader);
required.add(Attribute.KEYSTORE_PASSWORD);
break;
}
case KEY_MANAGER_FACTORY_PROVIDER: {
ComplexAttributes.PROVIDER.parseAndSetParameter(value, op.get(KEY_MANAGER), reader);
break;
}
case KEY_MANAGER_FACTORY_ALGORITHM: {
ComplexAttributes.ALGORITHM.parseAndSetParameter(value, op.get(KEY_MANAGER), reader);
break;
}
case TRUSTSTORE_PASSWORD: {
ComplexAttributes.PASSWORD.parseAndSetParameter(value, op.get(TRUSTSTORE), reader);
visited.add(attribute);
break;
}
case TRUSTSTORE_TYPE: {
ComplexAttributes.TYPE.parseAndSetParameter(value, op.get(TRUSTSTORE), reader);
required.add(Attribute.TRUSTSTORE_PASSWORD);
break;
}
case TRUSTSTORE_URL: {
ComplexAttributes.URL.parseAndSetParameter(value, op.get(TRUSTSTORE), reader);
required.add(Attribute.TRUSTSTORE_PASSWORD);
break;
}
case TRUSTSTORE_PROVIDER: {
ComplexAttributes.PROVIDER.parseAndSetParameter(value, op.get(TRUSTSTORE), reader);
required.add(Attribute.TRUSTSTORE_PASSWORD);
break;
}
case TRUSTSTORE_PROVIDER_ARGUMENT: {
ComplexAttributes.PROVIDER_ARGUMENT.parseAndSetParameter(value, op.get(TRUSTSTORE), reader);
required.add(Attribute.TRUSTSTORE_PASSWORD);
break;
}
case TRUST_MANAGER_FACTORY_PROVIDER: {
ComplexAttributes.PROVIDER.parseAndSetParameter(value, op.get(TRUST_MANAGER), reader);
break;
}
case TRUST_MANAGER_FACTORY_ALGORITHM: {
ComplexAttributes.ALGORITHM.parseAndSetParameter(value, op.get(TRUST_MANAGER), reader);
break;
}
case CLIENT_ALIAS: {
JSSEResourceDefinition.CLIENT_ALIAS.parseAndSetParameter(value, op, reader);
break;
}
case SERVER_ALIAS: {
JSSEResourceDefinition.SERVER_ALIAS.parseAndSetParameter(value, op, reader);
break;
}
case CLIENT_AUTH: {
JSSEResourceDefinition.CLIENT_AUTH.parseAndSetParameter(value, op, reader);
break;
}
case SERVICE_AUTH_TOKEN: {
JSSEResourceDefinition.SERVICE_AUTH_TOKEN.parseAndSetParameter(value, op, reader);
break;
}
case CIPHER_SUITES: {
JSSEResourceDefinition.CIPHER_SUITES.parseAndSetParameter(value, op, reader);
break;
}
case PROTOCOLS: {
JSSEResourceDefinition.PROTOCOLS.parseAndSetParameter(value, op, reader);
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
if (!visited.containsAll(required)) {
throw SecurityLogger.ROOT_LOGGER.xmlStreamExceptionMissingAttribute(Attribute.KEYSTORE_PASSWORD.getLocalName(),
Attribute.TRUSTSTORE_PASSWORD.getLocalName(), reader.getLocation());
}
parseProperties(Element.PROPERTY.getLocalName(), reader, op, JSSEResourceDefinition.ADDITIONAL_PROPERTIES);
}
}
| 31,747
| 44.41917
| 192
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/MappingResourceDefinition.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.security;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.ListAttributeDefinition;
import org.jboss.as.controller.ModelOnlyRemoveStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
/**
* @author Jason T. Greene
*/
class MappingResourceDefinition extends SimpleResourceDefinition {
public static final MappingResourceDefinition INSTANCE = new MappingResourceDefinition();
public static final ListAttributeDefinition MAPPING_MODULES = new LegacySupport.MappingModulesAttributeDefinition();
private static final OperationStepHandler LEGACY_ADD_HANDLER = new LegacySupport.LegacyModulesConverter(Constants.MAPPING_MODULE, MAPPING_MODULES);
private MappingResourceDefinition() {
super(SecurityExtension.PATH_MAPPING_CLASSIC,
SecurityExtension.getResourceDescriptionResolver(Constants.MAPPING),
new LoginModuleStackResourceDefinitionAdd(), ModelOnlyRemoveStepHandler.INSTANCE);
setDeprecated(SecurityExtension.DEPRECATED_SINCE);
}
@Override
public void registerAttributes(final ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerReadWriteAttribute(MAPPING_MODULES, new LegacySupport.LegacyModulesAttributeReader(Constants.MAPPING_MODULE), new LegacySupport.LegacyModulesAttributeWriter(Constants.MAPPING_MODULE));
}
static class LoginModuleStackResourceDefinitionAdd extends AbstractAddStepHandler {
@Override
protected void populateModel(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException {
if (operation.hasDefined(MAPPING_MODULES.getName())) {
context.addStep(new ModelNode(), operation, LEGACY_ADD_HANDLER, OperationContext.Stage.MODEL, true);
}
}
}
@Override
public void registerChildren(ManagementResourceRegistration resourceRegistration) {
super.registerChildren(resourceRegistration);
resourceRegistration.registerSubModel(new MappingModuleDefinition(Constants.MAPPING_MODULE));
}
}
| 3,480
| 45.413333
| 221
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/LegacySupport.java
|
/*
*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
* /
*/
package org.jboss.as.security;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ALLOWED;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CODE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DESCRIPTION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MIN_LENGTH;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NILLABLE;
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.TYPE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE_TYPE;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.xml.stream.XMLStreamWriter;
import org.jboss.as.controller.ListAttributeDefinition;
import org.jboss.as.controller.ModelOnlyRemoveStepHandler;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.descriptions.ResourceDescriptionResolver;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.operations.validation.EnumValidator;
import org.jboss.as.controller.operations.validation.ModelTypeValidator;
import org.jboss.as.controller.operations.validation.ParameterValidator;
import org.jboss.as.controller.operations.validation.ParametersValidator;
import org.jboss.as.controller.operations.validation.StringLengthValidator;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.security.logging.SecurityLogger;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.dmr.Property;
/**
* In this class there are all legacy attributes and code to enable backward compatibility with them
*
* @author <a href="mailto:tomaz.cerar@redhat.com">Tomaz Cerar</a> (c) 2012 Red Hat Inc.
*/
class LegacySupport {
private LegacySupport() {
}
/**
* @author Jason T. Greene
*/
static class JASPIAuthenticationModulesAttributeDefinition extends ListAttributeDefinition {
private static final ParameterValidator validator;
static {
final ParametersValidator delegate = new ParametersValidator();
delegate.registerValidator(CODE, new StringLengthValidator(1));
delegate.registerValidator(Constants.FLAG, EnumValidator.create(ModuleFlag.class));
delegate.registerValidator(Constants.MODULE, new StringLengthValidator(1, true));
delegate.registerValidator(Constants.MODULE_OPTIONS, new ModelTypeValidator(ModelType.OBJECT, true));
delegate.registerValidator(Constants.LOGIN_MODULE_STACK_REF, new StringLengthValidator(1, true));
validator = new ParametersOfValidator(delegate);
}
public JASPIAuthenticationModulesAttributeDefinition() {
super(LegacySupportListAttributeBuilder.of(Constants.AUTH_MODULES, Constants.AUTH_MODULE, validator));
}
@Override
protected void addValueTypeDescription(ModelNode node, ResourceBundle bundle) {
// This method being used indicates a misuse of this class
throw SecurityLogger.ROOT_LOGGER.unsupportedOperationExceptionUseResourceDesc();
}
@Override
protected void addAttributeValueTypeDescription(ModelNode node, ResourceDescriptionResolver resolver, Locale locale, ResourceBundle bundle) {
final ModelNode valueType = getNoTextValueTypeDescription(node);
valueType.get(CODE, DESCRIPTION).set(resolver.getResourceAttributeValueTypeDescription(getName(), locale, bundle, CODE));
valueType.get(Constants.FLAG, DESCRIPTION).set(resolver.getResourceAttributeValueTypeDescription(getName(), locale, bundle, Constants.FLAG));
valueType.get(Constants.MODULE, DESCRIPTION).set(resolver.getResourceAttributeValueTypeDescription(getName(), locale, bundle, Constants.MODULE));
valueType.get(Constants.MODULE_OPTIONS, DESCRIPTION).set(resolver.getResourceAttributeValueTypeDescription(getName(), locale, bundle, Constants.MODULE_OPTIONS));
valueType.get(Constants.LOGIN_MODULE_STACK_REF, DESCRIPTION).set(resolver.getResourceAttributeValueTypeDescription(getName(), locale, bundle, Constants.LOGIN_MODULE_STACK_REF));
}
@Override
protected void addOperationParameterValueTypeDescription(ModelNode node, String operationName, ResourceDescriptionResolver resolver, Locale locale, ResourceBundle bundle) {
final ModelNode valueType = getNoTextValueTypeDescription(node);
valueType.get(CODE, DESCRIPTION).set(resolver.getOperationParameterValueTypeDescription(operationName, getName(), locale, bundle, CODE));
valueType.get(Constants.FLAG, DESCRIPTION).set(resolver.getOperationParameterValueTypeDescription(operationName, getName(), locale, bundle, Constants.FLAG));
valueType.get(Constants.MODULE, DESCRIPTION).set(resolver.getOperationParameterValueTypeDescription(operationName, getName(), locale, bundle, Constants.MODULE));
valueType.get(Constants.MODULE_OPTIONS, DESCRIPTION).set(resolver.getOperationParameterValueTypeDescription(operationName, getName(), locale, bundle, Constants.MODULE_OPTIONS));
valueType.get(Constants.LOGIN_MODULE_STACK_REF, DESCRIPTION).set(resolver.getOperationParameterValueTypeDescription(operationName, getName(), locale, bundle, Constants.LOGIN_MODULE_STACK_REF));
}
@Override
public void marshallAsElement(ModelNode resourceModel, final boolean marshalDefault, XMLStreamWriter writer) {
throw SecurityLogger.ROOT_LOGGER.unsupportedOperation();
}
private ModelNode getNoTextValueTypeDescription(final ModelNode parent) {
final ModelNode valueType = parent.get(VALUE_TYPE);
final ModelNode code = valueType.get(CODE);
code.get(DESCRIPTION); // placeholder
code.get(TYPE).set(ModelType.STRING);
code.get(NILLABLE).set(false);
code.get(MIN_LENGTH).set(1);
final ModelNode flag = valueType.get(Constants.FLAG);
flag.get(DESCRIPTION); // placeholder
flag.get(TYPE).set(ModelType.STRING);
flag.get(NILLABLE).set(true);
for (ModuleFlag value : ModuleFlag.values()) { flag.get(ALLOWED).add(value.toString()); }
final ModelNode module = valueType.get(Constants.MODULE);
module.get(TYPE).set(ModelType.STRING);
module.get(NILLABLE).set(true);
final ModelNode moduleOptions = valueType.get(Constants.MODULE_OPTIONS);
moduleOptions.get(DESCRIPTION); // placeholder
moduleOptions.get(TYPE).set(ModelType.OBJECT);
moduleOptions.get(VALUE_TYPE).set(ModelType.STRING);
moduleOptions.get(NILLABLE).set(true);
final ModelNode ref = valueType.get(Constants.LOGIN_MODULE_STACK_REF);
ref.get(DESCRIPTION); // placeholder
ref.get(TYPE).set(ModelType.STRING);
ref.get(NILLABLE).set(true);
ref.get(MIN_LENGTH).set(1);
return valueType;
}
}
/**
* @author Jason T. Greene
*/
public static class LoginModulesAttributeDefinition extends ListAttributeDefinition {
public static final ParameterValidator validator;
static {
final ParametersValidator delegate = new ParametersValidator();
delegate.registerValidator(CODE, new StringLengthValidator(1));
delegate.registerValidator(Constants.FLAG, EnumValidator.create(ModuleFlag.class));
delegate.registerValidator(Constants.MODULE, new StringLengthValidator(1, true));
delegate.registerValidator(Constants.MODULE_OPTIONS, new ModelTypeValidator(ModelType.OBJECT, true));
validator = new ParametersOfValidator(delegate);
}
public LoginModulesAttributeDefinition(String name, String xmlName) {
super(LegacySupportListAttributeBuilder.of(name, xmlName, validator).setDeprecated(ModelVersion.create(1, 2, 0)));
}
@Override
protected void addValueTypeDescription(ModelNode node, ResourceBundle bundle) {
// This method being used indicates a misuse of this class
throw SecurityLogger.ROOT_LOGGER.unsupportedOperationExceptionUseResourceDesc();
}
@Override
protected void addAttributeValueTypeDescription(ModelNode node, ResourceDescriptionResolver resolver, Locale locale, ResourceBundle bundle) {
final ModelNode valueType = getNoTextValueTypeDescription(node);
valueType.get(CODE, DESCRIPTION).set(resolver.getResourceAttributeValueTypeDescription(getName(), locale, bundle, CODE));
valueType.get(Constants.FLAG, DESCRIPTION).set(resolver.getResourceAttributeValueTypeDescription(getName(), locale, bundle, Constants.FLAG));
valueType.get(Constants.MODULE, DESCRIPTION).set(resolver.getResourceAttributeValueTypeDescription(getName(), locale, bundle, Constants.MODULE));
valueType.get(Constants.MODULE_OPTIONS, DESCRIPTION).set(resolver.getResourceAttributeValueTypeDescription(getName(), locale, bundle, Constants.MODULE_OPTIONS));
}
@Override
protected void addOperationParameterValueTypeDescription(ModelNode node, String operationName, ResourceDescriptionResolver resolver, Locale locale, ResourceBundle bundle) {
final ModelNode valueType = getNoTextValueTypeDescription(node);
valueType.get(CODE, DESCRIPTION).set(resolver.getOperationParameterValueTypeDescription(operationName, getName(), locale, bundle, CODE));
valueType.get(Constants.FLAG, DESCRIPTION).set(resolver.getOperationParameterValueTypeDescription(operationName, getName(), locale, bundle, Constants.FLAG));
valueType.get(Constants.MODULE, DESCRIPTION).set(resolver.getOperationParameterValueTypeDescription(operationName, getName(), locale, bundle, Constants.MODULE));
valueType.get(Constants.MODULE_OPTIONS, DESCRIPTION).set(resolver.getOperationParameterValueTypeDescription(operationName, getName(), locale, bundle, Constants.MODULE_OPTIONS));
}
@Override
public void marshallAsElement(ModelNode resourceModel, final boolean marshalDefault, XMLStreamWriter writer) {
throw SecurityLogger.ROOT_LOGGER.unsupportedOperation();
}
private ModelNode getNoTextValueTypeDescription(final ModelNode parent) {
final ModelNode valueType = parent.get(VALUE_TYPE);
final ModelNode code = valueType.get(CODE);
code.get(DESCRIPTION); // placeholder
code.get(TYPE).set(ModelType.STRING);
code.get(NILLABLE).set(false);
code.get(MIN_LENGTH).set(1);
final ModelNode flag = valueType.get(Constants.FLAG);
flag.get(DESCRIPTION); // placeholder
flag.get(TYPE).set(ModelType.STRING);
flag.get(NILLABLE).set(false);
for (ModuleFlag value : ModuleFlag.values()) { flag.get(ALLOWED).add(value.toString()); }
final ModelNode module = valueType.get(Constants.MODULE);
module.get(TYPE).set(ModelType.STRING);
module.get(NILLABLE).set(true);
final ModelNode moduleOptions = valueType.get(Constants.MODULE_OPTIONS);
moduleOptions.get(DESCRIPTION); // placeholder
moduleOptions.get(TYPE).set(ModelType.OBJECT);
moduleOptions.get(VALUE_TYPE).set(ModelType.STRING);
moduleOptions.get(NILLABLE).set(true);
return valueType;
}
}
/**
* @author Jason T. Greene
*/
public static class MappingModulesAttributeDefinition extends ListAttributeDefinition {
private static final ParameterValidator validator;
static {
final ParametersValidator delegate = new ParametersValidator();
delegate.registerValidator(CODE, new StringLengthValidator(1));
delegate.registerValidator(Constants.TYPE, new StringLengthValidator(1));
delegate.registerValidator(Constants.MODULE, new StringLengthValidator(1, true));
delegate.registerValidator(Constants.MODULE_OPTIONS, new ModelTypeValidator(ModelType.OBJECT, true));
validator = new ParametersOfValidator(delegate);
}
public MappingModulesAttributeDefinition() {
super(LegacySupportListAttributeBuilder.of(Constants.MAPPING_MODULES, Constants.MAPPING_MODULE, validator)
.setDeprecated(ModelVersion.create(1, 2, 0))
);
}
@Override
protected void addValueTypeDescription(ModelNode node, ResourceBundle bundle) {
// This method being used indicates a misuse of this class
throw SecurityLogger.ROOT_LOGGER.unsupportedOperationExceptionUseResourceDesc();
}
@Override
protected void addAttributeValueTypeDescription(ModelNode node, ResourceDescriptionResolver resolver, Locale locale, ResourceBundle bundle) {
final ModelNode valueType = getNoTextValueTypeDescription(node);
valueType.get(CODE, DESCRIPTION).set(resolver.getResourceAttributeValueTypeDescription(getName(), locale, bundle, CODE));
valueType.get(Constants.TYPE, DESCRIPTION).set(resolver.getResourceAttributeValueTypeDescription(getName(), locale, bundle, Constants.TYPE));
valueType.get(Constants.MODULE_OPTIONS, DESCRIPTION).set(resolver.getResourceAttributeValueTypeDescription(getName(), locale, bundle, Constants.MODULE_OPTIONS));
}
@Override
protected void addOperationParameterValueTypeDescription(ModelNode node, String operationName, ResourceDescriptionResolver resolver, Locale locale, ResourceBundle bundle) {
final ModelNode valueType = getNoTextValueTypeDescription(node);
valueType.get(CODE, DESCRIPTION).set(resolver.getOperationParameterValueTypeDescription(operationName, getName(), locale, bundle, CODE));
valueType.get(Constants.TYPE, DESCRIPTION).set(resolver.getOperationParameterValueTypeDescription(operationName, getName(), locale, bundle, Constants.TYPE));
valueType.get(Constants.MODULE_OPTIONS, DESCRIPTION).set(resolver.getOperationParameterValueTypeDescription(operationName, getName(), locale, bundle, Constants.MODULE_OPTIONS));
}
@Override
public void marshallAsElement(ModelNode resourceModel, final boolean marshalDefault, XMLStreamWriter writer) {
throw SecurityLogger.ROOT_LOGGER.unsupportedOperation();
}
private ModelNode getNoTextValueTypeDescription(final ModelNode parent) {
final ModelNode valueType = parent.get(VALUE_TYPE);
final ModelNode code = valueType.get(CODE);
code.get(DESCRIPTION); // placeholder
code.get(TYPE).set(ModelType.STRING);
code.get(NILLABLE).set(false);
code.get(MIN_LENGTH).set(1);
final ModelNode flag = valueType.get(Constants.TYPE);
flag.get(DESCRIPTION); // placeholder
flag.get(TYPE).set(ModelType.STRING);
flag.get(NILLABLE).set(false);
final ModelNode moduleOptions = valueType.get(Constants.MODULE_OPTIONS);
moduleOptions.get(DESCRIPTION); // placeholder
moduleOptions.get(TYPE).set(ModelType.OBJECT);
moduleOptions.get(VALUE_TYPE).set(ModelType.STRING);
moduleOptions.get(NILLABLE).set(true);
return valueType;
}
}
/**
* @author Jason T. Greene
*/
public static class ProviderModulesAttributeDefinition extends ListAttributeDefinition {
public static final ParameterValidator validator;
static {
final ParametersValidator delegate = new ParametersValidator();
delegate.registerValidator(CODE, new StringLengthValidator(1));
delegate.registerValidator(Constants.MODULE_OPTIONS, new ModelTypeValidator(ModelType.OBJECT, true));
validator = new ParametersOfValidator(delegate);
}
public ProviderModulesAttributeDefinition(String name, String xmlName) {
super(LegacySupportListAttributeBuilder.of(name, xmlName, validator)
.setDeprecated(ModelVersion.create(1, 2, 0))
);
}
@Override
protected void addValueTypeDescription(ModelNode node, ResourceBundle bundle) {
// This method being used indicates a misuse of this class
throw SecurityLogger.ROOT_LOGGER.unsupportedOperationExceptionUseResourceDesc();
}
@Override
protected void addAttributeValueTypeDescription(ModelNode node, ResourceDescriptionResolver resolver, Locale locale, ResourceBundle bundle) {
final ModelNode valueType = getNoTextValueTypeDescription(node);
valueType.get(CODE, DESCRIPTION).set(resolver.getResourceAttributeValueTypeDescription(getName(), locale, bundle, CODE));
valueType.get(Constants.MODULE_OPTIONS, DESCRIPTION).set(resolver.getResourceAttributeValueTypeDescription(getName(), locale, bundle, Constants.MODULE_OPTIONS));
}
@Override
protected void addOperationParameterValueTypeDescription(ModelNode node, String operationName, ResourceDescriptionResolver resolver, Locale locale, ResourceBundle bundle) {
final ModelNode valueType = getNoTextValueTypeDescription(node);
valueType.get(CODE, DESCRIPTION).set(resolver.getOperationParameterValueTypeDescription(operationName, getName(), locale, bundle, CODE));
valueType.get(Constants.MODULE_OPTIONS, DESCRIPTION).set(resolver.getOperationParameterValueTypeDescription(operationName, getName(), locale, bundle, Constants.MODULE_OPTIONS));
}
@Override
public void marshallAsElement(ModelNode resourceModel, final boolean marshalDefault, XMLStreamWriter writer) {
throw SecurityLogger.ROOT_LOGGER.unsupportedOperation();
}
private ModelNode getNoTextValueTypeDescription(final ModelNode parent) {
final ModelNode valueType = parent.get(VALUE_TYPE);
final ModelNode code = valueType.get(CODE);
code.get(DESCRIPTION); // placeholder
code.get(TYPE).set(ModelType.STRING);
code.get(NILLABLE).set(false);
code.get(MIN_LENGTH).set(1);
final ModelNode moduleOptions = valueType.get(Constants.MODULE_OPTIONS);
moduleOptions.get(DESCRIPTION); // placeholder
moduleOptions.get(TYPE).set(ModelType.OBJECT);
moduleOptions.get(VALUE_TYPE).set(ModelType.STRING);
moduleOptions.get(NILLABLE).set(true);
return valueType;
}
}
/*
* handlers
*/
static class LegacyModulesAttributeReader implements OperationStepHandler {
private final String newKeyName;
LegacyModulesAttributeReader(String newKeyName) {
this.newKeyName = newKeyName;
}
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
Resource resource = context.readResource(PathAddress.EMPTY_ADDRESS);
ModelNode authModules = Resource.Tools.readModel(resource).get(newKeyName);
ModelNode result = new ModelNode();
if (authModules.isDefined()) {
List<Property> loginModules = authModules.asPropertyList();
for (Property p : loginModules) {
result.add(p.getValue());
}
}
context.getResult().set(result);
}
}
static class LegacyModulesAttributeWriter implements OperationStepHandler {
private final String newKeyName;
LegacyModulesAttributeWriter(String newKeyName) {
this.newKeyName = newKeyName;
}
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
Resource existing = context.readResource(PathAddress.EMPTY_ADDRESS);
OperationStepHandler addHandler = context.getResourceRegistration().getSubModel(PathAddress.EMPTY_ADDRESS.append(newKeyName)).getOperationHandler(PathAddress.EMPTY_ADDRESS, "add");
ModelNode value = operation.get(VALUE);
if (value.isDefined()) {
List<ModelNode> modules = new ArrayList<>(value.asList());
Collections.reverse(modules); //need to reverse it to make sure they are added in proper order
for (ModelNode module : modules) {
ModelNode addModuleOp = module.clone();
String code = addModuleOp.get(Constants.CODE).asString();
PathElement relativePath = PathElement.pathElement(newKeyName, code);
PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR)).append(relativePath);
addModuleOp.get(OP_ADDR).set(address.toModelNode());
addModuleOp.get(OP).set(ADD);
context.addStep(new ModelNode(), addModuleOp, addHandler, OperationContext.Stage.MODEL, true);
}
}
//remove on the end to make sure it is executed first
for (Resource.ResourceEntry entry : existing.getChildren(newKeyName)) {
PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR)).append(entry.getPathElement());
ModelNode removeModuleOp = Util.createRemoveOperation(address);
context.addStep(new ModelNode(), removeModuleOp, ModelOnlyRemoveStepHandler.INSTANCE, OperationContext.Stage.MODEL, true);
}
}
}
static class LegacyModulesConverter implements OperationStepHandler {
private final String newKeyName;
private final ListAttributeDefinition oldAttribute;
LegacyModulesConverter(String newKeyName, ListAttributeDefinition oldAttribute) {
this.newKeyName = newKeyName;
this.oldAttribute = oldAttribute;
}
/*public ModelNode convertOperationAddress(ModelNode op){
PathAddress address = PathAddress.pathAddress(op.get(ModelDescriptionConstants.OP_ADDR));
op.get(ModelDescriptionConstants.OP_ADDR).set()
}*/
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
Resource existing = context.readResource(PathAddress.EMPTY_ADDRESS);
OperationStepHandler addHandler = context.getResourceRegistration().getSubModel(PathAddress.EMPTY_ADDRESS.append(newKeyName)).getOperationHandler(PathAddress.EMPTY_ADDRESS, "add");
oldAttribute.validateOperation(operation);
List<ModelNode> modules = new ArrayList<>(operation.get(oldAttribute.getName()).asList());
Collections.reverse(modules); //need to reverse it to make sure they are added in proper order
for (ModelNode module : modules) {
ModelNode addModuleOp = module.clone();
String code = addModuleOp.get(Constants.CODE).asString();
PathElement relativePath = PathElement.pathElement(newKeyName, code);
PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR)).append(relativePath);
addModuleOp.get(OP_ADDR).set(address.toModelNode());
addModuleOp.get(OP).set(ADD);
context.addStep(new ModelNode(), addModuleOp, addHandler, OperationContext.Stage.MODEL, true);
}
//remove on the end to make sure it is executed first
for (Resource.ResourceEntry entry : existing.getChildren(newKeyName)) {
PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR)).append(entry.getPathElement());
ModelNode removeModuleOp = Util.createRemoveOperation(address);
context.addStep(new ModelNode(), removeModuleOp, ModelOnlyRemoveStepHandler.INSTANCE, OperationContext.Stage.MODEL, true);
}
}
}
private static class LegacySupportListAttributeBuilder
extends ListAttributeDefinition.Builder<LegacySupportListAttributeBuilder, ListAttributeDefinition> {
private static LegacySupportListAttributeBuilder of(String attributeName, String xmlName,
ParameterValidator elementValidator) {
return new LegacySupportListAttributeBuilder(attributeName)
.setXmlName(xmlName)
.setElementValidator(elementValidator)
.setRequired(false)
.setMinSize(1)
.setMaxSize(Integer.MAX_VALUE)
.setDeprecated(ModelVersion.create(1, 2))
.setRestartAllServices();
}
private LegacySupportListAttributeBuilder(String attributeName) {
super(attributeName);
}
@Override
public ListAttributeDefinition build() {
// This should not be called. We only use this class to carry properties to the AD constructors
throw new UnsupportedOperationException();
}
}
private static class ParametersOfValidator implements ParameterValidator {
private final ParametersValidator delegate;
private ParametersOfValidator(final ParametersValidator delegate) {
this.delegate = delegate;
}
@Override
public void validateParameter(String parameterName, ModelNode value) throws OperationFailedException {
try {
delegate.validate(value);
} catch (OperationFailedException e) {
final ModelNode failureDescription = new ModelNode().add(SecurityLogger.ROOT_LOGGER.validationFailed(parameterName));
failureDescription.add(e.getFailureDescription());
throw new OperationFailedException(e.getMessage(), e.getCause(), failureDescription);
}
}
}
}
| 28,035
| 52.098485
| 205
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/SecurityDomainAdd.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.security;
import static org.jboss.as.security.Constants.CACHE_TYPE;
import static org.jboss.as.security.SecurityDomainResourceDefinition.CACHE_CONTAINER_BASE_CAPABILTIY;
import static org.jboss.as.security.SecurityDomainResourceDefinition.CACHE_CONTAINER_NAME;
import static org.jboss.as.security.SecurityDomainResourceDefinition.LEGACY_SECURITY_DOMAIN;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
/**
* Add a security domain configuration.
*
* @author Marcus Moyses
* @author Brian Stansberry
* @author Jason T. Greene
*/
class SecurityDomainAdd extends AbstractAddStepHandler {
static final SecurityDomainAdd INSTANCE = new SecurityDomainAdd();
/**
* Private to ensure a singleton.
*/
private SecurityDomainAdd() {
super(SecurityDomainResourceDefinition.CACHE_TYPE);
}
@Override
protected void recordCapabilitiesAndRequirements(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException {
super.recordCapabilitiesAndRequirements(context, operation, resource);
String cacheType = getAuthenticationCacheType(resource.getModel());
if (SecurityDomainResourceDefinition.INFINISPAN_CACHE_TYPE.equals(cacheType)) {
context.registerAdditionalCapabilityRequirement(
RuntimeCapability.buildDynamicCapabilityName(CACHE_CONTAINER_BASE_CAPABILTIY, CACHE_CONTAINER_NAME),
LEGACY_SECURITY_DOMAIN.getDynamicName(context.getCurrentAddressValue()),
SecurityDomainResourceDefinition.CACHE_TYPE.getName());
}
}
static String getAuthenticationCacheType(ModelNode node) {
String type = null;
if (node.hasDefined(CACHE_TYPE)) {
type = node.get(CACHE_TYPE).asString();
}
return type;
}
}
| 3,126
| 40.144737
| 152
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/ComplexAttributes.java
|
/*
*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
* /
*/
package org.jboss.as.security;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.DefaultAttributeMarshaller;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.operations.validation.ParameterValidator;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
/**
* @author Jason T. Greene
* @author Tomaz Cerar
*/
class ComplexAttributes {
static final SimpleAttributeDefinition PASSWORD = new SimpleAttributeDefinitionBuilder(Constants.PASSWORD, ModelType.STRING)
.setRequired(true)
.setAllowExpression(true)
.build();
static final SimpleAttributeDefinition TYPE = new SimpleAttributeDefinitionBuilder(Constants.TYPE, ModelType.STRING)
.setRequired(false)
.setAllowExpression(true)
.build();
static final SimpleAttributeDefinition URL = new SimpleAttributeDefinitionBuilder(Constants.URL, ModelType.STRING)
.setRequired(false)
.setAllowExpression(true)
.build();
static final SimpleAttributeDefinition PROVIDER = new SimpleAttributeDefinitionBuilder(Constants.PROVIDER, ModelType.STRING)
.setRequired(false)
.setAllowExpression(true)
.build();
static final SimpleAttributeDefinition PROVIDER_ARGUMENT = new SimpleAttributeDefinitionBuilder(Constants.PROVIDER_ARGUMENT, ModelType.STRING)
.setRequired(false)
.setAllowExpression(true)
.build();
static final SimpleAttributeDefinition ALGORITHM = new SimpleAttributeDefinitionBuilder(Constants.ALGORITHM, ModelType.STRING)
.setRequired(false)
.setAllowExpression(true)
.build();
static final SimpleAttributeDefinition[] KEY_STORE_FIELDS = {PASSWORD, TYPE, URL, PROVIDER, PROVIDER_ARGUMENT};
static final SimpleAttributeDefinition[] KEY_MANAGER_FIELDS = {ALGORITHM, PROVIDER};
protected static final class KeyStoreAttributeMarshaller extends DefaultAttributeMarshaller {
@Override
public void marshallAsAttribute(AttributeDefinition attribute, ModelNode resourceModel, boolean marshallDefault, XMLStreamWriter writer) throws XMLStreamException {
if (attribute.isMarshallable(resourceModel, marshallDefault)) {
resourceModel = resourceModel.get(attribute.getName());
if (resourceModel.hasDefined(Constants.PASSWORD)) {
writer.writeAttribute(attribute.getName() + "-" + Constants.PASSWORD, resourceModel.get(Constants.PASSWORD).asString());
}
if (resourceModel.hasDefined(Constants.TYPE)) {
writer.writeAttribute(attribute.getName() + "-" + Constants.TYPE, resourceModel.get(Constants.TYPE).asString());
}
if (resourceModel.hasDefined(Constants.URL)) {
writer.writeAttribute(attribute.getName() + "-" + Constants.URL, resourceModel.get(Constants.URL).asString());
}
if (resourceModel.hasDefined(Constants.PROVIDER)) {
writer.writeAttribute(attribute.getName() + "-" + Constants.PROVIDER, resourceModel.get(Constants.PROVIDER).asString());
}
if (resourceModel.hasDefined(Constants.PROVIDER_ARGUMENT)) {
writer.writeAttribute(attribute.getName() + "-" + Constants.PROVIDER_ARGUMENT, resourceModel.get(Constants.PROVIDER_ARGUMENT).asString());
}
}
}
}
protected static final class KeyManagerAttributeMarshaller extends DefaultAttributeMarshaller {
@Override
public void marshallAsAttribute(AttributeDefinition attribute, ModelNode resourceModel, boolean marshallDefault, XMLStreamWriter writer) throws XMLStreamException {
if (attribute.isMarshallable(resourceModel, marshallDefault)) {
resourceModel = resourceModel.get(attribute.getName());
if (resourceModel.hasDefined(Constants.ALGORITHM)) {
writer.writeAttribute(attribute.getName() + "-factory-" + Constants.ALGORITHM, resourceModel.get(Constants.ALGORITHM).asString());
}
if (resourceModel.hasDefined(Constants.PROVIDER)) {
writer.writeAttribute(attribute.getName() + "-factory-" + Constants.PROVIDER, resourceModel.get(Constants.PROVIDER).asString());
}
}
}
}
protected static final class KeyStoreAttributeValidator implements ParameterValidator {
private final String name;
public KeyStoreAttributeValidator(String name) {
this.name = name;
}
@Override
public void validateParameter(String parameterName, ModelNode value) throws OperationFailedException {
if (name.equals(parameterName)) {
ModelNode parameters = value.clone();
if (isConfigured(parameters)) {
for (SimpleAttributeDefinition attribute : KEY_STORE_FIELDS) {
attribute.getValidator().validateParameter(attribute.getName(), parameters.get(attribute.getName()));
}
}
}
}
private boolean isConfigured(ModelNode keystore) {
return keystore.hasDefined(Constants.TYPE) || keystore.hasDefined(Constants.URL) ||
keystore.hasDefined(Constants.PROVIDER) || keystore.hasDefined(Constants.PROVIDER_ARGUMENT);
}
}
}
| 6,833
| 45.489796
| 172
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/Attribute.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.security;
import java.util.HashMap;
import java.util.Map;
/**
* Enum for the Security container attributes
*
* @author <a href="mailto:mmoyses@redhat.com">Marcus Moyses</a>
*/
enum Attribute {
// must be first
UNKNOWN(null),
AUDIT_MANAGER_CLASS_NAME("audit-manager-class-name"),
AUTHENTICATION_MANAGER_CLASS_NAME("authentication-manager-class-name"),
AUTHORIZATION_MANAGER_CLASS_NAME("authorization-manager-class-name"),
CACHE_TYPE("cache-type"),
CIPHER_SUITES("cipher-suites"),
CLIENT_ALIAS("client-alias"),
CLIENT_AUTH("client-auth"),
CODE("code"),
DEEP_COPY_SUBJECT_MODE("deep-copy-subject-mode"),
DEFAULT_CALLBACK_HANDLER_CLASS_NAME("default-callback-handler-class-name"),
EXTENDS("extends"),
FLAG("flag"),
IDENTITY_TRUST_MANAGER_CLASS_NAME("identity-trust-manager-class-name"),
INITIALIZE_JACC("initialize-jacc"),
KEY_MANAGER_FACTORY_ALGORITHM("key-manager-factory-algorithm"),
KEY_MANAGER_FACTORY_PROVIDER("key-manager-factory-provider"),
KEYSTORE_PASSWORD("keystore-password"),
KEYSTORE_PROVIDER("keystore-provider"),
KEYSTORE_PROVIDER_ARGUMENT("keystore-provider-argument"),
KEYSTORE_TYPE("keystore-type"),
KEYSTORE_URL("keystore-url"),
LOGIN_MODULE_STACK_REF("login-module-stack-ref"),
MAPPING_MANAGER_CLASS_NAME("mapping-manager-class-name"),
MODULE("module"),
NAME("name"),
PROTOCOLS("protocols"),
SERVER_ALIAS("server-alias"),
SERVICE_AUTH_TOKEN("service-auth-token"),
SUBJECT_FACTORY_CLASS_NAME("subject-factory-class-name"),
TRUST_MANAGER_FACTORY_ALGORITHM("trust-manager-factory-algorithm"),
TRUST_MANAGER_FACTORY_PROVIDER("trust-manager-factory-provider"),
TRUSTSTORE_PASSWORD("truststore-password"),
TRUSTSTORE_PROVIDER("truststore-provider"),
TRUSTSTORE_PROVIDER_ARGUMENT("truststore-provider-argument"),
TRUSTSTORE_TYPE("truststore-type"),
TRUSTSTORE_URL("truststore-url"),
TYPE("type"),
VALUE("value"),
// ELYTRON INTEGRATION ATTRIBUTES
LEGACY_JAAS_CONFIG(Constants.LEGACY_JAAS_CONFIG),
LEGACY_JSSE_CONFIG(Constants.LEGACY_JSSE_CONFIG),
APPLY_ROLE_MAPPERS(Constants.APPLY_ROLE_MAPPERS);
private final String name;
Attribute(final String name) {
this.name = name;
}
/**
* Get the local name of this element.
*
* @return the local name
*/
public String getLocalName() {
return name;
}
private static final Map<String, Attribute> MAP;
static {
final Map<String, Attribute> map = new HashMap<>();
for (Attribute element : values()) {
final String name = element.getLocalName();
if (name != null)
map.put(name, element);
}
MAP = map;
}
public static Attribute forName(String localName) {
final Attribute element = MAP.get(localName);
return element == null ? UNKNOWN : element;
}
@Override
public String toString() {
return getLocalName();
}
}
| 4,083
| 33.610169
| 79
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/SecuritySubsystemRootResourceDefinition.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.security;
import org.jboss.as.controller.AbstractBoottimeAddStepHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
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.constraint.SensitivityClassification;
import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.controller.registry.RuntimePackageDependency;
import org.jboss.as.security.logging.SecurityLogger;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
/**
* @author Jason T. Greene
*/
class SecuritySubsystemRootResourceDefinition extends SimpleResourceDefinition {
private static final RuntimeCapability<Void> SECURITY_SUBSYSTEM = RuntimeCapability.Builder.of("org.wildfly.legacy-security").build();
private static final RuntimeCapability<Void> SERVER_SECURITY_MANAGER = RuntimeCapability.Builder.of("org.wildfly.legacy-security.server-security-manager")
.build();
private static final RuntimeCapability<Void> SUBJECT_FACTORY_CAP = RuntimeCapability.Builder.of("org.wildfly.legacy-security.subject-factory")
.build();
private static final RuntimeCapability<Void> JACC_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.legacy-security.jacc")
.build();
private static final RuntimeCapability<Void> JACC_CAPABILITY_TOMBSTONE = RuntimeCapability.Builder.of("org.wildfly.legacy-security.jacc.tombstone")
.build();
private static final SensitiveTargetAccessConstraintDefinition MISC_SECURITY_SENSITIVITY = new SensitiveTargetAccessConstraintDefinition(
new SensitivityClassification(SecurityExtension.SUBSYSTEM_NAME, "misc-security", false, true, true));
static final SecuritySubsystemRootResourceDefinition INSTANCE = new SecuritySubsystemRootResourceDefinition();
static final SimpleAttributeDefinition DEEP_COPY_SUBJECT_MODE = new SimpleAttributeDefinitionBuilder(Constants.DEEP_COPY_SUBJECT_MODE, ModelType.BOOLEAN, true)
.setAccessConstraints(MISC_SECURITY_SENSITIVITY)
.setDefaultValue(ModelNode.FALSE)
.setAllowExpression(true)
.build();
static final SimpleAttributeDefinition INITIALIZE_JACC = new SimpleAttributeDefinitionBuilder(Constants.INITIALIZE_JACC, ModelType.BOOLEAN, true)
.setDefaultValue(ModelNode.TRUE)
.setRestartJVM()
.setAllowExpression(true)
.build();
private SecuritySubsystemRootResourceDefinition() {
super(new Parameters(SecurityExtension.PATH_SUBSYSTEM,
SecurityExtension.getResourceDescriptionResolver(SecurityExtension.SUBSYSTEM_NAME))
.setAddHandler(SecuritySubsystemAdd.INSTANCE)
.setRemoveHandler(new ReloadRequiredRemoveStepHandler() {
@Override
protected void recordCapabilitiesAndRequirements(OperationContext context, ModelNode operation,
Resource resource) throws OperationFailedException {
super.recordCapabilitiesAndRequirements(context, operation, resource);
context.deregisterCapability(JACC_CAPABILITY.getName());
}
})
.setCapabilities(SECURITY_SUBSYSTEM, SERVER_SECURITY_MANAGER, SUBJECT_FACTORY_CAP));
setDeprecated(SecurityExtension.DEPRECATED_SINCE);
}
@Override
public void registerAttributes(final ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerReadWriteAttribute(DEEP_COPY_SUBJECT_MODE, null, new ReloadRequiredWriteAttributeHandler(DEEP_COPY_SUBJECT_MODE));
resourceRegistration.registerReadWriteAttribute(INITIALIZE_JACC, null, new ReloadRequiredWriteAttributeHandler(INITIALIZE_JACC) {
@Override
protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<Void> voidHandback) throws OperationFailedException {
// As the PolicyConfigurationFactory is a singleton, once it's initialized any changes will require a restart
CapabilityServiceSupport capabilitySupport = context.getCapabilityServiceSupport();
final boolean elytronJacc = capabilitySupport.hasCapability("org.wildfly.security.jacc-policy");
if (resolvedValue.asBoolean() == true && elytronJacc) {
throw SecurityLogger.ROOT_LOGGER.unableToEnableJaccSupport();
}
return super.applyUpdateToRuntime(context, operation, attributeName, resolvedValue, currentValue, voidHandback);
}
@Override
protected void recordCapabilitiesAndRequirements(OperationContext context,
AttributeDefinition attributeDefinition,
ModelNode newValue,
ModelNode oldValue) {
super.recordCapabilitiesAndRequirements(context, attributeDefinition, newValue, oldValue);
boolean shouldRegister = resolveValue(context, attributeDefinition, newValue);
boolean registered = resolveValue(context, attributeDefinition, oldValue);
if (!shouldRegister) {
context.deregisterCapability(JACC_CAPABILITY.getName());
}
if (!registered && shouldRegister) {
context.registerCapability(JACC_CAPABILITY);
// do not register the JACC_CAPABILITY_TOMBSTONE at this point - it will be registered on restart
}
}
private boolean resolveValue(OperationContext context, AttributeDefinition attributeDefinition, ModelNode node) {
try {
return attributeDefinition.resolveValue(context, node).asBoolean();
} catch (OperationFailedException e) {
throw new IllegalStateException(e);
}
}
});
}
private static class SecuritySubsystemAdd extends AbstractBoottimeAddStepHandler {
public static final OperationStepHandler INSTANCE = new SecuritySubsystemAdd();
@Override
protected void populateModel(ModelNode operation, ModelNode model) throws OperationFailedException {
DEEP_COPY_SUBJECT_MODE.validateAndSet(operation, model);
INITIALIZE_JACC.validateAndSet(operation, model);
}
@Override
protected void recordCapabilitiesAndRequirements(OperationContext context, ModelNode operation, Resource resource)
throws OperationFailedException {
super.recordCapabilitiesAndRequirements(context, operation, resource);
if (INITIALIZE_JACC.resolveModelAttribute(context, resource.getModel()).asBoolean()) {
context.registerCapability(JACC_CAPABILITY);
// tombstone marks the Policy being initiated and should not be removed until restart
if (context.isBooting()) {
context.registerCapability(JACC_CAPABILITY_TOMBSTONE);
}
}
}
}
@Override
public void registerAdditionalRuntimePackages(ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerAdditionalRuntimePackages(RuntimePackageDependency.required("jakarta.security.auth.message.api"));
}
}
| 9,362
| 55.403614
| 237
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/ModuleFlag.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.security;
/**
* Enumeration of valid login module flags.
*
* @author Jason T. Greene
*/
enum ModuleFlag {
REQUIRED("required"),
REQUISITE("requisite"),
SUFFICIENT("sufficient"),
OPTIONAL("optional");
private final String name;
ModuleFlag(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
| 1,435
| 30.217391
| 70
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/Namespace.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.security;
import java.util.HashMap;
import java.util.Map;
/**
* An enumeration of the supported Security subsystem namespaces
*
* @author <a href="mailto:mmoyses@redhat.com">Marcus Moyses</a>
*/
public enum Namespace {
// must be first
UNKNOWN(null),
SECURITY_1_0("urn:jboss:domain:security:1.0"),
SECURITY_1_1("urn:jboss:domain:security:1.1"),
SECURITY_1_2("urn:jboss:domain:security:1.2"),
SECURITY_2_0("urn:jboss:domain:security:2.0");
/**
* The current namespace version.
*/
public static final Namespace CURRENT = SECURITY_2_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;
}
private static final Map<String, Namespace> MAP;
static {
final Map<String, Namespace> map = new HashMap<String, Namespace>();
for (Namespace namespace : values()) {
final String name = namespace.getUriString();
if (name != null) map.put(name, namespace);
}
MAP = map;
}
public static Namespace forUri(String uri) {
final Namespace element = MAP.get(uri);
return element == null ? UNKNOWN : element;
}
}
| 2,375
| 29.075949
| 76
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/SecuritySubsystemPersister.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.security;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CODE;
import static org.jboss.as.security.Constants.*;
import static org.jboss.as.security.elytron.ElytronIntegrationResourceDefinitions.APPLY_ROLE_MAPPERS;
import static org.jboss.as.security.elytron.ElytronIntegrationResourceDefinitions.LEGACY_JAAS_CONFIG;
import static org.jboss.as.security.elytron.ElytronIntegrationResourceDefinitions.LEGACY_JSSE_CONFIG;
import java.util.List;
import java.util.Set;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.persistence.SubsystemMarshallingContext;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.jboss.staxmapper.XMLElementWriter;
import org.jboss.staxmapper.XMLExtendedStreamWriter;
/**
* A {@link XMLElementWriter} that is responsible for writing the configuration of the legacy security subsystem. The
* subsystem is written according to the current (latest) version of the schema.
*
* @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a>
*/
class SecuritySubsystemPersister implements XMLElementWriter<SubsystemMarshallingContext> {
public static final SecuritySubsystemPersister INSTANCE = new SecuritySubsystemPersister();
protected SecuritySubsystemPersister() {
}
@Override
public void writeContent(XMLExtendedStreamWriter writer, SubsystemMarshallingContext context) throws XMLStreamException {
context.startSubsystemElement(Namespace.CURRENT.getUriString(), false);
ModelNode node = context.getModelNode();
if (SecuritySubsystemRootResourceDefinition.DEEP_COPY_SUBJECT_MODE.isMarshallable(node) ||
SecuritySubsystemRootResourceDefinition.INITIALIZE_JACC.isMarshallable(node)) {
writer.writeEmptyElement(Element.SECURITY_MANAGEMENT.getLocalName());
if (SecuritySubsystemRootResourceDefinition.DEEP_COPY_SUBJECT_MODE.isMarshallable(node)) {
SecuritySubsystemRootResourceDefinition.DEEP_COPY_SUBJECT_MODE.marshallAsAttribute(node, writer);
}
if (SecuritySubsystemRootResourceDefinition.INITIALIZE_JACC.isMarshallable(node)) {
SecuritySubsystemRootResourceDefinition.INITIALIZE_JACC.marshallAsAttribute(node, writer);
}
}
if (node.hasDefined(SECURITY_DOMAIN) && node.get(SECURITY_DOMAIN).asInt() > 0) {
writer.writeStartElement(Element.SECURITY_DOMAINS.getLocalName());
ModelNode securityDomains = node.get(SECURITY_DOMAIN);
for (String policy : securityDomains.keys()) {
writer.writeStartElement(Element.SECURITY_DOMAIN.getLocalName());
writer.writeAttribute(Attribute.NAME.getLocalName(), policy);
ModelNode policyDetails = securityDomains.get(policy);
SecurityDomainResourceDefinition.CACHE_TYPE.marshallAsAttribute(policyDetails, writer);
writeSecurityDomainContent(writer, policyDetails);
writer.writeEndElement();
}
writer.writeEndElement();
}
if (node.hasDefined(Constants.VAULT)) {
ModelNode vault = node.get(Constants.VAULT, Constants.CLASSIC);
writer.writeStartElement(Element.VAULT.getLocalName());
VaultResourceDefinition.CODE.marshallAsAttribute(vault, writer);
if (vault.hasDefined(Constants.VAULT_OPTIONS)) {
ModelNode properties = vault.get(Constants.VAULT_OPTIONS);
for (Property prop : properties.asPropertyList()) {
writer.writeEmptyElement(Element.VAULT_OPTION.getLocalName());
writer.writeAttribute(Attribute.NAME.getLocalName(), prop.getName());
writer.writeAttribute(Attribute.VALUE.getLocalName(), prop.getValue().asString());
}
}
writer.writeEndElement();
}
writeElytronIntegration(writer, node);
writer.writeEndElement();
}
private void writeSecurityDomainContent(XMLExtendedStreamWriter writer, ModelNode policyDetails) throws XMLStreamException {
Set<String> keys = policyDetails.keys();
keys.remove(NAME);
keys.remove(CACHE_TYPE);
for (String key : keys) {
Element element = Element.forName(key);
switch (element) {
case AUTHENTICATION: {
ModelNode kind = policyDetails.get(AUTHENTICATION);
for (Property prop : kind.asPropertyList()) {
if (CLASSIC.equals(prop.getName())) {
writeAuthentication(writer, prop.getValue());
} else if (JASPI.equals(prop.getName())) {
writeAuthenticationJaspi(writer, prop.getValue());
}
}
break;
}
case AUTHORIZATION: {
writeAuthorization(writer, policyDetails.get(AUTHORIZATION, CLASSIC));
break;
}
case ACL: {
writeACL(writer, policyDetails.get(ACL, CLASSIC));
break;
}
case AUDIT: {
writeAudit(writer, policyDetails.get(AUDIT, CLASSIC));
break;
}
case IDENTITY_TRUST: {
writeIdentityTrust(writer, policyDetails.get(IDENTITY_TRUST, CLASSIC));
break;
}
case MAPPING: {
writeMapping(writer, policyDetails.get(MAPPING, CLASSIC));
break;
}
case JSSE: {
writeJSSE(writer, policyDetails.get(JSSE, CLASSIC));
break;
}
}
}
}
private void writeAuthentication(XMLExtendedStreamWriter writer, ModelNode modelNode) throws XMLStreamException {
if (modelNode.isDefined() && modelNode.asInt() > 0) {
writer.writeStartElement(Element.AUTHENTICATION.getLocalName());
writeLoginModule(writer, modelNode, Constants.LOGIN_MODULE);
writer.writeEndElement();
}
}
private void writeAuthorization(XMLExtendedStreamWriter writer, ModelNode modelNode) throws XMLStreamException {
if (modelNode.isDefined() && modelNode.asInt() > 0) {
writer.writeStartElement(Element.AUTHORIZATION.getLocalName());
writeLoginModule(writer, modelNode, Constants.POLICY_MODULE, Element.POLICY_MODULE.getLocalName());
writer.writeEndElement();
}
}
private void writeACL(XMLExtendedStreamWriter writer, ModelNode modelNode) throws XMLStreamException {
if (modelNode.isDefined() && modelNode.asInt() > 0) {
writer.writeStartElement(Element.ACL.getLocalName());
writeLoginModule(writer, modelNode, Constants.ACL_MODULE, Element.ACL_MODULE.getLocalName());
writer.writeEndElement();
}
}
private void writeAudit(XMLExtendedStreamWriter writer, ModelNode modelNode) throws XMLStreamException {
if (modelNode.isDefined() && modelNode.asInt() > 0) {
writer.writeStartElement(Element.AUDIT.getLocalName());
writeLoginModule(writer, modelNode, Constants.PROVIDER_MODULE, Element.PROVIDER_MODULE.getLocalName());
writer.writeEndElement();
}
}
private void writeIdentityTrust(XMLExtendedStreamWriter writer, ModelNode modelNode) throws XMLStreamException {
if (modelNode.isDefined() && modelNode.asInt() > 0) {
writer.writeStartElement(Element.IDENTITY_TRUST.getLocalName());
writeLoginModule(writer, modelNode, Constants.TRUST_MODULE, Element.TRUST_MODULE.getLocalName());
writer.writeEndElement();
}
}
private void writeMapping(XMLExtendedStreamWriter writer, ModelNode modelNode) throws XMLStreamException {
if (modelNode.isDefined() && modelNode.asInt() > 0) {
writer.writeStartElement(Element.MAPPING.getLocalName());
writeLoginModule(writer, modelNode, Constants.MAPPING_MODULE, Constants.MAPPING_MODULE);
writer.writeEndElement();
}
}
private void writeAuthenticationJaspi(XMLExtendedStreamWriter writer, ModelNode modelNode) throws XMLStreamException {
if (modelNode.isDefined() && modelNode.asInt() > 0) {
writer.writeStartElement(Element.AUTHENTICATION_JASPI.getLocalName());
ModelNode moduleStack = modelNode.get(LOGIN_MODULE_STACK);
writeLoginModuleStack(writer, moduleStack);
writeLoginModule(writer, modelNode, Constants.AUTH_MODULE, Element.AUTH_MODULE.getLocalName());
writer.writeEndElement();
}
}
private void writeLoginModuleStack(XMLExtendedStreamWriter writer, ModelNode modelNode) throws XMLStreamException {
if (modelNode.isDefined() && modelNode.asInt() > 0) {
List<Property> stacks = modelNode.asPropertyList();
for (Property stack : stacks) {
writer.writeStartElement(Element.LOGIN_MODULE_STACK.getLocalName());
writer.writeAttribute(Attribute.NAME.getLocalName(), stack.getName());
writeLoginModule(writer, stack.getValue(), Constants.LOGIN_MODULE);
writer.writeEndElement();
}
}
}
private void writeLoginModule(XMLExtendedStreamWriter writer, ModelNode modelNode, String key) throws XMLStreamException {
writeLoginModule(writer, modelNode, key, Element.LOGIN_MODULE.getLocalName());
}
private void writeLoginModule(XMLExtendedStreamWriter writer, ModelNode modelNode, String key, final String elementName) throws XMLStreamException {
if (!modelNode.hasDefined(key)){
return;
}
final ModelNode modules = modelNode.get(key);
for (Property moduleProp : modules.asPropertyList()) {
ModelNode module = moduleProp.getValue();
writer.writeStartElement(elementName);
if (!moduleProp.getName().equals(module.get(CODE).asString())) {
writer.writeAttribute(NAME, moduleProp.getName());
}
LoginModuleResourceDefinition.CODE.marshallAsAttribute(module, writer);
LoginModuleResourceDefinition.FLAG.marshallAsAttribute(module, writer);
MappingModuleDefinition.TYPE.marshallAsAttribute(module, writer);
JASPIMappingModuleDefinition.LOGIN_MODULE_STACK_REF.marshallAsAttribute(module, writer);
LoginModuleResourceDefinition.MODULE.marshallAsAttribute(module, false, writer);
if (module.hasDefined(Constants.MODULE_OPTIONS)) {
for (ModelNode option : module.get(Constants.MODULE_OPTIONS).asList()) {
writer.writeEmptyElement(Element.MODULE_OPTION.getLocalName());
writer.writeAttribute(Attribute.NAME.getLocalName(), option.asProperty().getName());
writer.writeAttribute(Attribute.VALUE.getLocalName(), option.asProperty().getValue().asString());
}
}
writer.writeEndElement();
}
}
private void writeJSSE(XMLExtendedStreamWriter writer, ModelNode modelNode) throws XMLStreamException {
if (modelNode.isDefined() && modelNode.asInt() > 0) {
writer.writeStartElement(Element.JSSE.getLocalName());
JSSEResourceDefinition.KEYSTORE.marshallAsAttribute(modelNode, false, writer);
JSSEResourceDefinition.TRUSTSTORE.marshallAsAttribute(modelNode, false, writer);
JSSEResourceDefinition.KEYMANAGER.marshallAsAttribute(modelNode, false, writer);
JSSEResourceDefinition.TRUSTMANAGER.marshallAsAttribute(modelNode, false, writer);
JSSEResourceDefinition.CIPHER_SUITES.marshallAsAttribute(modelNode, false, writer);
JSSEResourceDefinition.SERVER_ALIAS.marshallAsAttribute(modelNode, false, writer);
JSSEResourceDefinition.SERVICE_AUTH_TOKEN.marshallAsAttribute(modelNode, false, writer);
JSSEResourceDefinition.CLIENT_ALIAS.marshallAsAttribute(modelNode, false, writer);
JSSEResourceDefinition.CLIENT_AUTH.marshallAsAttribute(modelNode, false, writer);
JSSEResourceDefinition.PROTOCOLS.marshallAsAttribute(modelNode, false, writer);
JSSEResourceDefinition.ADDITIONAL_PROPERTIES.marshallAsElement(modelNode, writer);
writer.writeEndElement();
}
}
private void writeElytronIntegration(final XMLExtendedStreamWriter writer, final ModelNode modelNode) throws XMLStreamException {
boolean integrationStarted = false;
integrationStarted = integrationStarted | writeSecurityRealms(writer, modelNode, integrationStarted);
integrationStarted = integrationStarted | writeTLS(writer, modelNode, integrationStarted);
if (integrationStarted) {
writer.writeEndElement();
}
}
private boolean writeSecurityRealms(final XMLExtendedStreamWriter writer, final ModelNode modelNode,
final boolean integrationStarted) throws XMLStreamException {
if (modelNode.hasDefined(ELYTRON_REALM)) {
if (integrationStarted == false) {
writer.writeStartElement(ELYTRON_INTEGRATION);
}
writer.writeStartElement(SECURITY_REALMS);
ModelNode elytronRealms = modelNode.require(ELYTRON_REALM);
for (String realmName : elytronRealms.keys()) {
writer.writeStartElement(ELYTRON_REALM);
writer.writeAttribute(NAME, realmName);
LEGACY_JAAS_CONFIG.marshallAsAttribute(elytronRealms.require(realmName), writer);
APPLY_ROLE_MAPPERS.marshallAsAttribute(elytronRealms.require(realmName), false, writer);
writer.writeEndElement();
}
writer.writeEndElement();
return true;
}
return false;
}
private boolean writeTLS(final XMLExtendedStreamWriter writer, final ModelNode modelNode,
final boolean integrationStarted) throws XMLStreamException {
if (modelNode.hasDefined(ELYTRON_KEY_STORE) || modelNode.hasDefined(ELYTRON_TRUST_STORE) ||
modelNode.hasDefined(ELYTRON_KEY_MANAGER) || modelNode.hasDefined(ELYTRON_TRUST_MANAGER)) {
if (integrationStarted == false) {
writer.writeStartElement(ELYTRON_INTEGRATION);
}
writer.writeStartElement(TLS);
writeTLSEntity(writer, modelNode, ELYTRON_KEY_STORE);
writeTLSEntity(writer, modelNode, ELYTRON_TRUST_STORE);
writeTLSEntity(writer, modelNode, ELYTRON_KEY_MANAGER);
writeTLSEntity(writer, modelNode, ELYTRON_TRUST_MANAGER);
writer.writeEndElement();
return true;
}
return false;
}
private void writeTLSEntity(final XMLExtendedStreamWriter writer, final ModelNode modelNode,
final String tlsEntityName) throws XMLStreamException {
if (modelNode.hasDefined(tlsEntityName)) {
ModelNode tlsEntities = modelNode.require(tlsEntityName);
for (String entityName : tlsEntities.keys()) {
writer.writeStartElement(tlsEntityName);
writer.writeAttribute(NAME, entityName);
LEGACY_JSSE_CONFIG.marshallAsAttribute(tlsEntities.require(entityName), writer);
writer.writeEndElement();
}
}
}
}
| 16,406
| 49.021341
| 152
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/SecurityTransformers.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.security;
import static org.jboss.as.security.Constants.MODULE;
import static org.jboss.as.security.Constants.ORG_PICKETBOX;
import static org.jboss.as.security.MappingProviderModuleDefinition.PATH_PROVIDER_MODULE;
import static org.jboss.as.security.SecuritySubsystemRootResourceDefinition.INITIALIZE_JACC;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.transform.ExtensionTransformerRegistration;
import org.jboss.as.controller.transform.SubsystemTransformerRegistration;
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.TransformationDescription;
import org.jboss.dmr.ModelNode;
/**
* @author Tomaz Cerar (c) 2017 Red Hat Inc.
*/
public class SecurityTransformers implements ExtensionTransformerRegistration {
@Override
public String getSubsystemName() {
return SecurityExtension.SUBSYSTEM_NAME;
}
@Override
public void registerTransformers(SubsystemTransformerRegistration subsystemRegistration) {
// only register transformers for model version 1.3.0 (EAP 6.2+).
registerTransformers_1_3_0(subsystemRegistration);
}
private void registerTransformers_1_3_0(SubsystemTransformerRegistration subsystemRegistration) {
ResourceTransformationDescriptionBuilder builder = ResourceTransformationDescriptionBuilder.Factory.createSubsystemInstance();
builder.rejectChildResource(PathElement.pathElement(Constants.ELYTRON_REALM));
builder.rejectChildResource(PathElement.pathElement(Constants.ELYTRON_KEY_STORE));
builder.rejectChildResource(PathElement.pathElement(Constants.ELYTRON_TRUST_STORE));
builder.rejectChildResource(PathElement.pathElement(Constants.ELYTRON_KEY_MANAGER));
builder.rejectChildResource(PathElement.pathElement(Constants.ELYTRON_TRUST_MANAGER));
builder.getAttributeBuilder()
.setDiscard(DiscardAttributeChecker.DEFAULT_VALUE, INITIALIZE_JACC)
.addRejectCheck(RejectAttributeChecker.DEFINED, INITIALIZE_JACC);
builder
.addChildResource(SecurityExtension.SECURITY_DOMAIN_PATH)
.addChildResource(SecurityExtension.PATH_AUDIT_CLASSIC)
.addChildResource(PATH_PROVIDER_MODULE)
.getAttributeBuilder()
.setDiscard(new DiscardAttributeChecker.DiscardAttributeValueChecker(new ModelNode(ORG_PICKETBOX)), MODULE)
.addRejectCheck(RejectAttributeChecker.DEFINED, MODULE).end();
TransformationDescription.Tools.register(builder.build(), subsystemRegistration, ModelVersion.create(1, 3, 0));
}
}
| 3,947
| 49.615385
| 134
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/LoginModuleStackResourceDefinition.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.security;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.ListAttributeDefinition;
import org.jboss.as.controller.ModelOnlyRemoveStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
/**
* @author Jason T. Greene
*/
class LoginModuleStackResourceDefinition extends SimpleResourceDefinition {
static final LoginModuleStackResourceDefinition INSTANCE = new LoginModuleStackResourceDefinition();
static final ListAttributeDefinition LOGIN_MODULES = new LegacySupport.LoginModulesAttributeDefinition(Constants.LOGIN_MODULES, Constants.LOGIN_MODULE);
private static final OperationStepHandler LEGACY_ADD_HANDLER = new LegacySupport.LegacyModulesConverter(Constants.LOGIN_MODULE, LOGIN_MODULES);
private LoginModuleStackResourceDefinition() {
super(SecurityExtension.PATH_LOGIN_MODULE_STACK,
SecurityExtension.getResourceDescriptionResolver(Constants.LOGIN_MODULE_STACK),
new LoginModuleStackResourceDefinitionAdd(), ModelOnlyRemoveStepHandler.INSTANCE);
}
@Override
public void registerAttributes(final ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerReadWriteAttribute(LOGIN_MODULES, new LegacySupport.LegacyModulesAttributeReader(Constants.LOGIN_MODULE), new LegacySupport.LegacyModulesAttributeWriter(Constants.LOGIN_MODULE));
}
@Override
public void registerChildren(ManagementResourceRegistration resourceRegistration) {
super.registerChildren(resourceRegistration);
resourceRegistration.registerSubModel(new LoginModuleResourceDefinition(Constants.LOGIN_MODULE));
}
static class LoginModuleStackResourceDefinitionAdd extends AbstractAddStepHandler {
@Override
protected void populateModel(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException {
if (operation.hasDefined(LOGIN_MODULES.getName())) {
context.addStep(new ModelNode(), operation, LEGACY_ADD_HANDLER, OperationContext.Stage.MODEL, true);
}
}
}
}
| 3,490
| 47.486111
| 215
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/SecurityDomainResourceDefinition.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.security;
import java.util.Arrays;
import java.util.List;
import org.jboss.as.controller.ModelOnlyRemoveStepHandler;
import org.jboss.as.controller.ModelOnlyWriteAttributeHandler;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.access.constraint.ApplicationTypeConfig;
import org.jboss.as.controller.access.management.AccessConstraintDefinition;
import org.jboss.as.controller.access.management.ApplicationTypeAccessConstraintDefinition;
import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.operations.validation.StringAllowedValuesValidator;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelType;
/**
* @author Jason T. Greene
*/
class SecurityDomainResourceDefinition extends SimpleResourceDefinition {
static final String CACHE_CONTAINER_BASE_CAPABILTIY = "org.wildfly.clustering.infinispan.cache-container";
static final String CACHE_CONTAINER_NAME = "security";
static final String INFINISPAN_CACHE_TYPE = "infinispan";
static final RuntimeCapability<Void> LEGACY_SECURITY_DOMAIN = RuntimeCapability.Builder.of("org.wildfly.security.legacy-security-domain", true)
.build();
public static final SimpleAttributeDefinition CACHE_TYPE = new SimpleAttributeDefinitionBuilder(Constants.CACHE_TYPE, ModelType.STRING, true)
.setAllowExpression(true)
.setValidator(new StringAllowedValuesValidator("default", INFINISPAN_CACHE_TYPE))
.build();
private final List<AccessConstraintDefinition> accessConstraints;
SecurityDomainResourceDefinition() {
super(new Parameters(SecurityExtension.SECURITY_DOMAIN_PATH,
SecurityExtension.getResourceDescriptionResolver(Constants.SECURITY_DOMAIN))
.setAddHandler(SecurityDomainAdd.INSTANCE)
.setRemoveHandler(ModelOnlyRemoveStepHandler.INSTANCE)
.setCapabilities(LEGACY_SECURITY_DOMAIN));
ApplicationTypeConfig atc = new ApplicationTypeConfig(SecurityExtension.SUBSYSTEM_NAME, Constants.SECURITY_DOMAIN);
AccessConstraintDefinition acd = new ApplicationTypeAccessConstraintDefinition(atc);
this.accessConstraints = Arrays.asList(SensitiveTargetAccessConstraintDefinition.SECURITY_DOMAIN, acd);
setDeprecated(SecurityExtension.DEPRECATED_SINCE);
}
@Override
public void registerAttributes(final ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerReadWriteAttribute(CACHE_TYPE, null, new ModelOnlyWriteAttributeHandler(CACHE_TYPE));
}
@Override
public List<AccessConstraintDefinition> getAccessConstraints() {
return accessConstraints;
}
}
| 4,026
| 48.109756
| 147
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/elytron/BasicResourceDefinition.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.security.elytron;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.RestartParentWriteAttributeHandler;
import org.jboss.as.controller.ServiceRemoveStepHandler;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.access.constraint.ApplicationTypeConfig;
import org.jboss.as.controller.access.constraint.SensitivityClassification;
import org.jboss.as.controller.access.management.ApplicationTypeAccessConstraintDefinition;
import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.descriptions.ResourceDescriptionResolver;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.OperationEntry;
import org.jboss.as.security.Constants;
import org.jboss.as.security.SecurityExtension;
import org.jboss.msc.service.ServiceName;
/**
* This {@link SimpleResourceDefinition} implementation contains code that is common to all elytron integration resources.
*
* @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a>
*/
class BasicResourceDefinition extends SimpleResourceDefinition {
private final String pathKey;
private final RuntimeCapability<?> firstCapability;
private final AttributeDefinition[] attributes;
BasicResourceDefinition(String pathKey, ResourceDescriptionResolver resourceDescriptionResolver, AbstractAddStepHandler add, AttributeDefinition[] attributes, RuntimeCapability<?>... runtimeCapabilities) {
super(new Parameters(PathElement.pathElement(pathKey),
resourceDescriptionResolver)
.setAddHandler(add)
.setRemoveHandler(new ServiceRemoveStepHandler(add))
.setAddRestartLevel(OperationEntry.Flag.RESTART_RESOURCE_SERVICES)
.setRemoveRestartLevel(OperationEntry.Flag.RESTART_RESOURCE_SERVICES)
.setCapabilities(runtimeCapabilities)
.addAccessConstraints(new SensitiveTargetAccessConstraintDefinition(new SensitivityClassification(SecurityExtension.SUBSYSTEM_NAME, Constants.ELYTRON_SECURITY, true, true, true)),
new ApplicationTypeAccessConstraintDefinition(new ApplicationTypeConfig(SecurityExtension.SUBSYSTEM_NAME, Constants.ELYTRON_SECURITY, false))));
this.pathKey = pathKey;
this.firstCapability = runtimeCapabilities[0];
this.attributes = attributes;
}
BasicResourceDefinition(String pathKey, AbstractAddStepHandler add, AttributeDefinition[] attributes, RuntimeCapability<?> ... runtimeCapabilities) {
this(pathKey, SecurityExtension.getResourceDescriptionResolver(pathKey), add, attributes, runtimeCapabilities);
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
if (attributes != null && attributes.length > 0) {
WriteAttributeHandler write = new WriteAttributeHandler(pathKey, attributes);
for (AttributeDefinition current : attributes) {
resourceRegistration.registerReadWriteAttribute(current, null, write);
}
}
}
private class WriteAttributeHandler extends RestartParentWriteAttributeHandler {
WriteAttributeHandler(String parentName, AttributeDefinition ... attributes) {
super(parentName, attributes);
}
@Override
protected ServiceName getParentServiceName(PathAddress pathAddress) {
return firstCapability.fromBaseCapability(pathAddress.getLastElement().getValue()).getCapabilityServiceName();
}
}
}
| 4,464
| 48.065934
| 209
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/elytron/ElytronIntegrationResourceDefinitions.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.security.elytron;
import static org.jboss.as.security.elytron.Capabilities.KEY_MANAGER_RUNTIME_CAPABILITY;
import static org.jboss.as.security.elytron.Capabilities.KEY_STORE_RUNTIME_CAPABILITY;
import static org.jboss.as.security.elytron.Capabilities.SECURITY_REALM_RUNTIME_CAPABILITY;
import static org.jboss.as.security.elytron.Capabilities.TRUST_MANAGER_RUNTIME_CAPABILITY;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.ModelOnlyAddStepHandler;
import org.jboss.as.controller.ResourceDefinition;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition;
import org.jboss.as.controller.operations.validation.StringLengthValidator;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.security.Constants;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
/**
* This class defines methods used to obtain {@link ResourceDefinition} instances for the various components of the elytron
* integration.
*
* @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a>
*/
public class ElytronIntegrationResourceDefinitions {
public static final SimpleAttributeDefinition LEGACY_JAAS_CONFIG =
new SimpleAttributeDefinitionBuilder(Constants.LEGACY_JAAS_CONFIG, ModelType.STRING, false)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.setValidator(new StringLengthValidator(1))
.setAllowExpression(false)
.setAccessConstraints(SensitiveTargetAccessConstraintDefinition.SECURITY_DOMAIN_REF)
.build();
public static final SimpleAttributeDefinition LEGACY_JSSE_CONFIG =
new SimpleAttributeDefinitionBuilder(Constants.LEGACY_JSSE_CONFIG, ModelType.STRING, false)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.setValidator(new StringLengthValidator(1))
.setAllowExpression(false)
.setAccessConstraints(SensitiveTargetAccessConstraintDefinition.SECURITY_DOMAIN_REF)
.build();
public static final SimpleAttributeDefinition APPLY_ROLE_MAPPERS =
new SimpleAttributeDefinitionBuilder(Constants.APPLY_ROLE_MAPPERS, ModelType.BOOLEAN, true)
.setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.setDefaultValue(ModelNode.TRUE)
.setAllowExpression(true)
.build();
/**
* Defines a resource that represents an Elytron-compatible realm that can be exported by the legacy security subsystem.
* The constructed {@code SecurityRealm} wraps a legacy {@code SecurityDomainContext} and delegates authentication
* decisions to that context.
*
* To export the realm the resource uses a {@code BasicAddHandler} implementation that registers the security-realm
* capability and implements a {@code org.jboss.as.security.elytron.BasicService.ValueSupplier} that uses the injected
* {@code SecurityDomainContext} to create and return an instance of {@code SecurityDomainContextRealm}.
*/
public static ResourceDefinition getElytronRealmResourceDefinition() {
final AttributeDefinition[] attributes = new AttributeDefinition[] {LEGACY_JAAS_CONFIG, APPLY_ROLE_MAPPERS};
final AbstractAddStepHandler addHandler = new ModelOnlyAddStepHandler(attributes);
return new BasicResourceDefinition(Constants.ELYTRON_REALM, addHandler, attributes, SECURITY_REALM_RUNTIME_CAPABILITY);
}
/**
* Defines a resource that represents an Elytron-compatible key store that can be exported by a JSSE-enabled domain
* in the legacy security subsystem.
*
* To export the key store the resource uses a {@code BasicAddHandler} implementation that registers the elytron key-store
* capability and implements a {@code org.jboss.as.security.elytron.BasicService.ValueSupplier} that uses the injected
* {@code SecurityDomainContext} to obtain a {@code JSSESecurityDomain}. If such domain is found, its configured key
* store is obtained and returned.
*
* The {@code ValueSupplier} implementation throws an exception if the referenced legacy domain is not a JSSE-enabled
* domain or if the domain doesn't contain a key store configuration.
*/
public static ResourceDefinition getElytronKeyStoreResourceDefinition() {
final AttributeDefinition[] attributes = new AttributeDefinition[] {LEGACY_JSSE_CONFIG};
final AbstractAddStepHandler addHandler = new ModelOnlyAddStepHandler(attributes);
return new BasicResourceDefinition(Constants.ELYTRON_KEY_STORE, addHandler, attributes, KEY_STORE_RUNTIME_CAPABILITY);
}
/**
* Defines a resource that represents an Elytron-compatible trust store that will be exported by a JSSE-enabled domain
* in the legacy security subsystem.
*
* To export the trust store the resource uses a {@code BasicAddHandler} implementation that registers the elytron key-store
* capability and implements a {@code org.jboss.as.security.elytron.BasicService.ValueSupplier} that uses the injected
* {@code SecurityDomainContext} to obtain a {@code JSSESecurityDomain}. If such domain is found, its configured trust
* store is obtained and returned.
*
* NOTE 1: In the Elytron subsystem, both key stores and trust stores are registered using the same capability. This
* means that the name of the trust store must be unique across all configured trust stores and key stores. If a trust
* store resource is registered with the same name of a key store resource, an error will occur.
*
* The {@code ValueSupplier} implementation throws an exception if the referenced legacy domain is not a JSSE-enabled
* domain or if the domain doesn't contain a trust store configuration.
*
* NOTE 2: The {@code PicketBox} implementation of a {@code JSSESecurityDomain} returns a reference to the key store if
* a trust store was not configured. So extra care must be taken when that implementation is used (default) as the code
* will silently export the key store as a trust store instead of throwing an exception to alert about a missing trust
* store configuration in the legacy JSSE-enabled domain.
*/
public static ResourceDefinition getElytronTrustStoreResourceDefinition() {
final AttributeDefinition[] attributes = new AttributeDefinition[] {LEGACY_JSSE_CONFIG};
final AbstractAddStepHandler addHandler = new ModelOnlyAddStepHandler(attributes);
return new BasicResourceDefinition(Constants.ELYTRON_TRUST_STORE, addHandler, attributes, KEY_STORE_RUNTIME_CAPABILITY);
}
/**
* Defines a resource that represents Elytron-compatible key managers that can be exported by a JSSE-enabled domain
* in the legacy security subsystem.
*
* To export the key managers the resource uses a {@code BasicAddHandler} implementation that registers the elytron
* key-managers capability and implements a {@code org.jboss.as.security.elytron.BasicService.ValueSupplier} that uses
* the injected {@code SecurityDomainContext} to obtain a {@code JSSESecurityDomain}. If such domain is found, its
* configured key manager array is obtained and returned.
*
* The {@code ValueSupplier} implementation throws an exception if the referenced legacy domain is not a JSSE-enabled
* domain or if the domain doesn't contain a key store configuration that can be used to build the key managers.
*/
public static ResourceDefinition getElytronKeyManagersResourceDefinition() {
final AttributeDefinition[] attributes = new AttributeDefinition[] {LEGACY_JSSE_CONFIG};
final AbstractAddStepHandler addHandler = new ModelOnlyAddStepHandler(attributes);
return new BasicResourceDefinition(Constants.ELYTRON_KEY_MANAGER, addHandler, attributes, KEY_MANAGER_RUNTIME_CAPABILITY);
}
/**
* Defines a resource that represents Elytron-compatible trust managers that can be exported by a JSSE-enabled domain
* in the legacy security subsystem.
*
* To export the trust managers the resource uses a {@code BasicAddHandler} implementation that registers the elytron
* trust-managers capability and implements a {@code org.jboss.as.security.elytron.BasicService.ValueSupplier} that uses
* the injected {@code SecurityDomainContext} to obtain a {@code JSSESecurityDomain}. If such domain is found, its
* configured trust manager array is obtained and returned.
*
* The {@code ValueSupplier} implementation throws an exception if the referenced legacy domain is not a JSSE-enabled
* domain or if the domain doesn't contain a trust store configuration that can be used to build the trust managers.
*
* NOTE: The {@code PicketBox} implementation of a {@code JSSESecurityDomain} returns a reference to the key store if
* a trust store was not configured. This means that the trust managers that it builds will use the configured key store
* instead of throwing an exception to alert about a missing trust store configuration. So extra care must be taken
* to ensure that the exported trust managers are being built using the correct trust stores.
*/
public static ResourceDefinition getElytronTrustManagersResourceDefinition() {
final AttributeDefinition[] attributes = new AttributeDefinition[] {LEGACY_JSSE_CONFIG};
final AbstractAddStepHandler addHandler = new ModelOnlyAddStepHandler(attributes);
return new BasicResourceDefinition(Constants.ELYTRON_TRUST_MANAGER, addHandler, attributes, TRUST_MANAGER_RUNTIME_CAPABILITY);
}
}
| 10,606
| 59.95977
| 134
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/elytron/Capabilities.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.security.elytron;
import java.security.KeyStore;
import javax.net.ssl.KeyManager;
import javax.net.ssl.TrustManager;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.wildfly.security.auth.server.SecurityRealm;
/**
* Capabilies for the elytron integration section of the legacy security subsystem.
*
* @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a>
*/
class Capabilities {
private static final String CAPABILITY_BASE = "org.wildfly.security.";
static final String KEY_STORE_CAPABILITY = CAPABILITY_BASE + "key-store";
static final RuntimeCapability<Void> KEY_STORE_RUNTIME_CAPABILITY = RuntimeCapability
.Builder.of(KEY_STORE_CAPABILITY, true, KeyStore.class)
.build();
static final String KEY_MANAGER_CAPABILITY = CAPABILITY_BASE + "key-manager";
static final RuntimeCapability<Void> KEY_MANAGER_RUNTIME_CAPABILITY = RuntimeCapability
.Builder.of(KEY_MANAGER_CAPABILITY, true, KeyManager.class)
.build();
static final String SECURITY_REALM_CAPABILITY = CAPABILITY_BASE + "security-realm";
static final RuntimeCapability<Void> SECURITY_REALM_RUNTIME_CAPABILITY = RuntimeCapability
.Builder.of(SECURITY_REALM_CAPABILITY, true, SecurityRealm.class)
.build();
static final String TRUST_MANAGER_CAPABILITY = CAPABILITY_BASE + "trust-manager";
static final RuntimeCapability<Void> TRUST_MANAGER_RUNTIME_CAPABILITY = RuntimeCapability
.Builder.of(TRUST_MANAGER_CAPABILITY, true, TrustManager.class)
.build();
}
| 2,214
| 35.916667
| 94
|
java
|
null |
wildfly-main/security/subsystem/src/main/java/org/jboss/as/security/logging/SecurityLogger.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.security.logging;
import javax.xml.stream.Location;
import javax.xml.stream.XMLStreamException;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
import org.jboss.logging.annotations.Param;
/**
* Date: 05.11.2011
*
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@MessageLogger(projectCode = "WFLYSEC", length = 4)
public interface SecurityLogger extends BasicLogger {
/**
* A logger with a category of the package name.
*/
SecurityLogger ROOT_LOGGER = Logger.getMessageLogger(SecurityLogger.class, "org.jboss.as.security");
// /** Logs a message indicating the current version of the PicketBox library
// *
// * @param version a {@link String} representing the current version
// */
// @LogMessage(level = Level.INFO)
// @Message(id = 1, value = "Current PicketBox version=%s")
// void currentVersion(String version);
//
// /**
// * Logs a message indicating that the security subsystem is being activated
// */
// @LogMessage(level = Level.INFO)
// @Message(id = 2, value = "Activating Security Subsystem")
// void activatingSecuritySubsystem();
// /**
// * Logs a message indicating that there was an exception while trying to delete the Jakarta Authorization Policy
// * @param t the underlying exception
// */
// @LogMessage(level = Level.WARN)
// @Message(id = 3, value = "Error deleting Jakarta Authorization Policy")
// void errorDeletingJACCPolicy(@Cause Throwable t);
// /**
// * Creates an exception indicating the inability to get the {@link org.jboss.modules.ModuleClassLoader}
// *
// * @return an {@link IllegalStateException} for the error.
// */
// @Message(id = 4, value = "Unable to get the Module Class Loader")
// IllegalStateException unableToGetModuleClassLoader(@Cause Throwable e);
//
// /**
// * Creates an exception indicating that the operation is not supported
// *
// * @return an {@link javax.naming.OperationNotSupportedException} for the error.
// */
// @Message(id = 5, value = "Operation not supported : %s")
// OperationNotSupportedException operationNotSupported(Method method);
//
// /**
// * Creates an exception indicating that the module name was missing
// * @param name the missing module name
// * @return {@link IllegalArgumentException}
// */
// @Message(id = 6, value = "Missing module name for the %s")
// IllegalArgumentException missingModuleName(String name);
/**
* Creates a {@link RuntimeException}
* @param e the underlying exception
* @return the exception
*/
@Message(id = 7, value = "Runtime Exception:")
RuntimeException runtimeException(@Cause Throwable e);
// /**
// * Creates a {@link org.jboss.modules.ModuleLoadException}
// * @param e the underlying exception
// * @return
// */
// @Message(id = 8, value = "Module Load Exception:")
// ModuleLoadException moduleLoadException(@Cause Throwable e);
// /**
// * Creates an exception indicating that the name passed to jndi is null or empty
// * @return {@link javax.naming.InvalidNameException}
// */
// @Message(id = 9, value = "Name cannot be null or empty")
// InvalidNameException nullName();
// /**
// * Create a {@link javax.security.auth.login.LoginException} to indicate that there was no User Principal even though
// * a remoting connection existed
// * @return {@link javax.security.auth.login.LoginException}
// */
// @Message(id = 10, value = "Remoting connection found but no UserPrincipal.")
// LoginException remotingConnectionWithNoUserPrincipal();
// /**
// * Create a {@link IllegalArgumentException} when a null argument is passed
// * @param arg an argument that is null
// * @return {@link IllegalArgumentException}
// */
// @Message(id = 11, value = "Argument %s is null")
// IllegalArgumentException nullArgument(String arg);
// /**
// * Create a {@link org.jboss.msc.service.StartException} to indicate that a service could not be started
// * @param service the name of the service
// * @param t underlying exception
// * @return {@link org.jboss.msc.service.StartException}
// */
// @Message(id = 12, value = "Unable to start the %s service")
// StartException unableToStartException(String service, @Cause Throwable t);
// /**
// * Create a {@link ClassNotFoundException} to indicate that a class could not be found
// * @param name name of the class
// * @return {@link ClassNotFoundException}
// */
// @Message(id = 13, value = "Class not found : %s")
// ClassNotFoundException cnfe(String name);
// /**
// * Create a {@link ClassNotFoundException} to indicate that a class could not be found
// * @param name name of the class
// * @param t underlying exception
// * @return {@link ClassNotFoundException}
// */
// @Message(id = 14, value = "Class not found : %s")
// ClassNotFoundException cnfeThrow(String name, @Cause Throwable t);
/**
* Create a {@link SecurityException}
* @param t underlying exception
* @return {@link SecurityException}
*/
@Message(id = 15, value = "Security Exception")
SecurityException securityException(@Cause Throwable t);
// /**
// * Create a {@link SecurityException}
// * @param msg message that is passed in creating the exception
// * @return {@link SecurityException}
// */
// @Message(id = 16, value = "Security Exception: %s")
// SecurityException securityException(String msg);
// /**
// * Create a {@link org.jboss.as.server.services.security.VaultReaderException} to indicate there was an exception while reading from the vault
// * @param t underlying exception
// * @return {@link org.jboss.as.server.services.security.VaultReaderException}
// */
// @Message(id = 17, value = "Vault Reader Exception:")
// VaultReaderException vaultReaderException(@Cause Throwable t);
/**
* Exception indicates that the method being used indicates a misuse of this class
*
* @return {@link UnsupportedOperationException}
*/
@Message(id = 18, value = "Use the ResourceDescriptionResolver variant")
UnsupportedOperationException unsupportedOperationExceptionUseResourceDesc();
/**
* Create a {@link UnsupportedOperationException} to indicate that the intended operation is not supported
* @return {@link UnsupportedOperationException}
*/
@Message(id = 19, value = "Unsupported Operation")
UnsupportedOperationException unsupportedOperation();
// /**
// * Create a {@link IllegalArgumentException} to indicate an argument to a method was illegal
// * @param str string message to the exception
// * @return {@link IllegalArgumentException}
// */
// @Message(id = 20, value = "Illegal Argument:%s")
// IllegalArgumentException illegalArgument(String str);
//
// /**
// * Create a {@link javax.xml.stream.XMLStreamException} indicating a failure during the stax parsing
// * @param msg failure description
// * @param loc current location of the stax parser
// * @return {@link javax.xml.stream.XMLStreamException}
// */
// @Message(id = 21, value = "Illegal Argument:%s")
// XMLStreamException xmlStreamException(String msg, @Param Location loc);
/**
* Create a {@link XMLStreamException} to indicate that the security domain configuration cannot have both JAAS and JASPI config
* @param loc the current location of the stax parser
* @return {@link XMLStreamException}
*/
@Message(id = 22, value = "A security domain can have either an <authentication> or <authentication-jaspi> element, not both")
XMLStreamException xmlStreamExceptionAuth(@Param Location loc);
/**
* Creates a {@link XMLStreamException} to indicate a missing required attribute
* @param a the first attribute
* @param b the second attribute
* @param loc the current location of the stax parser
* @return {@link XMLStreamException}
*/
@Message(id = 23, value = "Missing required attribute: either %s or %s must be present")
XMLStreamException xmlStreamExceptionMissingAttribute(String a, String b, @Param Location loc);
// /**
// * Create a {@link IllegalArgumentException} to indicate that the auth-module references a login module stack that does not exist
// * @param str login module stack name
// * @return {@link IllegalArgumentException}
// */
// @Message(id = 24, value = "auth-module references a login module stack that doesn't exist::%s")
// IllegalArgumentException loginModuleStackIllegalArgument(String str);
//
// /**
// * Create a {@link IllegalArgumentException} when the path address does not contain a security domain name
// * @return {@link IllegalArgumentException}
// */
// @Message(id = 25, value = "Address did not contain a security domain name")
// IllegalArgumentException addressDidNotContainSecurityDomain();
// /**
// * Create a {@link SecurityException} to indicate that the vault is not initialized
// * @return {@link SecurityException}
// */
// @Message(id = 26, value = "Vault is not initialized")
// SecurityException vaultNotInitializedException();
// /**
// * Create a {@link SecurityException} to indicate that the user is invalid.
// * @return {@link SecurityException}
// */
// @Message(id = 27, value = "Invalid User")
// SecurityException invalidUserException();
//
// /**
// * Create a {@link SecurityException} to indicate that the security management has not been injected
// * @return {@link SecurityException}
// */
// @Message(id = 28, value = "Security Management not injected")
// SecurityException securityManagementNotInjected();
// /**
// * Create a {@link SecurityException} to indicate that the specified realm has not been found.
// * @return {@link SecurityException}
// */
// @Message(id = 29, value = "Security realm '%s' not found.")
// SecurityException realmNotFound(final String name);
// /**
// * Create a {@link SecurityException} to indicate that no password validation mechanism has been identified.
// * @return {@link SecurityException}
// */
//@Message(id = 30, value = "No suitable password validation mechanism identified for realm '%s'")
//SecurityException noPasswordValidationAvailable(final String realmName);
// /**
// * Create a {@link LoginException} to indicate a failure calling the security realm.
// * @return {@link LoginException}
// */
// @Message(id = 31, value = "Failure calling CallbackHandler '%s'")
// LoginException failureCallingSecurityRealm(String cause);
//
// /**
// * Create an OperationFailedException to indicate a failure to find an authentication cache
// * @return the exception
// */
// @Message(id = 32, value = "No authentication cache for security domain '%s' available")
// OperationFailedException noAuthenticationCacheAvailable(String securityDomain);
//
// /**
// * Create an IllegalStateFoundException to indicate no UserPrincipal was found on the underlying connection.
// * @return the exception
// */
// @Message(id= 33, value = "No UserPrincipalFound constructing RemotingConnectionPrincipal.")
// IllegalStateException noUserPrincipalFound();
//
// @Message(id = 34, value = "Interrupted waiting for security domain '%s'")
// OperationFailedException interruptedWaitingForSecurityDomain(String securityDomainName);
//
// @Message(id = 35, value = "Required security domain is not available '%s'")
// OperationFailedException requiredSecurityDomainServiceNotAvailable(String securityDomainName);
// @Message(id = 36, value = "At least one attribute is to be defined")
// OperationFailedException requiredJSSEConfigurationAttribute();
// /**
// * Create an Exception when KeyStore cannot be located with example how to create one.
// *
// * @param keystoreURL nonexistent keystore URL
// * @param keystoreURLExample example keystore url
// * @return the exception
// */
// @Message(id = 37, value = "Keystore '%s' doesn't exist."
// + "\nkeystore could be created: "
// + "keytool -genseckey -alias Vault -storetype jceks -keyalg AES -keysize 128 -storepass secretsecret -keypass secretsecret -keystore %s")
// Exception keyStoreDoesnotExistWithExample(final String keystoreURL, final String keystoreURLExample);
// /**
// * Create an Exception when one cannot write to the KeyStore or it is not a file.
// *
// * @param keystoreURL URL of the keystore
// * @return the exception
// */
// @Message(id = 38, value = "Keystore [%s] is not writable or not a file.")
// Exception keyStoreNotWritable(final String keystoreURL);
// /**
// * Create an exception when KeyStore password is not specified.
// *
// * @return the exception
// */
// @Message(id = 39, value = "Keystore password has to be specified.")
// Exception keyStorePasswordNotSpecified();
// /**
// * Create an exception when encryption directory is not specified.
// *
// * @return
// */
// @Message(id = 40, value = "Encryption directory has to be specified.")
// Exception encryptionDirectoryHasToBeSpecified();
// /**
// * Create an exception when encryption directory does not exist or is not a directory.
// *
// * @param directory directory name
// * @return the exception
// */
// @Message(id = 41, value = "Encryption directory is not a directory or doesn't exist. (%s)")
// Exception encryptionDirectoryDoesNotExist(final String directory);
// /**
// * Create an exception when encryption directory cannot be created.
// *
// * @param directory directory name
// * @return the exception
// */
// @Message(id = 42, value = "Cannot create encryption directory %s")
// Exception cannotCreateEncryptionDirectory(final String directory);
// /**
// * Create an exception when iteration count is out of range.
// *
// * @param iteration iteration count
// * @return the exception
// */
// @Message(id = 43, value = "Iteration count has to be within 1 - " + Integer.MAX_VALUE + ", but it is %s.")
// Exception iterationCountOutOfRange(final String iteration);
// /**
// * Create an exception when salt has different length than 8.
// *
// * @return the exception
// */
// @Message(id = 44, value = "Salt has to be exactly 8 characters long.")
// Exception saltWrongLength();
// /**
// * Unspecified exception encountered.
// *
// * @return the exception
// */
// @Message(id = 45, value = "Exception encountered:")
// Exception securityVaultException(@Cause SecurityVaultException cause);
// /**
// * Create an exception when Vault alias is not specified.
// *
// * @return the exception
// */
// @Message(id = 46, value = "Vault alias has to be specified.")
// Exception vaultAliasNotSpecified();
// /**
// * Display string at the end of successful attribute creation.
// *
// * @param VaultBlock name of vault block
// * @param attributeName name of value attribute
// * @param configurationString configuration details
// * @return the localized text
// */
// @Message(id = 47, value =
// "Secured attribute value has been stored in Vault.\n" +
// "Please make note of the following:\n" +
// "********************************************\n" +
// "Vault Block:%s\n" + "Attribute Name:%s\n" +
// "Configuration should be done as follows:\n" +
// "%s\n" +
// "********************************************")
// String vaultAttributeCreateDisplay(String VaultBlock, String attributeName, String configurationString);
// /**
// * i18n version of string from Vault Tool utility
// *
// * @return the localized text
// */
// @Message(id = 48, value = "Vault Configuration commands in WildFly for CLI:")
// String vaultConfigurationTitle();
// /**
// * i18n version of string from Vault Tool utility
// *
// * @return the localized text
// */
// @Message(id = 49, value = "No console.")
// String noConsole();
// /**
// * i18n version of string from Vault Tool utility
// *
// * @return the localized text
// */
// @Message(id = 56, value = "Initializing Vault")
// String initializingVault();
// /**
// * i18n version of string from Vault Tool utility
// *
// * @return the localized text
// */
// @Message(id = 57, value = "Vault is initialized and ready for use")
// String vaultInitialized();
// /**
// * i18n version of string from Vault Tool utility
// *
// * @return the localized text
// */
// @Message(id = 58, value = "Handshake with Vault complete")
// String handshakeComplete();
// /**
// * i18n version of string from Vault Tool utility
// *
// * @return the localized text
// */
// @Message(id = 59, value = "Exception encountered:")
// String exceptionEncountered();
/**
* i18n version of string from Vault Tool utility
*
* @deprecated do not use this message to build confirmation message
*
* @return the localized text
*/
@Deprecated
@Message(id = 61, value = " again: ")
String passwordAgain();
// /**
// * i18n version of string from Vault Tool utility
// *
// * @return the localized text
// */
// @Message(id = 68, value = "Problem while parsing command line parameters:")
// String problemParsingCommandLineParameters();
// /**
// * i18n version of string from Vault Tool utility
// *
// * @return the localized text
// */
// @Message(id = 80, value = "Secured attribute (password) already exists.")
// String cmdLineSecuredAttributeAlreadyExists();
// /**
// * i18n version of string from Vault Tool utility
// *
// * @return the localized text
// */
// @Message(id = 81, value = "Secured attribute (password) doesn't exist.")
// String cmdLineSecuredAttributeDoesNotExist();
// /**
// * Keystore parameter type checking
// *
// * @return
// */
// @Message(id = 84, value = "'%s' parameter type or length is incorrect")
// IllegalArgumentException incorrectKeystoreParameters(final String keystoreName);
// /**
// * Creates an exception indicating the inability to find a JSSE-enabled security domain with the specified name.
// *
// * @return a {@link StartException} instance.
// */
// @Message(id = 100, value = "Legacy security domain %s doesn't contain a valid JSSE configuration")
// StartException unableToLocateJSSEConfig(final String legacyDomainName);
//
// /**
// * Creates an exception indicating the inability to find a component (keystore, truststore, keymanager, etc) in
// * the specified JSSE security domain.
// *
// * @return a {@link StartException} instance.
// */
// @Message(id = 101, value = "Unable to find a %s configuration in JSSE security domain %s")
// StartException unableToLocateComponentInJSSEDomain(final String componentName, final String legacyDomainName);
// /**
// * Creates an exception indicating that the expected manager type was not found in the JSSE security domain.
// *
// * @param managerName the name of the manager being retrieved (KeyManager or TrustManager).
// * @param managerType the expected type.
// * @return a {@link StartException} instance.
// */
// @Message(id = 102, value = "Could not find a %s of type %s in the JSSE security domain %s")
// StartException expectedManagerTypeNotFound(final String managerName, final String managerType, final String legacyDomainName);
//
// /**
// * Creates an exception indicating that an {@link org.wildfly.security.authz.AuthorizationIdentity} could not be created
// * because a valid authenticated Subject was not established yet.
// *
// * @return a {@link IllegalStateException} instance.
// */
// @Message(id = 103, value = "Unable to create AuthorizationIdentity: no authenticated Subject was found")
// IllegalStateException unableToCreateAuthorizationIdentity();
//
// @LogMessage(level = Level.WARN)
// @Message(id = 104, value = "Default %s cache capability missing. Assuming %s as default-cache.")
// void defaultCacheRequirementMissing(String containerName, String legacyCacheName);
@Message(id=105, value = "Unable to initialize legacy JACC support while elytron JACC support is enabled.")
IllegalStateException unableToEnableJaccSupport();
// /**
// * A message indicating an unsupported resource in the model during Model Stage.
// *
// * @param name the name of the resource.
// * @param minUnsupportedVersion the minimal JVM major version where this resource is no longer supported.
// * @return The exception for the error.
// */
// @Message(id = 106, value = "The resource '%s' is unsupported since Java %d")
// OperationFailedException unsupportedResourceSinceJavaVersion(String name, int minUnsupportedVersion);
/**
* A message indicating the validation failed.
*
* @param name the parameter name the validation failed on.
*
* @return the message.
*/
@Message(id = 107, value = "Validation failed for %s")
String validationFailed(String name);
}
| 22,980
| 39.106457
| 151
|
java
|
null |
wildfly-main/datasources-agroal/src/test/java/org/wildfly/extension/datasources/agroal/SubsystemFullParsingTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal;
import org.jboss.as.controller.security.CredentialReference;
import org.jboss.as.subsystem.test.AbstractSubsystemTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.as.subsystem.test.KernelServicesBuilder;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.subsystem.test.AdditionalInitialization.MANAGEMENT;
/**
* Tests parsing of XML files with all elements and attributes
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
*/
public class SubsystemFullParsingTestCase extends AbstractSubsystemTest {
public SubsystemFullParsingTestCase() {
super(AgroalExtension.SUBSYSTEM_NAME, new AgroalExtension());
}
private static AdditionalInitialization createAdditionalInitialization() {
// Create a AdditionalInitialization.MANAGEMENT variant that has all the external capabilities used by the various configs used in this test class
return AdditionalInitialization.withCapabilities(
AbstractDataSourceDefinition.AUTHENTICATION_CONTEXT_CAPABILITY + ".secure-context",
CredentialReference.CREDENTIAL_STORE_CAPABILITY + ".test-store"
);
}
/**
* Tests that the xml is parsed into the correct operations
*/
@Test
public void testParseSubsystem() throws Exception {
parseXmlResource("agroal_2_0-full.xml");
}
@SuppressWarnings("SameParameterValue")
private void parseXmlResource(String xmlResource) throws Exception {
KernelServicesBuilder kernelBuilder = createKernelServicesBuilder(createAdditionalInitialization());
KernelServices services = kernelBuilder.build();
for (ModelNode op : kernelBuilder.parseXmlResource(xmlResource)) {
services.executeOperation(op);
}
// Read the whole model and make sure it looks as expected
ModelNode model = services.readWholeModel();
Assert.assertTrue(model.get(SUBSYSTEM).hasDefined(AgroalExtension.SUBSYSTEM_NAME));
// for debug purposes: System.out.println( model ); System.out.println( services.getPersistedSubsystemXml() );
ModelNode marshaledModel = createKernelServicesBuilder(MANAGEMENT).setSubsystemXml(services.getPersistedSubsystemXml()).build().readWholeModel();
Assert.assertEquals(model, marshaledModel);
}
}
| 3,595
| 42.325301
| 154
|
java
|
null |
wildfly-main/datasources-agroal/src/test/java/org/wildfly/extension/datasources/agroal/SubsystemBaseParsingTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import java.io.IOException;
/**
* This is the bare bones test example that tests subsystem
* It does same things that {@link SubsystemParsingTestCase} does but most of internals are already done in AbstractSubsystemBaseTest
* If you need more control over what happens in tests look at {@link SubsystemParsingTestCase}
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
*/
public class SubsystemBaseParsingTestCase extends AbstractSubsystemBaseTest {
public SubsystemBaseParsingTestCase() {
super(AgroalExtension.SUBSYSTEM_NAME, new AgroalExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
return "<subsystem xmlns=\"" + AgroalNamespace.CURRENT.getUriString() + "\"/>";
}
@Override
protected String getSubsystemXsdPath() throws Exception {
return "schema/wildfly-agroal_2_0.xsd";
}
}
| 2,028
| 38.784314
| 133
|
java
|
null |
wildfly-main/datasources-agroal/src/test/java/org/wildfly/extension/datasources/agroal/SubsystemParsingTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.subsystem.test.AbstractSubsystemTest;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.*;
/**
* Tests all management expects for subsystem, parsing, marshaling, model definition and other
* Here is an example that allows you a fine grained controller over what is tested and how. So it can give you ideas what can be done and tested.
* If you have no need for advanced testing of subsystem you look at {@link SubsystemBaseParsingTestCase} that testes same stuff but most of the code
* is hidden inside of test harness
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
*/
public class SubsystemParsingTestCase extends AbstractSubsystemTest {
public SubsystemParsingTestCase() {
super(AgroalExtension.SUBSYSTEM_NAME, new AgroalExtension());
}
/**
* Tests that the xml is parsed into the correct operations
*/
@Test
public void testParseSubsystem() throws Exception {
//Parse the subsystem xml into operations
String subsystemXml = "<subsystem xmlns=\"" + AgroalNamespace.CURRENT.getUriString() + "\"/>";
List<ModelNode> operations = super.parse(subsystemXml);
///Check that we have the expected number of operations
Assert.assertEquals(1, operations.size());
//Check that each operation has the correct content
ModelNode addSubsystem = operations.get(0);
Assert.assertEquals(ADD, addSubsystem.get(OP).asString());
PathAddress address = PathAddress.pathAddress(addSubsystem.get(OP_ADDR));
Assert.assertEquals(1, address.size());
PathElement element = address.getElement(0);
Assert.assertEquals(SUBSYSTEM, element.getKey());
Assert.assertEquals(AgroalExtension.SUBSYSTEM_NAME, element.getValue());
}
/**
* Test that the model created from the xml looks as expected
*/
@Test
public void testInstallIntoController() throws Exception {
//Parse the subsystem xml and install into the controller
String subsystemXml = "<subsystem xmlns=\"" + AgroalNamespace.CURRENT.getUriString() + "\"/>";
KernelServices services = super.createKernelServicesBuilder(null).setSubsystemXml(subsystemXml).build();
//Read the whole model and make sure it looks as expected
ModelNode model = services.readWholeModel();
Assert.assertTrue(model.get(SUBSYSTEM).hasDefined(AgroalExtension.SUBSYSTEM_NAME));
}
/**
* Starts a controller with a given subsystem xml and then checks that a second
* controller started with the xml marshaled from the first one results in the same model
*/
@Test
public void testParseAndMarshalModel() throws Exception {
//Parse the subsystem xml and install into the first controller
String subsystemXml = "<subsystem xmlns=\"" + AgroalNamespace.CURRENT.getUriString() + "\"/>";
KernelServices servicesA = super.createKernelServicesBuilder(null).setSubsystemXml(subsystemXml).build();
//Get the model and the persisted xml from the first controller
ModelNode modelA = servicesA.readWholeModel();
String marshaled = servicesA.getPersistedSubsystemXml();
//Install the persisted xml from the first controller into a second controller
KernelServices servicesB = super.createKernelServicesBuilder(null).setSubsystemXml(marshaled).build();
ModelNode modelB = servicesB.readWholeModel();
//Make sure the models from the two controllers are identical
super.compare(modelA, modelB);
}
/**
* Tests that the subsystem can be removed
*/
@Test
public void testSubsystemRemoval() throws Exception {
//Parse the subsystem xml and install into the first controller
String subsystemXml = "<subsystem xmlns=\"" + AgroalNamespace.CURRENT.getUriString() + "\"/>";
KernelServices services = super.createKernelServicesBuilder(null).setSubsystemXml(subsystemXml).build();
//Checks that the subsystem was removed from the model
super.assertRemoveSubsystemResources(services);
//TODO Check that any services that were installed were removed here
}
}
| 5,532
| 43.98374
| 149
|
java
|
null |
wildfly-main/datasources-agroal/src/test/java/org/wildfly/extension/datasources/agroal/SubsystemFullParsing10TestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal;
import org.jboss.as.controller.security.CredentialReference;
import org.jboss.as.subsystem.test.AbstractSubsystemTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.as.subsystem.test.KernelServicesBuilder;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.subsystem.test.AdditionalInitialization.MANAGEMENT;
/**
* Tests parsing of XML files with all elements and attributes
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
*/
public class SubsystemFullParsing10TestCase extends AbstractSubsystemTest {
public SubsystemFullParsing10TestCase() {
super(AgroalExtension.SUBSYSTEM_NAME, new AgroalExtension());
}
private static AdditionalInitialization createAdditionalInitialization() {
// Create a AdditionalInitialization.MANAGEMENT variant that has all the external capabilities used by the various configs used in this test class
return AdditionalInitialization.withCapabilities(
AbstractDataSourceDefinition.AUTHENTICATION_CONTEXT_CAPABILITY + ".secure-context",
CredentialReference.CREDENTIAL_STORE_CAPABILITY + ".test-store"
);
}
/**
* Tests that the xml is parsed into the correct operations
*/
@Test
public void testParse_1_0_Subsystem() throws Exception {
parseXmlResource("agroal_1_0-full.xml");
}
@SuppressWarnings("SameParameterValue")
private void parseXmlResource(String xmlResource) throws Exception {
KernelServicesBuilder kernelBuilder = createKernelServicesBuilder(createAdditionalInitialization());
KernelServices services = kernelBuilder.build();
for (ModelNode op : kernelBuilder.parseXmlResource(xmlResource)) {
services.executeOperation(op);
}
// Read the whole model and make sure it looks as expected
ModelNode model = services.readWholeModel();
Assert.assertTrue(model.get(SUBSYSTEM).hasDefined(AgroalExtension.SUBSYSTEM_NAME));
// for debug purposes: System.out.println( model ); System.out.println( services.getPersistedSubsystemXml() );
ModelNode marshaledModel = createKernelServicesBuilder(MANAGEMENT).setSubsystemXml(services.getPersistedSubsystemXml()).build().readWholeModel();
Assert.assertEquals(model, marshaledModel);
}
}
| 3,604
| 42.433735
| 154
|
java
|
null |
wildfly-main/datasources-agroal/src/main/java/org/wildfly/extension/datasources/agroal/AgroalExtension.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal;
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.descriptions.ParentResourceDescriptionResolver;
import org.jboss.as.controller.descriptions.SubsystemResourceDescriptionResolver;
import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler;
import org.jboss.as.controller.parsing.ExtensionParsingContext;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.msc.service.ServiceName;
/**
* Defines an extension to provide DataSources based on the Agroal project
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
*/
public class AgroalExtension implements Extension {
/**
* The name of the subsystem within the model
*/
static final String SUBSYSTEM_NAME = "datasources-agroal";
public static final ServiceName BASE_SERVICE_NAME = ServiceName.JBOSS.append(SUBSYSTEM_NAME);
private static final ModelVersion CURRENT_MODEL_VERSION = ModelVersion.create(2, 0, 0);
static final ParentResourceDescriptionResolver SUBSYSTEM_RESOLVER = new SubsystemResourceDescriptionResolver(SUBSYSTEM_NAME, AgroalExtension.class);
@Override
public void initializeParsers(ExtensionParsingContext context) {
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, AgroalNamespace.AGROAL_1_0.getUriString(), AgroalSubsystemParser_1_0.INSTANCE);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, AgroalNamespace.AGROAL_2_0.getUriString(), AgroalSubsystemParser_2_0.INSTANCE);
}
@Override
public void initialize(ExtensionContext context) {
SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION);
ManagementResourceRegistration registration = subsystem.registerSubsystemModel(new AgroalSubsystemDefinition());
registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE);
subsystem.registerXMLElementWriter(AgroalSubsystemParser_2_0.INSTANCE);
}
}
| 3,241
| 46.676471
| 152
|
java
|
null |
wildfly-main/datasources-agroal/src/main/java/org/wildfly/extension/datasources/agroal/DriverDefinition.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal;
import static java.util.Arrays.asList;
import static java.util.Collections.unmodifiableList;
import static org.jboss.as.controller.PathElement.pathElement;
import static org.jboss.as.controller.SimpleAttributeDefinitionBuilder.create;
import java.util.Collection;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.PersistentResourceDefinition;
import org.jboss.as.controller.PropertiesAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.access.constraint.ApplicationTypeConfig;
import org.jboss.as.controller.access.management.ApplicationTypeAccessConstraintDefinition;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.operations.validation.StringLengthValidator;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelType;
/**
* Definition for the driver resource
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
*/
class DriverDefinition extends PersistentResourceDefinition {
private static final String AGROAL_DRIVER_CAPABILITY_NAME = "org.wildfly.data-source.agroal-driver";
static final PathElement PATH = pathElement("driver");
static final RuntimeCapability<Void> AGROAL_DRIVER_CAPABILITY = RuntimeCapability.Builder.of(AGROAL_DRIVER_CAPABILITY_NAME, true, Class.class).build();
static final String DRIVERS_ELEMENT_NAME = "drivers";
static final SimpleAttributeDefinition MODULE_ATTRIBUTE = create("module", ModelType.STRING)
.setRestartAllServices()
.setValidator(new StringLengthValidator(1))
.build();
static final SimpleAttributeDefinition CLASS_ATTRIBUTE = create("class", ModelType.STRING)
.setRequired(false)
.setRestartAllServices()
.setValidator(new StringLengthValidator(1))
.build();
static final PropertiesAttributeDefinition CLASS_INFO = new PropertiesAttributeDefinition.Builder("class-info", true)
.setStorageRuntime()
.build();
static final Collection<AttributeDefinition> ATTRIBUTES = unmodifiableList(asList(MODULE_ATTRIBUTE, CLASS_ATTRIBUTE));
// --- //
DriverDefinition() {
super(new SimpleResourceDefinition.Parameters(PATH, AgroalExtension.SUBSYSTEM_RESOLVER.createChildResolver(PATH))
.setCapabilities(AGROAL_DRIVER_CAPABILITY)
.setAddHandler(DriverOperations.ADD_OPERATION)
.setRemoveHandler(DriverOperations.REMOVE_OPERATION)
.setAccessConstraints(new ApplicationTypeAccessConstraintDefinition(
new ApplicationTypeConfig(AgroalExtension.SUBSYSTEM_NAME, "driver"))));
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return ATTRIBUTES;
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
super.registerAttributes(resourceRegistration);
resourceRegistration.registerReadOnlyAttribute(CLASS_INFO, DriverOperations.INFO_OPERATION);
}
}
| 4,310
| 43.443299
| 155
|
java
|
null |
wildfly-main/datasources-agroal/src/main/java/org/wildfly/extension/datasources/agroal/AgroalSubsystemOperations.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal;
import org.jboss.as.controller.AbstractBoottimeAddStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.server.AbstractDeploymentChainStep;
import org.jboss.as.server.DeploymentProcessorTarget;
import org.jboss.as.server.deployment.Phase;
import org.jboss.dmr.ModelNode;
import org.wildfly.extension.datasources.agroal.deployment.DataSourceDefinitionAnnotationProcessor;
import org.wildfly.extension.datasources.agroal.deployment.DataSourceDefinitionDescriptorProcessor;
import org.wildfly.extension.datasources.agroal.logging.AgroalLogger;
/**
* Operations for adding and removing the subsystem resource to the model
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
*/
class AgroalSubsystemOperations {
static final OperationStepHandler ADD_OPERATION = new AgroalSubsystemAdd();
private static class AgroalSubsystemAdd extends AbstractBoottimeAddStepHandler {
@Override
protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
context.addStep(new AbstractDeploymentChainStep() {
public void execute(DeploymentProcessorTarget processorTarget) {
AgroalLogger.SERVICE_LOGGER.addingDeploymentProcessors();
processorTarget.addDeploymentProcessor(AgroalExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_RESOURCE_DEF_ANNOTATION_DATA_SOURCE, new DataSourceDefinitionAnnotationProcessor());
processorTarget.addDeploymentProcessor(AgroalExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_RESOURCE_DEF_XML_DATA_SOURCE, new DataSourceDefinitionDescriptorProcessor());
}
}, OperationContext.Stage.RUNTIME);
}
}
}
| 2,971
| 48.533333
| 205
|
java
|
null |
wildfly-main/datasources-agroal/src/main/java/org/wildfly/extension/datasources/agroal/AgroalNamespace.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal;
import java.util.HashMap;
import java.util.Map;
/**
* Namespace definitions for the XML parser
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
*/
enum AgroalNamespace {
UNKNOWN(null), // must be first
AGROAL_1_0("urn:jboss:domain:datasources-agroal:1.0"),
AGROAL_2_0("urn:jboss:domain:datasources-agroal:2.0");
public static final AgroalNamespace CURRENT = AGROAL_2_0;
private static final Map<String, AgroalNamespace> MAP;
static {
Map<String, AgroalNamespace> map = new HashMap<>();
for (AgroalNamespace namespace : values()) {
final String name = namespace.getUriString();
if (name != null) {
map.put(name, namespace);
}
}
MAP = map;
}
// --- //
private final String name;
AgroalNamespace(final String name) {
this.name = name;
}
/**
* Get the Namespace instance for a given URI
*/
@SuppressWarnings("unused")
public static AgroalNamespace forUri(String uri) {
AgroalNamespace element = MAP.get(uri);
return element == null ? UNKNOWN : element;
}
/**
* Get the URI of this AgroalNamespace
*/
public String getUriString() {
return name;
}
}
| 2,354
| 28.810127
| 70
|
java
|
null |
wildfly-main/datasources-agroal/src/main/java/org/wildfly/extension/datasources/agroal/DataSourceDefinition.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.access.constraint.ApplicationTypeConfig;
import org.jboss.as.controller.access.management.ApplicationTypeAccessConstraintDefinition;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import java.util.Collection;
import static java.util.Arrays.asList;
import static java.util.Collections.unmodifiableList;
import static org.jboss.as.controller.PathElement.pathElement;
import static org.jboss.as.controller.SimpleAttributeDefinitionBuilder.create;
/**
* Definition for the datasource resource
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
*/
class DataSourceDefinition extends AbstractDataSourceDefinition {
static final PathElement PATH = pathElement("datasource");
static final SimpleAttributeDefinition JTA_ATTRIBUTE = create("jta", ModelType.BOOLEAN)
.setAllowExpression(true)
.setDefaultValue(ModelNode.TRUE)
.setRequired(false)
.setRestartAllServices()
.build();
static final SimpleAttributeDefinition CONNECTABLE_ATTRIBUTE = create("connectable", ModelType.BOOLEAN)
.setAllowExpression(true)
.setDefaultValue(ModelNode.FALSE)
.setRequired(false)
.setRestartAllServices()
.build();
static final Collection<AttributeDefinition> ATTRIBUTES = unmodifiableList(asList(JTA_ATTRIBUTE, CONNECTABLE_ATTRIBUTE, JNDI_NAME_ATTRIBUTE, STATISTICS_ENABLED_ATTRIBUTE, CONNECTION_FACTORY_ATTRIBUTE, CONNECTION_POOL_ATTRIBUTE));
// --- //
DataSourceDefinition() {
super(new SimpleResourceDefinition.Parameters(PATH, AgroalExtension.SUBSYSTEM_RESOLVER.createChildResolver(PATH))
.setAddHandler(DataSourceOperations.ADD_OPERATION)
.setRemoveHandler(DataSourceOperations.REMOVE_OPERATION)
.setAccessConstraints(new ApplicationTypeAccessConstraintDefinition(
new ApplicationTypeConfig(AgroalExtension.SUBSYSTEM_NAME, "datasource"))));
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return ATTRIBUTES;
}
}
| 3,418
| 41.7375
| 233
|
java
|
null |
wildfly-main/datasources-agroal/src/main/java/org/wildfly/extension/datasources/agroal/DataSourceOperations.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal;
import static org.jboss.as.controller.security.CredentialReference.handleCredentialReferenceUpdate;
import static org.jboss.as.controller.security.CredentialReference.rollbackCredentialStoreUpdate;
import static org.wildfly.extension.datasources.agroal.AbstractDataSourceDefinition.CREDENTIAL_REFERENCE;
import java.util.function.Consumer;
import java.util.function.Supplier;
import io.agroal.api.AgroalDataSource;
import io.agroal.api.configuration.supplier.AgroalConnectionFactoryConfigurationSupplier;
import io.agroal.api.configuration.supplier.AgroalConnectionPoolConfigurationSupplier;
import io.agroal.api.configuration.supplier.AgroalDataSourceConfigurationSupplier;
import jakarta.transaction.TransactionSynchronizationRegistry;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.AbstractRemoveStepHandler;
import org.jboss.as.controller.CapabilityServiceBuilder;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceName;
import org.wildfly.common.function.ExceptionSupplier;
import org.wildfly.security.auth.client.AuthenticationContext;
import org.wildfly.security.credential.source.CredentialSource;
/**
* Operations for adding and removing a datasource resource to the model
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
* @author <a href="mailto:ropalka@redhat.com">Richard Opalka</a>
*/
class DataSourceOperations {
static final String DATASOURCE_SERVICE_NAME = "datasource";
// --- //
static final OperationStepHandler ADD_OPERATION = new DataSourceAdd();
static final OperationStepHandler REMOVE_OPERATION = new DataSourceRemove();
// --- //
private static class DataSourceAdd extends AbstractAddStepHandler {
private DataSourceAdd() {
super(DataSourceDefinition.ATTRIBUTES);
}
protected void populateModel(final OperationContext context, final ModelNode operation, final Resource resource) throws OperationFailedException {
super.populateModel(context, operation, resource);
handleCredentialReferenceUpdate(context, resource.getModel());
}
@Override
@SuppressWarnings("unchecked")
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
String datasourceName = context.getCurrentAddressValue();
ModelNode factoryModel = AbstractDataSourceDefinition.CONNECTION_FACTORY_ATTRIBUTE.resolveModelAttribute(context, model);
AgroalConnectionFactoryConfigurationSupplier connectionFactoryConfiguration = AbstractDataSourceOperations.connectionFactoryConfiguration(context, factoryModel);
ModelNode poolModel = AbstractDataSourceDefinition.CONNECTION_POOL_ATTRIBUTE.resolveModelAttribute(context, model);
AgroalConnectionPoolConfigurationSupplier connectionPoolConfiguration = AbstractDataSourceOperations.connectionPoolConfiguration(context, poolModel);
connectionPoolConfiguration.connectionFactoryConfiguration(connectionFactoryConfiguration);
AgroalDataSourceConfigurationSupplier dataSourceConfiguration = new AgroalDataSourceConfigurationSupplier();
dataSourceConfiguration.connectionPoolConfiguration(connectionPoolConfiguration);
dataSourceConfiguration.metricsEnabled(AbstractDataSourceDefinition.STATISTICS_ENABLED_ATTRIBUTE.resolveModelAttribute(context, model).asBoolean());
String jndiName = AbstractDataSourceDefinition.JNDI_NAME_ATTRIBUTE.resolveModelAttribute(context, model).asString();
boolean jta = DataSourceDefinition.JTA_ATTRIBUTE.resolveModelAttribute(context, model).asBoolean();
boolean connectable = DataSourceDefinition.CONNECTABLE_ATTRIBUTE.resolveModelAttribute(context, model).asBoolean();
String driverName = AbstractDataSourceDefinition.DRIVER_ATTRIBUTE.resolveModelAttribute(context, factoryModel).asString();
final CapabilityServiceBuilder serviceBuilder = context.getCapabilityServiceTarget().addCapability(AbstractDataSourceDefinition.DATA_SOURCE_CAPABILITY.fromBaseCapability(datasourceName));
final Consumer<AgroalDataSource> consumer = serviceBuilder.provides(AbstractDataSourceDefinition.DATA_SOURCE_CAPABILITY.fromBaseCapability(datasourceName));
final Supplier<Class> driverSupplier = serviceBuilder.requiresCapability(DriverDefinition.AGROAL_DRIVER_CAPABILITY.getDynamicName(driverName), Class.class);
final Supplier<AuthenticationContext> authenticationContextSupplier = AbstractDataSourceOperations.setupAuthenticationContext(context, factoryModel, serviceBuilder);
final Supplier<ExceptionSupplier<CredentialSource, Exception>> credentialSourceSupplier = AbstractDataSourceOperations.setupCredentialReference(context, factoryModel, serviceBuilder);
// TODO add a Stage.MODEL requirement
final Supplier<TransactionSynchronizationRegistry> txnRegistrySupplier = jta ? serviceBuilder.requiresCapability("org.wildfly.transactions.transaction-synchronization-registry", TransactionSynchronizationRegistry.class) : null;
DataSourceService dataSourceService = new DataSourceService(consumer, driverSupplier, authenticationContextSupplier, credentialSourceSupplier, txnRegistrySupplier, datasourceName, jndiName, jta, connectable, false, dataSourceConfiguration);
serviceBuilder.setInstance(dataSourceService);
serviceBuilder.install();
}
@Override
protected void rollbackRuntime(OperationContext context, final ModelNode operation, final Resource resource) {
rollbackCredentialStoreUpdate(CREDENTIAL_REFERENCE, context, resource);
}
}
// --- //
private static class DataSourceRemove extends AbstractRemoveStepHandler {
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
String datasourceName = context.getCurrentAddressValue();
ServiceName datasourceServiceName = AbstractDataSourceDefinition.DATA_SOURCE_CAPABILITY.getCapabilityServiceName(datasourceName);
context.removeService(datasourceServiceName);
}
}
}
| 7,603
| 58.40625
| 252
|
java
|
null |
wildfly-main/datasources-agroal/src/main/java/org/wildfly/extension/datasources/agroal/AgroalSubsystemDefinition.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.PersistentResourceDefinition;
import org.jboss.as.controller.ReloadRequiredRemoveStepHandler;
import java.util.Collection;
import java.util.List;
import static java.util.Collections.emptyList;
import static org.jboss.as.controller.PathElement.pathElement;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
/**
* Definition for the Agroal subsystem
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
*/
class AgroalSubsystemDefinition extends PersistentResourceDefinition {
static final PathElement PATH = pathElement(SUBSYSTEM, AgroalExtension.SUBSYSTEM_NAME);
AgroalSubsystemDefinition() {
super(PATH, AgroalExtension.SUBSYSTEM_RESOLVER, AgroalSubsystemOperations.ADD_OPERATION, ReloadRequiredRemoveStepHandler.INSTANCE);
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return emptyList();
}
@Override
public List<PersistentResourceDefinition> getChildren() {
return List.of(new DataSourceDefinition(), new XADataSourceDefinition(), new DriverDefinition());
}
}
| 2,303
| 38.724138
| 139
|
java
|
null |
wildfly-main/datasources-agroal/src/main/java/org/wildfly/extension/datasources/agroal/XADataSourceDefinition.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal;
import static java.util.Arrays.asList;
import static java.util.Collections.unmodifiableList;
import static org.jboss.as.controller.PathElement.pathElement;
import java.util.Collection;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.access.constraint.ApplicationTypeConfig;
import org.jboss.as.controller.access.management.ApplicationTypeAccessConstraintDefinition;
/**
* Definition for the xa-datasource resource
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
*/
class XADataSourceDefinition extends AbstractDataSourceDefinition {
static final PathElement PATH = pathElement("xa-datasource");
static final Collection<AttributeDefinition> ATTRIBUTES = unmodifiableList(asList(JNDI_NAME_ATTRIBUTE, STATISTICS_ENABLED_ATTRIBUTE, CONNECTION_FACTORY_ATTRIBUTE, CONNECTION_POOL_ATTRIBUTE));
// --- //
XADataSourceDefinition() {
super(new SimpleResourceDefinition.Parameters(PATH, AgroalExtension.SUBSYSTEM_RESOLVER.createChildResolver(PATH))
.setAddHandler(XADataSourceOperations.ADD_OPERATION)
.setRemoveHandler(XADataSourceOperations.REMOVE_OPERATION)
.setAccessConstraints(new ApplicationTypeAccessConstraintDefinition(
new ApplicationTypeConfig(AgroalExtension.SUBSYSTEM_NAME, "xa-datasource"))));
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return ATTRIBUTES;
}
}
| 2,644
| 42.360656
| 195
|
java
|
null |
wildfly-main/datasources-agroal/src/main/java/org/wildfly/extension/datasources/agroal/DataSourceService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal;
import io.agroal.api.AgroalDataSource;
import io.agroal.api.configuration.supplier.AgroalDataSourceConfigurationSupplier;
import io.agroal.api.security.SimplePassword;
import io.agroal.api.transaction.TransactionIntegration;
import io.agroal.narayana.NarayanaTransactionIntegration;
import org.ietf.jgss.GSSException;
import org.jboss.as.naming.ImmediateManagedReferenceFactory;
import org.jboss.as.naming.ServiceBasedNamingStore;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.service.BinderService;
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.common.function.ExceptionSupplier;
import org.wildfly.extension.datasources.agroal.logging.AgroalLogger;
import org.wildfly.extension.datasources.agroal.logging.LoggingDataSourceListener;
import org.wildfly.security.auth.callback.CredentialCallback;
import org.wildfly.security.auth.client.AuthenticationConfiguration;
import org.wildfly.security.auth.client.AuthenticationContext;
import org.wildfly.security.auth.client.AuthenticationContextConfigurationClient;
import org.wildfly.security.auth.principal.NamePrincipal;
import org.wildfly.security.credential.GSSKerberosCredential;
import org.wildfly.security.credential.PasswordCredential;
import org.wildfly.security.credential.source.CredentialSource;
import org.wildfly.security.password.interfaces.ClearPassword;
import org.wildfly.transaction.client.ContextTransactionManager;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.sql.DataSource;
import javax.sql.XADataSource;
import jakarta.transaction.TransactionManager;
import jakarta.transaction.TransactionSynchronizationRegistry;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.AccessController;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* Defines an extension to provide DataSources based on the Agroal project
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
*/
public class DataSourceService implements Service<AgroalDataSource>, Supplier<AgroalDataSource> {
private static final AuthenticationContextConfigurationClient AUTH_CONFIG_CLIENT = AccessController.doPrivileged(AuthenticationContextConfigurationClient.ACTION);
private final Consumer<AgroalDataSource> consumer;
private final String dataSourceName;
private final String jndiName;
private final boolean jta;
private final boolean connectable;
private final boolean xa;
private final AgroalDataSourceConfigurationSupplier dataSourceConfiguration;
private AgroalDataSource agroalDataSource;
private final Supplier<Class> driverSupplier;
private final Supplier<AuthenticationContext> authenticationContextSupplier;
private final Supplier<ExceptionSupplier<CredentialSource, Exception>> credentialSourceSupplier;
private final Supplier<TransactionSynchronizationRegistry> transactionSynchronizationRegistrySupplier;
public DataSourceService(final Consumer<AgroalDataSource> consumer,
final Supplier<Class> driverSupplier,
final Supplier<AuthenticationContext> authenticationContextSupplier,
final Supplier<ExceptionSupplier<CredentialSource, Exception>> credentialSourceSupplier,
final Supplier<TransactionSynchronizationRegistry> transactionSynchronizationRegistrySupplier,
String dataSourceName, String jndiName, boolean jta, boolean connectable, boolean xa, AgroalDataSourceConfigurationSupplier dataSourceConfiguration) {
this.consumer = consumer;
this.driverSupplier = driverSupplier;
this.authenticationContextSupplier = authenticationContextSupplier;
this.credentialSourceSupplier = credentialSourceSupplier;
this.transactionSynchronizationRegistrySupplier = transactionSynchronizationRegistrySupplier;
this.dataSourceName = dataSourceName;
this.jndiName = jndiName;
this.jta = jta;
this.connectable = connectable;
this.xa = xa;
this.dataSourceConfiguration = dataSourceConfiguration;
}
@Override
public void start(StartContext context) throws StartException {
Class<?> providerClass = driverSupplier != null ? driverSupplier.get() : null;
if (xa) {
if (!XADataSource.class.isAssignableFrom(providerClass)) {
throw AgroalLogger.SERVICE_LOGGER.invalidXAConnectionProvider();
}
} else {
if (providerClass != null && !DataSource.class.isAssignableFrom(providerClass) && !Driver.class.isAssignableFrom(providerClass)) {
throw AgroalLogger.SERVICE_LOGGER.invalidConnectionProvider();
}
}
dataSourceConfiguration.connectionPoolConfiguration().connectionFactoryConfiguration().connectionProviderClass(providerClass);
if (jta || xa) {
TransactionManager transactionManager = ContextTransactionManager.getInstance();
TransactionSynchronizationRegistry transactionSynchronizationRegistry = transactionSynchronizationRegistrySupplier != null ? transactionSynchronizationRegistrySupplier.get() : null;
if (transactionManager == null || transactionSynchronizationRegistry == null) {
throw AgroalLogger.SERVICE_LOGGER.missingTransactionManager();
}
TransactionIntegration txIntegration = new NarayanaTransactionIntegration(transactionManager, transactionSynchronizationRegistry, jndiName, connectable);
dataSourceConfiguration.connectionPoolConfiguration().transactionIntegration(txIntegration);
}
AuthenticationContext authenticationContext = authenticationContextSupplier != null ? authenticationContextSupplier.get() : null;
if (authenticationContext != null) {
try {
// Probably some other thing should be used as URI. Using jndiName for consistency with the datasources subsystem (simplicity as a bonus)
URI targetURI = new URI(jndiName);
NameCallback nameCallback = new NameCallback("Username: ");
PasswordCallback passwordCallback = new PasswordCallback("Password: ", false);
CredentialCallback credentialCallback = new CredentialCallback(GSSKerberosCredential.class);
AuthenticationConfiguration authenticationConfiguration = AUTH_CONFIG_CLIENT.getAuthenticationConfiguration(targetURI, authenticationContext, -1, "jdbc", "jboss");
AUTH_CONFIG_CLIENT.getCallbackHandler(authenticationConfiguration).handle(new Callback[] { nameCallback , passwordCallback, credentialCallback});
// if a GSSKerberosCredential was found, add the enclosed GSSCredential and KerberosTicket to the private set in the Subject.
if (credentialCallback.getCredential() != null) {
GSSKerberosCredential kerberosCredential = credentialCallback.getCredential(GSSKerberosCredential.class);
// use the GSSName to build a kerberos principal
dataSourceConfiguration.connectionPoolConfiguration().connectionFactoryConfiguration().principal(new NamePrincipal(kerberosCredential.getGssCredential().getName().toString()));
dataSourceConfiguration.connectionPoolConfiguration().connectionFactoryConfiguration().credential(kerberosCredential.getKerberosTicket());
dataSourceConfiguration.connectionPoolConfiguration().connectionFactoryConfiguration().credential(kerberosCredential.getGssCredential());
}
// use the name / password from the callbacks
if (nameCallback.getName() != null) {
dataSourceConfiguration.connectionPoolConfiguration().connectionFactoryConfiguration().principal(new NamePrincipal(nameCallback.getName()));
}
if (passwordCallback.getPassword() != null) {
dataSourceConfiguration.connectionPoolConfiguration().connectionFactoryConfiguration().credential(new SimplePassword(new String(passwordCallback.getPassword())));
}
} catch (URISyntaxException | UnsupportedCallbackException | IOException | GSSException e) {
throw AgroalLogger.SERVICE_LOGGER.invalidAuthentication(e, dataSourceName);
}
}
ExceptionSupplier<CredentialSource, Exception> credentialSourceExceptionExceptionSupplier = credentialSourceSupplier != null ? credentialSourceSupplier.get() : null;
if (credentialSourceExceptionExceptionSupplier != null) {
try {
String password = new String(credentialSourceExceptionExceptionSupplier.get().getCredential(PasswordCredential.class).getPassword(ClearPassword.class).getPassword());
dataSourceConfiguration.connectionPoolConfiguration().connectionFactoryConfiguration().credential(new SimplePassword(password));
} catch (Exception e) {
throw AgroalLogger.SERVICE_LOGGER.invalidCredentialSourceSupplier(e, dataSourceName);
}
}
try {
agroalDataSource = AgroalDataSource.from(dataSourceConfiguration, new LoggingDataSourceListener(dataSourceName));
ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(jndiName);
BinderService binderService = new BinderService(bindInfo.getBindName());
binderService.getManagedObjectInjector().inject(new ImmediateManagedReferenceFactory(agroalDataSource));
context.getChildTarget().addService(bindInfo.getBinderServiceName(), binderService)
.addDependency(bindInfo.getParentContextServiceName(), ServiceBasedNamingStore.class, binderService.getNamingStoreInjector())
.install();
if (xa) {
AgroalLogger.SERVICE_LOGGER.startedXADataSource(dataSourceName, jndiName);
} else {
AgroalLogger.SERVICE_LOGGER.startedDataSource(dataSourceName, jndiName);
}
} catch (SQLException e) {
agroalDataSource = null;
if (xa) {
throw AgroalLogger.SERVICE_LOGGER.xaDatasourceStartException(e, dataSourceName);
} else {
throw AgroalLogger.SERVICE_LOGGER.datasourceStartException(e, dataSourceName);
}
}
consumer.accept(agroalDataSource);
}
@Override
public void stop(StopContext context) {
consumer.accept(null);
agroalDataSource.close();
if (xa) {
AgroalLogger.SERVICE_LOGGER.stoppedXADataSource(dataSourceName);
} else {
AgroalLogger.SERVICE_LOGGER.stoppedDataSource(dataSourceName);
}
}
@Override
public AgroalDataSource getValue() throws IllegalStateException, IllegalArgumentException {
return agroalDataSource;
}
@Override
public AgroalDataSource get() {
return agroalDataSource;
}
}
| 12,519
| 52.276596
| 196
|
java
|
null |
wildfly-main/datasources-agroal/src/main/java/org/wildfly/extension/datasources/agroal/DriverOperations.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.AbstractRemoveStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.dmr.ModelNode;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleLoadException;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
import org.wildfly.extension.datasources.agroal.logging.AgroalLogger;
import java.lang.reflect.Method;
import java.sql.Driver;
import java.util.ServiceLoader;
/**
* Handler responsible for adding a driver resource to the model
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
* @author <a href="mailto:ropalka@redhat.com">Richard Opalka</a>
*/
class DriverOperations {
static final OperationStepHandler ADD_OPERATION = new DriverAdd();
static final OperationStepHandler REMOVE_OPERATION = new DriverRemove();
static final OperationStepHandler INFO_OPERATION = new DriverInfo();
// --- //
private static class DriverAdd extends AbstractAddStepHandler {
private DriverAdd() {
super(DriverDefinition.ATTRIBUTES);
}
private static Class<?> loadClass(String driverName, String moduleName, String className) throws IllegalArgumentException {
try {
Module module = Module.getCallerModuleLoader().loadModule(moduleName);
AgroalLogger.DRIVER_LOGGER.debugf("loaded module '%s' for driver: %s", moduleName, driverName);
Class<?> providerClass = module.getClassLoader().loadClass(className);
AgroalLogger.DRIVER_LOGGER.driverLoaded(className, driverName);
return providerClass;
} catch (ModuleLoadException e) {
throw AgroalLogger.DRIVER_LOGGER.loadModuleException(e, moduleName);
} catch (ClassNotFoundException e) {
throw AgroalLogger.DRIVER_LOGGER.loadClassException(e, className);
}
}
private static Class<?> loadDriver(String driverName, String moduleName) throws IllegalArgumentException {
try {
Module module = Module.getCallerModuleLoader().loadModule(moduleName);
AgroalLogger.DRIVER_LOGGER.debugf("loaded module '%s' for driver: %s", moduleName, driverName);
ServiceLoader<Driver> serviceLoader = module.loadService(Driver.class);
if (serviceLoader.iterator().hasNext()) {
// Consider just the first definition. User can use different implementation only with explicit declaration of class attribute
Class<?> driverClass = serviceLoader.iterator().next().getClass();
AgroalLogger.DRIVER_LOGGER.driverLoaded(driverClass.getName(), driverName);
return driverClass;
}
return null;
} catch (ModuleLoadException e) {
throw AgroalLogger.DRIVER_LOGGER.loadModuleException(e, moduleName);
}
}
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
String driverName = context.getCurrentAddressValue();
String moduleName = DriverDefinition.MODULE_ATTRIBUTE.resolveModelAttribute(context, model).asString();
boolean classDefined = DriverDefinition.CLASS_ATTRIBUTE.resolveModelAttribute(context, model).isDefined();
String className = classDefined ? DriverDefinition.CLASS_ATTRIBUTE.resolveModelAttribute(context, model).asString() : null;
Service<?> driverService = new Service<Class<?>>() {
@Override
public void start(final StartContext startContext) {
// noop
}
@Override
public void stop(final StopContext stopContext) {
// noop
}
@Override
public Class<?> getValue() throws IllegalStateException, IllegalArgumentException {
if (className != null) {
return loadClass(driverName, moduleName, className);
} else {
return loadDriver(driverName, moduleName);
}
}
};
context.getCapabilityServiceTarget().addCapability(DriverDefinition.AGROAL_DRIVER_CAPABILITY.fromBaseCapability(driverName)).setInstance(driverService).install();
}
}
// --- //
private static class DriverRemove extends AbstractRemoveStepHandler {
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
context.removeService(DriverDefinition.AGROAL_DRIVER_CAPABILITY.getCapabilityServiceName(context.getCurrentAddress()));
AgroalLogger.DRIVER_LOGGER.debugf("unloaded driver: %s", context.getCurrentAddressValue());
}
}
// --- //
private static class DriverInfo implements OperationStepHandler {
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
if (context.isNormalServer()) {
Class<?> providerClass = (Class<?>) context.getServiceRegistry(false).getService(DriverDefinition.AGROAL_DRIVER_CAPABILITY.getCapabilityServiceName(context.getCurrentAddress())).getValue();
if (providerClass == null) {
context.getResult().set(new ModelNode());
return;
}
ModelNode result = new ModelNode();
// consistent with io.agroal.pool.util.PropertyInjector
if (javax.sql.XADataSource.class.isAssignableFrom(providerClass) || javax.sql.DataSource.class.isAssignableFrom(providerClass)) {
for (Method method : providerClass.getMethods()) {
String name = method.getName();
if (method.getParameterCount() == 1 && name.startsWith("set")) {
result.get(name.substring(3)).set(method.getParameterTypes()[0].getName());
}
}
}
// from java.sql.Driver maybe use Driver.getPropertyInfo
context.getResult().set(result);
}
}
}
}
| 7,720
| 43.630058
| 205
|
java
|
null |
wildfly-main/datasources-agroal/src/main/java/org/wildfly/extension/datasources/agroal/XADataSourceOperations.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import io.agroal.api.AgroalDataSource;
import jakarta.transaction.TransactionSynchronizationRegistry;
import io.agroal.api.configuration.supplier.AgroalConnectionFactoryConfigurationSupplier;
import io.agroal.api.configuration.supplier.AgroalConnectionPoolConfigurationSupplier;
import io.agroal.api.configuration.supplier.AgroalDataSourceConfigurationSupplier;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.AbstractRemoveStepHandler;
import org.jboss.as.controller.CapabilityServiceBuilder;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceName;
import org.wildfly.common.function.ExceptionSupplier;
import org.wildfly.security.auth.client.AuthenticationContext;
import org.wildfly.security.credential.source.CredentialSource;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* Operations for adding and removing an xa-datasource resource to the model
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
* @author <a href="mailto:ropalka@redhat.com">Richard Opalka</a>
*/
class XADataSourceOperations extends AbstractAddStepHandler {
static final String XADATASOURCE_SERVICE_NAME = "xa-datasource";
// --- //
static final OperationStepHandler ADD_OPERATION = new XADataSourceAdd();
static final OperationStepHandler REMOVE_OPERATION = new XADataSourceRemove();
// --- //
private static class XADataSourceAdd extends AbstractAddStepHandler {
private XADataSourceAdd() {
super(XADataSourceDefinition.ATTRIBUTES);
}
@Override
@SuppressWarnings("unchecked")
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
String datasourceName = PathAddress.pathAddress(operation.require(OP_ADDR)).getLastElement().getValue();
ModelNode factoryModel = AbstractDataSourceDefinition.CONNECTION_FACTORY_ATTRIBUTE.resolveModelAttribute(context, model);
AgroalConnectionFactoryConfigurationSupplier connectionFactoryConfiguration = AbstractDataSourceOperations.connectionFactoryConfiguration(context, factoryModel);
ModelNode poolModel = AbstractDataSourceDefinition.CONNECTION_POOL_ATTRIBUTE.resolveModelAttribute(context, model);
AgroalConnectionPoolConfigurationSupplier connectionPoolConfiguration = AbstractDataSourceOperations.connectionPoolConfiguration(context, poolModel);
connectionPoolConfiguration.connectionFactoryConfiguration(connectionFactoryConfiguration);
AgroalDataSourceConfigurationSupplier dataSourceConfiguration = new AgroalDataSourceConfigurationSupplier();
dataSourceConfiguration.connectionPoolConfiguration(connectionPoolConfiguration);
dataSourceConfiguration.metricsEnabled(AbstractDataSourceDefinition.STATISTICS_ENABLED_ATTRIBUTE.resolveModelAttribute(context, model).asBoolean());
String jndiName = AbstractDataSourceDefinition.JNDI_NAME_ATTRIBUTE.resolveModelAttribute(context, model).asString();
String driverName = AbstractDataSourceDefinition.DRIVER_ATTRIBUTE.resolveModelAttribute(context, factoryModel).asString();
CapabilityServiceBuilder serviceBuilder = context.getCapabilityServiceTarget().addCapability(AbstractDataSourceDefinition.DATA_SOURCE_CAPABILITY.fromBaseCapability(datasourceName));
final Consumer<AgroalDataSource> consumer = serviceBuilder.provides(AbstractDataSourceDefinition.DATA_SOURCE_CAPABILITY.fromBaseCapability(datasourceName));
final Supplier<Class> driverSupplier = serviceBuilder.requiresCapability(DriverDefinition.AGROAL_DRIVER_CAPABILITY.getDynamicName(driverName), Class.class);
final Supplier<AuthenticationContext> authenticationContextSupplier = AbstractDataSourceOperations.setupAuthenticationContext(context, factoryModel, serviceBuilder);
final Supplier<ExceptionSupplier<CredentialSource, Exception>> credentialSourceSupplier = AbstractDataSourceOperations.setupCredentialReference(context, factoryModel, serviceBuilder);
// TODO add a Stage.MODEL requirement
final Supplier<TransactionSynchronizationRegistry> txnRegistrySupplier = serviceBuilder.requiresCapability("org.wildfly.transactions.transaction-synchronization-registry", TransactionSynchronizationRegistry.class);
DataSourceService dataSourceService = new DataSourceService(consumer, driverSupplier, authenticationContextSupplier, credentialSourceSupplier, txnRegistrySupplier, datasourceName, jndiName, false, false, true, dataSourceConfiguration);
serviceBuilder.setInstance(dataSourceService);
serviceBuilder.install();
}
}
// --- //
private static class XADataSourceRemove extends AbstractRemoveStepHandler {
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
String datasourceName = PathAddress.pathAddress(operation.require(OP_ADDR)).getLastElement().getValue();
ServiceName datasourceServiceName = AbstractDataSourceDefinition.DATA_SOURCE_CAPABILITY.getCapabilityServiceName(datasourceName);
context.removeService(datasourceServiceName);
}
}
}
| 6,727
| 57.504348
| 247
|
java
|
null |
wildfly-main/datasources-agroal/src/main/java/org/wildfly/extension/datasources/agroal/AgroalSubsystemParser_2_0.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PersistentResourceXMLDescription;
import org.jboss.as.controller.PersistentResourceXMLDescription.PersistentResourceXMLBuilder;
import org.jboss.as.controller.PersistentResourceXMLParser;
import static org.jboss.as.controller.PersistentResourceXMLDescription.builder;
/**
* The subsystem parser and marshaller, that reads the model to and from it's xml persistent representation
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
*/
class AgroalSubsystemParser_2_0 extends PersistentResourceXMLParser {
static final AgroalSubsystemParser_2_0 INSTANCE = new AgroalSubsystemParser_2_0();
private static final PersistentResourceXMLDescription XML_DESCRIPTION;
static {
PersistentResourceXMLBuilder subsystemXMLBuilder = builder(AgroalSubsystemDefinition.PATH, AgroalNamespace.AGROAL_2_0.getUriString());
PersistentResourceXMLBuilder datasourceXMLBuilder = builder(DataSourceDefinition.PATH);
for (AttributeDefinition attributeDefinition : DataSourceDefinition.ATTRIBUTES) {
datasourceXMLBuilder.addAttribute(attributeDefinition);
}
subsystemXMLBuilder.addChild(datasourceXMLBuilder);
PersistentResourceXMLBuilder xaDatasourceXMLBuilder = builder(XADataSourceDefinition.PATH);
for (AttributeDefinition attributeDefinition : XADataSourceDefinition.ATTRIBUTES) {
xaDatasourceXMLBuilder.addAttribute(attributeDefinition);
}
subsystemXMLBuilder.addChild(xaDatasourceXMLBuilder);
PersistentResourceXMLBuilder driverXMLBuilder = PersistentResourceXMLDescription.builder(DriverDefinition.PATH);
driverXMLBuilder.setXmlWrapperElement(DriverDefinition.DRIVERS_ELEMENT_NAME);
for (AttributeDefinition attributeDefinition : DriverDefinition.ATTRIBUTES) {
driverXMLBuilder.addAttribute(attributeDefinition);
}
subsystemXMLBuilder.addChild(driverXMLBuilder);
XML_DESCRIPTION = subsystemXMLBuilder.build();
}
private AgroalSubsystemParser_2_0() {
}
@Override
public PersistentResourceXMLDescription getParserDescription() {
return XML_DESCRIPTION;
}
}
| 3,316
| 43.226667
| 142
|
java
|
null |
wildfly-main/datasources-agroal/src/main/java/org/wildfly/extension/datasources/agroal/AgroalSubsystemParser_1_0.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PersistentResourceXMLDescription;
import org.jboss.as.controller.PersistentResourceXMLDescription.PersistentResourceXMLBuilder;
import org.jboss.as.controller.PersistentResourceXMLParser;
import static org.jboss.as.controller.PersistentResourceXMLDescription.builder;
/**
* The subsystem parser and marshaller, that reads the model to and from it's xml persistent representation
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
*/
class AgroalSubsystemParser_1_0 extends PersistentResourceXMLParser {
static final AgroalSubsystemParser_1_0 INSTANCE = new AgroalSubsystemParser_1_0();
private static final PersistentResourceXMLDescription XML_DESCRIPTION;
static {
PersistentResourceXMLBuilder subsystemXMLBuilder = builder(AgroalSubsystemDefinition.PATH, AgroalNamespace.AGROAL_1_0.getUriString());
PersistentResourceXMLBuilder datasourceXMLBuilder = builder(DataSourceDefinition.PATH);
for (AttributeDefinition attributeDefinition : DataSourceDefinition.ATTRIBUTES) {
datasourceXMLBuilder.addAttribute(attributeDefinition);
}
subsystemXMLBuilder.addChild(datasourceXMLBuilder);
PersistentResourceXMLBuilder xaDatasourceXMLBuilder = builder(XADataSourceDefinition.PATH);
for (AttributeDefinition attributeDefinition : XADataSourceDefinition.ATTRIBUTES) {
xaDatasourceXMLBuilder.addAttribute(attributeDefinition);
}
subsystemXMLBuilder.addChild(xaDatasourceXMLBuilder);
PersistentResourceXMLBuilder driverXMLBuilder = PersistentResourceXMLDescription.builder(DriverDefinition.PATH);
driverXMLBuilder.setXmlWrapperElement(DriverDefinition.DRIVERS_ELEMENT_NAME);
for (AttributeDefinition attributeDefinition : DriverDefinition.ATTRIBUTES) {
driverXMLBuilder.addAttribute(attributeDefinition);
}
subsystemXMLBuilder.addChild(driverXMLBuilder);
XML_DESCRIPTION = subsystemXMLBuilder.build();
}
private AgroalSubsystemParser_1_0() {
}
@Override
public PersistentResourceXMLDescription getParserDescription() {
return XML_DESCRIPTION;
}
}
| 3,316
| 43.226667
| 142
|
java
|
null |
wildfly-main/datasources-agroal/src/main/java/org/wildfly/extension/datasources/agroal/AbstractDataSourceOperations.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal;
import io.agroal.api.AgroalDataSource;
import io.agroal.api.AgroalDataSourceMetrics;
import io.agroal.api.configuration.AgroalConnectionFactoryConfiguration;
import io.agroal.api.configuration.AgroalConnectionFactoryConfiguration.TransactionIsolation;
import io.agroal.api.configuration.AgroalConnectionPoolConfiguration;
import io.agroal.api.configuration.supplier.AgroalConnectionFactoryConfigurationSupplier;
import io.agroal.api.configuration.supplier.AgroalConnectionPoolConfigurationSupplier;
import io.agroal.api.security.NamePrincipal;
import io.agroal.api.security.SimplePassword;
import org.jboss.as.controller.AbstractWriteAttributeHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.security.CredentialReference;
import org.jboss.as.controller.security.CredentialReferenceWriteAttributeHandler;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceRegistry;
import org.wildfly.common.function.ExceptionSupplier;
import org.wildfly.extension.datasources.agroal.logging.AgroalLogger;
import org.wildfly.security.auth.client.AuthenticationContext;
import org.wildfly.security.credential.source.CredentialSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.Duration;
import java.util.function.Supplier;
import static io.agroal.api.configuration.AgroalConnectionPoolConfiguration.ConnectionValidator.defaultValidator;
import static java.time.Duration.ofMillis;
import static java.time.Duration.ofMinutes;
/**
* Operations common to XA and non-XA DataSources
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
*/
class AbstractDataSourceOperations {
static final OperationStepHandler STATISTICS_ENABLED_WRITE_OPERATION = new StatisticsEnabledAttributeWriter(AbstractDataSourceDefinition.STATISTICS_ENABLED_ATTRIBUTE);
static final OperationStepHandler CONNECTION_FACTORY_WRITE_OPERATION = new ConnectionFactoryAttributeWriter(AbstractDataSourceDefinition.CONNECTION_FACTORY_ATTRIBUTE.getValueTypes());
static final OperationStepHandler CONNECTION_POOL_WRITE_OPERATION = new ConnectionPoolAttributeWriter(AbstractDataSourceDefinition.CONNECTION_POOL_ATTRIBUTE.getValueTypes());
static final OperationStepHandler CREDENTIAL_REFERENCE_WRITE_OPERATION = new CredentialReferenceWriteAttributeHandler(AbstractDataSourceDefinition.CREDENTIAL_REFERENCE);
// --- //
static final OperationStepHandler FLUSH_ALL_OPERATION = new FlushOperation(AgroalDataSource.FlushMode.ALL);
static final OperationStepHandler FLUSH_GRACEFUL_OPERATION = new FlushOperation(AgroalDataSource.FlushMode.GRACEFUL);
static final OperationStepHandler FLUSH_INVALID_OPERATION = new FlushOperation(AgroalDataSource.FlushMode.INVALID);
static final OperationStepHandler FLUSH_IDLE_OPERATION = new FlushOperation(AgroalDataSource.FlushMode.IDLE);
static final OperationStepHandler RESET_STATISTICS_OPERATION = new ResetStatisticsOperation();
static final OperationStepHandler STATISTICS_GET_OPERATION = new StatisticsGetOperation();
static final OperationStepHandler TEST_CONNECTION_OPERATION = new TestConnectionOperation();
// --- //
protected static AgroalConnectionFactoryConfigurationSupplier connectionFactoryConfiguration(OperationContext context, ModelNode model) throws OperationFailedException {
AgroalConnectionFactoryConfigurationSupplier configuration = new AgroalConnectionFactoryConfigurationSupplier();
if (AbstractDataSourceDefinition.URL_ATTRIBUTE.resolveModelAttribute(context, model).isDefined()) {
configuration.jdbcUrl(AbstractDataSourceDefinition.URL_ATTRIBUTE.resolveModelAttribute(context, model).asString());
}
if (AbstractDataSourceDefinition.NEW_CONNECTION_SQL_ATTRIBUTE.resolveModelAttribute(context, model).isDefined()) {
configuration.initialSql(AbstractDataSourceDefinition.NEW_CONNECTION_SQL_ATTRIBUTE.resolveModelAttribute(context, model).asString());
}
if (AbstractDataSourceDefinition.TRANSACTION_ISOLATION_ATTRIBUTE.resolveModelAttribute(context, model).isDefined()) {
configuration.jdbcTransactionIsolation(TransactionIsolation.valueOf(AbstractDataSourceDefinition.TRANSACTION_ISOLATION_ATTRIBUTE.resolveModelAttribute(context, model).asString()));
}
if (AbstractDataSourceDefinition.CONNECTION_PROPERTIES_ATTRIBUTE.resolveModelAttribute(context, model).isDefined()) {
for (Property jdbcProperty : AbstractDataSourceDefinition.CONNECTION_PROPERTIES_ATTRIBUTE.resolveModelAttribute(context, model).asPropertyList()) {
configuration.jdbcProperty(jdbcProperty.getName(), jdbcProperty.getValue().asString());
}
}
if (AbstractDataSourceDefinition.USERNAME_ATTRIBUTE.resolveModelAttribute(context, model).isDefined()) {
configuration.principal(new NamePrincipal(AbstractDataSourceDefinition.USERNAME_ATTRIBUTE.resolveModelAttribute(context, model).asString()));
}
if (AbstractDataSourceDefinition.PASSWORD_ATTRIBUTE.resolveModelAttribute(context, model).isDefined()) {
configuration.credential(new SimplePassword(AbstractDataSourceDefinition.PASSWORD_ATTRIBUTE.resolveModelAttribute(context, model).asString()));
}
return configuration;
}
protected static Supplier<AuthenticationContext> setupAuthenticationContext(OperationContext context, ModelNode model, ServiceBuilder<?> serviceBuilder) throws OperationFailedException {
if (AbstractDataSourceDefinition.AUTHENTICATION_CONTEXT.resolveModelAttribute(context, model).isDefined()) {
String authenticationContextName = AbstractDataSourceDefinition.AUTHENTICATION_CONTEXT.resolveModelAttribute(context, model).asString();
ServiceName authenticationContextCapability = context.getCapabilityServiceName(AbstractDataSourceDefinition.AUTHENTICATION_CONTEXT_CAPABILITY, authenticationContextName, AuthenticationContext.class);
return serviceBuilder.requires(authenticationContextCapability);
}
return null;
}
protected static Supplier<ExceptionSupplier<CredentialSource, Exception>> setupCredentialReference(OperationContext context, ModelNode model, ServiceBuilder<?> serviceBuilder) throws OperationFailedException {
if (AbstractDataSourceDefinition.CREDENTIAL_REFERENCE.resolveModelAttribute(context, model).isDefined()) {
ExceptionSupplier<CredentialSource, Exception> credentialSourceSupplier = CredentialReference.getCredentialSourceSupplier(context, AbstractDataSourceDefinition.CREDENTIAL_REFERENCE, model, serviceBuilder);
return () -> credentialSourceSupplier;
}
return null;
}
protected static AgroalConnectionPoolConfigurationSupplier connectionPoolConfiguration(OperationContext context, ModelNode model) throws OperationFailedException {
AgroalConnectionPoolConfigurationSupplier configuration = new AgroalConnectionPoolConfigurationSupplier();
configuration.maxSize(AbstractDataSourceDefinition.MAX_SIZE_ATTRIBUTE.resolveModelAttribute(context, model).asInt());
configuration.minSize(AbstractDataSourceDefinition.MIN_SIZE_ATTRIBUTE.resolveModelAttribute(context, model).asInt());
configuration.initialSize(AbstractDataSourceDefinition.INITIAL_SIZE_ATTRIBUTE.resolveModelAttribute(context, model).asInt());
configuration.acquisitionTimeout(ofMillis(AbstractDataSourceDefinition.BLOCKING_TIMEOUT_MILLIS_ATTRIBUTE.resolveModelAttribute(context, model).asInt()));
configuration.leakTimeout(ofMillis(AbstractDataSourceDefinition.LEAK_DETECTION_ATTRIBUTE.resolveModelAttribute(context, model).asInt()));
configuration.validationTimeout(ofMillis(AbstractDataSourceDefinition.BACKGROUND_VALIDATION_ATTRIBUTE.resolveModelAttribute(context, model).asInt()));
configuration.reapTimeout(ofMinutes(AbstractDataSourceDefinition.IDLE_REMOVAL_ATTRIBUTE.resolveModelAttribute(context, model).asInt()));
configuration.connectionValidator(defaultValidator());
return configuration;
}
// --- //
private static AgroalDataSource getDataSource(OperationContext context) throws OperationFailedException {
ServiceRegistry registry = context.getServiceRegistry(false);
String dataSourceName = context.getCurrentAddressValue();
switch (context.getCurrentAddress().getLastElement().getKey()) {
case DataSourceOperations.DATASOURCE_SERVICE_NAME:
ServiceController<?> controller = registry.getRequiredService(AbstractDataSourceDefinition.DATA_SOURCE_CAPABILITY.getCapabilityServiceName(dataSourceName));
return ((AgroalDataSource) controller.getValue());
case XADataSourceOperations.XADATASOURCE_SERVICE_NAME:
ServiceController<?> xaController = registry.getRequiredService(AbstractDataSourceDefinition.DATA_SOURCE_CAPABILITY.getCapabilityServiceName(dataSourceName));
return ((AgroalDataSource) xaController.getValue());
default:
throw AgroalLogger.SERVICE_LOGGER.unknownDatasourceServiceType(context.getCurrentAddress().getLastElement().getKey());
}
}
// --- //
private static class StatisticsEnabledAttributeWriter extends AbstractWriteAttributeHandler<Boolean> {
private StatisticsEnabledAttributeWriter(AttributeDefinition... definitions) {
super(definitions);
}
@Override
protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<Boolean> handbackHolder) throws OperationFailedException {
getDataSource(context).getConfiguration().setMetricsEnabled(resolvedValue.asBoolean());
return false;
}
@Override
protected void revertUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode valueToRestore, ModelNode valueToRevert, Boolean handback) throws OperationFailedException {
getDataSource(context).getConfiguration().setMetricsEnabled(valueToRevert.asBoolean());
}
}
private static class ConnectionFactoryAttributeWriter extends AbstractWriteAttributeHandler<AgroalConnectionFactoryConfiguration> {
private ConnectionFactoryAttributeWriter(AttributeDefinition... definitions) {
super(definitions);
}
@Override
protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<AgroalConnectionFactoryConfiguration> handbackHolder) throws OperationFailedException {
// At the moment no attributes support hot. Required
return false;
}
@Override
protected void revertUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode valueToRestore, ModelNode valueToRevert, AgroalConnectionFactoryConfiguration handback) throws OperationFailedException {
}
}
private static class ConnectionPoolAttributeWriter extends AbstractWriteAttributeHandler<AgroalConnectionPoolConfiguration> {
private ConnectionPoolAttributeWriter(AttributeDefinition... definitions) {
super(definitions);
}
@Override
protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<AgroalConnectionPoolConfiguration> handbackHolder) throws OperationFailedException {
ModelNode newBlockingTimeout = resolvedValue.remove(AbstractDataSourceDefinition.BLOCKING_TIMEOUT_MILLIS_ATTRIBUTE.getName());
ModelNode newMaxSize = resolvedValue.remove(AbstractDataSourceDefinition.MAX_SIZE_ATTRIBUTE.getName());
ModelNode newMinSize = resolvedValue.remove(AbstractDataSourceDefinition.MIN_SIZE_ATTRIBUTE.getName());
for (String attribute : resolvedValue.keys()) {
if (!currentValue.hasDefined(attribute) || !resolvedValue.get(attribute).equals(currentValue.get(attribute))) {
// Other attributes changed. Restart required
return true;
}
}
if (newBlockingTimeout != null) {
getDataSource(context).getConfiguration().connectionPoolConfiguration().setAcquisitionTimeout(Duration.ofMillis(newBlockingTimeout.asInt()));
}
if (newMaxSize != null) {
getDataSource(context).getConfiguration().connectionPoolConfiguration().setMaxSize(newMaxSize.asInt());
// if max-size decreases Agroal will gracefully destroy connections when they are returned to the pool, so there is nothing to do here
}
if (newMinSize != null) {
getDataSource(context).getConfiguration().connectionPoolConfiguration().setMinSize(newMinSize.asInt());
// if min-size increases Agroal will create new connections when looking into the (shared) pool. FlushMode.FILL could be used here to enforce the new min-size
}
return false;
}
@Override
protected void revertUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode valueToRestore, ModelNode valueToRevert, AgroalConnectionPoolConfiguration handback) throws OperationFailedException {
ModelNode newBlockingTimeout = valueToRevert.remove(AbstractDataSourceDefinition.BLOCKING_TIMEOUT_MILLIS_ATTRIBUTE.getName());
ModelNode newMaxSize = valueToRevert.remove(AbstractDataSourceDefinition.MAX_SIZE_ATTRIBUTE.getName());
ModelNode newMinSize = valueToRevert.remove(AbstractDataSourceDefinition.MIN_SIZE_ATTRIBUTE.getName());
if (newBlockingTimeout != null) {
getDataSource(context).getConfiguration().connectionPoolConfiguration().setAcquisitionTimeout(Duration.ofMillis(newBlockingTimeout.asInt()));
}
if (newMinSize != null) {
getDataSource(context).getConfiguration().connectionPoolConfiguration().setMinSize(newMinSize.asInt());
}
if (newMaxSize != null) {
getDataSource(context).getConfiguration().connectionPoolConfiguration().setMaxSize(newMaxSize.asInt());
}
}
}
// --- //
private static class FlushOperation implements OperationStepHandler {
private AgroalDataSource.FlushMode mode;
private FlushOperation(AgroalDataSource.FlushMode mode) {
this.mode = mode;
}
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
if (context.isNormalServer()) {
AgroalLogger.SERVICE_LOGGER.flushOperation(mode);
getDataSource(context).flush(mode);
}
}
}
// --- //
private static class StatisticsGetOperation implements OperationStepHandler {
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
if (context.isNormalServer()) {
AgroalDataSourceMetrics metrics = getDataSource(context).getMetrics();
ModelNode result = new ModelNode();
result.get(AbstractDataSourceDefinition.STATISTICS_ACQUIRE_COUNT_ATTRIBUTE.getName()).set(metrics.acquireCount());
result.get(AbstractDataSourceDefinition.STATISTICS_ACTIVE_COUNT_ATTRIBUTE.getName()).set(metrics.activeCount());
result.get(AbstractDataSourceDefinition.STATISTICS_AVAILABLE_COUNT_ATTRIBUTE.getName()).set(metrics.availableCount());
result.get(AbstractDataSourceDefinition.STATISTICS_AWAITING_COUNT_ATTRIBUTE.getName()).set(metrics.awaitingCount());
result.get(AbstractDataSourceDefinition.STATISTICS_CREATION_COUNT_ATTRIBUTE.getName()).set(metrics.creationCount());
result.get(AbstractDataSourceDefinition.STATISTICS_DESTOY_COUNT_ATTRIBUTE.getName()).set(metrics.destroyCount());
result.get(AbstractDataSourceDefinition.STATISTICS_FLUSH_COUNT_ATTRIBUTE.getName()).set(metrics.flushCount());
result.get(AbstractDataSourceDefinition.STATISTICS_INVALID_COUNT_ATTRIBUTE.getName()).set(metrics.invalidCount());
result.get(AbstractDataSourceDefinition.STATISTICS_LEAK_DETECTION_COUNT_ATTRIBUTE.getName()).set(metrics.leakDetectionCount());
result.get(AbstractDataSourceDefinition.STATISTICS_MAX_USED_COUNT_ATTRIBUTE.getName()).set(metrics.maxUsedCount());
result.get(AbstractDataSourceDefinition.STATISTICS_REAP_COUNT_ATTRIBUTE.getName()).set(metrics.reapCount());
result.get(AbstractDataSourceDefinition.STATISTICS_BLOCKING_TIME_AVERAGE_ATTRIBUTE.getName()).set(metrics.blockingTimeAverage().toMillis());
result.get(AbstractDataSourceDefinition.STATISTICS_BLOCKING_TIME_MAX_ATTRIBUTE.getName()).set(metrics.blockingTimeMax().toMillis());
result.get(AbstractDataSourceDefinition.STATISTICS_BLOCKING_TIME_TOTAL_ATTRIBUTE.getName()).set(metrics.blockingTimeTotal().toMillis());
result.get(AbstractDataSourceDefinition.STATISTICS_CREATION_TIME_AVERAGE_ATTRIBUTE.getName()).set(metrics.creationTimeAverage().toMillis());
result.get(AbstractDataSourceDefinition.STATISTICS_CREATION_TIME_MAX_ATTRIBUTE.getName()).set(metrics.creationTimeMax().toMillis());
result.get(AbstractDataSourceDefinition.STATISTICS_CREATION_TIME_TOTAL_ATTRIBUTE.getName()).set(metrics.creationTimeTotal().toMillis());
context.getResult().set(result);
}
}
}
private static class ResetStatisticsOperation implements OperationStepHandler {
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
if (context.isNormalServer()) {
getDataSource(context).getMetrics().reset();
}
}
}
// --- //
private static class TestConnectionOperation implements OperationStepHandler {
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
if (context.isNormalServer()) {
try (Connection connection = getDataSource(context).getConnection()) {
context.getResult().set(new ModelNode().add(connection.isValid(0)));
} catch (SQLException e) {
throw AgroalLogger.SERVICE_LOGGER.invalidConnection(e, context.getCurrentAddressValue());
}
}
}
}
}
| 20,391
| 58.107246
| 267
|
java
|
null |
wildfly-main/datasources-agroal/src/main/java/org/wildfly/extension/datasources/agroal/AbstractDataSourceDefinition.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal;
import static io.agroal.api.configuration.AgroalConnectionFactoryConfiguration.TransactionIsolation.NONE;
import static io.agroal.api.configuration.AgroalConnectionFactoryConfiguration.TransactionIsolation.READ_COMMITTED;
import static io.agroal.api.configuration.AgroalConnectionFactoryConfiguration.TransactionIsolation.READ_UNCOMMITTED;
import static io.agroal.api.configuration.AgroalConnectionFactoryConfiguration.TransactionIsolation.REPEATABLE_READ;
import static io.agroal.api.configuration.AgroalConnectionFactoryConfiguration.TransactionIsolation.SERIALIZABLE;
import static org.jboss.as.controller.SimpleAttributeDefinitionBuilder.create;
import java.util.EnumSet;
import javax.sql.DataSource;
import io.agroal.api.configuration.AgroalConnectionFactoryConfiguration;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.ObjectTypeAttributeDefinition;
import org.jboss.as.controller.OperationDefinition;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PersistentResourceDefinition;
import org.jboss.as.controller.PropertiesAttributeDefinition;
import org.jboss.as.controller.ReloadRequiredWriteAttributeHandler;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleOperationDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.client.helpers.MeasurementUnit;
import org.jboss.as.controller.operations.validation.EnumValidator;
import org.jboss.as.controller.operations.validation.IntRangeValidator;
import org.jboss.as.controller.operations.validation.ParameterValidator;
import org.jboss.as.controller.operations.validation.StringLengthValidator;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.security.CredentialReference;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.wildfly.extension.datasources.agroal.logging.AgroalLogger;
/**
* Common Definition for the datasource resource
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
*/
abstract class AbstractDataSourceDefinition extends PersistentResourceDefinition {
private static final String DATA_SOURCE_CAPABILITY_NAME = "org.wildfly.data-source";
public static final RuntimeCapability<Void> DATA_SOURCE_CAPABILITY = RuntimeCapability.Builder.of(DATA_SOURCE_CAPABILITY_NAME, true, DataSource.class).build();
static final String AUTHENTICATION_CONTEXT_CAPABILITY = "org.wildfly.security.authentication-context";
static final SimpleAttributeDefinition JNDI_NAME_ATTRIBUTE = create("jndi-name", ModelType.STRING)
.setAllowExpression(true)
.setRestartAllServices()
.setValidator(new ParameterValidator() {
@Override
public void validateParameter(String parameterName, ModelNode value) throws OperationFailedException {
if (value.getType() != ModelType.EXPRESSION) {
String str = value.asString();
if (!str.startsWith("java:/") && !str.startsWith("java:jboss/")) {
throw AgroalLogger.SERVICE_LOGGER.jndiNameInvalidFormat();
} else if (str.endsWith("/") || str.contains("//")) {
throw AgroalLogger.SERVICE_LOGGER.jndiNameShouldValidate();
}
}
}
})
.build();
static final SimpleAttributeDefinition STATISTICS_ENABLED_ATTRIBUTE = create("statistics-enabled", ModelType.BOOLEAN)
.setAllowExpression(true)
.setDefaultValue(ModelNode.FALSE)
.setRequired(false)
.build();
// --- connection-factory attributes //
static final SimpleAttributeDefinition DRIVER_ATTRIBUTE = create("driver", ModelType.STRING)
.setRequires()
.setRestartAllServices()
.setValidator(new StringLengthValidator(1))
.build();
static final SimpleAttributeDefinition URL_ATTRIBUTE = create("url", ModelType.STRING)
.setAllowExpression(true)
.setRestartAllServices()
.setRequired(false)
.setValidator(new StringLengthValidator(1))
.build();
static final SimpleAttributeDefinition TRANSACTION_ISOLATION_ATTRIBUTE = create("transaction-isolation", ModelType.STRING)
.setAllowExpression(true)
.setAllowedValues(NONE.name(), READ_UNCOMMITTED.name(), READ_COMMITTED.name(), REPEATABLE_READ.name(), SERIALIZABLE.name())
.setRequired(false)
.setRestartAllServices()
.setValidator(EnumValidator.create(AgroalConnectionFactoryConfiguration.TransactionIsolation.class, EnumSet.allOf(AgroalConnectionFactoryConfiguration.TransactionIsolation.class)))
.build();
static final SimpleAttributeDefinition NEW_CONNECTION_SQL_ATTRIBUTE = create("new-connection-sql", ModelType.STRING)
.setAllowExpression(true)
.setRequired(false)
.setRestartAllServices()
.build();
static final SimpleAttributeDefinition USERNAME_ATTRIBUTE = create("username", ModelType.STRING)
.addAccessConstraint(SensitiveTargetAccessConstraintDefinition.CREDENTIAL)
.addAlternatives("elytron-domain")
.setAllowExpression(true)
.setAttributeGroup("security")
.setRequired(false)
.setRestartAllServices()
.setValidator(new StringLengthValidator(1))
.build();
static final SimpleAttributeDefinition PASSWORD_ATTRIBUTE = create("password", ModelType.STRING)
.addAccessConstraint(SensitiveTargetAccessConstraintDefinition.CREDENTIAL)
.addAlternatives(CredentialReference.CREDENTIAL_REFERENCE)
.setAllowExpression(true)
.setAttributeGroup("security")
.setRequired(false)
.setRequires(USERNAME_ATTRIBUTE.getName())
.setRestartAllServices()
.setValidator(new StringLengthValidator(1))
.build();
static SimpleAttributeDefinition AUTHENTICATION_CONTEXT = new SimpleAttributeDefinitionBuilder("authentication-context", ModelType.STRING, true)
.addAccessConstraint(SensitiveTargetAccessConstraintDefinition.AUTHENTICATION_CLIENT_REF)
.addAlternatives(USERNAME_ATTRIBUTE.getName())
.setCapabilityReference(AUTHENTICATION_CONTEXT_CAPABILITY, DATA_SOURCE_CAPABILITY)
.setRestartAllServices()
.build();
static final ObjectTypeAttributeDefinition CREDENTIAL_REFERENCE = CredentialReference.getAttributeBuilder(true, true)
.addAlternatives(PASSWORD_ATTRIBUTE.getName())
.setAttributeGroup("security")
.build();
static final PropertiesAttributeDefinition CONNECTION_PROPERTIES_ATTRIBUTE = new PropertiesAttributeDefinition.Builder("connection-properties", true)
.setAllowExpression(true)
.setRequired(false)
.setRestartAllServices()
.build();
static final ObjectTypeAttributeDefinition CONNECTION_FACTORY_ATTRIBUTE = ObjectTypeAttributeDefinition.create("connection-factory", DRIVER_ATTRIBUTE, URL_ATTRIBUTE, TRANSACTION_ISOLATION_ATTRIBUTE, NEW_CONNECTION_SQL_ATTRIBUTE, USERNAME_ATTRIBUTE, PASSWORD_ATTRIBUTE, AUTHENTICATION_CONTEXT, CREDENTIAL_REFERENCE, CONNECTION_PROPERTIES_ATTRIBUTE)
.setRestartAllServices()
.build();
// --- connection-pool attributes //
static final SimpleAttributeDefinition MAX_SIZE_ATTRIBUTE = create("max-size", ModelType.INT)
.setAllowExpression(true)
.setValidator(new IntRangeValidator(0) )
.build();
static final SimpleAttributeDefinition MIN_SIZE_ATTRIBUTE = create("min-size", ModelType.INT)
.setAllowExpression(true)
.setDefaultValue(ModelNode.ZERO)
.setRequired(false)
.setValidator(new IntRangeValidator(0) )
.build();
static final SimpleAttributeDefinition INITIAL_SIZE_ATTRIBUTE = create("initial-size", ModelType.INT)
.setAllowExpression(true)
.setDefaultValue(ModelNode.ZERO)
.setRequired(false)
.setRestartAllServices()
.setValidator(new IntRangeValidator(0) )
.build();
// Agroal will validate that min-size <= initial-size <= max-size
static final SimpleAttributeDefinition BLOCKING_TIMEOUT_MILLIS_ATTRIBUTE = create("blocking-timeout", ModelType.INT)
.setAllowExpression(true)
.setDefaultValue(ModelNode.ZERO)
.setMeasurementUnit(MeasurementUnit.MILLISECONDS)
.setRequired(false)
.build();
static final SimpleAttributeDefinition BACKGROUND_VALIDATION_ATTRIBUTE = create("background-validation", ModelType.INT)
.setAllowExpression(true)
.setDefaultValue(ModelNode.ZERO)
.setMeasurementUnit(MeasurementUnit.MILLISECONDS)
.setRequired(false)
.setRestartAllServices()
.build();
static final SimpleAttributeDefinition LEAK_DETECTION_ATTRIBUTE = create("leak-detection", ModelType.INT)
.setAllowExpression(true)
.setDefaultValue(ModelNode.ZERO)
.setMeasurementUnit(MeasurementUnit.MILLISECONDS)
.setRequired(false)
.setRestartAllServices()
.build();
static final SimpleAttributeDefinition IDLE_REMOVAL_ATTRIBUTE = create("idle-removal", ModelType.INT)
.setAllowExpression(true)
.setDefaultValue(ModelNode.ZERO)
.setMeasurementUnit(MeasurementUnit.MINUTES)
.setRequired(false)
.setRestartAllServices()
.build();
static final ObjectTypeAttributeDefinition CONNECTION_POOL_ATTRIBUTE = ObjectTypeAttributeDefinition.create("connection-pool", MAX_SIZE_ATTRIBUTE, MIN_SIZE_ATTRIBUTE, INITIAL_SIZE_ATTRIBUTE, BLOCKING_TIMEOUT_MILLIS_ATTRIBUTE, BACKGROUND_VALIDATION_ATTRIBUTE, LEAK_DETECTION_ATTRIBUTE, IDLE_REMOVAL_ATTRIBUTE)
.build();
// --- Operations //
private static final OperationDefinition FLUSH_ALL = new SimpleOperationDefinitionBuilder("flush-all", AgroalExtension.SUBSYSTEM_RESOLVER).build();
private static final OperationDefinition FLUSH_GRACEFUL = new SimpleOperationDefinitionBuilder("flush-graceful", AgroalExtension.SUBSYSTEM_RESOLVER).build();
private static final OperationDefinition FLUSH_INVALID = new SimpleOperationDefinitionBuilder("flush-invalid", AgroalExtension.SUBSYSTEM_RESOLVER).build();
private static final OperationDefinition FLUSH_IDLE = new SimpleOperationDefinitionBuilder("flush-idle", AgroalExtension.SUBSYSTEM_RESOLVER).build();
private static final OperationDefinition RESET_STATISTICS = new SimpleOperationDefinitionBuilder("reset-statistics", AgroalExtension.SUBSYSTEM_RESOLVER).build();
private static final OperationDefinition TEST_CONNECTION = new SimpleOperationDefinitionBuilder("test-connection", AgroalExtension.SUBSYSTEM_RESOLVER).build();
// --- Runtime attributes //
static final SimpleAttributeDefinition STATISTICS_ACQUIRE_COUNT_ATTRIBUTE = create("acquire-count", ModelType.INT)
.setStorageRuntime()
.build();
static final SimpleAttributeDefinition STATISTICS_ACTIVE_COUNT_ATTRIBUTE = create("active-count", ModelType.INT)
.setStorageRuntime()
.build();
static final SimpleAttributeDefinition STATISTICS_AVAILABLE_COUNT_ATTRIBUTE = create("available-count", ModelType.INT)
.setStorageRuntime()
.build();
static final SimpleAttributeDefinition STATISTICS_AWAITING_COUNT_ATTRIBUTE = create("awaiting-count", ModelType.INT)
.setStorageRuntime()
.build();
static final SimpleAttributeDefinition STATISTICS_CREATION_COUNT_ATTRIBUTE = create("creation-count", ModelType.INT)
.setStorageRuntime()
.build();
static final SimpleAttributeDefinition STATISTICS_DESTOY_COUNT_ATTRIBUTE = create("destroy-count", ModelType.INT)
.setStorageRuntime()
.build();
static final SimpleAttributeDefinition STATISTICS_FLUSH_COUNT_ATTRIBUTE = create("flush-count", ModelType.INT)
.setStorageRuntime()
.build();
static final SimpleAttributeDefinition STATISTICS_INVALID_COUNT_ATTRIBUTE = create("invalid-count", ModelType.INT)
.setStorageRuntime()
.build();
static final SimpleAttributeDefinition STATISTICS_LEAK_DETECTION_COUNT_ATTRIBUTE = create("leak-detection-count", ModelType.INT)
.setStorageRuntime()
.build();
static final SimpleAttributeDefinition STATISTICS_MAX_USED_COUNT_ATTRIBUTE = create("max-used-count", ModelType.INT)
.setStorageRuntime()
.build();
static final SimpleAttributeDefinition STATISTICS_REAP_COUNT_ATTRIBUTE = create("reap-count", ModelType.INT)
.setStorageRuntime()
.build();
static final SimpleAttributeDefinition STATISTICS_BLOCKING_TIME_AVERAGE_ATTRIBUTE = create("blocking-time-average-ms", ModelType.INT)
.setMeasurementUnit(MeasurementUnit.MILLISECONDS)
.setStorageRuntime()
.build();
static final SimpleAttributeDefinition STATISTICS_BLOCKING_TIME_MAX_ATTRIBUTE = create("blocking-time-max-ms", ModelType.INT)
.setMeasurementUnit(MeasurementUnit.MILLISECONDS)
.setStorageRuntime()
.build();
static final SimpleAttributeDefinition STATISTICS_BLOCKING_TIME_TOTAL_ATTRIBUTE = create("blocking-time-total-ms", ModelType.INT)
.setMeasurementUnit(MeasurementUnit.MILLISECONDS)
.setStorageRuntime()
.build();
static final SimpleAttributeDefinition STATISTICS_CREATION_TIME_AVERAGE_ATTRIBUTE = create("creation-time-average-ms", ModelType.INT)
.setMeasurementUnit(MeasurementUnit.MILLISECONDS)
.setStorageRuntime()
.build();
static final SimpleAttributeDefinition STATISTICS_CREATION_TIME_MAX_ATTRIBUTE = create("creation-time-max-ms", ModelType.INT)
.setMeasurementUnit(MeasurementUnit.MILLISECONDS)
.setStorageRuntime()
.build();
static final SimpleAttributeDefinition STATISTICS_CREATION_TIME_TOTAL_ATTRIBUTE = create("creation-time-total-ms", ModelType.INT)
.setMeasurementUnit(MeasurementUnit.MILLISECONDS)
.setStorageRuntime()
.build();
private static final ObjectTypeAttributeDefinition STATISTICS = ObjectTypeAttributeDefinition.create("statistics", STATISTICS_ACQUIRE_COUNT_ATTRIBUTE, STATISTICS_ACTIVE_COUNT_ATTRIBUTE, STATISTICS_AVAILABLE_COUNT_ATTRIBUTE, STATISTICS_AWAITING_COUNT_ATTRIBUTE, STATISTICS_CREATION_COUNT_ATTRIBUTE, STATISTICS_DESTOY_COUNT_ATTRIBUTE, STATISTICS_FLUSH_COUNT_ATTRIBUTE, STATISTICS_INVALID_COUNT_ATTRIBUTE, STATISTICS_LEAK_DETECTION_COUNT_ATTRIBUTE, STATISTICS_MAX_USED_COUNT_ATTRIBUTE, STATISTICS_REAP_COUNT_ATTRIBUTE, STATISTICS_BLOCKING_TIME_AVERAGE_ATTRIBUTE, STATISTICS_BLOCKING_TIME_MAX_ATTRIBUTE, STATISTICS_BLOCKING_TIME_TOTAL_ATTRIBUTE, STATISTICS_CREATION_TIME_AVERAGE_ATTRIBUTE, STATISTICS_CREATION_TIME_MAX_ATTRIBUTE, STATISTICS_CREATION_TIME_TOTAL_ATTRIBUTE)
.setRequired(false)
.setStorageRuntime()
.build();
// --- //
AbstractDataSourceDefinition(SimpleResourceDefinition.Parameters parameters) {
super(parameters.setCapabilities(DATA_SOURCE_CAPABILITY));
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
ReloadRequiredWriteAttributeHandler handler = new ReloadRequiredWriteAttributeHandler(getAttributes());
for (AttributeDefinition attributeDefinition : getAttributes()) {
OperationStepHandler writeHandler = handler;
if (attributeDefinition == STATISTICS_ENABLED_ATTRIBUTE) {
writeHandler = AbstractDataSourceOperations.STATISTICS_ENABLED_WRITE_OPERATION;
}
if (attributeDefinition == CONNECTION_FACTORY_ATTRIBUTE) {
writeHandler = AbstractDataSourceOperations.CONNECTION_FACTORY_WRITE_OPERATION;
}
if (attributeDefinition == CONNECTION_POOL_ATTRIBUTE) {
writeHandler = AbstractDataSourceOperations.CONNECTION_POOL_WRITE_OPERATION;
}
if (attributeDefinition == CREDENTIAL_REFERENCE) {
writeHandler = AbstractDataSourceOperations.CREDENTIAL_REFERENCE_WRITE_OPERATION;
}
resourceRegistration.registerReadWriteAttribute(attributeDefinition, null, writeHandler);
}
// Runtime attributes
if (resourceRegistration.getProcessType().isServer()) {
resourceRegistration.registerReadOnlyAttribute(STATISTICS, AbstractDataSourceOperations.STATISTICS_GET_OPERATION);
}
}
@Override
public void registerOperations(ManagementResourceRegistration resourceRegistration) {
super.registerOperations(resourceRegistration);
if (resourceRegistration.getProcessType().isServer()) {
resourceRegistration.registerOperationHandler(FLUSH_ALL, AbstractDataSourceOperations.FLUSH_ALL_OPERATION);
resourceRegistration.registerOperationHandler(FLUSH_GRACEFUL, AbstractDataSourceOperations.FLUSH_GRACEFUL_OPERATION);
resourceRegistration.registerOperationHandler(FLUSH_INVALID, AbstractDataSourceOperations.FLUSH_INVALID_OPERATION);
resourceRegistration.registerOperationHandler(FLUSH_IDLE, AbstractDataSourceOperations.FLUSH_IDLE_OPERATION);
resourceRegistration.registerOperationHandler(RESET_STATISTICS, AbstractDataSourceOperations.RESET_STATISTICS_OPERATION);
resourceRegistration.registerOperationHandler(TEST_CONNECTION, AbstractDataSourceOperations.TEST_CONNECTION_OPERATION);
}
}
}
| 19,737
| 51.91689
| 771
|
java
|
null |
wildfly-main/datasources-agroal/src/main/java/org/wildfly/extension/datasources/agroal/logging/AgroalLogger.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal.logging;
import io.agroal.api.AgroalDataSource;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
import org.jboss.msc.service.StartException;
import java.sql.SQLException;
import static org.jboss.logging.Logger.Level.INFO;
import static org.jboss.logging.Logger.Level.WARN;
import static org.jboss.logging.Logger.getMessageLogger;
/**
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
*/
@MessageLogger(projectCode = "WFLYAG", length = 4)
public interface AgroalLogger extends BasicLogger {
AgroalLogger DRIVER_LOGGER = getMessageLogger(AgroalLogger.class, "org.wildfly.extension.datasources.agroal.driver");
AgroalLogger SERVICE_LOGGER = getMessageLogger(AgroalLogger.class, "org.wildfly.extension.datasources.agroal");
AgroalLogger POOL_LOGGER = getMessageLogger(AgroalLogger.class, "io.agroal.pool");
// --- Extension //
@LogMessage(level = INFO)
@Message(id = 1, value = "Adding deployment processors for DataSourceDefinition annotation and resource-ref entries")
void addingDeploymentProcessors();
// --- Datasource service //
@LogMessage(level = INFO)
@Message(id = 101, value = "Started datasource '%s' bound to [%s]")
void startedDataSource(String datasource, String jndiName);
@LogMessage(level = INFO)
@Message(id = 102, value = "Stopped datasource '%s'")
void stoppedDataSource(String datasource);
@LogMessage(level = INFO)
@Message(id = 103, value = "Started xa-datasource '%s' bound to [%s]")
void startedXADataSource(String datasource, String jndiName);
@LogMessage(level = INFO)
@Message(id = 104, value = "Stopped xa-datasource '%s'")
void stoppedXADataSource(String datasource);
@Message(id = 105, value = "Exception starting datasource '%s'")
StartException datasourceStartException(@Cause SQLException cause, String dataSourceName);
@Message(id = 106, value = "Exception starting xa-datasource '%s'")
StartException xaDatasourceStartException(@Cause SQLException cause, String dataSourceName);
@Message(id = 107, value = "Invalid connection provider. Either a java.sql.Driver or javax.sql.DataSource implementation is required. Fix the connection-provider for the driver")
StartException invalidConnectionProvider();
@Message(id = 108, value = "An xa-datasource requires a javax.sql.XADataSource as connection provider. Fix the connection-provider for the driver")
StartException invalidXAConnectionProvider();
@Message(id = 109, value = "Could not start datasource: transaction manager is missing")
StartException missingTransactionManager();
@Message(id = 110, value = "Error obtaining credentials from authentication context for datasource '%s'")
StartException invalidAuthentication(@Cause Throwable cause, String dataSourceName);
@Message(id = 111, value = "CredentialSourceSupplier for datasource '%s' is invalid")
StartException invalidCredentialSourceSupplier(@Cause Throwable cause, String dataSourceName);
// --- Driver service //
@LogMessage(level = INFO)
@Message(id = 201, value = "Performing flush operation, mode %s")
void flushOperation(AgroalDataSource.FlushMode mode);
// -- Operations //
@Message(id = 301, value = "Unknown datasource service of type: %s")
OperationFailedException unknownDatasourceServiceType(String serviceType);
@Message(id = 302, value = "Invalid connection in '%s'")
OperationFailedException invalidConnection(@Cause SQLException cause, String dataSourceName);
@Message(id = 303, value = "JNDI name have to start with java:/ or java:jboss/")
OperationFailedException jndiNameInvalidFormat();
@Message(id = 304, value = "JNDI name shouldn't include '//' or end with '/'")
OperationFailedException jndiNameShouldValidate();
// -- Deployment //
@Message(id = 401, value = "Invalid connection provider. Either a java.sql.Driver or javax.sql.DataSource implementation is required. Fix the connection-provider for the driver")
DeploymentUnitProcessingException invalidDeploymentConnectionProvider();
@Message(id = 402, value = "Failed to load connection provider class '%s'")
DeploymentUnitProcessingException loadClassDeploymentException(@Cause Throwable cause, String className);
@Message(id = 403, value = "Element <data-source> must provide attribute '%s'")
DeploymentUnitProcessingException missingAttributeInDatasourceMetadata(String attributeName);
// --- Driver //
@LogMessage(level = INFO)
@Message(id = 501, value = "Loaded class %s for driver '%s'")
void driverLoaded(String className, String driverName);
@Message(id = 502, value = "Failed to load driver module '%s'")
IllegalArgumentException loadModuleException(@Cause Throwable cause, String moduleName);
@Message(id = 503, value = "Failed to load driver class '%s'")
IllegalArgumentException loadClassException(@Cause Throwable cause, String className);
// --- Agroal Pool //
@LogMessage(level = WARN)
@Message(id = 601, value = "%s: %s")
void poolWarning(String datasourceName, String warn);
}
| 6,511
| 43.29932
| 182
|
java
|
null |
wildfly-main/datasources-agroal/src/main/java/org/wildfly/extension/datasources/agroal/logging/LoggingDataSourceListener.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal.logging;
import io.agroal.api.AgroalDataSourceListener;
import java.sql.Connection;
/**
* Provides log for important DataSource actions
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
*/
public class LoggingDataSourceListener implements AgroalDataSourceListener {
private final String datasourceName;
public LoggingDataSourceListener(String name) {
this.datasourceName = name;
}
@Override
public void beforeConnectionLeak(Connection connection) {
AgroalLogger.POOL_LOGGER.debugv("{0}: Leak test on connection {1}", datasourceName, connection);
}
@Override
public void beforeConnectionReap(Connection connection) {
AgroalLogger.POOL_LOGGER.debugv("{0}: Reap test on connection {1}", datasourceName, connection);
}
@Override
public void beforeConnectionValidation(Connection connection) {
AgroalLogger.POOL_LOGGER.debugv("{0}: Validation test on connection {1}", datasourceName, connection);
}
@Override
public void onConnectionAcquire(Connection connection) {
AgroalLogger.POOL_LOGGER.debugv("{0}: Acquire connection {1}", datasourceName, connection);
}
@Override
public void onConnectionCreation(Connection connection) {
AgroalLogger.POOL_LOGGER.debugv("{0}: Created connection {1}", datasourceName, connection);
}
@Override
public void onConnectionReap(Connection connection) {
AgroalLogger.POOL_LOGGER.debugv("{0}: Closing idle connection {1}", datasourceName, connection);
}
@Override
public void onConnectionReturn(Connection connection) {
AgroalLogger.POOL_LOGGER.debugv("{0}: Returning connection {1}", datasourceName, connection);
}
@Override
public void onConnectionDestroy(Connection connection) {
AgroalLogger.POOL_LOGGER.debugv("{0}: Destroyed connection {1}", datasourceName, connection);
}
@Override
public void onWarning(String warning) {
AgroalLogger.POOL_LOGGER.poolWarning(datasourceName, warning);
}
@Override
public void onWarning(Throwable throwable) {
AgroalLogger.POOL_LOGGER.poolWarning(datasourceName, throwable.getMessage());
AgroalLogger.POOL_LOGGER.debug("Cause: ", throwable);
}
}
| 3,341
| 35.326087
| 110
|
java
|
null |
wildfly-main/datasources-agroal/src/main/java/org/wildfly/extension/datasources/agroal/deployment/DataSourceDefinitionAnnotationProcessor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal.deployment;
import org.jboss.as.ee.resource.definition.ResourceDefinitionAnnotationProcessor;
import org.jboss.as.ee.resource.definition.ResourceDefinitionInjectionSource;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.DotName;
import org.jboss.metadata.property.PropertyReplacer;
import jakarta.annotation.sql.DataSourceDefinition;
import jakarta.annotation.sql.DataSourceDefinitions;
import static org.jboss.as.ee.resource.definition.ResourceDefinitionAnnotationProcessor.AnnotationElement.*;
/**
* Processor of the DataSourceDefinition annotation
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
*/
public class DataSourceDefinitionAnnotationProcessor extends ResourceDefinitionAnnotationProcessor {
private static final String NAME_PROP = "name";
private static final String CLASS_NAME_PROP = "className";
private static final String DESCRIPTION_PROP = "description";
private static final String URL_PROP = "url";
private static final String USER_PROP = "user";
private static final String PASSWORD_PROP = "password";
private static final String DATABASE_NAME_PROP = "databaseName";
private static final String PORT_NUMBER_PROP = "portNumber";
private static final String SERVER_NAME_PROP = "serverName";
private static final String ISOLATION_LEVEL_PROP = "isolationLevel";
private static final String TRANSACTIONAL_PROP = "transactional";
private static final String INITIAL_POOL_SIZE_PROP = "initialPoolSize";
private static final String MAX_POOL_SIZE_PROP = "maxPoolSize";
private static final String MIN_POOL_SIZE_PROP = "minPoolSize";
private static final String MAX_IDLE_TIME_PROP = "maxIdleTime";
private static final String MAX_STATEMENTS_PROP = "maxStatements";
private static final String PROPERTIES_PROP = "properties";
private static final String LOGIN_TIMEOUT_PROP = "loginTimeout";
private static final DotName DATASOURCE_DEFINITION = DotName.createSimple(DataSourceDefinition.class.getName());
private static final DotName DATASOURCE_DEFINITIONS = DotName.createSimple(DataSourceDefinitions.class.getName());
@Override
protected DotName getAnnotationDotName() {
return DATASOURCE_DEFINITION;
}
@Override
protected DotName getAnnotationCollectionDotName() {
return DATASOURCE_DEFINITIONS;
}
@Override
protected ResourceDefinitionInjectionSource processAnnotation(AnnotationInstance annotationInstance, PropertyReplacer propertyReplacer) throws DeploymentUnitProcessingException {
DataSourceDefinitionInjectionSource injectionSource = new DataSourceDefinitionInjectionSource(asRequiredString(annotationInstance, NAME_PROP));
injectionSource.setClassName(propertyReplacer.replaceProperties(asRequiredString(annotationInstance, CLASS_NAME_PROP)));
injectionSource.setDatabaseName(propertyReplacer.replaceProperties(asOptionalString(annotationInstance, DATABASE_NAME_PROP)));
injectionSource.setDescription(propertyReplacer.replaceProperties(asOptionalString(annotationInstance, DESCRIPTION_PROP)));
injectionSource.setInitialPoolSize(asOptionalInt(annotationInstance, INITIAL_POOL_SIZE_PROP));
injectionSource.setIsolationLevel(asOptionalInt(annotationInstance, ISOLATION_LEVEL_PROP));
injectionSource.setLoginTimeout(asOptionalInt(annotationInstance, LOGIN_TIMEOUT_PROP));
injectionSource.setMaxIdleTime(asOptionalInt(annotationInstance, MAX_IDLE_TIME_PROP));
injectionSource.setMaxStatements(asOptionalInt(annotationInstance, MAX_STATEMENTS_PROP));
injectionSource.setMaxPoolSize(asOptionalInt(annotationInstance, MAX_POOL_SIZE_PROP));
injectionSource.setMinPoolSize(asOptionalInt(annotationInstance, MIN_POOL_SIZE_PROP));
injectionSource.setInitialPoolSize(asOptionalInt(annotationInstance, INITIAL_POOL_SIZE_PROP));
injectionSource.setPassword(propertyReplacer.replaceProperties(asOptionalString(annotationInstance, PASSWORD_PROP)));
injectionSource.setPortNumber(asOptionalInt(annotationInstance, PORT_NUMBER_PROP));
injectionSource.addProperties(asOptionalStringArray(annotationInstance, PROPERTIES_PROP));
injectionSource.setServerName(propertyReplacer.replaceProperties(asOptionalString(annotationInstance, SERVER_NAME_PROP)));
injectionSource.setTransactional(asOptionalBoolean(annotationInstance, TRANSACTIONAL_PROP));
injectionSource.setUrl(propertyReplacer.replaceProperties(asOptionalString(annotationInstance, URL_PROP)));
injectionSource.setUser(propertyReplacer.replaceProperties(asOptionalString(annotationInstance, USER_PROP)));
return injectionSource;
}
}
| 5,875
| 57.178218
| 182
|
java
|
null |
wildfly-main/datasources-agroal/src/main/java/org/wildfly/extension/datasources/agroal/deployment/DataSourceDefinitionService.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal.deployment;
import io.agroal.api.AgroalDataSource;
import io.agroal.api.configuration.supplier.AgroalDataSourceConfigurationSupplier;
import io.agroal.narayana.NarayanaTransactionIntegration;
import org.jboss.as.naming.ContextListAndJndiViewManagedReferenceFactory;
import org.jboss.as.naming.ImmediateManagedReference;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.naming.deployment.ContextNames;
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.extension.datasources.agroal.logging.AgroalLogger;
import org.wildfly.extension.datasources.agroal.logging.LoggingDataSourceListener;
import org.wildfly.transaction.client.ContextTransactionManager;
import jakarta.transaction.TransactionManager;
import jakarta.transaction.TransactionSynchronizationRegistry;
import java.sql.SQLException;
import java.util.function.Supplier;
/**
* Defines an extension to provide DataSources based on the Agroal project
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
*/
public class DataSourceDefinitionService implements Service<ManagedReferenceFactory>, ContextListAndJndiViewManagedReferenceFactory {
private final String dataSourceName;
private final String jndiBinding;
private final boolean transactional;
private final AgroalDataSourceConfigurationSupplier dataSourceConfiguration;
private final Supplier<TransactionSynchronizationRegistry> tsrSupplier;
private AgroalDataSource agroalDataSource;
public DataSourceDefinitionService(ContextNames.BindInfo bindInfo, boolean transactional, AgroalDataSourceConfigurationSupplier dataSourceConfiguration,
Supplier<TransactionSynchronizationRegistry> tsrSupplier) {
this.dataSourceName = bindInfo.getParentContextServiceName().getSimpleName() + "." + bindInfo.getBindName().replace('/', '.');
this.jndiBinding = bindInfo.getBindName();
this.transactional = transactional;
this.tsrSupplier = tsrSupplier;
this.dataSourceConfiguration = dataSourceConfiguration;
}
@Override
public String getInstanceClassName() {
return agroalDataSource == null ? DEFAULT_INSTANCE_CLASS_NAME : agroalDataSource.getClass().getName();
}
@Override
public String getJndiViewInstanceValue() {
return agroalDataSource == null ? DEFAULT_JNDI_VIEW_INSTANCE_VALUE : agroalDataSource.toString();
}
@Override
public void start(StartContext context) throws StartException {
if (transactional) {
TransactionManager transactionManager = ContextTransactionManager.getInstance();
TransactionSynchronizationRegistry transactionSynchronizationRegistry = tsrSupplier != null ? tsrSupplier.get() : null;
if (transactionManager == null || transactionSynchronizationRegistry == null) {
throw AgroalLogger.SERVICE_LOGGER.missingTransactionManager();
}
NarayanaTransactionIntegration txIntegration = new NarayanaTransactionIntegration(transactionManager, transactionSynchronizationRegistry, jndiBinding, false);
dataSourceConfiguration.connectionPoolConfiguration().transactionIntegration(txIntegration);
}
try {
agroalDataSource = AgroalDataSource.from(dataSourceConfiguration, new LoggingDataSourceListener(dataSourceName));
AgroalLogger.SERVICE_LOGGER.startedDataSource(dataSourceName, jndiBinding);
} catch (SQLException e) {
agroalDataSource = null;
throw AgroalLogger.SERVICE_LOGGER.datasourceStartException(e, dataSourceName);
}
}
@Override
public void stop(StopContext context) {
agroalDataSource.close();
AgroalLogger.SERVICE_LOGGER.stoppedDataSource(dataSourceName);
}
@Override
public ManagedReferenceFactory getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
@Override
public ManagedReference getReference() {
return new ImmediateManagedReference(agroalDataSource);
}
}
| 5,323
| 44.118644
| 170
|
java
|
null |
wildfly-main/datasources-agroal/src/main/java/org/wildfly/extension/datasources/agroal/deployment/DataSourceDefinitionInjectionSource.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal.deployment;
import static org.jboss.as.server.deployment.Attachments.MODULE;
import java.sql.Driver;
import java.time.Duration;
import java.util.Map;
import java.util.function.Supplier;
import javax.sql.DataSource;
import jakarta.transaction.TransactionSynchronizationRegistry;
import io.agroal.api.configuration.AgroalConnectionFactoryConfiguration;
import io.agroal.api.configuration.supplier.AgroalConnectionFactoryConfigurationSupplier;
import io.agroal.api.configuration.supplier.AgroalConnectionPoolConfigurationSupplier;
import io.agroal.api.configuration.supplier.AgroalDataSourceConfigurationSupplier;
import io.agroal.api.security.NamePrincipal;
import io.agroal.api.security.SimplePassword;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.ee.resource.definition.ResourceDefinitionInjectionSource;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.naming.ServiceBasedNamingStore;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.service.BinderService;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.wildfly.extension.datasources.agroal.AgroalExtension;
import org.wildfly.extension.datasources.agroal.logging.AgroalLogger;
/**
* Injection source for a DataSource
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
*/
class DataSourceDefinitionInjectionSource extends ResourceDefinitionInjectionSource {
private static final ServiceName DATASOURCE_DEFINITION_SERVICE_PREFIX = AgroalExtension.BASE_SERVICE_NAME.append("datasource-definition");
private static final String DESCRIPTION_PROP = "description";
private static final String DATABASE_NAME_PROP = "databaseName";
private static final String PORT_NUMBER_PROP = "portNumber";
private static final String SERVER_NAME_PROP = "serverName";
private static final String MAX_STATEMENTS_PROP = "maxStatements";
private static final String LOGIN_TIMEOUT_PROP = "loginTimeout";
private String className;
private String description;
private String url;
private String databaseName = "";
private String serverName = "";
private int portNumber = -1;
private int loginTimeout = -1;
private int isolationLevel = -1;
private boolean transactional = true;
private int initialPoolSize = -1;
private int maxIdleTime = -1;
private int maxPoolSize = -1;
private int maxStatements = -1;
private int minPoolSize = -1;
private String user;
private String password;
public DataSourceDefinitionInjectionSource(String jndiName) {
super(jndiName);
}
// --- //
public void setClassName(String className) {
this.className = className;
}
public void setDescription(String description) {
this.description = description;
}
public void setUrl(String url) {
this.url = url;
}
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
public void setServerName(String serverName) {
this.serverName = serverName;
}
public void setPortNumber(int portNumber) {
this.portNumber = portNumber;
}
public void setLoginTimeout(int loginTimeout) {
this.loginTimeout = loginTimeout;
}
public void setIsolationLevel(int isolationLevel) {
this.isolationLevel = isolationLevel;
}
public void setTransactional(boolean transactional) {
this.transactional = transactional;
}
public void setInitialPoolSize(int initialPoolSize) {
this.initialPoolSize = initialPoolSize;
}
public void setMaxIdleTime(int maxIdleTime) {
this.maxIdleTime = maxIdleTime;
}
public void setMaxPoolSize(int maxPoolSize) {
this.maxPoolSize = maxPoolSize;
}
public void setMaxStatements(int maxStatements) {
this.maxStatements = maxStatements;
}
public void setMinPoolSize(int minPoolSize) {
this.minPoolSize = minPoolSize;
}
public void setUser(String user) {
this.user = user;
}
public void setPassword(String password) {
this.password = password;
}
// --- //
@Override
public void getResourceValue(ResolutionContext context, ServiceBuilder<?> serviceBuilder, DeploymentPhaseContext phaseContext, Injector<ManagedReferenceFactory> injector) throws DeploymentUnitProcessingException {
AgroalConnectionFactoryConfigurationSupplier connectionFactoryConfiguration = new AgroalConnectionFactoryConfigurationSupplier();
try {
Class<?> providerClass = phaseContext.getDeploymentUnit().getAttachment(MODULE).getClassLoader().loadClass(className);
if (providerClass != null && !DataSource.class.isAssignableFrom(providerClass) && !Driver.class.isAssignableFrom(providerClass)) {
throw AgroalLogger.SERVICE_LOGGER.invalidDeploymentConnectionProvider();
}
connectionFactoryConfiguration.connectionProviderClass(providerClass);
} catch (ClassNotFoundException e) {
throw AgroalLogger.SERVICE_LOGGER.loadClassDeploymentException(e, className);
}
for (Map.Entry<String, String> property : properties.entrySet()) {
connectionFactoryConfiguration.jdbcProperty(property.getKey(), property.getValue());
}
if (databaseName != null && !databaseName.isEmpty()) {
connectionFactoryConfiguration.jdbcProperty(DATABASE_NAME_PROP, databaseName);
}
if (description != null && !description.isEmpty()) {
connectionFactoryConfiguration.jdbcProperty(DESCRIPTION_PROP, description);
}
if (serverName != null && !serverName.isEmpty()) {
connectionFactoryConfiguration.jdbcProperty(SERVER_NAME_PROP, serverName);
}
if (portNumber >= 0) {
connectionFactoryConfiguration.jdbcProperty(PORT_NUMBER_PROP, Integer.toString(portNumber));
}
if (loginTimeout >= 0) {
connectionFactoryConfiguration.jdbcProperty(LOGIN_TIMEOUT_PROP, Integer.toString(loginTimeout));
}
if (maxStatements >= 0) {
connectionFactoryConfiguration.jdbcProperty(MAX_STATEMENTS_PROP, Integer.toString(maxStatements));
}
if (url != null && !url.isEmpty()) {
connectionFactoryConfiguration.jdbcUrl(url);
}
if (user != null && !user.isEmpty()) {
connectionFactoryConfiguration.principal(new NamePrincipal(user));
}
if (password != null && !password.isEmpty()) {
connectionFactoryConfiguration.credential(new SimplePassword(password));
}
connectionFactoryConfiguration.jdbcTransactionIsolation(AgroalConnectionFactoryConfiguration.TransactionIsolation.fromLevel(isolationLevel));
AgroalConnectionPoolConfigurationSupplier connectionPoolConfiguration = new AgroalConnectionPoolConfigurationSupplier();
connectionPoolConfiguration.connectionFactoryConfiguration(connectionFactoryConfiguration);
if (initialPoolSize >= 0) {
connectionPoolConfiguration.initialSize(initialPoolSize);
}
if (minPoolSize >= 0) {
connectionPoolConfiguration.minSize(minPoolSize);
}
if (maxPoolSize >= 0) {
connectionPoolConfiguration.maxSize(maxPoolSize);
}
if (maxIdleTime >= 0) {
connectionPoolConfiguration.reapTimeout(Duration.ofSeconds(maxIdleTime));
}
AgroalDataSourceConfigurationSupplier dataSourceConfiguration = new AgroalDataSourceConfigurationSupplier();
dataSourceConfiguration.connectionPoolConfiguration(connectionPoolConfiguration);
ContextNames.BindInfo bindInfo = ContextNames.bindInfoForEnvEntry(context.getApplicationName(), context.getModuleName(), context.getComponentName(), !context.isCompUsesModule(), jndiName);
ServiceName dataSourceServiceName = DATASOURCE_DEFINITION_SERVICE_PREFIX.append(bindInfo.getBinderServiceName().getCanonicalName());
// This is the service responsible for the JNDI binding, with a dependency on the datasource service that acts as a ManagedReferenceFactory and is used as the injection source
BinderService binderService = new BinderService(bindInfo.getBindName(), this);
phaseContext.getServiceTarget().addService(bindInfo.getBinderServiceName(), binderService)
.addDependency(dataSourceServiceName, ManagedReferenceFactory.class, binderService.getManagedObjectInjector())
.addDependency(bindInfo.getParentContextServiceName(), ServiceBasedNamingStore.class, binderService.getNamingStoreInjector())
.install();
ServiceBuilder svcBuilder = phaseContext.getServiceTarget().addService(dataSourceServiceName);
Supplier<TransactionSynchronizationRegistry> tsrSupplier = null;
if (transactional) {
CapabilityServiceSupport css = phaseContext.getDeploymentUnit().getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
ServiceName tsrName = css.getCapabilityServiceName("org.wildfly.transactions.transaction-synchronization-registry");
//noinspection unchecked
tsrSupplier = (Supplier<TransactionSynchronizationRegistry>) svcBuilder.requires(tsrName);
}
DataSourceDefinitionService dataSourceService = new DataSourceDefinitionService(bindInfo, transactional, dataSourceConfiguration, tsrSupplier);
svcBuilder.setInstance(dataSourceService).install();
serviceBuilder.requires(bindInfo.getBinderServiceName());
serviceBuilder.addDependency(dataSourceServiceName, ManagedReferenceFactory.class, injector);
}
}
| 11,099
| 43.223108
| 217
|
java
|
null |
wildfly-main/datasources-agroal/src/main/java/org/wildfly/extension/datasources/agroal/deployment/DataSourceDefinitionDescriptorProcessor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.datasources.agroal.deployment;
import org.jboss.as.ee.resource.definition.ResourceDefinitionDescriptorProcessor;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.metadata.javaee.spec.DataSourceMetaData;
import org.jboss.metadata.javaee.spec.DataSourcesMetaData;
import org.jboss.metadata.javaee.spec.RemoteEnvironment;
import org.wildfly.extension.datasources.agroal.logging.AgroalLogger;
/**
* Processor of the data-source element in ejb-jar.xml
*
* @author <a href="lbarreiro@redhat.com">Luis Barreiro</a>
*/
public class DataSourceDefinitionDescriptorProcessor extends ResourceDefinitionDescriptorProcessor {
@Override
protected void processEnvironment(RemoteEnvironment environment, ResourceDefinitionDescriptorProcessor.ResourceDefinitionInjectionSources injectionSources) throws DeploymentUnitProcessingException {
DataSourcesMetaData dataSources = environment.getDataSources();
if (dataSources != null) {
for (DataSourceMetaData dataSource : dataSources) {
if (dataSource.getName() == null || dataSource.getName().isEmpty()) {
throw AgroalLogger.SERVICE_LOGGER.missingAttributeInDatasourceMetadata("name");
}
if (dataSource.getClassName() == null || dataSource.getClassName().isEmpty()) {
throw AgroalLogger.SERVICE_LOGGER.missingAttributeInDatasourceMetadata("className");
}
DataSourceDefinitionInjectionSource injectionSource = new DataSourceDefinitionInjectionSource(dataSource.getName());
injectionSource.setClassName(dataSource.getClassName());
injectionSource.setDatabaseName(dataSource.getDatabaseName());
injectionSource.setInitialPoolSize(dataSource.getInitialPoolSize());
injectionSource.setLoginTimeout(dataSource.getLoginTimeout());
injectionSource.setMaxIdleTime(dataSource.getMaxIdleTime());
injectionSource.setMaxStatements(dataSource.getMaxStatements());
injectionSource.setMaxPoolSize(dataSource.getMaxPoolSize());
injectionSource.setMinPoolSize(dataSource.getMinPoolSize());
injectionSource.setPassword(dataSource.getPassword());
injectionSource.setPortNumber(dataSource.getPortNumber());
injectionSource.addProperties(dataSource.getProperties());
injectionSource.setServerName(dataSource.getServerName());
injectionSource.setTransactional(dataSource.getTransactional());
injectionSource.setUrl(dataSource.getUrl());
injectionSource.setUser(dataSource.getUser());
if (dataSource.getDescriptions() != null) {
injectionSource.setDescription(dataSource.getDescriptions().toString());
}
if (dataSource.getIsolationLevel() != null) {
injectionSource.setIsolationLevel(dataSource.getIsolationLevel().ordinal());
}
injectionSources.addResourceDefinitionInjectionSource(injectionSource);
}
}
}
}
| 4,259
| 51.592593
| 202
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/test/java/org/wildfly/extension/messaging/activemq/MessagingActiveMQSubsystem_14_0_TestCase.java
|
/*
* Copyright 2020 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.messaging.activemq;
import static org.jboss.as.model.test.ModelTestControllerVersion.EAP_7_4_0;
import static org.junit.Assert.assertTrue;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.BRIDGE;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.DEFAULT;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.SERVER;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.SUBSYSTEM;
import static org.wildfly.extension.messaging.activemq.MessagingDependencies.getActiveMQDependencies;
import static org.wildfly.extension.messaging.activemq.MessagingDependencies.getJGroupsDependencies;
import static org.wildfly.extension.messaging.activemq.MessagingDependencies.getMessagingActiveMQGAV;
import static org.wildfly.extension.messaging.activemq.MessagingExtension.BRIDGE_PATH;
import static org.wildfly.extension.messaging.activemq.MessagingExtension.EXTERNAL_JMS_QUEUE_PATH;
import static org.wildfly.extension.messaging.activemq.MessagingExtension.EXTERNAL_JMS_TOPIC_PATH;
import static org.wildfly.extension.messaging.activemq.MessagingExtension.SERVER_PATH;
import static org.wildfly.extension.messaging.activemq.MessagingExtension.SUBSYSTEM_PATH;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.security.CredentialReference;
import org.jboss.as.model.test.FailedOperationTransformationConfig;
import org.jboss.as.model.test.ModelTestControllerVersion;
import org.jboss.as.model.test.ModelTestUtils;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.as.subsystem.test.KernelServicesBuilder;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
import org.wildfly.clustering.jgroups.spi.JGroupsDefaultRequirement;
import org.wildfly.clustering.server.service.ClusteringDefaultRequirement;
import org.wildfly.clustering.server.service.ClusteringRequirement;
import org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes;
public class MessagingActiveMQSubsystem_14_0_TestCase extends AbstractSubsystemBaseTest {
public MessagingActiveMQSubsystem_14_0_TestCase() {
super(MessagingExtension.SUBSYSTEM_NAME, new MessagingExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource("subsystem_14_0.xml");
}
@Override
protected String getSubsystemXsdPath() throws IOException {
return "schema/wildfly-messaging-activemq_14_0.xsd";
}
@Override
protected Properties getResolvedProperties() {
Properties properties = new Properties();
properties.put("messaging.cluster.user.name", "myClusterUser");
properties.put("messaging.cluster.user.password", "myClusterPassword");
return properties;
}
@Override
protected KernelServices standardSubsystemTest(String configId, boolean compareXml) throws Exception {
return super.standardSubsystemTest(configId, false);
}
@Test
public void testJournalAttributes() throws Exception {
KernelServices kernelServices = standardSubsystemTest(null, false);
ModelNode rootModel = kernelServices.readWholeModel();
ModelNode serverModel = rootModel.require(SUBSYSTEM).require(MessagingExtension.SUBSYSTEM_NAME).require(SERVER)
.require(DEFAULT);
Assert.assertEquals(1357, serverModel.get(ServerDefinition.JOURNAL_BUFFER_TIMEOUT.getName()).resolve().asInt());
Assert.assertEquals(102400, serverModel.get(ServerDefinition.JOURNAL_FILE_SIZE.getName()).resolve().asInt());
Assert.assertEquals(2, serverModel.get(ServerDefinition.JOURNAL_MIN_FILES.getName()).resolve().asInt());
Assert.assertEquals(5, serverModel.get(ServerDefinition.JOURNAL_POOL_FILES.getName()).resolve().asInt());
Assert.assertEquals(7, serverModel.get(ServerDefinition.JOURNAL_FILE_OPEN_TIMEOUT.getName()).resolve().asInt());
kernelServices.shutdown();
}
@Test
public void testBridgeCallTimeout() throws Exception {
KernelServices kernelServices = standardSubsystemTest(null, false);
ModelNode rootModel = kernelServices.readWholeModel();
ModelNode bridgeModel = rootModel.require(SUBSYSTEM).require(MessagingExtension.SUBSYSTEM_NAME).require(SERVER)
.require(DEFAULT).require(BRIDGE).require("bridge1");
Assert.assertEquals("${call.timeout:60000}", bridgeModel.get(BridgeDefinition.CALL_TIMEOUT.getName()).asExpression().getExpressionString());
Assert.assertEquals(60000, bridgeModel.get(BridgeDefinition.CALL_TIMEOUT.getName()).resolve().asLong());
kernelServices.shutdown();
}
/////////////////////////////////////////
// Tests for HA Policy Configuration //
/////////////////////////////////////////
@Test
public void testHAPolicyConfiguration() throws Exception {
standardSubsystemTest("subsystem_14_0_ha-policy.xml");
}
///////////////////////
// Transformers test //
///////////////////////
@Test
public void testTransformersWildfly26_1() throws Exception {
testTransformers(ModelTestControllerVersion.MASTER, MessagingExtension.VERSION_13_1_0);
}
@Test
public void testTransformersWildfly25() throws Exception {
testTransformers(ModelTestControllerVersion.MASTER, MessagingExtension.VERSION_13_0_0);
}
@Test
public void testTransformersEAP_7_4_0() throws Exception {
testTransformers(EAP_7_4_0, MessagingExtension.VERSION_13_0_0);
}
@Test
public void testRejectingTransformersEAP_7_4_0() throws Exception {
testRejectingTransformers(EAP_7_4_0, MessagingExtension.VERSION_13_0_0);
}
private void testTransformers(ModelTestControllerVersion controllerVersion, ModelVersion messagingVersion) throws Exception {
//Boot up empty controllers with the resources needed for the ops coming from the xml to work
KernelServicesBuilder builder = createKernelServicesBuilder(createAdditionalInitialization())
.setSubsystemXmlResource("subsystem_14_0_transform.xml");
builder.createLegacyKernelServicesBuilder(createAdditionalInitialization(), controllerVersion, messagingVersion)
.addMavenResourceURL(getMessagingActiveMQGAV(controllerVersion))
.addMavenResourceURL(getActiveMQDependencies(controllerVersion))
.addMavenResourceURL(getJGroupsDependencies(controllerVersion))
.skipReverseControllerCheck()
.dontPersistXml();
KernelServices mainServices = builder.build();
assertTrue(mainServices.isSuccessfulBoot());
assertTrue(mainServices.getLegacyServices(messagingVersion).isSuccessfulBoot());
checkSubsystemModelTransformation(mainServices, messagingVersion, (ModelNode modelNode) -> {
ModelNode legacyModel = modelNode.clone();
if (modelNode.hasDefined("server", "default", "address-setting", "test", "page-size-bytes")) {
int legacyNodeValue = modelNode.get("server", "default", "address-setting", "test", "page-size-bytes").asInt();
legacyModel.get("server", "default", "address-setting", "test", "page-size-bytes").set(legacyNodeValue);
}
return legacyModel;
});
mainServices.shutdown();
}
private void testRejectingTransformers(ModelTestControllerVersion controllerVersion, ModelVersion messagingVersion) throws Exception {
//Boot up empty controllers with the resources needed for the ops coming from the xml to work
KernelServicesBuilder builder = createKernelServicesBuilder(createAdditionalInitialization());
builder.createLegacyKernelServicesBuilder(createAdditionalInitialization(), controllerVersion, messagingVersion)
.addMavenResourceURL(getMessagingActiveMQGAV(controllerVersion))
.addMavenResourceURL(getActiveMQDependencies(controllerVersion))
.addMavenResourceURL(getJGroupsDependencies(controllerVersion))
.skipReverseControllerCheck()
.dontPersistXml();
KernelServices mainServices = builder.build();
assertTrue(mainServices.isSuccessfulBoot());
assertTrue(mainServices.getLegacyServices(messagingVersion).isSuccessfulBoot());
List<ModelNode> ops = builder.parseXmlResource("subsystem_14_0_reject_transform.xml");
// System.out.println("ops = " + ops);
PathAddress subsystemAddress = PathAddress.pathAddress(SUBSYSTEM_PATH);
FailedOperationTransformationConfig config = new FailedOperationTransformationConfig();
config.addFailedAttribute(subsystemAddress.append(EXTERNAL_JMS_QUEUE_PATH),
new FailedOperationTransformationConfig.NewAttributesConfig(ConnectionFactoryAttributes.External.ENABLE_AMQ1_PREFIX));
config.addFailedAttribute(subsystemAddress.append(EXTERNAL_JMS_TOPIC_PATH),
new FailedOperationTransformationConfig.NewAttributesConfig(ConnectionFactoryAttributes.External.ENABLE_AMQ1_PREFIX));
config.addFailedAttribute(subsystemAddress.append(SERVER_PATH, BRIDGE_PATH), new FailedOperationTransformationConfig.NewAttributesConfig(BridgeDefinition.ROUTING_TYPE));
config.addFailedAttribute(subsystemAddress.append(SERVER_PATH), new FailedOperationTransformationConfig.NewAttributesConfig(
ServerDefinition.ADDRESS_QUEUE_SCAN_PERIOD
));
ModelTestUtils.checkFailedTransformedBootOperations(mainServices, messagingVersion, ops, config);
mainServices.shutdown();
}
@Override
protected Set<PathAddress> getIgnoredChildResourcesForRemovalTest() {
Set<PathAddress> ignoredChildResources = new HashSet<>(super.getIgnoredChildResourcesForRemovalTest());
ignoredChildResources.add(PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/discovery-group=groupS"));
return ignoredChildResources;
}
@Override
protected AdditionalInitialization createAdditionalInitialization() {
return AdditionalInitialization.withCapabilities(ClusteringRequirement.COMMAND_DISPATCHER_FACTORY.resolve("ee"),
ClusteringDefaultRequirement.COMMAND_DISPATCHER_FACTORY.getName(),
JGroupsDefaultRequirement.CHANNEL_FACTORY.getName(),
Capabilities.ELYTRON_DOMAIN_CAPABILITY,
Capabilities.ELYTRON_DOMAIN_CAPABILITY + ".elytronDomain",
CredentialReference.CREDENTIAL_STORE_CAPABILITY + ".cs1",
Capabilities.DATA_SOURCE_CAPABILITY + ".fooDS",
Capabilities.LEGACY_SECURITY_DOMAIN_CAPABILITY.getDynamicName("other"));
}
}
| 11,696
| 51.927602
| 177
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/test/java/org/wildfly/extension/messaging/activemq/MessagingActiveMQSubsystem_15_0_TestCase.java
|
/*
* Copyright 2020 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.messaging.activemq;
import static org.jboss.as.controller.PathElement.pathElement;
import static org.jboss.as.model.test.ModelTestControllerVersion.EAP_7_4_0;
import static org.junit.Assert.assertTrue;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.BRIDGE;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.DEFAULT;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.SERVER;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.SUBSYSTEM;
import static org.wildfly.extension.messaging.activemq.MessagingDependencies.getActiveMQDependencies;
import static org.wildfly.extension.messaging.activemq.MessagingDependencies.getJGroupsDependencies;
import static org.wildfly.extension.messaging.activemq.MessagingDependencies.getMessagingActiveMQGAV;
import static org.wildfly.extension.messaging.activemq.MessagingExtension.BRIDGE_PATH;
import static org.wildfly.extension.messaging.activemq.MessagingExtension.EXTERNAL_JMS_QUEUE_PATH;
import static org.wildfly.extension.messaging.activemq.MessagingExtension.EXTERNAL_JMS_TOPIC_PATH;
import static org.wildfly.extension.messaging.activemq.MessagingExtension.SERVER_PATH;
import static org.wildfly.extension.messaging.activemq.MessagingExtension.SUBSYSTEM_PATH;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.security.CredentialReference;
import org.jboss.as.model.test.FailedOperationTransformationConfig;
import org.jboss.as.model.test.ModelTestControllerVersion;
import org.jboss.as.model.test.ModelTestUtils;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.as.subsystem.test.KernelServicesBuilder;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
import org.wildfly.clustering.jgroups.spi.JGroupsDefaultRequirement;
import org.wildfly.clustering.server.service.ClusteringDefaultRequirement;
import org.wildfly.clustering.server.service.ClusteringRequirement;
import org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes;
public class MessagingActiveMQSubsystem_15_0_TestCase extends AbstractSubsystemBaseTest {
public MessagingActiveMQSubsystem_15_0_TestCase() {
super(MessagingExtension.SUBSYSTEM_NAME, new MessagingExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource("subsystem_15_0.xml");
}
@Override
protected String getSubsystemXsdPath() throws IOException {
return "schema/wildfly-messaging-activemq_15_0.xsd";
}
@Override
protected Properties getResolvedProperties() {
Properties properties = new Properties();
properties.put("messaging.cluster.user.name", "myClusterUser");
properties.put("messaging.cluster.user.password", "myClusterPassword");
return properties;
}
@Test
public void testJournalAttributes() throws Exception {
KernelServices kernelServices = standardSubsystemTest(null, false);
ModelNode rootModel = kernelServices.readWholeModel();
ModelNode serverModel = rootModel.require(SUBSYSTEM).require(MessagingExtension.SUBSYSTEM_NAME).require(SERVER)
.require(DEFAULT);
Assert.assertEquals(1357, serverModel.get(ServerDefinition.JOURNAL_BUFFER_TIMEOUT.getName()).resolve().asInt());
Assert.assertEquals(102400, serverModel.get(ServerDefinition.JOURNAL_FILE_SIZE.getName()).resolve().asInt());
Assert.assertEquals(2, serverModel.get(ServerDefinition.JOURNAL_MIN_FILES.getName()).resolve().asInt());
Assert.assertEquals(5, serverModel.get(ServerDefinition.JOURNAL_POOL_FILES.getName()).resolve().asInt());
Assert.assertEquals(7, serverModel.get(ServerDefinition.JOURNAL_FILE_OPEN_TIMEOUT.getName()).resolve().asInt());
kernelServices.shutdown();
}
@Test
public void testBridgeCallTimeout() throws Exception {
KernelServices kernelServices = standardSubsystemTest(null, false);
ModelNode rootModel = kernelServices.readWholeModel();
ModelNode bridgeModel = rootModel.require(SUBSYSTEM).require(MessagingExtension.SUBSYSTEM_NAME).require(SERVER)
.require(DEFAULT).require(BRIDGE).require("bridge1");
Assert.assertEquals("${call.timeout:60000}", bridgeModel.get(BridgeDefinition.CALL_TIMEOUT.getName()).asExpression().getExpressionString());
Assert.assertEquals(60000, bridgeModel.get(BridgeDefinition.CALL_TIMEOUT.getName()).resolve().asLong());
kernelServices.shutdown();
}
/////////////////////////////////////////
// Tests for HA Policy Configuration //
/////////////////////////////////////////
@Test
public void testHAPolicyConfiguration() throws Exception {
standardSubsystemTest("subsystem_15_0_ha-policy.xml");
}
///////////////////////
// Transformers test //
///////////////////////
@Test
public void testTransformersWildfly27() throws Exception {
testTransformers(ModelTestControllerVersion.MASTER, MessagingExtension.VERSION_14_0_0);
}
@Test
public void testTransformersWildfly26_1() throws Exception {
testTransformers(ModelTestControllerVersion.MASTER, MessagingExtension.VERSION_13_1_0);
}
@Test
public void testTransformersWildfly25() throws Exception {
testTransformers(ModelTestControllerVersion.MASTER, MessagingExtension.VERSION_13_0_0);
}
@Test
public void testTransformersEAP_7_4_0() throws Exception {
testTransformers(EAP_7_4_0, MessagingExtension.VERSION_13_0_0);
}
@Test
public void testRejectingTransformersEAP_7_4_0() throws Exception {
testRejectingTransformers(EAP_7_4_0, MessagingExtension.VERSION_13_0_0);
}
private void testTransformers(ModelTestControllerVersion controllerVersion, ModelVersion messagingVersion) throws Exception {
//Boot up empty controllers with the resources needed for the ops coming from the xml to work
KernelServicesBuilder builder = createKernelServicesBuilder(createAdditionalInitialization())
.setSubsystemXmlResource("subsystem_15_0_transform.xml");
builder.createLegacyKernelServicesBuilder(createAdditionalInitialization(), controllerVersion, messagingVersion)
.addMavenResourceURL(getMessagingActiveMQGAV(controllerVersion))
.addMavenResourceURL(getActiveMQDependencies(controllerVersion))
.addMavenResourceURL(getJGroupsDependencies(controllerVersion))
.skipReverseControllerCheck()
.dontPersistXml();
KernelServices mainServices = builder.build();
assertTrue(mainServices.isSuccessfulBoot());
assertTrue(mainServices.getLegacyServices(messagingVersion).isSuccessfulBoot());
checkSubsystemModelTransformation(mainServices, messagingVersion, (ModelNode modelNode) -> {
ModelNode legacyModel = modelNode.clone();
if (modelNode.hasDefined("server", "default", "address-setting", "test", "page-size-bytes")) {
int legacyNodeValue = modelNode.get("server", "default", "address-setting", "test", "page-size-bytes").asInt();
legacyModel.get("server", "default", "address-setting", "test", "page-size-bytes").set(legacyNodeValue);
}
return legacyModel;
});
mainServices.shutdown();
}
private void testRejectingTransformers(ModelTestControllerVersion controllerVersion, ModelVersion messagingVersion) throws Exception {
//Boot up empty controllers with the resources needed for the ops coming from the xml to work
KernelServicesBuilder builder = createKernelServicesBuilder(createAdditionalInitialization());
builder.createLegacyKernelServicesBuilder(createAdditionalInitialization(), controllerVersion, messagingVersion)
.addMavenResourceURL(getMessagingActiveMQGAV(controllerVersion))
.addMavenResourceURL(getActiveMQDependencies(controllerVersion))
.addMavenResourceURL(getJGroupsDependencies(controllerVersion))
.skipReverseControllerCheck()
.dontPersistXml();
KernelServices mainServices = builder.build();
assertTrue(mainServices.isSuccessfulBoot());
assertTrue(mainServices.getLegacyServices(messagingVersion).isSuccessfulBoot());
List<ModelNode> ops = builder.parseXmlResource("subsystem_15_0_reject_transform.xml");
// System.out.println("ops = " + ops);
PathAddress subsystemAddress = PathAddress.pathAddress(SUBSYSTEM_PATH);
FailedOperationTransformationConfig config = new FailedOperationTransformationConfig();
config.addFailedAttribute(subsystemAddress.append(EXTERNAL_JMS_QUEUE_PATH),
new FailedOperationTransformationConfig.NewAttributesConfig(ConnectionFactoryAttributes.External.ENABLE_AMQ1_PREFIX));
config.addFailedAttribute(subsystemAddress.append(EXTERNAL_JMS_TOPIC_PATH),
new FailedOperationTransformationConfig.NewAttributesConfig(ConnectionFactoryAttributes.External.ENABLE_AMQ1_PREFIX));
config.addFailedAttribute(subsystemAddress.append(SERVER_PATH, BRIDGE_PATH), new FailedOperationTransformationConfig.NewAttributesConfig(BridgeDefinition.ROUTING_TYPE));
config.addFailedAttribute(subsystemAddress.append(SERVER_PATH), new FailedOperationTransformationConfig.NewAttributesConfig(
ServerDefinition.ADDRESS_QUEUE_SCAN_PERIOD
));
config.addFailedAttribute(subsystemAddress.append(SERVER_PATH, pathElement(CommonAttributes.REMOTE_CONNECTOR)), new FailedOperationTransformationConfig.NewAttributesConfig(CommonAttributes.SSL_CONTEXT));
config.addFailedAttribute(subsystemAddress.append(SERVER_PATH, pathElement(CommonAttributes.HTTP_CONNECTOR)), new FailedOperationTransformationConfig.NewAttributesConfig(CommonAttributes.SSL_CONTEXT));
config.addFailedAttribute(subsystemAddress.append(SERVER_PATH, pathElement(CommonAttributes.REMOTE_ACCEPTOR)), new FailedOperationTransformationConfig.NewAttributesConfig(CommonAttributes.SSL_CONTEXT));
config.addFailedAttribute(subsystemAddress.append(SERVER_PATH, pathElement(CommonAttributes.HTTP_ACCEPTOR)), new FailedOperationTransformationConfig.NewAttributesConfig(CommonAttributes.SSL_CONTEXT));
ModelTestUtils.checkFailedTransformedBootOperations(mainServices, messagingVersion, ops, config);
mainServices.shutdown();
}
@Override
protected Set<PathAddress> getIgnoredChildResourcesForRemovalTest() {
Set<PathAddress> ignoredChildResources = new HashSet<>(super.getIgnoredChildResourcesForRemovalTest());
ignoredChildResources.add(PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/discovery-group=groupS"));
return ignoredChildResources;
}
@Override
protected AdditionalInitialization createAdditionalInitialization() {
return AdditionalInitialization.withCapabilities(ClusteringRequirement.COMMAND_DISPATCHER_FACTORY.resolve("ee"),
ClusteringDefaultRequirement.COMMAND_DISPATCHER_FACTORY.getName(),
JGroupsDefaultRequirement.CHANNEL_FACTORY.getName(),
Capabilities.ELYTRON_DOMAIN_CAPABILITY,
Capabilities.ELYTRON_DOMAIN_CAPABILITY + ".elytronDomain",
CredentialReference.CREDENTIAL_STORE_CAPABILITY + ".cs1",
Capabilities.DATA_SOURCE_CAPABILITY + ".fooDS",
Capabilities.LEGACY_SECURITY_DOMAIN_CAPABILITY.getDynamicName("other"),
Capabilities.ELYTRON_SSL_CONTEXT_CAPABILITY.getDynamicName("messaging"));
}
}
| 12,677
| 54.85022
| 211
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/test/java/org/wildfly/extension/messaging/activemq/BridgeAddTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq;
import org.apache.activemq.artemis.core.config.BridgeConfiguration;
import org.jboss.as.controller.ExpressionResolver;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
public class BridgeAddTestCase {
private static final String BRIDGE_NAME = "CoreBridge";
private static final String SOURCE_QUEUE_NAME = "SourceQueue";
private static final String TARGET_QUEUE_NAME = "TargetQueue";
@Test
public void testCreateBridgeConfiguration() throws OperationFailedException {
BridgeConfiguration bridgeConfiguration =
BridgeAdd.createBridgeConfiguration(ExpressionResolver.SIMPLE, BRIDGE_NAME, createModel());
Assert.assertEquals(BRIDGE_NAME, bridgeConfiguration.getName());
Assert.assertEquals(SOURCE_QUEUE_NAME, bridgeConfiguration.getQueueName());
Assert.assertEquals(TARGET_QUEUE_NAME, bridgeConfiguration.getForwardingAddress());
Assert.assertArrayEquals(new String[] {"in-vm"}, bridgeConfiguration.getStaticConnectors().toArray());
Assert.assertEquals(30000, bridgeConfiguration.getCallTimeout());
}
@Test
public void testCreateBridgeConfigurationCallTimeoutInModel() throws OperationFailedException {
ModelNode model = createModel();
model.get("call-timeout").set(70000);
BridgeConfiguration bridgeConfiguration =
BridgeAdd.createBridgeConfiguration(ExpressionResolver.SIMPLE, BRIDGE_NAME, model);
Assert.assertEquals(BRIDGE_NAME, bridgeConfiguration.getName());
Assert.assertEquals(SOURCE_QUEUE_NAME, bridgeConfiguration.getQueueName());
Assert.assertEquals(TARGET_QUEUE_NAME, bridgeConfiguration.getForwardingAddress());
Assert.assertArrayEquals(new String[] {"in-vm"}, bridgeConfiguration.getStaticConnectors().toArray());
Assert.assertEquals(70000, bridgeConfiguration.getCallTimeout());
}
@Test
public void testCreateBridgeConfigurationCallTimeoutSystemProperty() throws OperationFailedException {
try {
System.setProperty(BridgeAdd.CALL_TIMEOUT_PROPERTY, "80000");
BridgeConfiguration bridgeConfiguration =
BridgeAdd.createBridgeConfiguration(ExpressionResolver.SIMPLE, BRIDGE_NAME, createModel());
Assert.assertEquals(BRIDGE_NAME, bridgeConfiguration.getName());
Assert.assertEquals(SOURCE_QUEUE_NAME, bridgeConfiguration.getQueueName());
Assert.assertEquals(TARGET_QUEUE_NAME, bridgeConfiguration.getForwardingAddress());
Assert.assertArrayEquals(new String[] {"in-vm"}, bridgeConfiguration.getStaticConnectors().toArray());
Assert.assertEquals(80000, bridgeConfiguration.getCallTimeout());
} finally {
System.clearProperty(BridgeAdd.CALL_TIMEOUT_PROPERTY);
}
}
private static ModelNode createModel() {
ModelNode model = new ModelNode();
model.get("queue-name").set(SOURCE_QUEUE_NAME);
model.get("forwarding-address").set(TARGET_QUEUE_NAME);
model.get("static-connectors").add("in-vm");
return model;
}
}
| 4,263
| 46.910112
| 114
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/test/java/org/wildfly/extension/messaging/activemq/ClusterConnectionControlHandlerTest.java
|
/*
* Copyright 2022 JBoss by Red Hat.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.extension.messaging.activemq;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Emmanuel Hugonnet (c) 2021 Red Hat, Inc.
*/
public class ClusterConnectionControlHandlerTest {
public ClusterConnectionControlHandlerTest() {
}
/**
* Test of formatTopology method, of class ClusterConnectionControlHandler.
*/
@Test
public void testFormatTopology() {
String topology = "topology on Topology@2ec5aa9[owner=ClusterConnectionImpl@1518657274[nodeUUID=b7a794ee-b5af-11ec-ae2f-3ce1a1c35439, connector=TransportConfiguration(name=netty, factory=org-apache-activemq-artemis-core-remoting-impl-netty-NettyConnectorFactory) ?port=5445&useNio=true&"
+ "host=localhost&useNioGlobalWorkerPool=true, address=jms, server=ActiveMQServerImpl::name=default]]:"
+ "b7a794ee-b5af-11ec-ae2f-3ce1a1c35439 => TopologyMember[id=b7a794ee-b5af-11ec-ae2f-3ce1a1c35439, connector=Pair[a=TransportConfiguration(name=netty, factory=org-apache-activemq-artemis-core-remoting-impl-netty-NettyConnectorFactory) ?port=5445&useNio=true&host=localhost&useNioGlobalW"
+ "orkerPool=true, b=null], backupGroupName=group1, scaleDownGroupName=null]"
+ "nodes=1 members=1";
String expResult = "topology on Topology@2ec5aa9[owner=ClusterConnectionImpl@1518657274[nodeUUID=b7a794ee-b5af-11ec-ae2f-3ce1a1c35439," + System.lineSeparator()
+ "\t\tconnector=TransportConfiguration(name=netty," + System.lineSeparator()
+ "\t\t\tfactory=org-apache-activemq-artemis-core-remoting-impl-netty-NettyConnectorFactory)," + System.lineSeparator()
+ "\t\t{" + System.lineSeparator()
+ "\t\t\tport=5445," + System.lineSeparator()
+ "\t\t\tuseNio=true," + System.lineSeparator()
+ "\t\t\thost=localhost," + System.lineSeparator()
+ "\t\t\tuseNioGlobalWorkerPool=true" + System.lineSeparator()
+ "\t\t}," + System.lineSeparator()
+ "\t\t" + System.lineSeparator()
+ "\t\taddress=jms," + System.lineSeparator()
+ "\t\tserver=ActiveMQServerImpl::name=default" + System.lineSeparator()
+ "\t]" + System.lineSeparator()
+ "]:b7a794ee-b5af-11ec-ae2f-3ce1a1c35439 => TopologyMember[id=b7a794ee-b5af-11ec-ae2f-3ce1a1c35439," + System.lineSeparator()
+ "\tconnector=Pair[a=TransportConfiguration(name=netty," + System.lineSeparator()
+ "\t\t\tfactory=org-apache-activemq-artemis-core-remoting-impl-netty-NettyConnectorFactory)," + System.lineSeparator()
+ "\t\t{" + System.lineSeparator()
+ "\t\t\tport=5445," + System.lineSeparator()
+ "\t\t\tuseNio=true," + System.lineSeparator()
+ "\t\t\thost=localhost," + System.lineSeparator()
+ "\t\t\tuseNioGlobalWorkerPool=true" + System.lineSeparator()
+ "\t\t}," + System.lineSeparator()
+ "\t\t" + System.lineSeparator()
+ "\t\tb=null" + System.lineSeparator()
+ "\t]," + System.lineSeparator()
+ "\tbackupGroupName=group1," + System.lineSeparator()
+ "\tscaleDownGroupName=null" + System.lineSeparator()
+ "]nodes=1 members=1";
String result = ClusterConnectionControlHandler.formatTopology(topology);
assertEquals(expResult, result);
}
}
| 4,128
| 56.347222
| 303
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/test/java/org/wildfly/extension/messaging/activemq/AS7BindingRegistryTestCase.java
|
package org.wildfly.extension.messaging.activemq;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.wildfly.extension.messaging.activemq.jms.WildFlyBindingRegistry;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class AS7BindingRegistryTestCase {
private ServiceContainer container;
@Before
public void setUp() {
container = ServiceContainer.Factory.create("test");
}
@After
public void tearDown() {
if (container != null) {
container.shutdown();
try {
container.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
finally {
container = null;
}
}
}
/*
* https://issues.jboss.org/browse/AS7-4269
*/
@Test
public void bindUnbindBind() throws Exception {
WildFlyBindingRegistry registry = new WildFlyBindingRegistry(container);
Object obj = new Object();
String name = UUID.randomUUID().toString();
assertNull(getBinderServiceFor(name));
assertTrue(registry.bind(name, obj));
assertNotNull(getBinderServiceFor(name));
registry.unbind(name);
assertNull(getBinderServiceFor(name));
assertTrue(registry.bind(name, obj));
assertNotNull(getBinderServiceFor(name));
}
private ServiceController<?> getBinderServiceFor(String name) {
final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(name);
return container.getService(bindInfo.getBinderServiceName());
}
}
| 1,953
| 27.735294
| 80
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/test/java/org/wildfly/extension/messaging/activemq/MessagingActiveMQSubsystem_13_1_TestCase.java
|
/*
* Copyright 2020 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.messaging.activemq;
import static org.jboss.as.model.test.ModelTestControllerVersion.EAP_7_4_0;
import static org.junit.Assert.assertTrue;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.BRIDGE;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.DEFAULT;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.SERVER;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.SUBSYSTEM;
import static org.wildfly.extension.messaging.activemq.MessagingDependencies.getActiveMQDependencies;
import static org.wildfly.extension.messaging.activemq.MessagingDependencies.getJGroupsDependencies;
import static org.wildfly.extension.messaging.activemq.MessagingDependencies.getMessagingActiveMQGAV;
import static org.wildfly.extension.messaging.activemq.MessagingExtension.SERVER_PATH;
import static org.wildfly.extension.messaging.activemq.MessagingExtension.SUBSYSTEM_PATH;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.security.CredentialReference;
import org.jboss.as.model.test.FailedOperationTransformationConfig;
import org.jboss.as.model.test.ModelTestControllerVersion;
import org.jboss.as.model.test.ModelTestUtils;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.as.subsystem.test.KernelServicesBuilder;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
import org.wildfly.clustering.jgroups.spi.JGroupsDefaultRequirement;
import org.wildfly.clustering.server.service.ClusteringDefaultRequirement;
import org.wildfly.clustering.server.service.ClusteringRequirement;
public class MessagingActiveMQSubsystem_13_1_TestCase extends AbstractSubsystemBaseTest {
public MessagingActiveMQSubsystem_13_1_TestCase() {
super(MessagingExtension.SUBSYSTEM_NAME, new MessagingExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource("subsystem_13_1.xml");
}
@Override
protected String getSubsystemXsdPath() throws IOException {
return "schema/wildfly-messaging-activemq_13_1.xsd";
}
@Override
protected Properties getResolvedProperties() {
Properties properties = new Properties();
properties.put("messaging.cluster.user.name", "myClusterUser");
properties.put("messaging.cluster.user.password", "myClusterPassword");
return properties;
}
@Override
protected KernelServices standardSubsystemTest(String configId, boolean compareXml) throws Exception {
return super.standardSubsystemTest(configId, false);
}
@Test
public void testJournalAttributes() throws Exception {
KernelServices kernelServices = standardSubsystemTest(null, false);
ModelNode rootModel = kernelServices.readWholeModel();
ModelNode serverModel = rootModel.require(SUBSYSTEM).require(MessagingExtension.SUBSYSTEM_NAME).require(SERVER)
.require(DEFAULT);
Assert.assertEquals(1357, serverModel.get(ServerDefinition.JOURNAL_BUFFER_TIMEOUT.getName()).resolve().asInt());
Assert.assertEquals(102400, serverModel.get(ServerDefinition.JOURNAL_FILE_SIZE.getName()).resolve().asInt());
Assert.assertEquals(2, serverModel.get(ServerDefinition.JOURNAL_MIN_FILES.getName()).resolve().asInt());
Assert.assertEquals(5, serverModel.get(ServerDefinition.JOURNAL_POOL_FILES.getName()).resolve().asInt());
Assert.assertEquals(7, serverModel.get(ServerDefinition.JOURNAL_FILE_OPEN_TIMEOUT.getName()).resolve().asInt());
kernelServices.shutdown();
}
@Test
public void testBridgeCallTimeout() throws Exception {
KernelServices kernelServices = standardSubsystemTest(null, false);
ModelNode rootModel = kernelServices.readWholeModel();
ModelNode bridgeModel = rootModel.require(SUBSYSTEM).require(MessagingExtension.SUBSYSTEM_NAME).require(SERVER)
.require(DEFAULT).require(BRIDGE).require("bridge1");
Assert.assertEquals("${call.timeout:60000}", bridgeModel.get(BridgeDefinition.CALL_TIMEOUT.getName()).asExpression().getExpressionString());
Assert.assertEquals(60000, bridgeModel.get(BridgeDefinition.CALL_TIMEOUT.getName()).resolve().asLong());
kernelServices.shutdown();
}
/////////////////////////////////////////
// Tests for HA Policy Configuration //
/////////////////////////////////////////
@Test
public void testHAPolicyConfiguration() throws Exception {
standardSubsystemTest("subsystem_13_1_ha-policy.xml");
}
///////////////////////
// Transformers test //
///////////////////////
@Test
public void testTransformersWildfly25() throws Exception {
testTransformers(ModelTestControllerVersion.MASTER, MessagingExtension.VERSION_13_0_0);
}
@Test
public void testTransformersEAP_7_4_0() throws Exception {
testTransformers(EAP_7_4_0, MessagingExtension.VERSION_13_0_0);
}
@Test
public void testRejectingTransformersEAP_7_4_0() throws Exception {
testRejectingTransformers(EAP_7_4_0, MessagingExtension.VERSION_13_0_0);
}
private void testTransformers(ModelTestControllerVersion controllerVersion, ModelVersion messagingVersion) throws Exception {
//Boot up empty controllers with the resources needed for the ops coming from the xml to work
KernelServicesBuilder builder = createKernelServicesBuilder(createAdditionalInitialization())
.setSubsystemXmlResource("subsystem_13_1_transform.xml");
builder.createLegacyKernelServicesBuilder(createAdditionalInitialization(), controllerVersion, messagingVersion)
.addMavenResourceURL(getMessagingActiveMQGAV(controllerVersion))
.addMavenResourceURL(getActiveMQDependencies(controllerVersion))
.addMavenResourceURL(getJGroupsDependencies(controllerVersion))
.skipReverseControllerCheck()
.dontPersistXml();
KernelServices mainServices = builder.build();
assertTrue(mainServices.isSuccessfulBoot());
assertTrue(mainServices.getLegacyServices(messagingVersion).isSuccessfulBoot());
checkSubsystemModelTransformation(mainServices, messagingVersion, (ModelNode modelNode) -> {
ModelNode legacyModel = modelNode.clone();
if (modelNode.hasDefined("server", "default", "address-setting", "test", "page-size-bytes")) {
int legacyNodeValue = modelNode.get("server", "default", "address-setting", "test", "page-size-bytes").asInt();
legacyModel.get("server", "default", "address-setting", "test", "page-size-bytes").set(legacyNodeValue);
}
return legacyModel;
});
mainServices.shutdown();
}
private void testRejectingTransformers(ModelTestControllerVersion controllerVersion, ModelVersion messagingVersion) throws Exception {
//Boot up empty controllers with the resources needed for the ops coming from the xml to work
KernelServicesBuilder builder = createKernelServicesBuilder(createAdditionalInitialization());
builder.createLegacyKernelServicesBuilder(createAdditionalInitialization(), controllerVersion, messagingVersion)
.addMavenResourceURL(getMessagingActiveMQGAV(controllerVersion))
.addMavenResourceURL(getActiveMQDependencies(controllerVersion))
.addMavenResourceURL(getJGroupsDependencies(controllerVersion))
.skipReverseControllerCheck()
.dontPersistXml();
KernelServices mainServices = builder.build();
assertTrue(mainServices.isSuccessfulBoot());
assertTrue(mainServices.getLegacyServices(messagingVersion).isSuccessfulBoot());
List<ModelNode> ops = builder.parseXmlResource("subsystem_13_1_reject_transform.xml");
// System.out.println("ops = " + ops);
PathAddress subsystemAddress = PathAddress.pathAddress(SUBSYSTEM_PATH);
FailedOperationTransformationConfig config = new FailedOperationTransformationConfig();
config.addFailedAttribute(subsystemAddress.append(SERVER_PATH),
new FailedOperationTransformationConfig.NewAttributesConfig(
ServerDefinition.ADDRESS_QUEUE_SCAN_PERIOD));
ModelTestUtils.checkFailedTransformedBootOperations(mainServices, messagingVersion, ops, config);
mainServices.shutdown();
}
@Override
protected Set<PathAddress> getIgnoredChildResourcesForRemovalTest() {
Set<PathAddress> ignoredChildResources = new HashSet<>(super.getIgnoredChildResourcesForRemovalTest());
ignoredChildResources.add(PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/discovery-group=groupS"));
return ignoredChildResources;
}
@Override
protected AdditionalInitialization createAdditionalInitialization() {
return AdditionalInitialization.withCapabilities(ClusteringRequirement.COMMAND_DISPATCHER_FACTORY.resolve("ee"),
ClusteringDefaultRequirement.COMMAND_DISPATCHER_FACTORY.getName(),
JGroupsDefaultRequirement.CHANNEL_FACTORY.getName(),
Capabilities.ELYTRON_DOMAIN_CAPABILITY,
Capabilities.ELYTRON_DOMAIN_CAPABILITY + ".elytronDomain",
CredentialReference.CREDENTIAL_STORE_CAPABILITY + ".cs1",
Capabilities.DATA_SOURCE_CAPABILITY + ".fooDS",
Capabilities.LEGACY_SECURITY_DOMAIN_CAPABILITY.getDynamicName("other"));
}
}
| 10,566
| 50.296117
| 148
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/test/java/org/wildfly/extension/messaging/activemq/AttributeDefaultsTest.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.messaging.activemq;
import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration;
import org.apache.activemq.artemis.api.core.client.ActiveMQClient;
import org.hornetq.api.core.client.HornetQClient;
import org.jboss.as.subsystem.test.AbstractSubsystemTest;
import org.junit.Assert;
import org.junit.Test;
import org.wildfly.extension.messaging.activemq.ha.HAAttributes;
import org.wildfly.extension.messaging.activemq.jms.ConnectionFactoryAttributes;
import org.wildfly.extension.messaging.activemq.jms.legacy.LegacyConnectionFactoryDefinition;
public class AttributeDefaultsTest extends AbstractSubsystemTest {
public AttributeDefaultsTest() {
super(MessagingExtension.SUBSYSTEM_NAME, new MessagingExtension());
}
@Test
public void testAttributeValues() {
Assert.assertNotEquals(ServerDefinition.GLOBAL_MAX_DISK_USAGE.getName(), ServerDefinition.GLOBAL_MAX_DISK_USAGE.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultMaxDiskUsage());
Assert.assertNotEquals(ServerDefinition.GLOBAL_MAX_MEMORY_SIZE.getName(), ServerDefinition.GLOBAL_MAX_MEMORY_SIZE.getDefaultValue().asLong(), ActiveMQDefaultConfiguration.getDefaultMaxGlobalSize());
Assert.assertNotEquals(ServerDefinition.JOURNAL_POOL_FILES.getName(), ServerDefinition.JOURNAL_POOL_FILES.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultJournalPoolFiles());
// Assert.assertNotEquals(ClusterConnectionDefinition.PRODUCER_WINDOW_SIZE.getName(), ClusterConnectionDefinition.PRODUCER_WINDOW_SIZE.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultBridgeProducerWindowSize());
Assert.assertEquals(BridgeDefinition.INITIAL_CONNECT_ATTEMPTS.getName(), BridgeDefinition.INITIAL_CONNECT_ATTEMPTS.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultBridgeInitialConnectAttempts());
Assert.assertEquals(BridgeDefinition.RECONNECT_ATTEMPTS.getName(), BridgeDefinition.RECONNECT_ATTEMPTS.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultBridgeReconnectAttempts());
Assert.assertEquals(BridgeDefinition.RECONNECT_ATTEMPTS_ON_SAME_NODE.getName(), BridgeDefinition.RECONNECT_ATTEMPTS_ON_SAME_NODE.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultBridgeConnectSameNode());
Assert.assertEquals(BridgeDefinition.USE_DUPLICATE_DETECTION.getName(), BridgeDefinition.USE_DUPLICATE_DETECTION.getDefaultValue().asBoolean(), ActiveMQDefaultConfiguration.isDefaultBridgeDuplicateDetection());
Assert.assertEquals(ClusterConnectionDefinition.CHECK_PERIOD.getName(), ClusterConnectionDefinition.CHECK_PERIOD.getDefaultValue().asLong(), ActiveMQDefaultConfiguration.getDefaultClusterFailureCheckPeriod());
Assert.assertEquals(ClusterConnectionDefinition.CONNECTION_TTL.getName(), ClusterConnectionDefinition.CONNECTION_TTL.getDefaultValue().asLong(), ActiveMQDefaultConfiguration.getDefaultClusterConnectionTtl());
Assert.assertEquals(ClusterConnectionDefinition.INITIAL_CONNECT_ATTEMPTS.getName(), ClusterConnectionDefinition.INITIAL_CONNECT_ATTEMPTS.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultClusterInitialConnectAttempts());
Assert.assertEquals(ClusterConnectionDefinition.MAX_HOPS.getName(), ClusterConnectionDefinition.MAX_HOPS.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultClusterMaxHops());
Assert.assertEquals(ClusterConnectionDefinition.MAX_RETRY_INTERVAL.getName(), ClusterConnectionDefinition.MAX_RETRY_INTERVAL.getDefaultValue().asLong(), ActiveMQDefaultConfiguration.getDefaultClusterMaxRetryInterval());
Assert.assertEquals(ClusterConnectionDefinition.MESSAGE_LOAD_BALANCING_TYPE.getName(), ClusterConnectionDefinition.MESSAGE_LOAD_BALANCING_TYPE.getDefaultValue().asString(), ActiveMQDefaultConfiguration.getDefaultClusterMessageLoadBalancingType());
Assert.assertEquals(ClusterConnectionDefinition.NOTIFICATION_ATTEMPTS.getName(), ClusterConnectionDefinition.NOTIFICATION_ATTEMPTS.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultClusterNotificationAttempts());
Assert.assertEquals(ClusterConnectionDefinition.NOTIFICATION_INTERVAL.getName(), ClusterConnectionDefinition.NOTIFICATION_INTERVAL.getDefaultValue().asLong(), ActiveMQDefaultConfiguration.getDefaultClusterNotificationInterval());
Assert.assertEquals(ClusterConnectionDefinition.RECONNECT_ATTEMPTS.getName(), ClusterConnectionDefinition.RECONNECT_ATTEMPTS.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultClusterReconnectAttempts());
Assert.assertEquals(ClusterConnectionDefinition.RETRY_INTERVAL.getName(), ClusterConnectionDefinition.RETRY_INTERVAL.getDefaultValue().asLong(), ActiveMQDefaultConfiguration.getDefaultClusterRetryInterval());
Assert.assertEquals(ClusterConnectionDefinition.RETRY_INTERVAL_MULTIPLIER.getName(), ClusterConnectionDefinition.RETRY_INTERVAL_MULTIPLIER.getDefaultValue().asDouble(), ActiveMQDefaultConfiguration.getDefaultClusterRetryIntervalMultiplier(), 0);
Assert.assertEquals(CommonAttributes.BRIDGE_CONFIRMATION_WINDOW_SIZE.getName(), CommonAttributes.BRIDGE_CONFIRMATION_WINDOW_SIZE.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultBridgeConfirmationWindowSize());
Assert.assertEquals(CommonAttributes.CALL_TIMEOUT.getName(), CommonAttributes.CALL_TIMEOUT.getDefaultValue().asLong(), ActiveMQClient.DEFAULT_CALL_TIMEOUT);
Assert.assertEquals(CommonAttributes.CHECK_PERIOD.getName(), CommonAttributes.CHECK_PERIOD.getDefaultValue().asLong(), ActiveMQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD);
Assert.assertEquals(CommonAttributes.CONNECTION_TTL.getName(), CommonAttributes.CONNECTION_TTL.getDefaultValue().asLong(), ActiveMQClient.DEFAULT_CONNECTION_TTL);
Assert.assertEquals(CommonAttributes.HA.getName(), CommonAttributes.HA.getDefaultValue().asBoolean(), ActiveMQClient.DEFAULT_HA);
Assert.assertEquals(CommonAttributes.MAX_RETRY_INTERVAL.getName(), CommonAttributes.MAX_RETRY_INTERVAL.getDefaultValue().asLong(), ActiveMQClient.DEFAULT_MAX_RETRY_INTERVAL);
Assert.assertEquals(CommonAttributes.MIN_LARGE_MESSAGE_SIZE.getName(), CommonAttributes.MIN_LARGE_MESSAGE_SIZE.getDefaultValue().asLong(), ActiveMQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE);
Assert.assertEquals(CommonAttributes.RETRY_INTERVAL.getName(), CommonAttributes.RETRY_INTERVAL.getDefaultValue().asLong(), ActiveMQClient.DEFAULT_RETRY_INTERVAL);
Assert.assertEquals(CommonAttributes.RETRY_INTERVAL_MULTIPLIER.getName(), CommonAttributes.RETRY_INTERVAL_MULTIPLIER.getDefaultValue().asDouble(), ActiveMQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, 0);
Assert.assertEquals(ConnectionFactoryAttributes.Common.AUTO_GROUP.getName(), ConnectionFactoryAttributes.Common.AUTO_GROUP.getDefaultValue().asBoolean(), ActiveMQClient.DEFAULT_AUTO_GROUP);
Assert.assertEquals(ConnectionFactoryAttributes.Common.BLOCK_ON_ACKNOWLEDGE.getName(), ConnectionFactoryAttributes.Common.BLOCK_ON_ACKNOWLEDGE.getDefaultValue().asBoolean(), ActiveMQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE);
Assert.assertEquals(ConnectionFactoryAttributes.Common.BLOCK_ON_DURABLE_SEND.getName(), ConnectionFactoryAttributes.Common.BLOCK_ON_DURABLE_SEND.getDefaultValue().asBoolean(), ActiveMQClient.DEFAULT_BLOCK_ON_DURABLE_SEND);
Assert.assertEquals(ConnectionFactoryAttributes.Common.BLOCK_ON_NON_DURABLE_SEND.getName(), ConnectionFactoryAttributes.Common.BLOCK_ON_NON_DURABLE_SEND.getDefaultValue().asBoolean(), ActiveMQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND);
Assert.assertEquals(ConnectionFactoryAttributes.Common.CACHE_LARGE_MESSAGE_CLIENT.getName(), ConnectionFactoryAttributes.Common.CACHE_LARGE_MESSAGE_CLIENT.getDefaultValue().asBoolean(), ActiveMQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT);
Assert.assertEquals(ConnectionFactoryAttributes.Common.COMPRESS_LARGE_MESSAGES.getName(), ConnectionFactoryAttributes.Common.COMPRESS_LARGE_MESSAGES.getDefaultValue().asBoolean(), ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES);
Assert.assertEquals(ConnectionFactoryAttributes.Common.CONFIRMATION_WINDOW_SIZE.getName(), ConnectionFactoryAttributes.Common.CONFIRMATION_WINDOW_SIZE.getDefaultValue().asInt(), ActiveMQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE);
Assert.assertEquals(ConnectionFactoryAttributes.Common.CONNECTION_LOAD_BALANCING_CLASS_NAME.getName(), ConnectionFactoryAttributes.Common.CONNECTION_LOAD_BALANCING_CLASS_NAME.getDefaultValue().asString(), ActiveMQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME);
Assert.assertEquals(ConnectionFactoryAttributes.Common.CONSUMER_MAX_RATE.getName(), ConnectionFactoryAttributes.Common.CONSUMER_MAX_RATE.getDefaultValue().asInt(), ActiveMQClient.DEFAULT_CONSUMER_MAX_RATE);
Assert.assertEquals(ConnectionFactoryAttributes.Common.CONSUMER_WINDOW_SIZE.getName(), ConnectionFactoryAttributes.Common.CONSUMER_WINDOW_SIZE.getDefaultValue().asInt(), ActiveMQClient.DEFAULT_CONSUMER_WINDOW_SIZE);
Assert.assertEquals(ConnectionFactoryAttributes.Common.DUPS_OK_BATCH_SIZE.getName(), ConnectionFactoryAttributes.Common.DUPS_OK_BATCH_SIZE.getDefaultValue().asInt(), ActiveMQClient.DEFAULT_ACK_BATCH_SIZE);
Assert.assertEquals(ConnectionFactoryAttributes.Common.FAILOVER_ON_INITIAL_CONNECTION.getName(), ConnectionFactoryAttributes.Common.FAILOVER_ON_INITIAL_CONNECTION.getDefaultValue().asBoolean(), ActiveMQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION);
Assert.assertEquals(ConnectionFactoryAttributes.Common.PRE_ACKNOWLEDGE.getName(), ConnectionFactoryAttributes.Common.PRE_ACKNOWLEDGE.getDefaultValue().asBoolean(), ActiveMQClient.DEFAULT_PRE_ACKNOWLEDGE);
Assert.assertEquals(ConnectionFactoryAttributes.Common.PRODUCER_MAX_RATE.getName(), ConnectionFactoryAttributes.Common.PRODUCER_MAX_RATE.getDefaultValue().asInt(), ActiveMQClient.DEFAULT_PRODUCER_MAX_RATE);
Assert.assertEquals(ConnectionFactoryAttributes.Common.PRODUCER_WINDOW_SIZE.getName(), ConnectionFactoryAttributes.Common.PRODUCER_WINDOW_SIZE.getDefaultValue().asInt(), ActiveMQClient.DEFAULT_PRODUCER_WINDOW_SIZE);
Assert.assertEquals(ConnectionFactoryAttributes.Common.RECONNECT_ATTEMPTS.getName(), ConnectionFactoryAttributes.Common.RECONNECT_ATTEMPTS.getDefaultValue().asInt(), ActiveMQClient.DEFAULT_RECONNECT_ATTEMPTS);
Assert.assertEquals(ConnectionFactoryAttributes.Common.SCHEDULED_THREAD_POOL_MAX_SIZE.getName(), ConnectionFactoryAttributes.Common.SCHEDULED_THREAD_POOL_MAX_SIZE.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultScheduledThreadPoolMaxSize());
Assert.assertEquals(ConnectionFactoryAttributes.Common.USE_GLOBAL_POOLS.getName(), ConnectionFactoryAttributes.Common.USE_GLOBAL_POOLS.getDefaultValue().asBoolean(), ActiveMQClient.DEFAULT_USE_GLOBAL_POOLS);
Assert.assertEquals(ConnectionFactoryAttributes.Common.USE_TOPOLOGY.getName(), ConnectionFactoryAttributes.Common.USE_TOPOLOGY.getDefaultValue().asBoolean(), ActiveMQClient.DEFAULT_USE_TOPOLOGY_FOR_LOADBALANCING);
Assert.assertEquals(DivertDefinition.EXCLUSIVE.getName(), DivertDefinition.EXCLUSIVE.getDefaultValue().asBoolean(), ActiveMQDefaultConfiguration.isDefaultDivertExclusive());
Assert.assertEquals(GroupingHandlerDefinition.GROUP_TIMEOUT.getName(), GroupingHandlerDefinition.GROUP_TIMEOUT.getDefaultValue().asLong(), ActiveMQDefaultConfiguration.getDefaultGroupingHandlerGroupTimeout());
Assert.assertEquals(GroupingHandlerDefinition.REAPER_PERIOD.getName(), GroupingHandlerDefinition.REAPER_PERIOD.getDefaultValue().asLong(), ActiveMQDefaultConfiguration.getDefaultGroupingHandlerReaperPeriod());
Assert.assertEquals(GroupingHandlerDefinition.TIMEOUT.getName(), GroupingHandlerDefinition.TIMEOUT.getDefaultValue().asLong(), ActiveMQDefaultConfiguration.getDefaultGroupingHandlerTimeout());
Assert.assertEquals(HAAttributes.ALLOW_FAILBACK.getName(), HAAttributes.ALLOW_FAILBACK.getDefaultValue().asBoolean(), ActiveMQDefaultConfiguration.isDefaultAllowAutoFailback());
Assert.assertEquals(HAAttributes.BACKUP_PORT_OFFSET.getName(), HAAttributes.BACKUP_PORT_OFFSET.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultHapolicyBackupPortOffset());
Assert.assertEquals(HAAttributes.BACKUP_REQUEST_RETRIES.getName(), HAAttributes.BACKUP_REQUEST_RETRIES.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultHapolicyBackupRequestRetries());
Assert.assertEquals(HAAttributes.BACKUP_REQUEST_RETRY_INTERVAL.getName(), HAAttributes.BACKUP_REQUEST_RETRY_INTERVAL.getDefaultValue().asLong(), ActiveMQDefaultConfiguration.getDefaultHapolicyBackupRequestRetryInterval());
Assert.assertEquals(HAAttributes.FAILOVER_ON_SERVER_SHUTDOWN.getName(), HAAttributes.FAILOVER_ON_SERVER_SHUTDOWN.getDefaultValue().asBoolean(), ActiveMQDefaultConfiguration.isDefaultFailoverOnServerShutdown());
Assert.assertEquals(HAAttributes.INITIAL_REPLICATION_SYNC_TIMEOUT.getName(), HAAttributes.INITIAL_REPLICATION_SYNC_TIMEOUT.getDefaultValue().asLong(), ActiveMQDefaultConfiguration.getDefaultInitialReplicationSyncTimeout());
Assert.assertEquals(HAAttributes.MAX_BACKUPS.getName(), HAAttributes.MAX_BACKUPS.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultHapolicyMaxBackups());
Assert.assertEquals(HAAttributes.MAX_SAVED_REPLICATED_JOURNAL_SIZE.getName(), HAAttributes.MAX_SAVED_REPLICATED_JOURNAL_SIZE.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultMaxSavedReplicatedJournalsSize());
Assert.assertEquals(HAAttributes.REQUEST_BACKUP.getName(), HAAttributes.REQUEST_BACKUP.getDefaultValue().asBoolean(), ActiveMQDefaultConfiguration.isDefaultHapolicyRequestBackup());
Assert.assertEquals(HAAttributes.RESTART_BACKUP.getName(), HAAttributes.RESTART_BACKUP.getDefaultValue().asBoolean(), ActiveMQDefaultConfiguration.isDefaultRestartBackup());
Assert.assertEquals(JGroupsBroadcastGroupDefinition.BROADCAST_PERIOD.getName(), JGroupsBroadcastGroupDefinition.BROADCAST_PERIOD.getDefaultValue().asLong(), ActiveMQDefaultConfiguration.getDefaultBroadcastPeriod());
Assert.assertEquals(JGroupsDiscoveryGroupDefinition.INITIAL_WAIT_TIMEOUT.getName(), JGroupsDiscoveryGroupDefinition.INITIAL_WAIT_TIMEOUT.getDefaultValue().asLong(), ActiveMQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT);
Assert.assertEquals(JGroupsDiscoveryGroupDefinition.REFRESH_TIMEOUT.getName(), JGroupsDiscoveryGroupDefinition.REFRESH_TIMEOUT.getDefaultValue().asLong(), ActiveMQDefaultConfiguration.getDefaultBroadcastRefreshTimeout());
Assert.assertEquals(LegacyConnectionFactoryDefinition.AUTO_GROUP.getName(), LegacyConnectionFactoryDefinition.AUTO_GROUP.getDefaultValue().asBoolean(), HornetQClient.DEFAULT_AUTO_GROUP);
Assert.assertEquals(LegacyConnectionFactoryDefinition.BLOCK_ON_ACKNOWLEDGE.getName(), LegacyConnectionFactoryDefinition.BLOCK_ON_ACKNOWLEDGE.getDefaultValue().asBoolean(), HornetQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE);
Assert.assertEquals(LegacyConnectionFactoryDefinition.BLOCK_ON_DURABLE_SEND.getName(), LegacyConnectionFactoryDefinition.BLOCK_ON_DURABLE_SEND.getDefaultValue().asBoolean(), HornetQClient.DEFAULT_BLOCK_ON_DURABLE_SEND);
Assert.assertEquals(LegacyConnectionFactoryDefinition.BLOCK_ON_NON_DURABLE_SEND.getName(), LegacyConnectionFactoryDefinition.BLOCK_ON_NON_DURABLE_SEND.getDefaultValue().asBoolean(), HornetQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND);
Assert.assertEquals(LegacyConnectionFactoryDefinition.CACHE_LARGE_MESSAGE_CLIENT.getName(), LegacyConnectionFactoryDefinition.CACHE_LARGE_MESSAGE_CLIENT.getDefaultValue().asBoolean(), HornetQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT);
Assert.assertEquals(LegacyConnectionFactoryDefinition.CLIENT_FAILURE_CHECK_PERIOD.getName(), LegacyConnectionFactoryDefinition.CLIENT_FAILURE_CHECK_PERIOD.getDefaultValue().asLong(), HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD);
Assert.assertEquals(LegacyConnectionFactoryDefinition.COMPRESS_LARGE_MESSAGES.getName(), LegacyConnectionFactoryDefinition.COMPRESS_LARGE_MESSAGES.getDefaultValue().asBoolean(), HornetQClient.DEFAULT_COMPRESS_LARGE_MESSAGES);
Assert.assertEquals(LegacyConnectionFactoryDefinition.CONFIRMATION_WINDOW_SIZE.getName(), LegacyConnectionFactoryDefinition.CONFIRMATION_WINDOW_SIZE.getDefaultValue().asInt(), HornetQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE);
Assert.assertEquals(LegacyConnectionFactoryDefinition.CONNECTION_LOAD_BALANCING_CLASS_NAME.getName(), LegacyConnectionFactoryDefinition.CONNECTION_LOAD_BALANCING_CLASS_NAME.getDefaultValue().asString(), HornetQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME);
Assert.assertEquals(LegacyConnectionFactoryDefinition.CONNECTION_TTL.getName(), LegacyConnectionFactoryDefinition.CONNECTION_TTL.getDefaultValue().asLong(), HornetQClient.DEFAULT_CONNECTION_TTL);
Assert.assertEquals(LegacyConnectionFactoryDefinition.CONSUMER_MAX_RATE.getName(), LegacyConnectionFactoryDefinition.CONSUMER_MAX_RATE.getDefaultValue().asInt(), HornetQClient.DEFAULT_CONSUMER_MAX_RATE);
Assert.assertEquals(LegacyConnectionFactoryDefinition.CONSUMER_WINDOW_SIZE.getName(), LegacyConnectionFactoryDefinition.CONSUMER_WINDOW_SIZE.getDefaultValue().asInt(), HornetQClient.DEFAULT_CONSUMER_WINDOW_SIZE);
Assert.assertEquals(LegacyConnectionFactoryDefinition.DUPS_OK_BATCH_SIZE.getName(), LegacyConnectionFactoryDefinition.DUPS_OK_BATCH_SIZE.getDefaultValue().asInt(), HornetQClient.DEFAULT_ACK_BATCH_SIZE);
Assert.assertEquals(LegacyConnectionFactoryDefinition.FAILOVER_ON_INITIAL_CONNECTION.getName(), LegacyConnectionFactoryDefinition.FAILOVER_ON_INITIAL_CONNECTION.getDefaultValue().asBoolean(), HornetQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION);
Assert.assertEquals(LegacyConnectionFactoryDefinition.INITIAL_CONNECT_ATTEMPTS.getName(), LegacyConnectionFactoryDefinition.INITIAL_CONNECT_ATTEMPTS.getDefaultValue().asInt(), HornetQClient.INITIAL_CONNECT_ATTEMPTS);
Assert.assertEquals(LegacyConnectionFactoryDefinition.INITIAL_MESSAGE_PACKET_SIZE.getName(), LegacyConnectionFactoryDefinition.INITIAL_MESSAGE_PACKET_SIZE.getDefaultValue().asInt(), HornetQClient.DEFAULT_INITIAL_MESSAGE_PACKET_SIZE);
Assert.assertEquals(LegacyConnectionFactoryDefinition.MAX_RETRY_INTERVAL.getName(), LegacyConnectionFactoryDefinition.MAX_RETRY_INTERVAL.getDefaultValue().asLong(), HornetQClient.DEFAULT_MAX_RETRY_INTERVAL);
Assert.assertEquals(LegacyConnectionFactoryDefinition.MIN_LARGE_MESSAGE_SIZE.getName(), LegacyConnectionFactoryDefinition.MIN_LARGE_MESSAGE_SIZE.getDefaultValue().asInt(), HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE);
Assert.assertEquals(LegacyConnectionFactoryDefinition.PRE_ACKNOWLEDGE.getName(), LegacyConnectionFactoryDefinition.PRE_ACKNOWLEDGE.getDefaultValue().asBoolean(), HornetQClient.DEFAULT_PRE_ACKNOWLEDGE);
Assert.assertEquals(LegacyConnectionFactoryDefinition.PRODUCER_MAX_RATE.getName(), LegacyConnectionFactoryDefinition.PRODUCER_MAX_RATE.getDefaultValue().asInt(), HornetQClient.DEFAULT_PRODUCER_MAX_RATE);
Assert.assertEquals(LegacyConnectionFactoryDefinition.PRODUCER_WINDOW_SIZE.getName(), LegacyConnectionFactoryDefinition.PRODUCER_WINDOW_SIZE.getDefaultValue().asInt(), HornetQClient.DEFAULT_PRODUCER_WINDOW_SIZE);
Assert.assertEquals(LegacyConnectionFactoryDefinition.RECONNECT_ATTEMPTS.getName(), LegacyConnectionFactoryDefinition.RECONNECT_ATTEMPTS.getDefaultValue().asInt(), HornetQClient.DEFAULT_RECONNECT_ATTEMPTS);
Assert.assertEquals(LegacyConnectionFactoryDefinition.RETRY_INTERVAL.getName(), LegacyConnectionFactoryDefinition.RETRY_INTERVAL.getDefaultValue().asLong(), HornetQClient.DEFAULT_RETRY_INTERVAL);
Assert.assertEquals(LegacyConnectionFactoryDefinition.RETRY_INTERVAL_MULTIPLIER.getName(), LegacyConnectionFactoryDefinition.RETRY_INTERVAL_MULTIPLIER.getDefaultValue().asDouble(), HornetQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER, 0);
Assert.assertEquals(LegacyConnectionFactoryDefinition.USE_GLOBAL_POOLS.getName(), LegacyConnectionFactoryDefinition.USE_GLOBAL_POOLS.getDefaultValue().asBoolean(), HornetQClient.DEFAULT_USE_GLOBAL_POOLS);
Assert.assertEquals(ServerDefinition.ASYNC_CONNECTION_EXECUTION_ENABLED.getName(), ServerDefinition.ASYNC_CONNECTION_EXECUTION_ENABLED.getDefaultValue().asBoolean(), ActiveMQDefaultConfiguration.isDefaultAsyncConnectionExecutionEnabled());
Assert.assertEquals(ServerDefinition.CLUSTER_PASSWORD.getName(), ServerDefinition.CLUSTER_PASSWORD.getDefaultValue().asString(), ActiveMQDefaultConfiguration.getDefaultClusterPassword());
Assert.assertEquals(ServerDefinition.CLUSTER_USER.getName(), ServerDefinition.CLUSTER_USER.getDefaultValue().asString(), ActiveMQDefaultConfiguration.getDefaultClusterUser());
Assert.assertEquals(ServerDefinition.CONNECTION_TTL_OVERRIDE.getName(), ServerDefinition.CONNECTION_TTL_OVERRIDE.getDefaultValue().asLong(), ActiveMQDefaultConfiguration.getDefaultConnectionTtlOverride());
Assert.assertEquals(ServerDefinition.CREATE_BINDINGS_DIR.getName(), ServerDefinition.CREATE_BINDINGS_DIR.getDefaultValue().asBoolean(), ActiveMQDefaultConfiguration.isDefaultCreateBindingsDir());
Assert.assertEquals(ServerDefinition.CREATE_JOURNAL_DIR.getName(), ServerDefinition.CREATE_JOURNAL_DIR.getDefaultValue().asBoolean(), ActiveMQDefaultConfiguration.isDefaultCreateJournalDir());
Assert.assertEquals(ServerDefinition.DISK_SCAN_PERIOD.getName(), ServerDefinition.DISK_SCAN_PERIOD.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultDiskScanPeriod());
Assert.assertEquals(ServerDefinition.ID_CACHE_SIZE.getName(), ServerDefinition.ID_CACHE_SIZE.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultIdCacheSize());
Assert.assertEquals(ServerDefinition.JMX_DOMAIN.getName(), ServerDefinition.JMX_DOMAIN.getDefaultValue().asString(), ActiveMQDefaultConfiguration.getDefaultJmxDomain());
Assert.assertEquals(ServerDefinition.JOURNAL_BINDINGS_TABLE.getName(), ServerDefinition.JOURNAL_BINDINGS_TABLE.getDefaultValue().asString(), ActiveMQDefaultConfiguration.getDefaultBindingsTableName());
Assert.assertEquals(ServerDefinition.JOURNAL_COMPACT_MIN_FILES.getName(), ServerDefinition.JOURNAL_COMPACT_MIN_FILES.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultJournalCompactMinFiles());
Assert.assertEquals(ServerDefinition.JOURNAL_COMPACT_PERCENTAGE.getName(), ServerDefinition.JOURNAL_COMPACT_PERCENTAGE.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultJournalCompactPercentage());
Assert.assertEquals(ServerDefinition.JOURNAL_FILE_OPEN_TIMEOUT.getName(), ServerDefinition.JOURNAL_FILE_OPEN_TIMEOUT.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultJournalFileOpenTimeout());
Assert.assertEquals(ServerDefinition.JOURNAL_FILE_SIZE.getName(), ServerDefinition.JOURNAL_FILE_SIZE.getDefaultValue().asLong(), ActiveMQDefaultConfiguration.getDefaultJournalFileSize());
Assert.assertEquals(ServerDefinition.JOURNAL_JDBC_LOCK_EXPIRATION.getName(), ServerDefinition.JOURNAL_JDBC_LOCK_EXPIRATION.getDefaultValue().asInt() * 1000, ActiveMQDefaultConfiguration.getDefaultJdbcLockExpirationMillis());
Assert.assertEquals(ServerDefinition.JOURNAL_JDBC_LOCK_RENEW_PERIOD.getName(), ServerDefinition.JOURNAL_JDBC_LOCK_RENEW_PERIOD.getDefaultValue().asInt() * 1000, ActiveMQDefaultConfiguration.getDefaultJdbcLockRenewPeriodMillis());
Assert.assertEquals(ServerDefinition.JOURNAL_JDBC_NETWORK_TIMEOUT.getName(), ServerDefinition.JOURNAL_JDBC_NETWORK_TIMEOUT.getDefaultValue().asInt() * 1000, ActiveMQDefaultConfiguration.getDefaultJdbcNetworkTimeout());
Assert.assertEquals(ServerDefinition.JOURNAL_LARGE_MESSAGES_TABLE.getName(), ServerDefinition.JOURNAL_LARGE_MESSAGES_TABLE.getDefaultValue().asString(), ActiveMQDefaultConfiguration.getDefaultLargeMessagesTableName());
Assert.assertEquals(ServerDefinition.JOURNAL_MESSAGES_TABLE.getName(), ServerDefinition.JOURNAL_MESSAGES_TABLE.getDefaultValue().asString(), ActiveMQDefaultConfiguration.getDefaultMessageTableName());
Assert.assertEquals(ServerDefinition.JOURNAL_MIN_FILES.getName(), ServerDefinition.JOURNAL_MIN_FILES.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultJournalMinFiles());
Assert.assertEquals(ServerDefinition.JOURNAL_NODE_MANAGER_STORE_TABLE.getName(), ServerDefinition.JOURNAL_NODE_MANAGER_STORE_TABLE.getDefaultValue().asString(), ActiveMQDefaultConfiguration.getDefaultNodeManagerStoreTableName());
Assert.assertEquals(ServerDefinition.JOURNAL_PAGE_STORE_TABLE.getName(), ServerDefinition.JOURNAL_PAGE_STORE_TABLE.getDefaultValue().asString(), ActiveMQDefaultConfiguration.getDefaultPageStoreTableName());
Assert.assertEquals(ServerDefinition.JOURNAL_SYNC_NON_TRANSACTIONAL.getName(), ServerDefinition.JOURNAL_SYNC_NON_TRANSACTIONAL.getDefaultValue().asBoolean(), ActiveMQDefaultConfiguration.isDefaultJournalSyncNonTransactional());
Assert.assertEquals(ServerDefinition.JOURNAL_SYNC_TRANSACTIONAL.getName(), ServerDefinition.JOURNAL_SYNC_TRANSACTIONAL.getDefaultValue().asBoolean(), ActiveMQDefaultConfiguration.isDefaultJournalSyncTransactional());
Assert.assertEquals(ServerDefinition.LOG_JOURNAL_WRITE_RATE.getName(), ServerDefinition.LOG_JOURNAL_WRITE_RATE.getDefaultValue().asBoolean(), ActiveMQDefaultConfiguration.isDefaultJournalLogWriteRate());
Assert.assertEquals(ServerDefinition.MANAGEMENT_ADDRESS.getName(), ServerDefinition.MANAGEMENT_ADDRESS.getDefaultValue().asString(), ActiveMQDefaultConfiguration.getDefaultManagementAddress().toString());
Assert.assertEquals(ServerDefinition.MANAGEMENT_NOTIFICATION_ADDRESS.getName(), ServerDefinition.MANAGEMENT_NOTIFICATION_ADDRESS.getDefaultValue().asString(), ActiveMQDefaultConfiguration.getDefaultManagementNotificationAddress().toString());
Assert.assertEquals(ServerDefinition.MEMORY_MEASURE_INTERVAL.getName(), ServerDefinition.MEMORY_MEASURE_INTERVAL.getDefaultValue().asLong(), ActiveMQDefaultConfiguration.getDefaultMemoryMeasureInterval());
Assert.assertEquals(ServerDefinition.MEMORY_WARNING_THRESHOLD.getName(), ServerDefinition.MEMORY_WARNING_THRESHOLD.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultMemoryWarningThreshold());
Assert.assertEquals(ServerDefinition.MESSAGE_COUNTER_MAX_DAY_HISTORY.getName(), ServerDefinition.MESSAGE_COUNTER_MAX_DAY_HISTORY.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultMessageCounterMaxDayHistory());
Assert.assertEquals(ServerDefinition.MESSAGE_COUNTER_SAMPLE_PERIOD.getName(), ServerDefinition.MESSAGE_COUNTER_SAMPLE_PERIOD.getDefaultValue().asLong(), ActiveMQDefaultConfiguration.getDefaultMessageCounterSamplePeriod());
Assert.assertEquals(ServerDefinition.MESSAGE_EXPIRY_SCAN_PERIOD.getName(), ServerDefinition.MESSAGE_EXPIRY_SCAN_PERIOD.getDefaultValue().asLong(), ActiveMQDefaultConfiguration.getDefaultMessageExpiryScanPeriod());
Assert.assertEquals(ServerDefinition.MESSAGE_EXPIRY_THREAD_PRIORITY.getName(), ServerDefinition.MESSAGE_EXPIRY_THREAD_PRIORITY.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultMessageExpiryThreadPriority());
Assert.assertEquals(ServerDefinition.PAGE_MAX_CONCURRENT_IO.getName(), ServerDefinition.PAGE_MAX_CONCURRENT_IO.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultMaxConcurrentPageIo());
Assert.assertEquals(ServerDefinition.PERSISTENCE_ENABLED.getName(), ServerDefinition.PERSISTENCE_ENABLED.getDefaultValue().asBoolean(), ActiveMQDefaultConfiguration.isDefaultPersistenceEnabled());
Assert.assertEquals(ServerDefinition.PERSIST_DELIVERY_COUNT_BEFORE_DELIVERY.getName(), ServerDefinition.PERSIST_DELIVERY_COUNT_BEFORE_DELIVERY.getDefaultValue().asBoolean(), ActiveMQDefaultConfiguration.isDefaultPersistDeliveryCountBeforeDelivery());
Assert.assertEquals(ServerDefinition.PERSIST_ID_CACHE.getName(), ServerDefinition.PERSIST_ID_CACHE.getDefaultValue().asBoolean(), ActiveMQDefaultConfiguration.isDefaultPersistIdCache());
Assert.assertEquals(ServerDefinition.SECURITY_ENABLED.getName(), ServerDefinition.SECURITY_ENABLED.getDefaultValue().asBoolean(), ActiveMQDefaultConfiguration.isDefaultSecurityEnabled());
Assert.assertEquals(ServerDefinition.SECURITY_INVALIDATION_INTERVAL.getName(), ServerDefinition.SECURITY_INVALIDATION_INTERVAL.getDefaultValue().asLong(), ActiveMQDefaultConfiguration.getDefaultSecurityInvalidationInterval());
Assert.assertEquals(ServerDefinition.SERVER_DUMP_INTERVAL.getName(), ServerDefinition.SERVER_DUMP_INTERVAL.getDefaultValue().asLong(), ActiveMQDefaultConfiguration.getDefaultServerDumpInterval());
Assert.assertEquals(ServerDefinition.THREAD_POOL_MAX_SIZE.getName(), ServerDefinition.THREAD_POOL_MAX_SIZE.getDefaultValue().asInt(), ActiveMQDefaultConfiguration.getDefaultThreadPoolMaxSize());
Assert.assertEquals(ServerDefinition.TRANSACTION_TIMEOUT.getName(), ServerDefinition.TRANSACTION_TIMEOUT.getDefaultValue().asLong(), ActiveMQDefaultConfiguration.getDefaultTransactionTimeout());
Assert.assertEquals(ServerDefinition.TRANSACTION_TIMEOUT_SCAN_PERIOD.getName(), ServerDefinition.TRANSACTION_TIMEOUT_SCAN_PERIOD.getDefaultValue().asLong(), ActiveMQDefaultConfiguration.getDefaultTransactionTimeoutScanPeriod());
Assert.assertEquals(ServerDefinition.WILD_CARD_ROUTING_ENABLED.getName(), ServerDefinition.WILD_CARD_ROUTING_ENABLED.getDefaultValue().asBoolean(), ActiveMQDefaultConfiguration.isDefaultWildcardRoutingEnabled());
}
}
| 30,882
| 161.542105
| 281
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/test/java/org/wildfly/extension/messaging/activemq/MessagingPathsTestCase.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.wildfly.extension.messaging.activemq;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.wildfly.extension.messaging.activemq.PathDefinition.DEFAULT_LARGE_MESSAGE_DIR;
import static org.wildfly.extension.messaging.activemq.PathDefinition.DEFAULT_PAGING_DIR;
import static org.wildfly.extension.messaging.activemq.PathDefinition.DEFAULT_RELATIVE_TO;
import java.util.concurrent.TimeUnit;
import org.jboss.as.controller.services.path.PathManagerService;
import org.jboss.as.server.ServerEnvironment;
import org.jboss.msc.service.ServiceContainer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* @author <a href="http://jmesnil.net">Jeff Mesnil</a> (c) 2012 Red Hat Inc.
*/
public class MessagingPathsTestCase {
private static final String MY_SERVER_DATA_DIR = System.getProperty("java.io.tmpdir") + "datadir";
private static final String MY_RELATIVE_JOURNAL_DIR = "my-relative-journal";
private static final String MY_ABSOLUTE_BINDINGS_DIR = System.getProperty("java.io.tmpdir") + "bindingsdir";
private static final String MY_PAGING_RELATIVE_TO = "paging.relative-to.dir";
private static final String MY_PAGING_RELATIVE_TO_DIR = System.getProperty("java.io.tmpdir") + "pagingdir";
private ServiceContainer container;
@Before
public void setupContainer() {
container = ServiceContainer.Factory.create("test");
}
@After
public void shutdownContainer() {
if (container != null) {
container.shutdown();
try {
container.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
finally {
container = null;
}
}
}
@Test
public void testAddPath() throws Exception {
PathManagerService pathManagerService = new PathManagerService() {
{
// define the standard server data dir that is the default relative-to for messaging paths
super.addHardcodedAbsolutePath(container, ServerEnvironment.SERVER_DATA_DIR, MY_SERVER_DATA_DIR);
// define another related-to specific for paging directory
super.addHardcodedAbsolutePath(container, MY_PAGING_RELATIVE_TO, MY_PAGING_RELATIVE_TO_DIR);
}
};
ActiveMQServerService.PathConfig pathConfig = new ActiveMQServerService.PathConfig(
MY_ABSOLUTE_BINDINGS_DIR, DEFAULT_RELATIVE_TO, // => binding dir is absolute
MY_RELATIVE_JOURNAL_DIR, DEFAULT_RELATIVE_TO, // => specific journal dir is relative to default relative-to
DEFAULT_LARGE_MESSAGE_DIR, DEFAULT_RELATIVE_TO, // => default largeMessage is relative to default relative-to
DEFAULT_PAGING_DIR, MY_PAGING_RELATIVE_TO); // => paging is relative to specific relative-to
String resolvedJournalPath = pathConfig.resolveJournalPath(pathManagerService);
assertTrue("the specific relative path must be prepended by the resolved default relative-to, resolvedJournalPath=" + resolvedJournalPath + ", MY_SERVER_DATA_DIR" + MY_SERVER_DATA_DIR,
resolvedJournalPath.startsWith(MY_SERVER_DATA_DIR));
assertTrue(resolvedJournalPath.endsWith(MY_RELATIVE_JOURNAL_DIR));
String resolvedBindingsPath = pathConfig.resolveBindingsPath(pathManagerService);
assertEquals("the speficic absolute path must not be prepended by the resolved default relative-to, resolvedBindingsPath=" + resolvedBindingsPath,
MY_ABSOLUTE_BINDINGS_DIR, resolvedBindingsPath);
String resolvedPagingPath = pathConfig.resolvePagingPath(pathManagerService);
assertTrue("the default path must be prepended by the resolved specific relative-to, resolvedPagingPath=" + resolvedPagingPath,
resolvedPagingPath.startsWith(MY_PAGING_RELATIVE_TO_DIR));
assertTrue(resolvedPagingPath.endsWith(DEFAULT_PAGING_DIR));
String resolvedLargeMessagePath = pathConfig.resolveLargeMessagePath(pathManagerService);
assertTrue("by default, the default path MUST prepended by the resolved default relative-to, resolvedLargeMessagePath=" + resolvedLargeMessagePath,
resolvedLargeMessagePath.startsWith(MY_SERVER_DATA_DIR));
assertTrue(resolvedLargeMessagePath.endsWith(DEFAULT_LARGE_MESSAGE_DIR));
}
}
| 5,533
| 48.410714
| 192
|
java
|
null |
wildfly-main/messaging-activemq/subsystem/src/test/java/org/wildfly/extension/messaging/activemq/SubsystemDescriptionsUnitTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.messaging.activemq;
import java.util.Collections;
import java.util.List;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.subsystem.test.AbstractSubsystemTest;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests that the read-resource-description operation works.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class SubsystemDescriptionsUnitTestCase extends AbstractSubsystemTest {
public SubsystemDescriptionsUnitTestCase() {
super(MessagingExtension.SUBSYSTEM_NAME, new MessagingExtension());
}
@Test
public void testSubsystemDescriptions() throws Exception {
List<ModelNode> empty = Collections.emptyList();
KernelServices servicesA = createKernelServicesBuilder(null).setBootOperations(empty).build();
final ModelNode operation = createReadResourceDescriptionOperation();
final ModelNode result = servicesA.executeOperation(operation);
Assert.assertEquals(ModelDescriptionConstants.SUCCESS, result.get(ModelDescriptionConstants.OUTCOME).asString());
servicesA.shutdown();
}
static ModelNode createReadResourceDescriptionOperation() {
final ModelNode address = new ModelNode();
address.add("subsystem", "messaging-activemq");
final ModelNode operation = new ModelNode();
operation.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_RESOURCE_DESCRIPTION_OPERATION);
operation.get(ModelDescriptionConstants.OP_ADDR).set(address);
operation.get(ModelDescriptionConstants.RECURSIVE).set(true);
operation.get(ModelDescriptionConstants.OPERATIONS).set(true);
operation.get(ModelDescriptionConstants.INHERITED).set(false);
return operation;
}
}
| 2,933
| 38.648649
| 121
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.