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/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/JobOperatorService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.deployment; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import java.util.function.Supplier; import jakarta.batch.operations.JobExecutionAlreadyCompleteException; import jakarta.batch.operations.JobExecutionIsRunningException; import jakarta.batch.operations.JobExecutionNotMostRecentException; import jakarta.batch.operations.JobExecutionNotRunningException; import jakarta.batch.operations.JobOperator; import jakarta.batch.operations.JobRestartException; import jakarta.batch.operations.JobSecurityException; import jakarta.batch.operations.JobStartException; import jakarta.batch.operations.NoSuchJobException; import jakarta.batch.operations.NoSuchJobExecutionException; import jakarta.batch.operations.NoSuchJobInstanceException; import jakarta.batch.runtime.JobExecution; import jakarta.batch.runtime.JobInstance; import jakarta.batch.runtime.StepExecution; import org.jberet.operations.AbstractJobOperator; import org.jberet.runtime.JobExecutionImpl; import org.jberet.spi.BatchEnvironment; import org.jboss.as.controller.ControlledProcessState; import org.jboss.as.controller.ProcessStateNotifier; import org.jboss.as.server.suspend.ServerActivity; import org.jboss.as.server.suspend.ServerActivityCallback; import org.jboss.as.server.suspend.SuspendController; 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.batch.jberet.BatchConfiguration; import org.wildfly.extension.batch.jberet._private.BatchLogger; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.auth.server.SecurityIdentity; import org.wildfly.security.manager.WildFlySecurityManager; /** * A delegating {@linkplain jakarta.batch.operations.JobOperator job operator} to interact with the batch environment on * deployments. * <p> * Note that for each method the job name, or derived job name, must exist for the deployment. The allowed job names and * job XML descriptor are determined at deployment time. * </p> * <p> * This implementation does change some of the API's contracts however it's only intended to be used by management * resources and operations. Limits the interaction with the jobs to the scope of the deployments jobs. Any behavioral * change will be documented. * </p> * * @author <a href="mailto:[email protected]">James R. Perkins</a> * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class JobOperatorService extends AbstractJobOperator implements WildFlyJobOperator, JobOperator, Service<JobOperator> { private static final Properties RESTART_PROPS = new Properties(); private final Consumer<JobOperator> jobOperatorConsumer; private final Supplier<BatchConfiguration> batchConfigurationSupplier; private final Supplier<SecurityAwareBatchEnvironment> batchEnvironmentSupplier; private final Supplier<ExecutorService> executorSupplier; private final Supplier<SuspendController> suspendControllerSupplier; private final Supplier<ProcessStateNotifier> processStateSupplier; private volatile SecurityAwareBatchEnvironment batchEnvironment; private volatile ClassLoader classLoader; private final Boolean restartJobsOnResume; private final WildFlyJobXmlResolver resolver; private final BatchJobServerActivity serverActivity; private final String deploymentName; private final ThreadLocal<Boolean> permissionsCheckEnabled = ThreadLocal.withInitial(() -> Boolean.TRUE); public JobOperatorService(final Consumer<JobOperator> jobOperatorConsumer, final Supplier<BatchConfiguration> batchConfigurationSupplier, final Supplier<SecurityAwareBatchEnvironment> batchEnvironmentSupplier, final Supplier<ExecutorService> executorSupplier, final Supplier<SuspendController> suspendControllerSupplier, final Supplier<ProcessStateNotifier> processStateSupplier, final Boolean restartJobsOnResume, final String deploymentName, final WildFlyJobXmlResolver resolver) { this.jobOperatorConsumer = jobOperatorConsumer; this.batchConfigurationSupplier = batchConfigurationSupplier; this.batchEnvironmentSupplier = batchEnvironmentSupplier; this.executorSupplier = executorSupplier; this.suspendControllerSupplier = suspendControllerSupplier; this.processStateSupplier = processStateSupplier; this.restartJobsOnResume = restartJobsOnResume; this.deploymentName = deploymentName; this.resolver = resolver; this.serverActivity = new BatchJobServerActivity(); } @Override public void start(final StartContext context) throws StartException { final BatchEnvironment batchEnvironment = this.batchEnvironment = batchEnvironmentSupplier.get(); // Get the class loader from the environment classLoader = batchEnvironment.getClassLoader(); serverActivity.initialize(processStateSupplier.get().getCurrentState(), suspendControllerSupplier.get().getState()); processStateSupplier.get().addPropertyChangeListener(serverActivity); suspendControllerSupplier.get().registerActivity(serverActivity); jobOperatorConsumer.accept(this); } @Override public void stop(final StopContext context) { jobOperatorConsumer.accept(null); // Remove the server activity suspendControllerSupplier.get().unRegisterActivity(serverActivity); processStateSupplier.get().removePropertyChangeListener(serverActivity); final ExecutorService service = executorSupplier.get(); final Runnable task = () -> { // Should already be stopped, but just to be safe we'll make one more attempt serverActivity.stopRunningJobs(false); batchEnvironment = null; classLoader = null; context.complete(); }; try { service.execute(task); } catch (RejectedExecutionException e) { task.run(); } finally { context.asynchronous(); } } @Override public JobOperator getValue() throws IllegalStateException, IllegalArgumentException { return this; } @Override public SecurityAwareBatchEnvironment getBatchEnvironment() { if (batchEnvironment == null) { throw BatchLogger.LOGGER.jobOperatorServiceStopped(); } return batchEnvironment; } @Override public Set<String> getJobNames() throws JobSecurityException { checkState(); // job repository does not know a job if it has not been started. // So we rely on the resolver to provide complete job names for the deployment. return resolver.getJobNames(); } @Override public int getJobInstanceCount(final String jobName) throws NoSuchJobException, JobSecurityException { checkState(jobName); final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); try { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader); return super.getJobInstanceCount(jobName); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current); } } @Override public List<JobInstance> getJobInstances(final String jobName, final int start, final int count) throws NoSuchJobException, JobSecurityException { checkState(jobName); final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); try { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader); return super.getJobInstances(jobName, start, count); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current); } } @Override public List<Long> getRunningExecutions(final String jobName) throws NoSuchJobException, JobSecurityException { checkState(jobName); final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); try { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader); return super.getRunningExecutions(jobName); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current); } } @Override public List<Long> getJobExecutionsByJob(final String jobName) { checkState(jobName); final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); try { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader); return super.getJobExecutionsByJob(jobName); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current); } } @Override public Properties getParameters(final long executionId) throws NoSuchJobExecutionException, JobSecurityException { checkState(); final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); try { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader); final JobInstance instance = super.getJobInstance(executionId); validateJob(instance.getJobName()); return super.getParameters(executionId); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current); } } @Override public long start(final String jobXMLName, final Properties jobParameters) throws JobStartException, JobSecurityException { checkState(null, "start"); final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); try { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader); final String jobXml; if (jobXMLName.endsWith(".xml")) { jobXml = jobXMLName; } else { jobXml = jobXMLName + ".xml"; } if (resolver.isValidJobXmlName(jobXml)) { return super.start(jobXml, jobParameters, getBatchEnvironment().getCurrentUserName()); } throw BatchLogger.LOGGER.couldNotFindJobXml(jobXMLName); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current); } } @Override public long restart(final long executionId, final Properties restartParameters) throws JobExecutionAlreadyCompleteException, NoSuchJobExecutionException, JobExecutionNotMostRecentException, JobRestartException, JobSecurityException { checkState(null, "restart"); final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); try { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader); final JobInstance instance = super.getJobInstance(executionId); validateJob(instance.getJobName()); return super.restart(executionId, restartParameters, getBatchEnvironment().getCurrentUserName()); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current); } } @Override public void stop(final long executionId) throws NoSuchJobExecutionException, JobExecutionNotRunningException, JobSecurityException { checkState(null, "stop"); final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); try { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader); final JobInstance instance = super.getJobInstance(executionId); validateJob(instance.getJobName()); super.stop(executionId); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current); } } @Override public void abandon(final long executionId) throws NoSuchJobExecutionException, JobExecutionIsRunningException, JobSecurityException { checkState(null, "abandon"); final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); try { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader); final JobInstance instance = super.getJobInstance(executionId); validateJob(instance.getJobName()); super.abandon(executionId); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current); } } @Override public JobInstance getJobInstance(final long executionId) throws NoSuchJobExecutionException, JobSecurityException { checkState(); final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); try { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader); final JobInstance instance = super.getJobInstance(executionId); validateJob(instance.getJobName()); return super.getJobInstance(executionId); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current); } } @Override public List<JobExecution> getJobExecutions(final JobInstance instance) throws NoSuchJobInstanceException, JobSecurityException { checkState(); final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); try { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader); validateJob(instance == null ? null : instance.getJobName()); return super.getJobExecutions(instance); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current); } } @Override public JobExecution getJobExecution(final long executionId) throws NoSuchJobExecutionException, JobSecurityException { checkState(); final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); try { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader); final JobInstance instance = getJobInstance(executionId); validateJob(instance.getJobName()); return super.getJobExecution(executionId); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current); } } @Override public List<StepExecution> getStepExecutions(final long jobExecutionId) throws NoSuchJobExecutionException, JobSecurityException { checkState(); final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); try { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader); final JobInstance instance = super.getJobInstance(jobExecutionId); validateJob(instance.getJobName()); return super.getStepExecutions(jobExecutionId); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current); } } @Override public Collection<String> getJobXmlNames() { return resolver.getJobXmlNames(classLoader); } @Override public Collection<String> getJobXmlNames(final String jobName) { return resolver.getJobXmlNames(jobName); } @Override public Set<String> getAllJobNames() { return resolver.getJobNames(); } private void checkState() { checkState(null); } private void checkState(final String jobName) { checkState(jobName, "read"); } private void checkState(final String jobName, final String targetName) { if (batchEnvironment == null || classLoader == null) { throw BatchLogger.LOGGER.jobOperatorServiceStopped(); } checkPermission(targetName); if (jobName != null) { validateJob(jobName); } } private void checkPermission(final String targetName) { if (permissionsCheckEnabled.get()) { final SecurityAwareBatchEnvironment environment = getBatchEnvironment(); final SecurityIdentity identity = environment.getIdentity(); if (identity != null) { final BatchPermission permission = BatchPermission.forName(targetName); if (!identity.implies(permission)) { throw BatchLogger.LOGGER.unauthorized(identity.getPrincipal().getName(), permission); } } } } private synchronized void validateJob(final String name) { // In JBeret 1.2.x null means all jobs, in JBeret 1.3.x+ * means all jobs if the name is null or * then ignore // the check if (name == null || "*".equals(name)) return; // Check that this is a valid job name if (!resolver.isValidJobName(name)) { throw BatchLogger.LOGGER.noSuchJobException(name); } } private class BatchJobServerActivity implements ServerActivity, PropertyChangeListener { private final AtomicBoolean jobsStopped = new AtomicBoolean(false); private final AtomicBoolean jobsRestarted = new AtomicBoolean(false); private final Collection<Long> stoppedIds = Collections.synchronizedCollection(new ArrayList<>()); private boolean suspended; private boolean running; private synchronized void initialize(ControlledProcessState.State processState, SuspendController.State suspendState) { running = processState.isRunning(); suspended = suspendState != SuspendController.State.RUNNING; } @Override public void preSuspend(final ServerActivityCallback serverActivityCallback) { serverActivityCallback.done(); } @Override public void suspended(final ServerActivityCallback serverActivityCallback) { synchronized (this) { suspended = true; } try { stopRunningJobs(isRestartOnResume()); } finally { serverActivityCallback.done(); } } @Override public void resume() { boolean doResume; synchronized (this) { suspended = false; doResume = running; } if (doResume) { restartStoppedJobs(); } } @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) { restartStoppedJobs(); } } private void stopRunningJobs(final boolean queueForRestart) { if (jobsStopped.compareAndSet(false, true)) { final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); permissionsCheckEnabled.set(Boolean.FALSE); try { // Use the deployment's class loader to stop jobs WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader); // getJobNames() returns both active and inactive job names, so use // jobRepository.getJobNames() to get all active job names, which will // be filtered in the loop below for valid job names for the current deployment. final Collection<String> jobNames = getJobRepository().getJobNames(); // Look for running jobs and attempt to stop each one for (String jobName : jobNames) { if (resolver.isValidJobName(jobName)) { // Casting to (Supplier<List<Long>>) is done here on purpose as a workaround for a bug in 1.8.0_45 final List<Long> runningJobs = allowMissingJob((Supplier<List<Long>>) () -> getRunningExecutions(jobName), Collections.emptyList()); for (Long id : runningJobs) { try { BatchLogger.LOGGER.stoppingJob(id, jobName, deploymentName); // We want to skip the permissions check, we need to stop jobs regardless of the // permissions stop(id); // Queue for a restart on resume if required if (queueForRestart) { stoppedIds.add(id); } } catch (Exception e) { BatchLogger.LOGGER.stoppingJobFailed(e, id, jobName, deploymentName); } } } } } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current); // Reset the stopped state jobsStopped.set(false); permissionsCheckEnabled.set(Boolean.TRUE); } } } private void restartStoppedJobs() { if (isRestartOnResume() && jobsRestarted.compareAndSet(false, true)) { final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); try { // Use the deployment's class loader to stop jobs WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader); final Collection<Long> ids = new ArrayList<>(); synchronized (stoppedIds) { ids.addAll(stoppedIds); stoppedIds.clear(); } for (Long id : ids) { String jobName = null; String user = null; try { final JobExecutionImpl execution = getJobExecutionImpl(id); jobName = execution.getJobName(); user = execution.getUser(); } catch (Exception ignore) { } try { final long newId; // If the user is not null we need to restart the job with the user specified if (user == null) { newId = restart(id, RESTART_PROPS); } else { newId = privilegedRunAs(user, () -> restart(id, RESTART_PROPS)); } BatchLogger.LOGGER.restartingJob(jobName, id, newId); } catch (Exception e) { BatchLogger.LOGGER.failedRestartingJob(e, id, jobName, deploymentName); } } } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current); // Reset the restart state jobsRestarted.set(false); } } } private <V> V privilegedRunAs(final String user, final Callable<V> callable) throws Exception { final SecurityDomain securityDomain = getBatchEnvironment().getSecurityDomain(); if (securityDomain == null) { return callable.call(); } final SecurityIdentity securityIdentity; if (user != null) { if (WildFlySecurityManager.isChecking()) { securityIdentity = AccessController.doPrivileged((PrivilegedAction<SecurityIdentity>) () -> securityDomain.getAnonymousSecurityIdentity().createRunAsIdentity(user, false)); } else { securityIdentity = securityDomain.getAnonymousSecurityIdentity().createRunAsIdentity(user, false); } } else { securityIdentity = securityDomain.getCurrentSecurityIdentity(); } return securityIdentity.runAs(callable); } private boolean isRestartOnResume() { if (restartJobsOnResume == null) { return batchConfigurationSupplier.get().isRestartOnResume(); } return restartJobsOnResume; } } }
26,765
44.832192
237
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/NamespaceContextHandle.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.deployment; import org.jboss.as.naming.context.NamespaceContextSelector; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ class NamespaceContextHandle implements ContextHandle { private final NamespaceContextSelector namespaceContextSelector; NamespaceContextHandle(NamespaceContextSelector namespaceContextSelector) { this.namespaceContextSelector = namespaceContextSelector; } @Override public Handle setup() { NamespaceContextSelector.pushCurrentSelector(namespaceContextSelector); return new Handle() { @Override public void tearDown() { NamespaceContextSelector.popCurrentSelector(); } }; } }
1,806
35.877551
79
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/BatchAttachments.java
/* * Copyright 2016 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.batch.jberet.deployment; import org.jboss.as.server.deployment.AttachmentKey; /** * Attachment keys for the JBeret batch subsystem. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public interface BatchAttachments { /** * The attachment key for the {@link BatchEnvironmentMetaData} used for deployment descriptors. */ AttachmentKey<BatchEnvironmentMetaData> BATCH_ENVIRONMENT_META_DATA = AttachmentKey.create(BatchEnvironmentMetaData.class); /** * The attachment for the job operator. */ AttachmentKey<WildFlyJobOperator> JOB_OPERATOR = AttachmentKey.create(WildFlyJobOperator.class); /** * The attachment key for the {@linkplain WildFlyJobXmlResolver job XML resolver}. Installed during the batch * environment processing. * * @see BatchEnvironmentProcessor */ AttachmentKey<WildFlyJobXmlResolver> JOB_XML_RESOLVER = AttachmentKey.create(WildFlyJobXmlResolver.class); }
1,599
34.555556
127
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/JobOperationStepHandler.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.deployment; import java.util.Properties; import jakarta.batch.operations.JobOperator; 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.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.wildfly.extension.batch.jberet.BatchServiceNames; import org.wildfly.extension.batch.jberet._private.BatchLogger; /** * A handler to assist with batch operations that require a {@linkplain JobOperator}. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ abstract class JobOperationStepHandler implements OperationStepHandler { private final boolean modify; /** * Creates a new step handler with a modifiable {@link JobOperator}. */ JobOperationStepHandler() { this(true); } /** * Creates a new step handler. * * @param modify {@code true} if the {@link #execute(OperationContext, ModelNode, WildFlyJobOperator)} will modify a job * repository, {@code false} for a read-only service */ JobOperationStepHandler(final boolean modify) { this.modify = modify; } @Override public final void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { context.addStep(this::executeRuntime, OperationContext.Stage.RUNTIME); } private void executeRuntime(final OperationContext context, final ModelNode operation) throws OperationFailedException { final ServiceController<?> controller = context.getServiceRegistry(modify).getService(getServiceName(context)); final WildFlyJobOperator jobOperator = (WildFlyJobOperator) controller.getService(); execute(context, operation, jobOperator); } /** * Executes the step. Includes the {@linkplain JobOperator} for convenience. * * @param context the operation context used * @param operation the operation for the step * @param jobOperator the job operator * * @throws OperationFailedException if there is a step failure */ protected abstract void execute(OperationContext context, ModelNode operation, WildFlyJobOperator jobOperator) throws OperationFailedException; static ModelNode resolveValue(final OperationContext context, final ModelNode operation, final AttributeDefinition attribute) throws OperationFailedException { final ModelNode value = new ModelNode(); if (operation.has(attribute.getName())) { value.set(operation.get(attribute.getName())); } return attribute.resolveValue(context, value); } static Properties resolvePropertyValue(final OperationContext context, final ModelNode operation, final AttributeDefinition attribute) throws OperationFailedException { // Get the properties final Properties properties = new Properties(); if (operation.hasDefined(attribute.getName())) { for (Property p : resolveValue(context, operation, attribute).asPropertyList()) { properties.put(p.getName(), p.getValue().asString()); } } return properties; } static OperationFailedException createOperationFailure(final Throwable cause) { final String msg = cause.getLocalizedMessage(); // OperationFailedException's don't log the cause, for debug purposes logging the failure could be useful BatchLogger.LOGGER.debugf(cause, "Failed to process batch operation: %s", msg); return new OperationFailedException(msg, cause); } private static ServiceName getServiceName(final OperationContext context) { final PathAddress address = context.getCurrentAddress(); String deploymentName = null; String subdeploymentName = null; for (PathElement element : address) { if (ModelDescriptionConstants.DEPLOYMENT.equals(element.getKey())) { deploymentName = getRuntimeName(context, element); } else if (ModelDescriptionConstants.SUBDEPLOYMENT.endsWith(element.getKey())) { subdeploymentName = element.getValue(); } } if (deploymentName == null) { throw BatchLogger.LOGGER.couldNotFindDeploymentName(address.toString()); } if (subdeploymentName == null) { return BatchServiceNames.jobOperatorServiceName(deploymentName); } return BatchServiceNames.jobOperatorServiceName(deploymentName, subdeploymentName); } private static String getRuntimeName(final OperationContext context, final PathElement element) { final ModelNode deploymentModel = context.readResourceFromRoot(PathAddress.pathAddress(element), false).getModel(); if (!deploymentModel.hasDefined(ModelDescriptionConstants.RUNTIME_NAME)) { throw BatchLogger.LOGGER.couldNotFindDeploymentName(context.getCurrentAddress().toString()); } return deploymentModel.get(ModelDescriptionConstants.RUNTIME_NAME).asString(); } }
6,472
43.951389
172
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/BatchDeploymentDescriptorParser_1_0.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.deployment; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import org.jberet.repository.InMemoryRepository; import org.jberet.repository.JobRepository; import org.jboss.as.controller.parsing.ParseUtils; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.jbossallxml.JBossAllXMLParser; import org.jboss.staxmapper.XMLExtendedStreamReader; import org.wildfly.extension.batch.jberet.Attribute; import org.wildfly.extension.batch.jberet.Element; import org.wildfly.extension.batch.jberet._private.BatchLogger; /** * A parser for batch deployment descriptors in {@code jboss-all.xml}. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public class BatchDeploymentDescriptorParser_1_0 implements XMLStreamConstants, JBossAllXMLParser<BatchEnvironmentMetaData> { public static final String NAMESPACE = "urn:jboss:batch-jberet:1.0"; public static final QName ROOT_ELEMENT = new QName(NAMESPACE, "batch"); @Override public BatchEnvironmentMetaData parse(final XMLExtendedStreamReader reader, final DeploymentUnit deploymentUnit) throws XMLStreamException { JobRepository jobRepository = null; String jobRepositoryName = null; String dataSourceName = null; String jobExecutorName = null; Boolean restartJobsOnResume = null; Integer executionRecordsLimit = null; boolean empty = true; while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { final String localName = reader.getLocalName(); final Element element = Element.forName(localName); // Process the job repository if (element == Element.JOB_REPOSITORY) { executionRecordsLimit = parseExecutionRecordsLimit(reader); // Only one repository can be defined if (jobRepository != null || jobRepositoryName != null) { BatchLogger.LOGGER.multipleJobRepositoriesFound(); } else { if (reader.hasNext() && reader.nextTag() != END_ELEMENT) { final String name = reader.getLocalName(); final Element jobRepositoryElement = Element.forName(name); if (jobRepositoryElement == Element.IN_MEMORY) { ParseUtils.requireNoContent(reader); jobRepository = new InMemoryRepository(); } else if (jobRepositoryElement == Element.NAMED) { jobRepositoryName = readRequiredAttribute(reader, Attribute.NAME); ParseUtils.requireNoContent(reader); } else if (jobRepositoryElement == Element.JDBC) { dataSourceName = parseJdbcJobRepository(reader); } else { throw ParseUtils.unexpectedElement(reader); } } // Log an error indicating the job-repository is empty, but continue as normal if (jobRepository == null && jobRepositoryName == null && dataSourceName == null) { BatchLogger.LOGGER.emptyJobRepositoryElement(deploymentUnit.getName()); } } ParseUtils.requireNoContent(reader); } else if (element == Element.THREAD_POOL) { // Only thread-pool's defined on the subsystem are allowed to be referenced jobExecutorName = readRequiredAttribute(reader, Attribute.NAME); ParseUtils.requireNoContent(reader); } else if (element == Element.RESTART_JOBS_ON_RESUME) { restartJobsOnResume = Boolean.valueOf(readRequiredAttribute(reader, Attribute.VALUE)); ParseUtils.requireNoContent(reader); } else { throw ParseUtils.unexpectedElement(reader); } empty = false; } if (empty) { // An empty tag was found. A null value will result in the subsystem default being used. BatchLogger.LOGGER.debugf("An empty batch element in the deployment descriptor was found for %s.", deploymentUnit.getName()); return null; } return new BatchEnvironmentMetaData(jobRepository, jobRepositoryName, dataSourceName, jobExecutorName, restartJobsOnResume, executionRecordsLimit); } String parseJdbcJobRepository(final XMLExtendedStreamReader reader) throws XMLStreamException { throw ParseUtils.unexpectedElement(reader); } Integer parseExecutionRecordsLimit(final XMLExtendedStreamReader reader) throws XMLStreamException { if (reader.getAttributeCount() > 0) { throw ParseUtils.unexpectedAttribute(reader, 0); } return null; } static String readRequiredAttribute(final XMLExtendedStreamReader reader, final Attribute attribute) throws XMLStreamException { final int attributeCount = reader.getAttributeCount(); for (int i = 0; i < attributeCount; i++) { final Attribute current = Attribute.forName(reader.getAttributeLocalName(i)); if (current == attribute) { return reader.getAttributeValue(i); } } throw ParseUtils.missingRequired(reader, attribute.getLocalName()); } }
6,584
47.419118
144
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/BatchCleanupProcessor.java
/* * Copyright 2016 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.batch.jberet.deployment; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; /** * Cleans up attachments no longer required on {@linkplain DeploymentUnit deployment units}. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public class BatchCleanupProcessor implements DeploymentUnitProcessor { @Override public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { // Clean up job XML resolvers phaseContext.getDeploymentUnit().removeAttachment(BatchAttachments.JOB_XML_RESOLVER); // Clean jboss-all meta-data phaseContext.getDeploymentUnit().removeAttachment(BatchAttachments.BATCH_ENVIRONMENT_META_DATA); // Remove the JobOperatorService from the deployment unit phaseContext.getDeploymentUnit().removeAttachment(BatchAttachments.JOB_OPERATOR); } }
1,711
41.8
108
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/ContextHandle.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.deployment; import java.util.ArrayDeque; import java.util.Deque; /** * Allows a handle to setup any thread local context needed. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ interface ContextHandle { /** * Sets up any thread local context. * * @return a handle to tear down the thread local context when the invocation has finished */ Handle setup(); /** * Handles tearing down the thread local context. */ interface Handle { /** * Tears down the thread local context. */ void tearDown(); } /** * A handle that processes {@link ContextHandle context handles} in the order in which they are added. The {@link * ContextHandle.Handle#tearDown()} is processed in the reverse order that the {@link * ContextHandle context handles} are processed. * <p/> * If a {@link ContextHandle context handle} throws an exception the {@link ContextHandle.Handle#tearDown() * tear downs} will be processed. * <p/> * If an exception is thrown during the {@link ContextHandle.Handle#tearDown() tear * down} the remaining tear downs will be processed and only the initial exception will be re-thrown. */ class ChainedContextHandle implements ContextHandle { private final ContextHandle[] contextHandles; public ChainedContextHandle(final ContextHandle... contextHandles) { this.contextHandles = contextHandles; } @Override public Handle setup() { final Deque<Handle> handles = new ArrayDeque<>(); try { for (ContextHandle contextHandle : contextHandles) { // reverse order handles.addFirst(contextHandle.setup()); } return new Handle() { @Override public void tearDown() { Exception rethrow = null; for (Handle handle : handles) { try { handle.tearDown(); } catch (Exception e) { if (rethrow == null) rethrow = e; } } if (rethrow != null) { throw new RuntimeException(rethrow); } } }; } catch (Exception e) { for (Handle handle : handles) { try { handle.tearDown(); } catch (Exception ignore) { } } throw e; } } } }
3,848
34.638889
117
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/JobOperationReadOnlyStepHandler.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.deployment; import jakarta.batch.operations.JobOperator; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.dmr.ModelNode; /** * A handler to assist with updating the dynamic batch job resources. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ abstract class JobOperationReadOnlyStepHandler extends JobOperationStepHandler { /** * Creates a step handler with a read-only {@link JobOperator}. */ protected JobOperationReadOnlyStepHandler() { super(false); } @Override protected void execute(final OperationContext context, final ModelNode operation, final WildFlyJobOperator jobOperator) throws OperationFailedException { updateModel(context, context.getResult(), jobOperator, context.getCurrentAddressValue()); } /** * Updates the model with information from the {@link jakarta.batch.operations.JobOperator JobOperator}. * * @param context the operation context used * @param model the model to update * @param jobOperator the job operator * @param jobName the name of the job * * @throws OperationFailedException if an update failure occurs */ protected abstract void updateModel(OperationContext context, ModelNode model, WildFlyJobOperator jobOperator, String jobName) throws OperationFailedException; }
2,498
39.306452
163
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/ConcurrentContextHandle.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.deployment; import org.jboss.as.ee.concurrent.ConcurrentContext; /** * A handle to propagate EE concurrency context to batch thread. */ class ConcurrentContextHandle implements ContextHandle { private final ConcurrentContext concurrentContext; ConcurrentContextHandle() { this.concurrentContext = ConcurrentContext.current(); } @Override public Handle setup() { ConcurrentContext.pushCurrent(concurrentContext); return new Handle() { @Override public void tearDown() { ConcurrentContext.popCurrent(); } }; } }
1,692
33.55102
70
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/ArtifactFactoryService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.deployment; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; import java.util.function.Supplier; import jakarta.enterprise.context.Dependent; import jakarta.enterprise.context.RequestScoped; import jakarta.enterprise.context.spi.CreationalContext; import jakarta.enterprise.inject.spi.Bean; import jakarta.enterprise.inject.spi.BeanManager; import org.jberet.creation.AbstractArtifactFactory; import org.jberet.spi.ArtifactFactory; import org.jboss.msc.Service; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.jboss.weld.bean.builtin.BeanManagerProxy; import org.jboss.weld.context.RequestContext; import org.jboss.weld.context.unbound.UnboundLiteral; import org.jboss.weld.manager.BeanManagerImpl; import org.wildfly.extension.batch.jberet._private.BatchLogger; /** * ArtifactFactory for Jakarta EE runtime environment. * * @author <a href="mailto:[email protected]">James R. Perkins</a> * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class ArtifactFactoryService extends AbstractArtifactFactory implements Service, WildFlyArtifactFactory { private final Consumer<ArtifactFactory> artifactFactoryConsumer; private final Supplier<BeanManager> beanManagerSupplier; private final Map<Object, Holder> contexts = Collections.synchronizedMap(new HashMap<>()); private volatile BeanManager beanManager; public ArtifactFactoryService(final Consumer<ArtifactFactory> artifactFactoryConsumer, final Supplier<BeanManager> beanManagerSupplier) { this.artifactFactoryConsumer = artifactFactoryConsumer; this.beanManagerSupplier = beanManagerSupplier; } @Override public void destroy(final Object instance) { final Holder holder = contexts.remove(instance); if (holder == null) { // This bean was not created via Jakarta Contexts and Dependency Injection, we need to invoke the JBeret cleanup super.destroy(instance); } else { // Only release the context for @Dependent beans, Weld should take care of the other scopes if (holder.isDependent()) { // We're not destroying the bean here because weld should handle that for use when we release the // CreationalContext holder.context.release(); } } } @Override public Class<?> getArtifactClass(final String ref, final ClassLoader classLoader) { final Bean<?> bean = getBean(ref, getBeanManager(), classLoader); return bean == null ? null : bean.getBeanClass(); } @Override public Object create(final String ref, Class<?> cls, final ClassLoader classLoader) throws Exception { final BeanManager beanManager = getBeanManager(); final Bean<?> bean = getBean(ref, beanManager, classLoader); if (bean == null) { return null; } final CreationalContext<?> context = beanManager.createCreationalContext(bean); final Object result = beanManager.getReference(bean, bean.getBeanClass(), context); contexts.put(result, new Holder(bean, context)); return result; } @Override public void start(final StartContext context) throws StartException { beanManager = beanManagerSupplier != null ? beanManagerSupplier.get() : null; artifactFactoryConsumer.accept(this); } @Override public void stop(final StopContext context) { artifactFactoryConsumer.accept(null); beanManager = null; synchronized (contexts) { for (Holder holder : contexts.values()) { // Only release the context for @Dependent beans, Weld should take care of the other scopes if (holder.isDependent()) { holder.context.release(); } } contexts.clear(); } } @Override public ContextHandle createContextHandle() { final BeanManagerImpl beanManager = getBeanManager(); return () -> { if (beanManager == null || beanManager.isContextActive(RequestScoped.class)) { return () -> { }; } final RequestContext requestContext = beanManager.instance().select(RequestContext.class, UnboundLiteral.INSTANCE).get(); requestContext.activate(); return () -> { requestContext.invalidate(); requestContext.deactivate(); }; }; } private BeanManagerImpl getBeanManager() { final BeanManager beanManager = this.beanManager; return beanManager == null ? null : BeanManagerProxy.unwrap(beanManager); } private static Bean<?> getBean(final String ref, final BeanManager beanManager, final ClassLoader classLoader) { final Bean<?> result = beanManager == null ? null : AbstractArtifactFactory.findBean(ref, beanManager, classLoader); BatchLogger.LOGGER.tracef("Found bean: %s for ref: %s", result, ref); return result; } private static class Holder { final Bean<?> bean; final CreationalContext<?> context; private Holder(final Bean<?> bean, final CreationalContext<?> context) { this.bean = bean; this.context = context; } boolean isDependent() { return Dependent.class.equals(bean.getScope()); } } }
6,673
39.204819
133
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/deployment/BatchJobExecutionResource.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.deployment; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.registry.PlaceholderResource; import org.jboss.as.controller.registry.PlaceholderResource.PlaceholderResourceEntry; import org.jboss.as.controller.registry.Resource; import org.jboss.dmr.ModelNode; import org.wildfly.extension.batch.jberet._private.BatchLogger; /** * Represents a dynamic resource for batch {@link jakarta.batch.runtime.JobExecution job executions}. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public class BatchJobExecutionResource implements Resource { private final Resource delegate; private final WildFlyJobOperator jobOperator; private final String jobName; // Should be guarded by it's instance private final Set<String> children = new LinkedHashSet<>(); /** * Last time when job names were refreshed */ private volatile long lastRefreshedTime; /** * The minimum interval in milliseconds in which the job names are to be refreshed. * If the interval period has elapsed from the last refresh time, * any incoming refresh request will be performed; otherwise, it is ignored * and the current result is returned. */ private static final int refreshMinInterval = 3000; BatchJobExecutionResource(final WildFlyJobOperator jobOperator, final String jobName) { this(Factory.create(true), jobOperator, jobName); } private BatchJobExecutionResource(final Resource delegate, final WildFlyJobOperator jobOperator, final String jobName) { this.delegate = delegate; this.jobOperator = jobOperator; this.jobName = jobName; } @Override public ModelNode getModel() { return delegate.getModel(); } @Override public void writeModel(final ModelNode newModel) { delegate.writeModel(newModel); } @Override public boolean isModelDefined() { return delegate.isModelDefined(); } @Override public boolean hasChild(final PathElement element) { if (BatchJobExecutionResourceDefinition.EXECUTION.equals(element.getKey())) { return hasJobExecution(element.getValue()); } return delegate.hasChild(element); } @Override public Resource getChild(final PathElement element) { if (BatchJobExecutionResourceDefinition.EXECUTION.equals(element.getKey())) { if (hasJobExecution(element.getValue())) { return PlaceholderResource.INSTANCE; } return null; } return delegate.getChild(element); } @Override public Resource requireChild(final PathElement element) { if (BatchJobExecutionResourceDefinition.EXECUTION.equals(element.getKey())) { if (hasJobExecution(element.getValue())) { return PlaceholderResource.INSTANCE; } throw new NoSuchResourceException(element); } return delegate.requireChild(element); } @Override public boolean hasChildren(final String childType) { if (BatchJobExecutionResourceDefinition.EXECUTION.equals(childType)) { return !getChildrenNames(BatchJobExecutionResourceDefinition.EXECUTION).isEmpty(); } return delegate.hasChildren(childType); } @Override public Resource navigate(final PathAddress address) { if (address.size() > 0 && BatchJobExecutionResourceDefinition.EXECUTION.equals(address.getElement(0).getKey())) { if (address.size() > 1) { throw new NoSuchResourceException(address.getElement(1)); } return PlaceholderResource.INSTANCE; } return delegate.navigate(address); } @Override public Set<String> getChildTypes() { final Set<String> result = new LinkedHashSet<>(delegate.getChildTypes()); result.add(BatchJobExecutionResourceDefinition.EXECUTION); return result; } @Override public Set<String> getChildrenNames(final String childType) { if (BatchJobExecutionResourceDefinition.EXECUTION.equals(childType)) { synchronized (children) { refreshChildren(); return new LinkedHashSet<>(children); } } return delegate.getChildrenNames(childType); } @Override public Set<ResourceEntry> getChildren(final String childType) { if (BatchJobExecutionResourceDefinition.EXECUTION.equals(childType)) { final Set<String> names = getChildrenNames(childType); final Set<ResourceEntry> result = new LinkedHashSet<>(names.size()); for (String name : names) { result.add(new PlaceholderResourceEntry(BatchJobExecutionResourceDefinition.EXECUTION, name)); } return result; } return delegate.getChildren(childType); } @Override public void registerChild(final PathElement address, final Resource resource) { final String type = address.getKey(); if (BatchJobExecutionResourceDefinition.EXECUTION.equals(type)) { throw BatchLogger.LOGGER.cannotRemoveResourceOfType(type); } delegate.registerChild(address, resource); } @Override public void registerChild(PathElement address, int index, Resource resource) { throw BatchLogger.LOGGER.indexedChildResourceRegistrationNotAvailable(address); } @Override public Resource removeChild(final PathElement address) { final String type = address.getKey(); if (BatchJobExecutionResourceDefinition.EXECUTION.equals(type)) { throw BatchLogger.LOGGER.cannotRemoveResourceOfType(type); } return delegate.removeChild(address); } @Override public Set<String> getOrderedChildTypes() { return Collections.emptySet(); } @Override public boolean isRuntime() { return delegate.isRuntime(); } @Override public boolean isProxy() { return delegate.isProxy(); } @Override public Resource clone() { return new BatchJobExecutionResource(delegate.clone(), jobOperator, jobName); } private boolean hasJobExecution(final String executionName) { synchronized (children) { if (children.contains(executionName)) { return true; } // Load a cache of the names refreshChildren(); return children.contains(executionName); } } /** * Note the access to the {@link #children} is <strong>not</strong> guarded here and needs to be externally * guarded. */ private void refreshChildren() { if (System.currentTimeMillis() - lastRefreshedTime < refreshMinInterval) { return; } final List<Long> executionIds = jobOperator.getJobExecutionsByJob(jobName); final Set<String> asNames = executionIds.stream().map(Object::toString).collect(Collectors.toSet()); children.clear(); children.addAll(asNames); lastRefreshedTime = System.currentTimeMillis(); } }
8,444
34.1875
124
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/thread/pool/BatchThreadPoolResourceDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.thread.pool; import static org.wildfly.extension.batch.jberet.BatchResourceDescriptionResolver.BASE; import static org.wildfly.extension.batch.jberet.BatchResourceDescriptionResolver.RESOURCE_NAME; import java.util.Arrays; import java.util.HashSet; import java.util.Locale; import java.util.ResourceBundle; import java.util.Set; import java.util.function.Consumer; import java.util.function.Supplier; import org.jberet.spi.JobExecutor; 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.SimpleResourceDefinition; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.threads.CommonAttributes; import org.jboss.as.threads.ManagedJBossThreadPoolExecutorService; import org.jboss.as.threads.PoolAttributeDefinitions; import org.jboss.as.threads.ThreadFactoryResolver; import org.jboss.as.threads.ThreadsServices; import org.jboss.as.threads.UnboundedQueueThreadPoolAdd; import org.jboss.as.threads.UnboundedQueueThreadPoolMetricsHandler; import org.jboss.as.threads.UnboundedQueueThreadPoolRemove; import org.jboss.as.threads.UnboundedQueueThreadPoolWriteAttributeHandler; import org.jboss.dmr.ModelNode; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.wildfly.extension.batch.jberet.BatchServiceNames; import org.wildfly.extension.batch.jberet.BatchSubsystemExtension; import org.wildfly.extension.batch.jberet._private.Capabilities; /** * A resource definition for the batch thread pool. * * @author <a href="mailto:[email protected]">James R. Perkins</a> * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class BatchThreadPoolResourceDefinition extends SimpleResourceDefinition { public static final String NAME = "thread-pool"; static final PathElement PATH = PathElement.pathElement(NAME); private final boolean registerRuntimeOnly; public BatchThreadPoolResourceDefinition(final boolean registerRuntimeOnly) { super(new SimpleResourceDefinition.Parameters(PATH, BatchThreadPoolDescriptionResolver.INSTANCE) .setAddHandler(BatchThreadPoolAdd.INSTANCE) .setRemoveHandler(BatchThreadPoolRemove.INSTANCE) .addCapabilities(Capabilities.THREAD_POOL_CAPABILITY)); this.registerRuntimeOnly = registerRuntimeOnly; } @Override public void registerAttributes(final ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerReadOnlyAttribute(PoolAttributeDefinitions.NAME, ReadResourceNameOperationStepHandler.INSTANCE); new UnboundedQueueThreadPoolWriteAttributeHandler(BatchServiceNames.BASE_BATCH_THREAD_POOL_NAME).registerAttributes(resourceRegistration); if (registerRuntimeOnly) { new UnboundedQueueThreadPoolMetricsHandler(BatchServiceNames.BASE_BATCH_THREAD_POOL_NAME).registerAttributes(resourceRegistration); } } static class BatchThreadPoolAdd extends UnboundedQueueThreadPoolAdd { static final BatchThreadPoolAdd INSTANCE = new BatchThreadPoolAdd(BatchThreadFactoryResolver.INSTANCE, BatchServiceNames.BASE_BATCH_THREAD_POOL_NAME); private final ServiceName serviceNameBase; public BatchThreadPoolAdd(final ThreadFactoryResolver threadFactoryResolver, final ServiceName serviceNameBase) { super(threadFactoryResolver, serviceNameBase); this.serviceNameBase = serviceNameBase; } @Override protected void performRuntime(final OperationContext context, final ModelNode operation, final ModelNode model) throws OperationFailedException { super.performRuntime(context, operation, model); final String name = context.getCurrentAddressValue(); final ServiceTarget target = context.getServiceTarget(); final ServiceName serviceName = context.getCapabilityServiceName(Capabilities.THREAD_POOL_CAPABILITY.getName(), name, JobExecutor.class); final ServiceBuilder<?> serviceBuilder = target.addService(serviceName); final Consumer<JobExecutor> jobExecutorConsumer = serviceBuilder.provides(serviceName); final Supplier<ManagedJBossThreadPoolExecutorService> threadPoolSupplier = serviceBuilder.requires(serviceNameBase.append(name)); final JobExecutorService service = new JobExecutorService(jobExecutorConsumer, threadPoolSupplier); serviceBuilder.setInstance(service); serviceBuilder.install(); } } static class BatchThreadPoolRemove extends UnboundedQueueThreadPoolRemove { static final BatchThreadPoolRemove INSTANCE = new BatchThreadPoolRemove(); public BatchThreadPoolRemove() { super(BatchThreadPoolAdd.INSTANCE); } @Override protected void performRuntime(final OperationContext context, final ModelNode operation, final ModelNode model) throws OperationFailedException { // First remove the JobExecutor service, then delegate context.removeService(context.getCapabilityServiceName(Capabilities.THREAD_POOL_CAPABILITY.getName(), context.getCurrentAddressValue(), null)); super.performRuntime(context, operation, model); } } private static class BatchThreadFactoryResolver extends ThreadFactoryResolver.SimpleResolver { static final BatchThreadFactoryResolver INSTANCE = new BatchThreadFactoryResolver(); private BatchThreadFactoryResolver() { super(ThreadsServices.FACTORY); } @Override protected String getThreadGroupName(String threadPoolName) { return "Batch Thread"; } } private static class BatchThreadPoolDescriptionResolver extends StandardResourceDescriptionResolver { static final BatchThreadPoolDescriptionResolver INSTANCE = new BatchThreadPoolDescriptionResolver(); private static final Set<String> COMMON_ATTRIBUTE_NAMES; static { // Common attributes as copied from the ThreadPoolResourceDescriptionResolver minus the attributes not used // for an UnboundedThreadPoolResourceDefinition COMMON_ATTRIBUTE_NAMES = new HashSet<>(Arrays.asList( CommonAttributes.ACTIVE_COUNT, CommonAttributes.COMPLETED_TASK_COUNT, CommonAttributes.CURRENT_THREAD_COUNT, CommonAttributes.KEEPALIVE_TIME, CommonAttributes.LARGEST_THREAD_COUNT, CommonAttributes.MAX_THREADS, CommonAttributes.NAME, CommonAttributes.QUEUE_SIZE, CommonAttributes.TASK_COUNT, CommonAttributes.THREAD_FACTORY)); } private static final String COMMON_PREFIX = "threadpool.common"; private BatchThreadPoolDescriptionResolver() { super(BASE + '.' + NAME, RESOURCE_NAME, BatchSubsystemExtension.class.getClassLoader(), true, false); } @Override public String getResourceAttributeDescription(final String attributeName, final Locale locale, final ResourceBundle bundle) { if (COMMON_ATTRIBUTE_NAMES.contains(attributeName)) { return bundle.getString(getKey(attributeName)); } return super.getResourceAttributeDescription(attributeName, locale, bundle); } @Override public String getResourceAttributeValueTypeDescription(final String attributeName, final Locale locale, final ResourceBundle bundle, final String... suffixes) { if (COMMON_ATTRIBUTE_NAMES.contains(attributeName)) { return bundle.getString(getVariableBundleKey(COMMON_PREFIX, new String[]{attributeName}, suffixes)); } return super.getResourceAttributeValueTypeDescription(attributeName, locale, bundle, suffixes); } @Override public String getOperationParameterDescription(final String operationName, final String paramName, final Locale locale, final ResourceBundle bundle) { if (ModelDescriptionConstants.ADD.equals(operationName) && COMMON_ATTRIBUTE_NAMES.contains(paramName)) { return bundle.getString(getKey(paramName)); } return super.getOperationParameterDescription(operationName, paramName, locale, bundle); } @Override public String getOperationParameterValueTypeDescription(final String operationName, final String paramName, final Locale locale, final ResourceBundle bundle, final String... suffixes) { if (ModelDescriptionConstants.ADD.equals(operationName) && COMMON_ATTRIBUTE_NAMES.contains(paramName)) { return bundle.getString(getVariableBundleKey(COMMON_PREFIX, new String[]{paramName}, suffixes)); } return super.getOperationParameterValueTypeDescription(operationName, paramName, locale, bundle, suffixes); } private String getKey(final String... args) { return getVariableBundleKey(COMMON_PREFIX, args); } } }
10,569
49.817308
193
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/thread/pool/JobExecutorService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.thread.pool; import org.jberet.spi.JobExecutor; import org.jboss.as.threads.ManagedJBossThreadPoolExecutorService; import org.jboss.msc.Service; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import java.util.function.Consumer; import java.util.function.Supplier; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class JobExecutorService implements Service { private final Consumer<JobExecutor> jobExecutorConsumer; private final Supplier<ManagedJBossThreadPoolExecutorService> threadPoolSupplier; public JobExecutorService(final Consumer<JobExecutor> jobExecutorConsumer, final Supplier<ManagedJBossThreadPoolExecutorService> threadPoolSupplier) { this.jobExecutorConsumer = jobExecutorConsumer; this.threadPoolSupplier = threadPoolSupplier; } @Override public void start(final StartContext context) throws StartException { jobExecutorConsumer.accept(new WildFlyJobExecutor(threadPoolSupplier.get())); } @Override public void stop(final StopContext context) { jobExecutorConsumer.accept(null); } }
2,360
37.704918
105
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/thread/pool/WildFlyJobExecutor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.thread.pool; import org.jberet.spi.JobExecutor; import org.jberet.spi.JobTask; import org.jboss.as.threads.ManagedJBossThreadPoolExecutorService; import org.wildfly.extension.requestcontroller.ControlPointTask; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ class WildFlyJobExecutor extends JobExecutor { private final ManagedJBossThreadPoolExecutorService delegate; public WildFlyJobExecutor(final ManagedJBossThreadPoolExecutorService delegate) { super(delegate); this.delegate = delegate; } @Override protected int getMaximumPoolSize() { return delegate.getMaxThreads(); } @Override protected JobTask wrap(final Runnable task) { if (task instanceof JobTask) { return (JobTask) task; } final int requiredRemaining; if (task instanceof ControlPointTask) { final Runnable originalTask = ((ControlPointTask) task).getOriginalTask(); if (originalTask instanceof JobTask) { requiredRemaining = ((JobTask) originalTask).getRequiredRemainingPermits(); } else { requiredRemaining = 0; } } else { requiredRemaining = 0; } return new JobTask() { @Override public int getRequiredRemainingPermits() { return requiredRemaining; } @Override public void run() { task.run(); } }; } }
2,607
32.87013
91
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/job/repository/JdbcJobRepositoryService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.job.repository; import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionException; import java.util.function.Consumer; import java.util.function.Supplier; import javax.sql.DataSource; import org.jberet.repository.JdbcRepository; import org.jberet.repository.JobRepository; 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.batch.jberet._private.BatchLogger; /** * A service which provides a JDBC job repository. * * @author <a href="mailto:[email protected]">James R. Perkins</a> * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class JdbcJobRepositoryService extends JobRepositoryService implements Service<JobRepository> { private final Supplier<DataSource> dataSourceSupplier; private final Supplier<ExecutorService> executorSupplier; private volatile JdbcRepository jobRepository; public JdbcJobRepositoryService(final Consumer<JobRepository> jobRepositoryConsumer, final Supplier<DataSource> dataSourceSupplier, final Supplier<ExecutorService> executorSupplier, final Integer executionRecordsLimit) { super(jobRepositoryConsumer, executionRecordsLimit); this.dataSourceSupplier = dataSourceSupplier; this.executorSupplier = executorSupplier; } @Override public void startJobRepository(final StartContext context) throws StartException { final ExecutorService service = executorSupplier.get(); final Runnable task = () -> { try { // Currently in jBeret tables are created in the constructor which is why this is done asynchronously jobRepository = new JdbcRepository(dataSourceSupplier.get()); context.complete(); } catch (Exception e) { context.failed(BatchLogger.LOGGER.failedToCreateJobRepository(e, "JDBC")); } }; try { service.execute(task); } catch (RejectedExecutionException e) { task.run(); } finally { context.asynchronous(); } } @Override public void stopJobRepository(final StopContext context) { jobRepository = null; } @Override protected JobRepository getDelegate() { return jobRepository; } }
3,598
38.549451
117
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/job/repository/JdbcJobRepositoryDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.job.repository; import javax.sql.DataSource; import org.jberet.repository.JobRepository; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.ReloadRequiredRemoveStepHandler; import org.jboss.as.controller.ReloadRequiredWriteAttributeHandler; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.server.Services; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.wildfly.extension.batch.jberet.BatchResourceDescriptionResolver; import org.wildfly.extension.batch.jberet._private.Capabilities; import java.util.concurrent.ExecutorService; import java.util.function.Consumer; import java.util.function.Supplier; /** * Represents a JDBC job repository. * * @author <a href="mailto:[email protected]">James R. Perkins</a> * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class JdbcJobRepositoryDefinition extends SimpleResourceDefinition { public static final String NAME = "jdbc-job-repository"; public static final PathElement PATH = PathElement.pathElement(NAME); /** * A data-source attribute which requires the {@link Capabilities#DATA_SOURCE_CAPABILITY}. */ public static final SimpleAttributeDefinition DATA_SOURCE = SimpleAttributeDefinitionBuilder.create("data-source", ModelType.STRING, false) .setCapabilityReference(Capabilities.DATA_SOURCE_CAPABILITY, Capabilities.JOB_REPOSITORY_CAPABILITY) .setRestartAllServices() .build(); public JdbcJobRepositoryDefinition() { super( new Parameters(PATH, BatchResourceDescriptionResolver.getResourceDescriptionResolver(NAME)) .setAddHandler(new JdbcRepositoryAddHandler()) .setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE) .setCapabilities(Capabilities.JOB_REPOSITORY_CAPABILITY) ); } @Override public void registerAttributes(final ManagementResourceRegistration resourceRegistration) { super.registerAttributes(resourceRegistration); resourceRegistration.registerReadWriteAttribute(DATA_SOURCE, null, new ReloadRequiredWriteAttributeHandler(DATA_SOURCE)); resourceRegistration.registerReadWriteAttribute(CommonAttributes.EXECUTION_RECORDS_LIMIT, null, new ReloadRequiredWriteAttributeHandler(CommonAttributes.EXECUTION_RECORDS_LIMIT)); } private static class JdbcRepositoryAddHandler extends AbstractAddStepHandler { JdbcRepositoryAddHandler() { super(DATA_SOURCE, CommonAttributes.EXECUTION_RECORDS_LIMIT); } @Override protected void performRuntime(final OperationContext context, final ModelNode operation, final ModelNode model) throws OperationFailedException { super.performRuntime(context, operation, model); final String name = context.getCurrentAddressValue(); final String dsName = DATA_SOURCE.resolveModelAttribute(context, model).asString(); final Integer executionRecordsLimit = CommonAttributes.EXECUTION_RECORDS_LIMIT.resolveModelAttribute(context, model).asIntOrNull(); final ServiceTarget target = context.getServiceTarget(); final ServiceName sn = context.getCapabilityServiceName(Capabilities.JOB_REPOSITORY_CAPABILITY.getName(), name, JobRepository.class); final ServiceBuilder<?> sb = target.addService(sn); final Consumer<JobRepository> jobRepositoryConsumer = sb.provides(sn); final Supplier<ExecutorService> executorSupplier = Services.requireServerExecutor(sb); final Supplier<DataSource> dataSourceSupplier = sb.requires(context.getCapabilityServiceName(Capabilities.DATA_SOURCE_CAPABILITY, dsName, DataSource.class)); final JdbcJobRepositoryService service = new JdbcJobRepositoryService(jobRepositoryConsumer, dataSourceSupplier, executorSupplier, executionRecordsLimit); sb.setInstance(service); sb.install(); } } }
5,630
49.276786
169
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/job/repository/InMemoryJobRepositoryDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.job.repository; import org.jberet.repository.JobRepository; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.ReloadRequiredRemoveStepHandler; import org.jboss.as.controller.ReloadRequiredWriteAttributeHandler; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.dmr.ModelNode; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceName; import org.wildfly.extension.batch.jberet.BatchResourceDescriptionResolver; import org.wildfly.extension.batch.jberet._private.Capabilities; import java.util.function.Consumer; /** * Represents an in-memory job repository. * * @author <a href="mailto:[email protected]">James R. Perkins</a> * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class InMemoryJobRepositoryDefinition extends SimpleResourceDefinition { public static final String NAME = "in-memory-job-repository"; public static final PathElement PATH = PathElement.pathElement(NAME); public InMemoryJobRepositoryDefinition() { super( new Parameters(PATH, BatchResourceDescriptionResolver.getResourceDescriptionResolver(NAME)) .setAddHandler(new InMemoryAddHandler()) .setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE) .setCapabilities(Capabilities.JOB_REPOSITORY_CAPABILITY) ); } @Override public void registerAttributes(final ManagementResourceRegistration resourceRegistration) { super.registerAttributes(resourceRegistration); resourceRegistration.registerReadWriteAttribute(CommonAttributes.EXECUTION_RECORDS_LIMIT, null, new ReloadRequiredWriteAttributeHandler(CommonAttributes.EXECUTION_RECORDS_LIMIT)); } private static class InMemoryAddHandler extends AbstractAddStepHandler { InMemoryAddHandler() { super(CommonAttributes.EXECUTION_RECORDS_LIMIT); } @Override protected void performRuntime(final OperationContext context, final ModelNode operation, final ModelNode model) throws OperationFailedException { super.performRuntime(context, operation, model); final String name = context.getCurrentAddressValue(); final Integer executionRecordsLimit = CommonAttributes.EXECUTION_RECORDS_LIMIT.resolveModelAttribute(context, model).asIntOrNull(); final ServiceName inMemorySN = context.getCapabilityServiceName(Capabilities.JOB_REPOSITORY_CAPABILITY.getName(), name, JobRepository.class); final ServiceBuilder<?> sb = context.getServiceTarget().addService(inMemorySN); final Consumer<JobRepository> jobRepositoryConsumer = sb.provides(inMemorySN); sb.setInstance(new InMemoryJobRepositoryService(jobRepositoryConsumer, executionRecordsLimit)); sb.install(); } } }
4,210
47.402299
153
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/job/repository/InMemoryJobRepositoryService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.job.repository; import org.jberet.repository.InMemoryRepository; import org.jberet.repository.JobRepository; 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 java.util.function.Consumer; /** * A service which provides an in-memory job repository. * * @author <a href="mailto:[email protected]">James R. Perkins</a> * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class InMemoryJobRepositoryService extends JobRepositoryService implements Service<JobRepository> { private volatile InMemoryRepository repository; public InMemoryJobRepositoryService(final Consumer<JobRepository> jobRepositoryConsumer, final Integer executionRecordsLimit) { super(jobRepositoryConsumer, executionRecordsLimit); } @Override public void startJobRepository(final StartContext context) throws StartException { repository = new InMemoryRepository(); } @Override public void stopJobRepository(final StopContext context) { repository = null; } @Override protected JobRepository getDelegate() { return repository; } }
2,306
35.619048
131
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/job/repository/CommonAttributes.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.batch.jberet.job.repository; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.dmr.ModelType; public class CommonAttributes { /** * The limit of how many job execution records should be retrieved by the job repository. * * Setting this attribute allows improving application deployment time when the number of execution records in * the job repository grows too large. */ public static final SimpleAttributeDefinition EXECUTION_RECORDS_LIMIT = SimpleAttributeDefinitionBuilder.create("execution-records-limit", ModelType.INT, true) .setRestartAllServices() .build(); }
1,774
41.261905
163
java
null
wildfly-main/batch-jberet/src/main/java/org/wildfly/extension/batch/jberet/job/repository/JobRepositoryService.java
/* * Copyright 2015 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.batch.jberet.job.repository; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.function.Consumer; import jakarta.batch.runtime.JobExecution; import jakarta.batch.runtime.JobInstance; import jakarta.batch.runtime.StepExecution; import org.jberet.job.model.Job; import org.jberet.repository.ApplicationAndJobName; import org.jberet.repository.JobExecutionSelector; import org.jberet.repository.JobRepository; import org.jberet.runtime.AbstractStepExecution; import org.jberet.runtime.JobExecutionImpl; import org.jberet.runtime.JobInstanceImpl; import org.jberet.runtime.PartitionExecutionImpl; import org.jberet.runtime.StepExecutionImpl; 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.batch.jberet._private.BatchLogger; /** * An abstract service which delegates to a {@link JobRepository} throwing an {@link IllegalStateException} if the * service has been stopped. * * @author <a href="mailto:[email protected]">James R. Perkins</a> * @author <a href="mailto:[email protected]">Richard Opalka</a> */ abstract class JobRepositoryService implements JobRepository, Service<JobRepository> { private volatile boolean started; private final Integer executionRecordsLimit; private final Consumer<JobRepository> jobRepositoryConsumer; public JobRepositoryService(final Consumer<JobRepository> jobRepositoryConsumer, final Integer executionRecordsLimit) { this.jobRepositoryConsumer = jobRepositoryConsumer; this.executionRecordsLimit = executionRecordsLimit; } @Override public final void start(final StartContext context) throws StartException { startJobRepository(context); started = true; jobRepositoryConsumer.accept(this); } @Override public final void stop(final StopContext context) { jobRepositoryConsumer.accept(null); stopJobRepository(context); started = false; } @Override public JobRepository getValue() throws IllegalStateException, IllegalArgumentException { return this; } @Override public void addJob(final ApplicationAndJobName applicationAndJobName, final Job job) { getAndCheckDelegate().addJob(applicationAndJobName, job); } @Override public void removeJob(final String jobId) { getAndCheckDelegate().removeJob(jobId); } @Override public Job getJob(final ApplicationAndJobName applicationAndJobName) { return getAndCheckDelegate().getJob(applicationAndJobName); } @Override public Set<String> getJobNames() { return getAndCheckDelegate().getJobNames(); } /** * {@inheritDoc} * <p> * WildFly JBeret subsystem validates a job name before each batch job operations. * If a job name is invalid, {@code NoSuchJobException} would already have been thrown. * So this method is optimized to always return true. */ @Override public boolean jobExists(final String jobName) { return true; } @Override public JobInstanceImpl createJobInstance(final Job job, final String applicationName, final ClassLoader classLoader) { return getAndCheckDelegate().createJobInstance(job, applicationName, classLoader); } @Override public void removeJobInstance(final long jobInstanceId) { getAndCheckDelegate().removeJobInstance(jobInstanceId); } @Override public JobInstance getJobInstance(final long jobInstanceId) { return getAndCheckDelegate().getJobInstance(jobInstanceId); } @Override public List<JobInstance> getJobInstances(final String jobName) { return getAndCheckDelegate().getJobInstances(jobName); } @Override public int getJobInstanceCount(final String jobName) { return getAndCheckDelegate().getJobInstanceCount(jobName); } @Override public JobExecutionImpl createJobExecution(final JobInstanceImpl jobInstance, final Properties jobParameters) { return getAndCheckDelegate().createJobExecution(jobInstance, jobParameters); } @Override public JobExecution getJobExecution(final long jobExecutionId) { return getAndCheckDelegate().getJobExecution(jobExecutionId); } @Override public List<JobExecution> getJobExecutions(final JobInstance jobInstance) { return getAndCheckDelegate().getJobExecutions(jobInstance); } @Override public void updateJobExecution(final JobExecutionImpl jobExecution, final boolean fullUpdate, final boolean saveJobParameters) { getAndCheckDelegate().updateJobExecution(jobExecution, fullUpdate, saveJobParameters); } @Override public void stopJobExecution(final JobExecutionImpl jobExecution) { getAndCheckDelegate().stopJobExecution(jobExecution); } @Override public List<Long> getRunningExecutions(final String jobName) { return getAndCheckDelegate().getRunningExecutions(jobName); } @Override public void removeJobExecutions(final JobExecutionSelector jobExecutionSelector) { getAndCheckDelegate().removeJobExecutions(jobExecutionSelector); } @Override public List<StepExecution> getStepExecutions(final long jobExecutionId, final ClassLoader classLoader) { return getAndCheckDelegate().getStepExecutions(jobExecutionId, classLoader); } @Override public StepExecutionImpl createStepExecution(final String stepName) { return getAndCheckDelegate().createStepExecution(stepName); } @Override public void addStepExecution(final JobExecutionImpl jobExecution, final StepExecutionImpl stepExecution) { getAndCheckDelegate().addStepExecution(jobExecution, stepExecution); } @Override public void updateStepExecution(final StepExecution stepExecution) { getAndCheckDelegate().updateStepExecution(stepExecution); } @Override public StepExecutionImpl findOriginalStepExecutionForRestart(final String stepName, final JobExecutionImpl jobExecutionToRestart, final ClassLoader classLoader) { return getAndCheckDelegate().findOriginalStepExecutionForRestart(stepName, jobExecutionToRestart, classLoader); } @Override public int countStepStartTimes(final String stepName, final long jobInstanceId) { return getAndCheckDelegate().countStepStartTimes(stepName, jobInstanceId); } @Override public void addPartitionExecution(final StepExecutionImpl enclosingStepExecution, final PartitionExecutionImpl partitionExecution) { getAndCheckDelegate().addPartitionExecution(enclosingStepExecution, partitionExecution); } @Override public List<PartitionExecutionImpl> getPartitionExecutions(final long stepExecutionId, final StepExecutionImpl stepExecution, final boolean notCompletedOnly, final ClassLoader classLoader) { return getAndCheckDelegate().getPartitionExecutions(stepExecutionId, stepExecution, notCompletedOnly, classLoader); } @Override public void savePersistentData(final JobExecution jobExecution, final AbstractStepExecution stepOrPartitionExecution) { getAndCheckDelegate().savePersistentData(jobExecution, stepOrPartitionExecution); } @Override public int savePersistentDataIfNotStopping(final JobExecution jobExecution, final AbstractStepExecution abstractStepExecution) { return getAndCheckDelegate().savePersistentDataIfNotStopping(jobExecution, abstractStepExecution); } @Override public List<Long> getJobExecutionsByJob(final String jobName) { return getAndCheckDelegate().getJobExecutionsByJob(jobName, executionRecordsLimit); } @Override public List<Long> getJobExecutionsByJob(String jobName, Integer executionRecordsLimit) { return getAndCheckDelegate().getJobExecutionsByJob(jobName, executionRecordsLimit); } protected abstract void startJobRepository(StartContext context) throws StartException; protected abstract void stopJobRepository(StopContext context); protected abstract JobRepository getDelegate(); private JobRepository getAndCheckDelegate() { final JobRepository delegate = getDelegate(); if (started && delegate != null) { return delegate; } throw BatchLogger.LOGGER.jobOperatorServiceStopped(); } }
9,118
36.372951
194
java
null
wildfly-main/jdr/src/test/java/org/jboss/as/jdr/JdrTestCase.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.jdr; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import org.jboss.as.jdr.commands.JdrEnvironment; import org.jboss.as.jdr.util.JdrZipFile; import org.jboss.as.jdr.util.PatternSanitizer; import org.jboss.as.jdr.util.XMLSanitizer; import org.jboss.as.jdr.vfs.Filters; import org.jboss.vfs.TempFileProvider; import org.jboss.vfs.VFS; import org.jboss.vfs.VFSUtils; import org.jboss.vfs.VirtualFile; import org.jboss.vfs.VirtualFileFilter; import org.junit.Test; public class JdrTestCase { @Test public void testJdrZipName() throws Exception { // create a test-files dir to store the test JDR File testFilesDir = new File("target/test-files"); testFilesDir.mkdirs(); JdrEnvironment env = new JdrEnvironment(); env.setOutputDirectory(testFilesDir.getAbsolutePath()); env.setJbossHome("/foo/bar/baz"); env.setServerName("localhost"); env.setHostControllerName("host"); env.setProductName("wildfly"); env.setProductVersion("20"); env.setZip(new JdrZipFile(new JdrEnvironment(env))); JdrZipFile jzf = env.getZip(); File jdrZipFile = new File(jzf.name()); try { jzf.add("test1", "test1\\sub1\\sub2\\test1.txt"); jzf.add("test2", "test2/sub1/sub2/test2.txt"); } finally { jzf.close(); } // Make sure the JDR zip got created assertTrue(jdrZipFile.exists()); assertTrue(jzf.name().endsWith(".zip")); assertTrue(jzf.name().contains("host")); List<Closeable> mounts = null; try { VirtualFile jdrReport = VFS.getChild(jzf.name()); mounts = recursiveMount(jdrReport); VirtualFile root = jdrReport.getChildren().get(0); String dir = ""; for(String path : new String[] { "sos_strings" , jzf.getProductDirName(), "test1", "sub1", "sub2" }) { dir = dir + "/" + path; assertTrue(root.getChild(dir).isDirectory()); } dir = ""; for(String path : new String[] { "sos_strings" , jzf.getProductDirName(), "test2", "sub1", "sub2" }) { dir = dir + "/" + path; assertTrue(root.getChild(dir).isDirectory()); } assertTrue(root.getChild("sos_strings/" + jzf.getProductDirName() + "/test1/sub1/sub2/test1.txt").isFile()); assertTrue(root.getChild("sos_strings/" + jzf.getProductDirName() + "/test2/sub1/sub2/test2.txt").isFile()); } finally { if(mounts != null) VFSUtils.safeClose(mounts); // Clean up the test JDR zip file jdrZipFile.delete(); } } public static List<Closeable> recursiveMount(VirtualFile file) throws IOException { TempFileProvider provider = TempFileProvider.create("test", Executors.newSingleThreadScheduledExecutor()); ArrayList<Closeable> mounts = new ArrayList<Closeable>(); if (!file.isDirectory() && file.getName().matches("^.*\\.([EeWwJj][Aa][Rr]|[Zz][Ii][Pp])$")) { mounts.add(VFS.mountZip(file, file, provider)); } if (file.isDirectory()) { for (VirtualFile child : file.getChildren()) { mounts.addAll(recursiveMount(child)); } } return mounts; } @Test public void testBlockListFilter() { VirtualFileFilter blf = Filters.regexBlockList(); assertFalse(blf.accepts(VFS.getChild("/foo/bar/baz/mgmt-users.properties"))); assertFalse(blf.accepts(VFS.getChild("/foo/bar/baz/application-users.properties"))); } @Test public void testXMLSanitizer() throws Exception { String xml = "<test><password>foobar</password></test>"; InputStream is = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)); XMLSanitizer s = new XMLSanitizer("//password", Filters.TRUE); InputStream res = s.sanitize(is); byte [] buf = new byte [res.available()]; res.read(buf); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><test><password/></test>", new String(buf, StandardCharsets.UTF_8)); } @Test public void testPatternSanitizer() throws Exception { String propf = "password=123456"; InputStream is = new ByteArrayInputStream(propf.getBytes(StandardCharsets.UTF_8)); PatternSanitizer s = new PatternSanitizer("password=.*", "password=*", Filters.TRUE); InputStream res = s.sanitize(is); byte [] buf = new byte [res.available()]; res.read(buf); assertEquals("password=*", new String(buf, StandardCharsets.UTF_8)); } @Test public void testWildcardFilterAcceptAnything() throws Exception { VirtualFileFilter filter = Filters.wildcard("*"); VirtualFile good = VFS.getChild("/this/is/a/test.txt"); assertTrue(filter.accepts(good)); } @Test public void testWildcardFilterPrefixGlob() throws Exception { VirtualFileFilter filter = Filters.wildcard("*.txt"); VirtualFile good = VFS.getChild("/this/is/a/test.txt"); VirtualFile bad = VFS.getChild("/this/is/a/test.xml"); VirtualFile wingood = VFS.getChild("/C:/this/is/a/test.txt"); VirtualFile winbad = VFS.getChild("/C:/this/is/a/test.xml"); assertTrue(filter.accepts(good)); assertFalse(filter.accepts(bad)); assertTrue(filter.accepts(wingood)); assertFalse(filter.accepts(winbad)); } @Test public void testWildcardFilterSuffixGlob() throws Exception { VirtualFileFilter filter = Filters.wildcard("/this/is*"); VirtualFile good = VFS.getChild("/this/is/a/test.txt"); VirtualFile bad = VFS.getChild("/that/is/a/test.txt"); VirtualFile wingood = VFS.getChild("/C:/this/is/a/test.txt"); VirtualFile winbad = VFS.getChild("/C:/that/is/a/test.txt"); assertTrue(filter.accepts(good)); assertFalse(filter.accepts(bad)); assertTrue(filter.accepts(wingood)); assertFalse(filter.accepts(winbad)); } @Test public void testWildcardFilterMiddleGlob() throws Exception { VirtualFileFilter filter = Filters.wildcard("/this*test.txt"); VirtualFile good = VFS.getChild("/this/is/a/test.txt"); VirtualFile bad1 = VFS.getChild("/that/is/a/test.txt"); VirtualFile bad2 = VFS.getChild("/this/is/a/test.xml"); VirtualFile win = VFS.getChild("/C:/this/is/a/test.txt"); VirtualFile winbad = VFS.getChild("/C:/this/is/a/test.xml"); assertTrue(filter.accepts(good)); assertTrue(filter.accepts(win)); assertFalse(filter.accepts(bad1)); assertFalse(filter.accepts(bad2)); assertFalse(filter.accepts(winbad)); } private void safeClose(JdrZipFile zf) { try { zf.close(); } catch (Exception ignored) { } } }
8,265
39.920792
152
java
null
wildfly-main/jdr/src/test/java/org/jboss/as/jdr/JdrSubsystemTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.jdr; import static org.jboss.as.jdr.JdrReportSubsystemDefinition.EXECUTOR_CAPABILITY; import java.io.IOException; import java.util.Collections; import java.util.EnumSet; import java.util.Locale; import java.util.concurrent.ExecutorService; import javax.xml.stream.XMLStreamException; import org.jboss.as.controller.RunningMode; 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.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * Performs basic parsing and configuration testing of the JDR subsystem. * * @author Mike M. Clark */ @RunWith(Parameterized.class) public class JdrSubsystemTestCase extends AbstractSubsystemBaseTest { @Parameters public static Iterable<JdrReportSubsystemSchema> parameters() { return EnumSet.allOf(JdrReportSubsystemSchema.class); } private final JdrReportSubsystemSchema schema; public JdrSubsystemTestCase(JdrReportSubsystemSchema schema) { super(JdrReportExtension.SUBSYSTEM_NAME, new JdrReportExtension()); this.schema = schema; } @Test(expected = XMLStreamException.class) public void testParseSubsystemWithBadChild() throws Exception { String subsystemXml = "<subsystem xmlns=\"" + this.schema.getNamespace() + "\"><invalid/></subsystem>"; super.parse(subsystemXml); } @Test(expected = XMLStreamException.class) public void testParseSubsystemWithBadAttribute() throws Exception { String subsystemXml = "<subsystem xmlns=\"" + this.schema.getNamespace() + "\" attr=\"wrong\"/>"; super.parse(subsystemXml); } @Override protected String getSubsystemXml() throws IOException { return "<subsystem xmlns=\"" + this.schema.getNamespace() + "\"/>"; } @Override protected String getSubsystemXsdPath() throws Exception { return String.format(Locale.ROOT, "schema/jboss-as-jdr_%d_%d.xsd", this.schema.getVersion().major(), this.schema.getVersion().minor()); } @Override protected AdditionalInitialization createAdditionalInitialization() { return new AdditionalInitialization() { @Override protected RunningMode getRunningMode() { return RunningMode.NORMAL; } @Override protected void initializeExtraSubystemsAndModel(ExtensionRegistry extensionRegistry, Resource rootResource, ManagementResourceRegistration rootRegistration, RuntimeCapabilityRegistry capabilityRegistry) { super.initializeExtraSubystemsAndModel(extensionRegistry, rootResource, rootRegistration, capabilityRegistry); registerServiceCapabilities(capabilityRegistry, Collections.singletonMap(EXECUTOR_CAPABILITY, ExecutorService.class)); } }; } }
4,248
38.71028
216
java
null
wildfly-main/jdr/src/test/java/org/jboss/as/jdr/FSTreeTest.java
package org.jboss.as.jdr; import org.apache.commons.io.FileUtils; import org.jboss.as.jdr.util.FSTree; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; import static org.junit.Assert.assertEquals; public class FSTreeTest { private File baseDirectory; @Before public void setUp() throws Exception { File tmpDir = FileUtils.getTempDirectory(); baseDirectory = FileUtils.getFile(tmpDir, "FSTreeTest"); FileUtils.forceMkdir(baseDirectory); } @After public void tearDown() throws Exception { FileUtils.deleteDirectory(baseDirectory); } @Test public void testTree() throws Exception { FSTree tree = new FSTree(baseDirectory.getPath()); assertEquals("FSTreeTest\n", tree.toString()); } }
821
22.485714
64
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/JdrReportSubsystemAdd.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.jdr; import java.util.function.Consumer; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.dmr.ModelNode; /** * Adds the JDR subsystem. * * @author Brian Stansberry */ public class JdrReportSubsystemAdd extends AbstractAddStepHandler { private final Consumer<JdrReportCollector> collectorConsumer; /** * Creates a new add handler for the JDR subsystem root resource. * * @param collectorConsumer consumer to pass a ref to the started JdrReportService to the rest of the subsystem. Cannot be {@code null} */ JdrReportSubsystemAdd(final Consumer<JdrReportCollector> collectorConsumer) { this.collectorConsumer = collectorConsumer; } @Override protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { JdrReportService.addService(context.getCapabilityServiceTarget(), collectorConsumer); } @Override protected boolean requiresRuntime(OperationContext context) { return context.getProcessType().isServer(); } }
2,244
37.050847
139
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/JdrReportRequestHandler.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.jdr; import java.util.function.Supplier; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.OperationStepHandler; import org.jboss.as.controller.SimpleOperationDefinition; import org.jboss.as.controller.SimpleOperationDefinitionBuilder; import org.jboss.dmr.ModelNode; /** * Operation handler for an end user request to generate a JDR report. * * @author Brian Stansberry * @author Mike M. Clark */ public class JdrReportRequestHandler implements OperationStepHandler { private static final String OPERATION_NAME = "generate-jdr-report"; static final SimpleOperationDefinition DEFINITION = new SimpleOperationDefinitionBuilder(OPERATION_NAME, JdrReportExtension.SUBSYSTEM_RESOLVER) .setReplyParameters(CommonAttributes.START_TIME, CommonAttributes.END_TIME, CommonAttributes.REPORT_LOCATION) .setReadOnly() .setRuntimeOnly() .addAccessConstraint(JdrReportExtension.JDR_SENSITIVITY_DEF) .build(); private final Supplier<JdrReportCollector> collectorSupplier; /** * Create a new handler for the {@code generate-jdr-report} operation. * * @param collectorSupplier supplier of the {@link JdrReportCollector} to use to collect the report. Cannot be {@code null}. */ JdrReportRequestHandler(Supplier<JdrReportCollector> collectorSupplier) { this.collectorSupplier = collectorSupplier; } @Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { // Register a handler for the RUNTIME stage context.addStep(new OperationStepHandler() { @Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { JdrReportCollector jdrCollector = collectorSupplier.get(); if (jdrCollector == null) { // JdrReportService must have failed or been stopped throw new IllegalStateException(); } ModelNode response = context.getResult(); JdrReport report = jdrCollector.collect(); if (report.getStartTime() != null) { response.get("start-time").set(report.getStartTime()); } if (report.getEndTime() != null) { response.get("end-time").set(report.getEndTime()); } response.get("report-location").set(report.getLocation()); context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER); } }, OperationContext.Stage.RUNTIME); } }
3,805
39.924731
147
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/JdrReportSubsystemDefinition.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.jdr; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import org.jboss.as.controller.OperationStepHandler; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.wildfly.common.function.Functions; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2012 Red Hat Inc. */ public class JdrReportSubsystemDefinition extends SimpleResourceDefinition { static final String MCF_CAPABILITY = "org.wildfly.management.model-controller-client-factory"; static final String EXECUTOR_CAPABILITY = "org.wildfly.management.executor"; static final RuntimeCapability<Void> JDR_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.jdr", JdrReportCollector.class) //.addRequirements(MCF_CAPABILITY, EXECUTOR_CAPABILITY) TODO determine why this breaks domain mode provisioning .build(); private final AtomicReference<JdrReportCollector> collectorReference; JdrReportSubsystemDefinition(AtomicReference<JdrReportCollector> collectorReference) { super(getParameters(collectorReference)); this.collectorReference = collectorReference; } private static Parameters getParameters(AtomicReference<JdrReportCollector> collectorReference) { Consumer<JdrReportCollector> subsystemConsumer = collectorReference == null ? Functions.discardingConsumer() : collectorReference::set; OperationStepHandler addHandler = new JdrReportSubsystemAdd(subsystemConsumer); return new Parameters(JdrReportExtension.SUBSYSTEM_PATH, JdrReportExtension.SUBSYSTEM_RESOLVER) .setAddHandler(addHandler) .setRemoveHandler(JdrReportSubsystemRemove.INSTANCE) .setCapabilities(JDR_CAPABILITY); } @Override public void registerOperations(ManagementResourceRegistration resourceRegistration) { super.registerOperations(resourceRegistration); resourceRegistration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE); if (collectorReference != null) { resourceRegistration.registerOperationHandler(JdrReportRequestHandler.DEFINITION, new JdrReportRequestHandler(collectorReference::get)); } } }
3,541
48.194444
148
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/JdrReportExtension.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.jdr; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import java.util.EnumSet; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import org.jboss.as.controller.Extension; import org.jboss.as.controller.ExtensionContext; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PersistentResourceXMLDescription; import org.jboss.as.controller.PersistentResourceXMLDescriptionReader; import org.jboss.as.controller.PersistentResourceXMLDescriptionWriter; import org.jboss.as.controller.SubsystemRegistration; import org.jboss.as.controller.access.constraint.SensitivityClassification; import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition; import org.jboss.as.controller.descriptions.ParentResourceDescriptionResolver; import org.jboss.as.controller.descriptions.SubsystemResourceDescriptionResolver; import org.jboss.as.controller.parsing.ExtensionParsingContext; import org.jboss.dmr.ModelNode; import org.jboss.staxmapper.XMLElementReader; /** * Extension for triggering, requesting, generating and accessing JDR reports. * * @author Brian Stansberry */ public class JdrReportExtension implements Extension { public static final String SUBSYSTEM_NAME = "jdr"; private static final ModelVersion CURRENT_MODEL_VERSION = ModelVersion.create(2, 0, 0); static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME); static final ParentResourceDescriptionResolver SUBSYSTEM_RESOLVER = new SubsystemResourceDescriptionResolver(SUBSYSTEM_NAME, JdrReportExtension.class); static final SensitivityClassification JDR_SENSITIVITY = new SensitivityClassification(SUBSYSTEM_NAME, "jdr", false, false, true); static final SensitiveTargetAccessConstraintDefinition JDR_SENSITIVITY_DEF = new SensitiveTargetAccessConstraintDefinition(JDR_SENSITIVITY); private final PersistentResourceXMLDescription currentDescription = JdrReportSubsystemSchema.CURRENT.getXMLDescription(); @Override public void initialize(ExtensionContext context) { SubsystemRegistration subsystemRegistration = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION); AtomicReference<JdrReportCollector> collectorReference = context.isRuntimeOnlyRegistrationValid() ? new AtomicReference<>() : null; subsystemRegistration.registerSubsystemModel(new JdrReportSubsystemDefinition(collectorReference)); subsystemRegistration.registerXMLElementWriter(new PersistentResourceXMLDescriptionWriter(this.currentDescription)); } @Override public void initializeParsers(ExtensionParsingContext context) { for (JdrReportSubsystemSchema schema : EnumSet.allOf(JdrReportSubsystemSchema.class)) { XMLElementReader<List<ModelNode>> reader = (schema == JdrReportSubsystemSchema.CURRENT) ? new PersistentResourceXMLDescriptionReader(this.currentDescription) : schema; context.setSubsystemXmlMapping(SUBSYSTEM_NAME, schema.getNamespace().getUri(), reader); } } }
4,204
46.784091
179
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/JdrReportSubsystemSchema.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.jdr; import static org.jboss.as.controller.PersistentResourceXMLDescription.builder; import org.jboss.as.controller.PersistentResourceXMLDescription; import org.jboss.as.controller.PersistentSubsystemSchema; import org.jboss.as.controller.SubsystemSchema; import org.jboss.as.controller.xml.VersionedNamespace; import org.jboss.staxmapper.IntVersion; /** * The namespaces supported by the JDR extension. * * @author Brian Stansberry * @author Mike M. Clark */ enum JdrReportSubsystemSchema implements PersistentSubsystemSchema<JdrReportSubsystemSchema> { VERSION_1_0(1), ; static final JdrReportSubsystemSchema CURRENT = VERSION_1_0; private final VersionedNamespace<IntVersion, JdrReportSubsystemSchema> namespace; JdrReportSubsystemSchema(int major) { this.namespace = SubsystemSchema.createLegacySubsystemURN(JdrReportExtension.SUBSYSTEM_NAME, new IntVersion(major)); } @Override public VersionedNamespace<IntVersion, JdrReportSubsystemSchema> getNamespace() { return this.namespace; } @Override public PersistentResourceXMLDescription getXMLDescription() { return builder(JdrReportExtension.SUBSYSTEM_PATH, this.namespace).build(); } }
2,270
36.229508
124
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/JdrReport.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.jdr; import static org.jboss.as.jdr.logger.JdrLogger.ROOT_LOGGER; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import org.jboss.dmr.ModelNode; /** * Provides metadata about and access to the data collected by a {@link JdrReportCollector}. * * @author Brian Stansberry * @author Mike M. Clark */ public class JdrReport { public static final String JBOSS_PROPERTY_DIR = "jboss.server.data.dir"; public static final String JDR_PROPERTY_FILE_NAME = "jdr.properties"; public static final String UUID_NAME = "UUID"; public static final String JDR_PROPERTIES_COMMENT = "JDR Properties"; public static final String JBOSS_HOME_DIR = "jboss.home.dir"; public static final String DEFAULT_PROPERTY_DIR = "standalone"; public static final String DATA_DIR = "data"; private Long startTime; private Long endTime; private String location; private String jdrUuid; private static DateFormat DATE_FORMAT = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy"); public JdrReport() { } public JdrReport(ModelNode result) { setStartTime(result.get("start-time").asLong()); setEndTime(result.get("end-time").asLong()); setLocation(result.get("report-location").asString()); } /** * Indicates the time the JDR report collection was initiated. */ public Long getStartTime() { return startTime; } public String getFormattedStartTime() { if(startTime == null) return ""; return DATE_FORMAT.format(startTime); } public void setStartTime(Date date) { startTime = date.getTime(); } public void setStartTime(long startTime) { this.startTime = startTime; } public void setStartTime() { setStartTime(System.currentTimeMillis()); } /** * Indicates the time the JDR report collection was complete. */ public Long getEndTime() { return endTime; } public String getFormattedEndTime() { if(endTime == null) return ""; return DATE_FORMAT.format(endTime); } public void setEndTime(Date date) { endTime = date.getTime(); } public void setEndTime(long endTime) { this.endTime = endTime; } public void setEndTime() { setEndTime(System.currentTimeMillis()); } /** * Indicates the location of the generated JDR report. * * @return location of report. */ public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public void setJdrUuid(String jdrUuid) { this.jdrUuid = jdrUuid; String jbossConfig = System.getProperty(JBOSS_PROPERTY_DIR); Path jbossConfigPath; // JDR is being ran from command line if (jbossConfig == null) { String jbossHome = System.getProperty(JBOSS_HOME_DIR); // if JBoss standalone directory does not exist then go no further Path defaultDir = new File(jbossHome, DEFAULT_PROPERTY_DIR).toPath(); if (Files.notExists(defaultDir)) { ROOT_LOGGER.couldNotFindJDRPropertiesFile(); } jbossConfigPath = defaultDir.resolve(DATA_DIR); } else { jbossConfigPath = new File(jbossConfig).toPath(); } Path jdrPropertiesFilePath = jbossConfigPath.resolve(JdrReportExtension.SUBSYSTEM_NAME).resolve(JDR_PROPERTY_FILE_NAME); Properties jdrProperties = new Properties(); try { Files.createDirectories(jdrPropertiesFilePath.getParent()); } catch (IOException e) { ROOT_LOGGER.couldNotCreateJDRPropertiesFile(e, jdrPropertiesFilePath); } if (jdrUuid == null && Files.exists(jdrPropertiesFilePath)) { try (InputStream in = Files.newInputStream(jdrPropertiesFilePath)) { jdrProperties.load(in); this.jdrUuid = jdrProperties.getProperty(UUID_NAME); } catch (IOException e) { ROOT_LOGGER.couldNotFindJDRPropertiesFile(); } } else { try (OutputStream fileOut = Files.newOutputStream(jdrPropertiesFilePath, StandardOpenOption.CREATE)) { jdrProperties.setProperty(UUID_NAME, jdrUuid); jdrProperties.store(fileOut, JDR_PROPERTIES_COMMENT); } catch (IOException e) { ROOT_LOGGER.couldNotCreateJDRPropertiesFile(e, jdrPropertiesFilePath); } } } public String getJdrUuid() { return jdrUuid; } }
5,960
31.221622
128
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/JdrReportService.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.jdr; import static org.jboss.as.jdr.JdrReportSubsystemDefinition.EXECUTOR_CAPABILITY; import static org.jboss.as.jdr.JdrReportSubsystemDefinition.JDR_CAPABILITY; import static org.jboss.as.jdr.JdrReportSubsystemDefinition.MCF_CAPABILITY; import java.util.concurrent.ExecutorService; import java.util.function.Consumer; import java.util.function.Supplier; import org.jboss.as.controller.CapabilityServiceBuilder; import org.jboss.as.controller.CapabilityServiceTarget; import org.jboss.as.controller.LocalModelControllerClient; import org.jboss.as.controller.ModelControllerClientFactory; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.server.ServerEnvironment; import org.jboss.as.server.ServerEnvironmentService; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StopContext; /** * Service that provides a {@link JdrReportCollector}. * * @author Brian Stansberry * @author Mike M. Clark * @author Jesse Jaggars */ class JdrReportService implements JdrReportCollector, Service { /** * Install the JdrReportService. * * @param target MSC target to use to install * @param subsystemConsumer consumer to provide a ref to the started service to the rest of the subsystem for its use in OSHs. */ static void addService(final CapabilityServiceTarget target, final Consumer<JdrReportCollector> subsystemConsumer) { CapabilityServiceBuilder<?> builder = target.addCapability(JDR_CAPABILITY); Consumer<JdrReportCollector> mscConsumer = builder.provides(JDR_CAPABILITY); Supplier<ModelControllerClientFactory> mcfSupplier = builder.requiresCapability(MCF_CAPABILITY, ModelControllerClientFactory.class); Supplier<ExecutorService> esSupplier = builder.requiresCapability(EXECUTOR_CAPABILITY, ExecutorService.class); Supplier<ServerEnvironment> seSupplier = builder.requires(ServerEnvironmentService.SERVICE_NAME); builder.setInstance(new JdrReportService(subsystemConsumer, mscConsumer, mcfSupplier, esSupplier, seSupplier)) .setInitialMode(ServiceController.Mode.ACTIVE).install(); } /** Consumer we use to pass a ref back to our subsystem code for its use in OSHs */ private final Consumer<JdrReportCollector> subsystemConsumer; /** Consumer we use to pass a ref to MSC for its use in service-based injection */ private final Consumer<JdrReportCollector> mscConsumer; private final Supplier<ServerEnvironment> serverEnvironmentSupplier; private final Supplier<ModelControllerClientFactory> clientFactorySupplier; private final Supplier<ExecutorService> executorServiceSupplier; private JdrReportService(final Consumer<JdrReportCollector> subsystemConsumer, final Consumer<JdrReportCollector> consumer, final Supplier<ModelControllerClientFactory> mcfSupplier, final Supplier<ExecutorService> executorServiceSupplier, final Supplier<ServerEnvironment> seSupplier) { this.subsystemConsumer = subsystemConsumer; this.mscConsumer = consumer; this.serverEnvironmentSupplier = seSupplier; this.clientFactorySupplier = mcfSupplier; this.executorServiceSupplier = executorServiceSupplier; } /** * Collect a JDR report. */ public JdrReport collect() throws OperationFailedException { try (LocalModelControllerClient client = clientFactorySupplier.get().createSuperUserClient(executorServiceSupplier.get())) { JdrRunner runner = new JdrRunner(true); ServerEnvironment serverEnvironment = serverEnvironmentSupplier.get(); runner.setJbossHomeDir(serverEnvironment.getHomeDir().getAbsolutePath()); runner.setReportLocationDir(serverEnvironment.getServerTempDir().getAbsolutePath()); runner.setControllerClient(client); runner.setHostControllerName(serverEnvironment.getHostControllerName()); runner.setServerName(serverEnvironment.getServerName()); return runner.collect(); } } public synchronized void start(StartContext context) { mscConsumer.accept(this); subsystemConsumer.accept(this); } public synchronized void stop(StopContext context) { mscConsumer.accept(null); subsystemConsumer.accept(null); } }
5,586
45.558333
132
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/CommonAttributes.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.jdr; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.dmr.ModelType; /** * Strings holding the attributes used in the configuration of the jdr subsystem. * * @author Mike M. Clark * @author Tomaz Cerar */ public interface CommonAttributes { SimpleAttributeDefinition START_TIME = new SimpleAttributeDefinitionBuilder("start-time", ModelType.LONG, false).build(); SimpleAttributeDefinition END_TIME = new SimpleAttributeDefinitionBuilder("end-time", ModelType.LONG, false).build(); SimpleAttributeDefinition REPORT_LOCATION = new SimpleAttributeDefinitionBuilder("report-location", ModelType.STRING, true).build(); }
1,772
42.243902
136
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/CommandLineMain.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.jdr; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.jboss.as.cli.scriptsupport.CLI; import org.jboss.as.cli.scriptsupport.CLI.Result; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.client.helpers.ClientConstants; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.jdr.logger.JdrLogger; import org.jboss.dmr.ModelNode; /** * Provides a main for collecting a JDR report from the command line. * * @author Mike M. Clark * @author Jesse Jaggars */ public class CommandLineMain { private static final CommandLineParser parser = new GnuParser(); private static final Options options = new Options(); private static final HelpFormatter formatter = new HelpFormatter(); private static final String usage = "jdr.{sh,bat,ps1} [options]"; private static final String NEW_LINE = String.format("%n"); static { options.addOption("h", "help", false, JdrLogger.ROOT_LOGGER.jdrHelpMessage()); options.addOption("H", "host", true, JdrLogger.ROOT_LOGGER.jdrHostnameMessage()); options.addOption("p", "port", true, JdrLogger.ROOT_LOGGER.jdrPortMessage()); options.addOption("s", "protocol", true, JdrLogger.ROOT_LOGGER.jdrProtocolMessage()); options.addOption("c", "config", true, JdrLogger.ROOT_LOGGER.jdrConfigMessage()); } /** * Creates a JBoss Diagnostic Reporter (JDR) Report. A JDR report response * is printed to <code>System.out</code>. * * @param args ignored */ public static void main(String[] args) { int port = 9990; String host = "localhost"; String protocol = "remote+http"; String config = null; try { CommandLine line = parser.parse(options, args, false); if (line.hasOption("help")) { formatter.printHelp(usage, NEW_LINE + JdrLogger.ROOT_LOGGER.jdrDescriptionMessage(), options, null); return; } if (line.hasOption("host")) { host = line.getOptionValue("host"); } if (line.hasOption("port")) { port = Integer.parseInt(line.getOptionValue("port")); } if (line.hasOption("protocol")) { protocol = line.getOptionValue("protocol"); } if (line.hasOption("config")) { config = line.getOptionValue("config"); } } catch (ParseException | NumberFormatException e) { System.out.println(e.getMessage()); formatter.printHelp(usage, options); return; } System.out.println("Initializing JBoss Diagnostic Reporter..."); // Try to run JDR on the Wildfly JVM CLI cli = CLI.newInstance(); boolean embedded = false; JdrReport report; try { System.out.printf("Trying to connect to %s %s:%s%n", protocol, host, port); cli.connect(protocol, host, port, null, null); } catch (IllegalStateException ex) { System.out.println("Starting embedded server"); String startEmbeddedServer = "embed-server --std-out=echo " + ((config != null && ! config.isEmpty()) ? (" --server-config=" + config) : ""); cli.getCommandContext().handleSafe(startEmbeddedServer); embedded = true; } try { Result cmdResult = cli.cmd("/subsystem=jdr:generate-jdr-report()"); ModelNode response = cmdResult.getResponse(); if(Operations.isSuccessfulOutcome(response) || !embedded) { reportFailure(response); ModelNode result = response.get(ClientConstants.RESULT); report = new JdrReport(result); } else { report = standaloneCollect(cli, protocol, host, port); } } catch(IllegalStateException ise) { System.out.println(ise.getMessage()); report = standaloneCollect(cli, protocol, host, port); } finally { try { if(embedded) cli.getCommandContext().handleSafe("stop-embedded-server"); else cli.disconnect(); } catch(Exception e) { System.out.println("Caught exception while disconnecting: " + e.getMessage()); } } printJdrReportInfo(report); System.exit(0); } private static void printJdrReportInfo(JdrReport report) { if(report != null) { System.out.println("JDR started: " + report.getFormattedStartTime()); System.out.println("JDR ended: " + report.getFormattedEndTime()); System.out.println("JDR location: " + report.getLocation()); System.out.flush(); } } private static JdrReport standaloneCollect(CLI cli, String protocol, String host, int port) { // Unable to connect to a running server, so proceed without it JdrReport report = null; try { report = new JdrRunner(cli, protocol, host, port, null, null).collect(); } catch (OperationFailedException e) { System.out.println("Failed to complete the JDR report: " + e.getMessage()); } return report; } private static void reportFailure(final ModelNode node) { if (!node.get(ClientConstants.OUTCOME).asString().equals(ClientConstants.SUCCESS)) { final String msg; if (node.hasDefined(ClientConstants.FAILURE_DESCRIPTION)) { if (node.hasDefined(ClientConstants.OP)) { msg = String.format("Operation '%s' at address '%s' failed: %s", node.get(ClientConstants.OP), node.get(ClientConstants.OP_ADDR), node.get(ClientConstants.FAILURE_DESCRIPTION)); } else { msg = String.format("Operation failed: %s", node.get(ClientConstants.FAILURE_DESCRIPTION)); } } else { msg = String.format("Operation failed: %s", node); } throw new RuntimeException(msg); } } }
7,404
40.601124
197
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/JdrReportSubsystemRemove.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.jdr; import static org.jboss.as.jdr.JdrReportSubsystemDefinition.JDR_CAPABILITY; import org.jboss.as.controller.AbstractRemoveStepHandler; import org.jboss.as.controller.OperationContext; import org.jboss.dmr.ModelNode; /** * Remove the JDR subsystem. * * @author Brian Stansberry */ public class JdrReportSubsystemRemove extends AbstractRemoveStepHandler { static final JdrReportSubsystemRemove INSTANCE = new JdrReportSubsystemRemove(); @Override protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) { context.removeService(JDR_CAPABILITY.getCapabilityServiceName()); } @Override protected boolean requiresRuntime(OperationContext context) { return context.getProcessType().isServer(); } }
1,831
36.387755
99
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/JdrRunner.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.jdr; import org.jboss.as.cli.CommandContext; import org.jboss.as.cli.scriptsupport.CLI; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.jdr.commands.JdrCommand; import org.jboss.as.jdr.commands.JdrEnvironment; import org.jboss.as.jdr.logger.JdrLogger; import org.jboss.as.jdr.plugins.JdrPlugin; import org.jboss.as.jdr.util.JdrZipFile; import org.jboss.dmr.ModelNode; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.jboss.as.cli.CommandContextFactory; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.*; import static org.jboss.as.jdr.logger.JdrLogger.ROOT_LOGGER; public class JdrRunner implements JdrReportCollector { JdrEnvironment env = new JdrEnvironment(); CommandContext ctx; public JdrRunner(boolean serverRunning) { this.env.setServerRunning(serverRunning); } public JdrRunner(CLI cli, String protocol, String host, int port, String user, String pass) { this.env.setServerRunning(false); this.env.setUsername(user); this.env.setPassword(pass); this.env.setHost(cli.getCommandContext().getControllerHost()); this.env.setPort("" + cli.getCommandContext().getControllerPort()); this.env.setCli(cli); try { ctx = CommandContextFactory.getInstance().newCommandContext(constructUri(protocol, host, port), user, pass == null ? new char[0] : pass.toCharArray()); ctx.connectController(); this.env.setClient(ctx.getModelControllerClient()); } catch (Exception e) { ctx.terminateSession(); // the server isn't available, carry on } } @Override public JdrReport collect() throws OperationFailedException { this.env.setProductName(obtainProductName()); this.env.setProductVersion(obtainProductVersion()); try { this.env.setZip(new JdrZipFile(new JdrEnvironment(this.env))); } catch (Exception e) { ROOT_LOGGER.error(ROOT_LOGGER.couldNotCreateZipfile(), e); throw new OperationFailedException(JdrLogger.ROOT_LOGGER.couldNotCreateZipfile()); } List<JdrCommand> commands = new ArrayList<JdrCommand>(); ByteArrayOutputStream versionStream = new ByteArrayOutputStream(); PrintWriter versionWriter = new PrintWriter(new OutputStreamWriter(versionStream, StandardCharsets.UTF_8)); versionWriter.println("JDR: " + JdrReportSubsystemSchema.CURRENT.getNamespace().getUri()); try { InputStream is = this.getClass().getClassLoader().getResourceAsStream("plugins.properties"); Properties plugins = new Properties(); plugins.load(is); for (String pluginName : plugins.stringPropertyNames()) { Class<?> pluginClass = Class.forName(pluginName); JdrPlugin plugin = (JdrPlugin) pluginClass.newInstance(); commands.addAll(plugin.getCommands()); versionWriter.println(plugin.getPluginId()); } versionWriter.close(); this.env.getZip().add(new ByteArrayInputStream(versionStream.toByteArray()), "version.txt"); this.env.getZip().add(new ByteArrayInputStream(this.env.getZip().getProductDirName().getBytes(StandardCharsets.UTF_8)), "product.txt"); } catch (Exception e) { ROOT_LOGGER.error(ROOT_LOGGER.couldNotConfigureJDR(), e); throw new OperationFailedException(ROOT_LOGGER.couldNotConfigureJDR()); } if (commands.isEmpty()) { ROOT_LOGGER.error(JdrLogger.ROOT_LOGGER.noCommandsToRun()); throw new OperationFailedException(JdrLogger.ROOT_LOGGER.noCommandsToRun()); } JdrReport report = new JdrReport(); StringBuilder skips = new StringBuilder(); report.setStartTime(); report.setJdrUuid(obtainServerUUID()); for (JdrCommand command : commands) { command.setEnvironment(new JdrEnvironment(this.env)); try { command.execute(); } catch (Throwable t) { String message = "Skipping command " + command.toString(); ROOT_LOGGER.debugf(message); skips.append(message); PrintWriter pw = new PrintWriter(new StringWriter()); t.printStackTrace(pw); skips.append(pw.toString()); pw.close(); } } try { this.env.getZip().addLog(skips.toString(), "skips.log"); } catch (Exception e) { ROOT_LOGGER.debugf(e, "Could not add skipped commands log to jdr zip file."); } try { this.env.getZip().close(); } catch (Exception e) { ROOT_LOGGER.debugf(e, "Could not close zip file."); } report.setEndTime(); report.setLocation(this.env.getZip().name()); try { ctx.terminateSession(); } catch (Exception e) { // idk } return report; } public void setJbossHomeDir(String dir) { this.env.setJbossHome(dir); } public void setReportLocationDir(String dir) { this.env.setOutputDirectory(dir); } public void setControllerClient(ModelControllerClient client) { this.env.setClient(client); } public void setHostControllerName(String name) { this.env.setHostControllerName(name); } public void setServerName(String name) { this.env.setServerName(name); } private String obtainServerUUID() throws OperationFailedException { try { ModelNode operation = Operations.createReadAttributeOperation(new ModelNode().setEmptyList(), UUID); operation.get(INCLUDE_RUNTIME).set(true); ModelControllerClient client = env.getClient(); if (client == null) { client = env.getCli().getCommandContext().getModelControllerClient(); } ModelNode result = client.execute(operation); if (Operations.isSuccessfulOutcome(result)) { return Operations.readResult(result).asString(); } return null; } catch (IOException ex) { return null; } } private String constructUri(final String protocol, final String host, final int port) throws URISyntaxException { URI uri = new URI(protocol, null, host, port, null, null, null); // String the leading '//' if there is no protocol. return protocol == null ? uri.toString().substring(2) : uri.toString(); } private String obtainProductName() { try { ModelNode operation = Operations.createReadAttributeOperation(new ModelNode().setEmptyList(), PRODUCT_NAME); operation.get(INCLUDE_RUNTIME).set(false); ModelControllerClient client = env.getClient(); if (client == null) { client = env.getCli().getCommandContext().getModelControllerClient(); } ModelNode result = client.execute(operation); if (Operations.isSuccessfulOutcome(result)) { return Operations.readResult(result).asString(); } return "undefined"; } catch (IOException e) { // This should not be needed since a product name is always returned, even if it doesn't exist. // In that case "undefined" is returned return "undefined"; } } private String obtainProductVersion() { try { ModelNode operation = Operations.createReadAttributeOperation(new ModelNode().setEmptyList(), PRODUCT_VERSION); operation.get(INCLUDE_RUNTIME).set(false); ModelControllerClient client = env.getClient(); if (client == null) { client = env.getCli().getCommandContext().getModelControllerClient(); } ModelNode result = client.execute(operation); if (Operations.isSuccessfulOutcome(result)) { return Operations.readResult(result).asString(); } return "undefined"; } catch (IOException e) { // This should not be needed since a product version is always returned, even if it doesn't exist. // In that case "undefined" is returned return "undefined"; } } }
10,000
37.763566
163
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/JdrReportCollector.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.jdr; import org.jboss.as.controller.OperationFailedException; /** * Used to create a JBoss Diagnostic Report (JDR). * * @author Brian Stansberry * @author Mike M. Clark */ public interface JdrReportCollector { /** * Create a JDR report. * * @return information about the generated report. */ JdrReport collect() throws OperationFailedException; }
1,427
33.829268
70
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/plugins/JdrPlugin.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.jdr.plugins; import org.jboss.as.jdr.commands.JdrCommand; import java.util.List; public interface JdrPlugin { List<JdrCommand> getCommands() throws Exception; PluginId getPluginId(); }
1,241
36.636364
70
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/plugins/AS7Plugin.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.jdr.plugins; import java.util.Arrays; import java.util.List; import org.jboss.as.jdr.commands.CallAS7; import org.jboss.as.jdr.commands.CollectFiles; import org.jboss.as.jdr.commands.DeploymentDependencies; import org.jboss.as.jdr.commands.JarCheck; import org.jboss.as.jdr.commands.JdrCommand; import org.jboss.as.jdr.commands.LocalModuleDependencies; import org.jboss.as.jdr.commands.SystemProperties; import org.jboss.as.jdr.commands.TreeCommand; import org.jboss.as.jdr.util.Sanitizer; import org.jboss.as.jdr.util.Sanitizers; import org.jboss.as.jdr.util.Utils; public class AS7Plugin implements JdrPlugin { private final PluginId pluginId = new PluginId("AS7_PLUGIN", 1, 0, null); @Override public List<JdrCommand> getCommands() throws Exception { Sanitizer xmlSanitizer = Sanitizers.xml("//password"); Sanitizer passwordSanitizer = Sanitizers.pattern("password=.*", "password=*"); Sanitizer systemPropertiesPasswordSanitizer = Sanitizers.pattern("([^=]*password[^=]*)=.*", "$1=*"); return Arrays.asList( new TreeCommand(), new JarCheck(), new CallAS7("configuration").param("recursive", "true"), new CallAS7("dump-services").operation("dump-services").resource("core-service", "service-container"), new CallAS7("cluster-proxies-configuration").resource("subsystem", "modcluster"), new CallAS7("jndi-view").operation("jndi-view").resource("subsystem", "naming"), new CollectFiles("*/standalone/configuration/*").sanitizer(xmlSanitizer, passwordSanitizer), new CollectFiles("*/domain/configuration/*").sanitizer(xmlSanitizer, passwordSanitizer), new CollectFiles("*server.log").limit(50 * Utils.ONE_MB), new CollectFiles("*.log").omit("*server.log"), new CollectFiles("*gc.log.*"), new CollectFiles("*.properties").sanitizer(passwordSanitizer), new CollectFiles("*.xml").sanitizer(xmlSanitizer), new CollectFiles("*/modules/system/*/.overlays/.overlays"), new CollectFiles("*/.installation/*.conf"), new CollectFiles("*/.installation/*.txt"), new SystemProperties().sanitizer(systemPropertiesPasswordSanitizer), new DeploymentDependencies(), new LocalModuleDependencies() ); } @Override public PluginId getPluginId() { return pluginId; } }
3,501
43.897436
114
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/plugins/PluginId.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.jdr.plugins; /** * @author [email protected] * Date: 11/9/12 */ public final class PluginId implements Comparable<PluginId> { final String name; final int major; final int minor; final String release; final String idString; public PluginId(String name, int major, int minor, String release) { this.name = name; this.major = major; this.minor = minor; this.release = release; StringBuffer sb = new StringBuffer(name).append(": ") .append(major).append('.') .append(minor); if (null != release) { sb.append('-').append(release); } idString = sb.toString(); } public String getName() { return name; } public int getMajor() { return major; } public int getMinor() { return minor; } public String getRelease() { return release; } @Override public String toString() { return idString; } @Override public int compareTo(PluginId o) { int result = name.compareTo(o.name); if (result != 0) { return result; } result = major - o.major; if (result != 0) { return result; } result = minor - o.minor; if (result != 0) { return result; } if (null != release) { return release.compareTo(o.release); } return result; } }
2,485
27.574713
72
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/util/FSTree.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.jdr.util; import org.jboss.vfs.VFS; import org.jboss.vfs.VirtualFile; import java.util.List; public class FSTree { int directoryCount = 0; int fileCount = 0; StringBuilder buf = new StringBuilder(); String topDirectory = null; String fmt = "%s%s%s %s"; public FSTree(String root) throws Exception { this.traverse(root, "", true); } private static double div(long left, long right) { return (double)left / (double)right; } private static String formatBytes(long size) { if (size > Utils.ONE_TB) { return String.format("%.1fT", div(size, Utils.ONE_TB)); } else if (size > Utils.ONE_GB) { return String.format("%.1fG", div(size, Utils.ONE_GB)); } else if (size > Utils.ONE_MB) { return String.format("%.1fM", div(size, Utils.ONE_MB)); } else if (size > Utils.ONE_KB) { return String.format("%.1fK", div(size, Utils.ONE_KB)); } else { return String.format("%d", size); } } private void traverse(String dir, String padding) throws java.io.IOException { traverse(dir, padding, false); } private void append(VirtualFile f, String padding) { String baseName = f.getName(); String size = formatBytes(f.getSize()); buf.append(String.format(fmt, padding, "+-- ", size, baseName)); buf.append("\n"); } private void traverse(String dir, String padding, boolean first) throws java.io.IOException { VirtualFile path = VFS.getChild(dir); if (!first) { String _p = padding.substring(0, padding.length() -1); append(path, _p); padding += " "; } else { buf.append(path.getName()); buf.append("\n"); } int count = 0; List<VirtualFile> files = path.getChildren(); for (VirtualFile f : files ) { count += 1; if (f.getPathName().startsWith(".")) { continue; } else if (f.isFile()) { append(f, padding); } else if (Utils.isSymlink(f)) { buf.append(padding); buf.append("+-- "); buf.append(f.getName()); buf.append(" -> "); buf.append(f.getPathName()); buf.append("\n"); } else if (f.isDirectory()) { if (count == files.size()) { traverse(f.getPathName(), padding + " "); } else { traverse(f.getPathName(), padding + "|"); } } } } public String toString() { return buf.toString(); } }
3,848
31.618644
82
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/util/Utils.java
package org.jboss.as.jdr.util; import org.jboss.vfs.VirtualFile; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.jar.JarFile; /** * User: csams * Date: 11/4/12 * Time: 3:40 PM */ public final class Utils { public static void safeClose(JarFile jf){ try{ if(jf != null) { jf.close(); } }catch(Exception e){ } } public static void safelyClose(InputStream is){ try{ if(is != null) { is.close(); } }catch(Exception e){ } } public static List<String> readLines(InputStream input) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(input,StandardCharsets.UTF_8)); List<String> result = new ArrayList<String>(); String line = reader.readLine(); while(line != null){ result.add(line); line = reader.readLine(); } return result; } public static String toString(VirtualFile r) throws IOException { return new String(toBytes(r), StandardCharsets.UTF_8); } public static byte[] toBytes(VirtualFile r) throws IOException { try(InputStream is = r.openStream()) { return toByteArray(is); } } /** * Reads the content of an {@code InputStream} as {@code byte[]}. * This does not close the InputStream * * @param is the input stream * @return the byte array read from the input stream * @throws IOException if an I/O error occurs */ static byte[] toByteArray(InputStream is) throws IOException { byte [] buffer = new byte[1024]; try(ByteArrayOutputStream os = new ByteArrayOutputStream()) { int bytesRead = is.read(buffer); while( bytesRead > -1 ) { os.write(buffer, 0, bytesRead); bytesRead = is.read(buffer); } return os.toByteArray(); } } /** * Ensure InputStream actually skips ahead the required number of bytes * @param is * @param amount * @throws IOException */ public static void skip(InputStream is, long amount) throws IOException { long leftToSkip = amount; long amountSkipped = 0; while(leftToSkip > 0 && amountSkipped >= 0){ amountSkipped = is.skip(leftToSkip); leftToSkip -= amountSkipped; } } public static boolean isSymlink(VirtualFile vFile) throws IOException { File file = vFile.getPhysicalFile(); if(Utils.isWindows()){ return false; } File fileInCanonicalDir = null; if (file.getParent() == null) { fileInCanonicalDir = file; } else { File canonicalDir = file.getParentFile().getCanonicalFile(); fileInCanonicalDir = new File(canonicalDir, file.getName()); } if (fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile())) { return false; } else { return true; } } public static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; public static final String LINE_SEP = String.format("%n"); public static final char WIN_SEP = '\\'; public static final char SYS_SEP = File.separatorChar; public static boolean isWindows() { return SYS_SEP == WIN_SEP; } public static final long ONE_KB = 1024; public static final long ONE_MB = ONE_KB * ONE_KB; public static final long ONE_GB = ONE_KB * ONE_MB; public static final long ONE_TB = ONE_KB * ONE_GB; }
3,910
26.34965
104
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/util/Sanitizer.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.jdr.util; import org.jboss.vfs.VirtualFile; import java.io.InputStream; public interface Sanitizer { InputStream sanitize(InputStream in) throws Exception; boolean accepts(VirtualFile resource); }
1,252
38.15625
70
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/util/JdrZipFile.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.jdr.util; import static org.jboss.as.jdr.logger.JdrLogger.ROOT_LOGGER; import java.io.ByteArrayInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.Date; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipOutputStream; import org.jboss.as.jdr.commands.JdrEnvironment; import org.jboss.vfs.VirtualFile; /** * Abstracts the zipfile used for packaging the JDR Report. */ public class JdrZipFile { ZipOutputStream zos; String jbossHome; JdrEnvironment env; String name; String baseName; String productDirName; public JdrZipFile(JdrEnvironment env) throws Exception { this.env = env; this.jbossHome = this.env.getJbossHome(); SimpleDateFormat fmt = new SimpleDateFormat("yy-MM-dd_hh-mm-ss"); baseName = "jdr_" + fmt.format(new Date()); if (this.env.getHostControllerName() != null) { this.baseName += "." + this.env.getHostControllerName(); } if (this.env.getServerName() != null) { this.baseName += "_" + this.env.getServerName(); } this.name = this.env.getOutputDirectory() + java.io.File.separator + baseName + ".zip"; zos = new ZipOutputStream(new FileOutputStream(this.name)); } /** * @return the full pathname to the zipfile on disk */ public String name() { return this.name; } /** * Adds the contents of the {@link InputStream} to the path in the zip. * * This method allows for absolute control of the destination of the content to be stored. * It is not common to use this method. * @param is content to write * @param path destination to write to in the zip file */ public void add(InputStream is, String path) { byte [] buffer = new byte[1024]; try { // WFLY-13728 - File Path Separators must be / for ZipEntry even on Windows String entryName = this.baseName + "/" + path.replace("\\","/"); ZipEntry ze = new ZipEntry(entryName); zos.putNextEntry(ze); int bytesRead = is.read(buffer); while( bytesRead > -1 ) { zos.write(buffer, 0, bytesRead); bytesRead = is.read(buffer); } } catch (ZipException ze) { ROOT_LOGGER.debugf(ze, "%s is already in the zip", path); } catch (Exception e) { ROOT_LOGGER.debugf(e, "Error when adding %s", path); } finally { try { zos.closeEntry(); } catch (Exception e) { ROOT_LOGGER.debugf(e, "Error when closing entry for %s", path); } } } /** * Adds the content of the {@link InputStream} to the zip in a location that mirrors where {@link VirtualFile file} is located. * * For example if {@code file} is at {@code /tmp/foo/bar} and {@code $JBOSS_HOME} is {@code tmp} then the destination will be {@code JBOSSHOME/foo/bar} * * @param file {@link VirtualFile} where metadata is read from * @param is content to write to the zip file * @throws Exception */ public void add(VirtualFile file, InputStream is) throws Exception { String name = "JBOSS_HOME" + file.getPhysicalFile().getAbsolutePath().substring(this.jbossHome.length()); this.add(is, name); } /** * Adds content to the zipfile at path * * path is prepended with the directory reserved for generated text files in JDR * * @param content * @param path * @throws Exception */ public void add(String content, String path) throws Exception { StringBuilder name = new StringBuilder("sos_strings/"); name.append(getProductDirName()); name.append("/"); name.append(path); this.add(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)), name.toString()); } /** * Adds content to the zipfile at path * * path is prepended with the directory reserved for generated text files in JDR * * @param stream * @param path * @throws Exception */ public void addAsString(InputStream stream, String path) throws Exception { StringBuilder name = new StringBuilder("sos_strings/"); name.append(getProductDirName()); name.append("/"); name.append(path); this.add(stream, name.toString()); } public String getProductDirName() { if(this.productDirName == null) this.productDirName = String.format("%s-%s", this.env.getProductName().replace(" ", "_").toLowerCase(), this.env.getProductVersion().split("\\.")[0]); return this.productDirName; } /** * Adds content to the zipfile in a file named logName * * path is prepended with the directory reserved for JDR log files * * @param content * @param logName * @throws Exception */ public void addLog(String content, String logName) throws Exception { String name = "sos_logs/" + logName; this.add(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)), name); } public void close() throws Exception { this.zos.close(); } }
6,496
32.663212
162
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/util/PatternSanitizer.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.jdr.util; import org.jboss.vfs.VirtualFileFilter; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.PrintWriter; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * {@link Sanitizer} subclass that replaces all instance of {@code pattern} with * the {@code replacement} text. */ public class PatternSanitizer extends AbstractSanitizer { private final Pattern pattern; private final String replacement; public PatternSanitizer(String pattern, String replacement, VirtualFileFilter filter) throws Exception { this.pattern = Pattern.compile(pattern); this.replacement = replacement; this.filter = filter; } public InputStream sanitize(InputStream in) throws Exception { ByteArrayOutputStream output = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(output); String[] lines = Utils.readLines(in).toArray(new String[0]); int lineCount = lines.length; for(int i = 0; i < lineCount; i++) { Matcher matcher = pattern.matcher(lines[i]); writer.write(matcher.replaceAll(replacement)); if(i < (lineCount-1)){ writer.write(Utils.LINE_SEP); } } writer.close(); return new ByteArrayInputStream(output.toByteArray()); } }
2,439
37.125
108
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/util/AbstractSanitizer.java
package org.jboss.as.jdr.util; import org.jboss.as.jdr.vfs.Filters; import org.jboss.vfs.VirtualFile; import org.jboss.vfs.VirtualFileFilter; import java.io.InputStream; /** * Provides a default implementation of {@link Sanitizer} that uses default * filtering. Sanitizers should subclass this unless they wish to use complex * accepts filtering. */ abstract class AbstractSanitizer implements Sanitizer { protected VirtualFileFilter filter = Filters.TRUE; @Override public abstract InputStream sanitize(InputStream in) throws Exception; /** * returns whether or not a VirtualFile should be processed by this sanitizer. * * @param resource {@link VirtualFile} resource to test * @return */ @Override public boolean accepts(VirtualFile resource) { return filter.accepts(resource); } }
856
24.969697
82
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/util/WildcardPattern.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.jdr.util; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * Simple wildcard matcher for * * @author [email protected] * Date: 11/6/12 */ public class WildcardPattern { private static final String WILDCARDS = "*"; private final String[] tokens; public WildcardPattern(String pattern){ if (!pattern.startsWith("*")) { pattern = "*" + pattern; } StringTokenizer st = new StringTokenizer(pattern, WILDCARDS, true); List<String> t = new ArrayList<String>(); while(st.hasMoreTokens()){ t.add(st.nextToken()); } tokens = t.toArray(new String[t.size()]); } public boolean matches(final String target){ int targetIdx = 0; int targetEnd = target.length(); int tokenIdx = 0; int tokenEnd = tokens.length; while(tokenIdx < tokenEnd && targetIdx < targetEnd && targetIdx > -1){ if("*".equals(tokens[tokenIdx])){ if(tokenIdx == (tokenEnd - 1)){ targetIdx = targetEnd; tokenIdx = tokenEnd; } else { targetIdx = target.indexOf(tokens[tokenIdx+1], targetIdx); tokenIdx++; } } else{ if(target.substring(targetIdx).startsWith(tokens[tokenIdx])){ targetIdx += tokens[tokenIdx].length(); tokenIdx++; } else { targetIdx = -1; break; } } } return (tokenIdx == tokenEnd && targetIdx == targetEnd); } public static boolean matches(final String pattern, final String target) { return new WildcardPattern(pattern).matches(target); } }
2,896
31.920455
78
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/util/XMLSanitizer.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.jdr.util; import static org.jboss.as.jdr.logger.JdrLogger.ROOT_LOGGER; import static javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.jboss.vfs.VirtualFileFilter; import org.wildfly.common.xml.DocumentBuilderFactoryUtil; import org.wildfly.common.xml.TransformerFactoryUtil; import org.w3c.dom.Document; import org.w3c.dom.NodeList; /** * {@link Sanitizer} subclass that removes the contents of the matched xpath expression * in {@code pattern}. */ public class XMLSanitizer extends AbstractSanitizer { private XPathExpression expression; private DocumentBuilder builder; private Transformer transformer; public XMLSanitizer(String pattern, VirtualFileFilter filter) throws Exception { this.filter = filter; XPathFactory factory = XPathFactory.newInstance(); factory.setFeature(FEATURE_SECURE_PROCESSING, true); XPath xpath = factory.newXPath(); expression = xpath.compile(pattern); DocumentBuilderFactory DBfactory = DocumentBuilderFactoryUtil.create(); DBfactory.setNamespaceAware(true); builder = DBfactory.newDocumentBuilder(); builder.setErrorHandler(null); TransformerFactory transformerFactory = TransformerFactoryUtil.create(); transformer = transformerFactory.newTransformer(); } public InputStream sanitize(InputStream in) throws Exception { byte [] content = Utils.toByteArray(in); try { // storing the entire file in memory in case we need to bail. Document doc = builder.parse(new ByteArrayInputStream(content)); doc.setXmlStandalone(true); Object result = expression.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { nodes.item(i).setTextContent(""); } DOMSource source = new DOMSource(doc); ByteArrayOutputStream output = new ByteArrayOutputStream(); StreamResult outStream = new StreamResult(output); transformer.transform(source, outStream); return new ByteArrayInputStream(output.toByteArray()); } catch (Exception e) { ROOT_LOGGER.debug("Error while sanitizing an xml document", e); return new ByteArrayInputStream(content); } } }
3,939
40.041667
87
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/util/Sanitizers.java
package org.jboss.as.jdr.util; import org.jboss.as.jdr.vfs.Filters; /** * Provides the most commonly used sanitizers with their most common configurations. */ public class Sanitizers { /** * creates and returns a {@link Sanitizer} instance that only operates on * files that end with a {@code .properties} suffix. * * @param pattern {@link WildcardPattern} compatible pattern to search for * @param replacement text content to replace matches with * @return {@link Sanitizer} that only operates on files with names ending with {@code .properties}. * @throws Exception */ public static Sanitizer pattern(String pattern, String replacement) throws Exception { return new PatternSanitizer(pattern, replacement, Filters.suffix(".properties")); } /** * creates and returns a {@link Sanitizer} instance that only operates on * files that end with a {@code .xml} suffix. * * @param xpath to search for and nullify * @return a {@link Sanitizer} instance that only operates on files that end with a {@code .xml} suffix. * @throws Exception */ public static Sanitizer xml(String xpath) throws Exception { return new XMLSanitizer(xpath, Filters.suffix(".xml")); } }
1,276
35.485714
108
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/logger/JdrLogger.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.jdr.logger; import java.io.IOException; import java.nio.file.Path; import org.jboss.logging.BasicLogger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; import static org.jboss.logging.Logger.Level.*; /** * JBoss Diagnostic Reporter (JDR) logger. * * @author Mike M. Clark * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ @MessageLogger(projectCode = "WFLYJDR", length = 4) public interface JdrLogger extends BasicLogger { /** * A logger with the category of the default jdr package. */ JdrLogger ROOT_LOGGER = Logger.getMessageLogger(JdrLogger.class, "org.jboss.as.jdr"); // /** // * Indicates that a JDR report has been initiated. // */ // @LogMessage(level = INFO) // @Message(id = 1, value = "Starting creation of a JBoss Diagnostic Report (JDR).") // void startingCollection(); // // /** // * Indicates that a JDR report has completed // */ // @LogMessage(level = INFO) // @Message(id = 2, value = "Completed creation of a JBoss Diagnostic Report (JDR).") // void endingCollection(); // // /** // * Indicates that the JBoss home directory was not set. // */ // @LogMessage(level = ERROR) // @Message(id = 3, value = "Unable to create JDR report, JBoss Home directory cannot be determined.") // void jbossHomeNotSet(); // // /** // * The sosreport python library threw an exception // */ // @LogMessage(level = WARN) // @Message(id = 4, value = "JDR python interpreter encountered an exception.") // void pythonExceptionEncountered(@Cause Throwable cause); // // /** // * JDR was unable to decode a path URL for standardization across platforms. // */ // @LogMessage(level = WARN) // @Message(id = 5, value = "Unable to decode a url while creating JDR report.") // void urlDecodeExceptionEncountered(@Cause Throwable cause); // // /** // * JDR plugin location is not a directory as expected. // */ // @LogMessage(level = WARN) // @Message(id = 6, value = "Plugin contrib location is not a directory. Ignoring.") // void contribNotADirectory(); /** * JDR could not create a zipfile to store the report. */ @Message(id = 7, value="Could not create zipfile.") String couldNotCreateZipfile(); /** * One of the configuration steps in JDR threw an exception. */ @Message(id = 8, value="Could not configure JDR. At least one configuration step failed.") String couldNotConfigureJDR(); /** * No Commands to run, probably no valid plugin loaded */ @Message(id = 9, value = "No JDR commands were loaded. Be sure that a valid Plugin class is specified in plugins.properties.") String noCommandsToRun(); // /** // * Indicates an invalid, <code>null</code> argument was // * passed into a method. // * // * @param var method variable that was <code>null</code> // * @return Exception describing the invalid parameter. // */ // @Message(id = 10, value = "Parameter %s may not be null.") // IllegalArgumentException varNull(String var); /** * Standalone property directory could not be located which is needed to find/create the JDR properties file. */ @LogMessage(level = ERROR) @Message(id = 11, value = "Could not find JDR properties file.") void couldNotFindJDRPropertiesFile(); @LogMessage(level = ERROR) @Message(id = 12, value = "Could not create JDR properties file at %s") void couldNotCreateJDRPropertiesFile(@Cause IOException ioex, Path path); @Message(id = Message.NONE, value = "Display this message and exit") String jdrHelpMessage(); @Message(id = Message.NONE, value = "hostname that the management api is bound to. (default: localhost)") String jdrHostnameMessage(); @Message(id = Message.NONE, value = "port that the management api is bound to. (default: 9990)") String jdrPortMessage(); @Message(id = Message.NONE, value = "Protocol that is used to connect. Can be remote, http or https (default: http)") String jdrProtocolMessage(); @Message(id = Message.NONE, value = "Configuration file of the server if it is not running.") String jdrConfigMessage(); @Message(id = Message.NONE, value = "JBoss Diagnostic Reporter (JDR) is a subsystem built to collect information to aid in troubleshooting. The jdr script is a utility for generating JDR reports.") String jdrDescriptionMessage(); }
5,685
37.418919
201
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/commands/CallAS7.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.jdr.commands; import java.util.Map; import java.util.HashMap; import java.util.LinkedList; import org.jboss.dmr.ModelNode; /** * <p> * Command to call the AS 7 management system and store the output in a file. *</p> * <p> * This class' methods are meant to be chained together to describe a management call. For example: *</p> * <pre> * new CallAS7("my_file").resource("foo", "bar").operation("read-resource") *</pre> * * <p> * will return a configured CallAS7 instance that will, when executed call {@code read-resource} * on the {@code /foo=bar/} resource, and store the output in a file called {@code my_file.json}. * </p> */ public class CallAS7 extends JdrCommand { private String operation = "read-resource"; private LinkedList<String> resource = new LinkedList<String>(); private Map<String, String> parameters = new HashMap<String, String>(); private String name; /** * constructs an instance and sets the resulting file name * * @param name of the file to write results to */ public CallAS7(String name) { this.name = name + ".json"; } /** * sets the operation to call * * @param operation to call, defaults to {@code read-resource} * @return this */ public CallAS7 operation(String operation) { this.operation = operation; return this; } /** * adds a key/value parameter pair to the call * * @param key * @param val * @return this */ public CallAS7 param(String key, String val) { this.parameters.put(key, val); return this; } /** * appends resource parts to the resource to call * <p></p> * If you want to call /foo=bar/baz=boo/, do this: * <pre> * .resource("foo", "bar", "baz", "boo") * </pre> * * @param parts to call * @return this */ public CallAS7 resource(String... parts) { for(String part : parts ) { this.resource.add(part); } return this; } @Override public void execute() throws Exception { ModelNode request = new ModelNode(); request.get("operation").set(this.operation); assert this.resource.size() % 2 == 0; while (!this.resource.isEmpty()) { request.get("address").add(this.resource.removeFirst(), this.resource.removeFirst()); } for (Map.Entry<String, String> entry : parameters.entrySet()) { request.get(entry.getKey()).set(entry.getValue()); } if (this.env.getHostControllerName() != null) { request.get("host").set(this.env.getHostControllerName()); } if (this.env.getServerName() != null) { request.get("server").set(this.env.getServerName()); } this.env.getZip().add(this.env.getClient().execute(request).toJSONString(true), this.name); } }
3,989
29.930233
99
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/commands/JdrCommand.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.jdr.commands; /** * Abstract class that should be subclassed by JDR Commands. * * The purpose of this class is to standardize the method by which the * JdrEnvironment is shared with Commands. */ public abstract class JdrCommand { JdrEnvironment env; public void setEnvironment(JdrEnvironment env) { this.env = env; } /** * executes the command * {@link org.jboss.as.jdr.plugins.JdrPlugin} implementations do not need to call this method. * @throws Exception */ public abstract void execute() throws Exception; }
1,612
35.659091
98
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/commands/LocalModuleDependencies.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.jdr.commands; import java.lang.management.ManagementFactory; import javax.management.ObjectName; import javax.management.MBeanServer; /** * Call MBean method dumpAllModuleInformation to get module information for local modules * * @author Brad Maxwell */ public class LocalModuleDependencies extends JdrCommand { private static String OUTPUT_FILE = "local-module-dependencies.txt"; @Override public void execute() throws Exception { if(!this.env.isServerRunning()) return; StringBuilder buffer = new StringBuilder(); MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer(); // see if we can get rid of the -* number // jboss.modules:type=ModuleLoader,name=LocalModuleLoader-2 - String dumpAllModuleInformation // jboss.modules:type=ModuleLoader,name=ServiceModuleLoader-3 - String dumpAllModuleInformation ObjectName base = new ObjectName("jboss.modules:type=ModuleLoader,name=LocalModuleLoader-*"); for(ObjectName localModuleLoader : platformMBeanServer.queryNames(base, null)) { buffer.append( (String) platformMBeanServer.invoke(localModuleLoader, "dumpAllModuleInformation", null, null) ); } this.env.getZip().add(buffer.toString(), OUTPUT_FILE); } }
2,353
40.298246
124
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/commands/SystemProperties.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.jdr.commands; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.Enumeration; import java.util.LinkedList; import java.util.Properties; import org.jboss.as.jdr.util.Sanitizer; import org.jboss.as.jdr.util.Utils; /** * Add the JVM System properties to the JDR report * * @author Brad Maxwell */ public class SystemProperties extends JdrCommand { private LinkedList<Sanitizer> sanitizers = new LinkedList<Sanitizer>(); public SystemProperties sanitizer(Sanitizer ... sanitizers) { for (Sanitizer s : sanitizers) { this.sanitizers.add(s); } return this; } @Override public void execute() throws Exception { if(!this.env.isServerRunning()) return; StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); Properties properties = System.getProperties(); Enumeration<?> names = properties.propertyNames(); while(names.hasMoreElements()) { String name = (String) names.nextElement(); printWriter.println(name + "=" + properties.getProperty(name)); } InputStream stream = new ByteArrayInputStream(stringWriter.toString().getBytes(StandardCharsets.UTF_8)); for (Sanitizer sanitizer : this.sanitizers) { stream = sanitizer.sanitize(stream); } this.env.getZip().addAsString(stream, "system-properties.txt"); Utils.safelyClose(stream); } }
2,667
34.573333
112
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/commands/TreeCommand.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.jdr.commands; import org.jboss.as.jdr.util.FSTree; public class TreeCommand extends JdrCommand { @Override public void execute() throws Exception { FSTree tree = new FSTree(this.env.getJbossHome()); this.env.getZip().add(tree.toString(), "tree.txt"); } }
1,330
38.147059
70
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/commands/CollectFiles.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.jdr.commands; import org.jboss.as.jdr.util.Utils; import org.jboss.as.jdr.util.Sanitizer; import org.jboss.as.jdr.vfs.Filters; import org.jboss.vfs.VFS; import org.jboss.vfs.VirtualFile; import org.jboss.vfs.VirtualFileFilter; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class CollectFiles extends JdrCommand { private VirtualFileFilter filter = Filters.TRUE; private Filters.BlocklistFilter blocklistFilter = Filters.wildcardBlockList(); private LinkedList<Sanitizer> sanitizers = new LinkedList<Sanitizer>(); private Comparator<VirtualFile> sorter = new Comparator<VirtualFile>() { @Override public int compare(VirtualFile resource, VirtualFile resource1) { return Long.signum(resource.getLastModified() - resource1.getLastModified()); } }; // -1 means no limit private long limit = -1; public CollectFiles(VirtualFileFilter filter) { this.filter = filter; } public CollectFiles(String pattern) { this.filter = Filters.wildcard(pattern); } public CollectFiles sanitizer(Sanitizer ... sanitizers) { for (Sanitizer s : sanitizers) { this.sanitizers.add(s); } return this; } public CollectFiles sorter(Comparator<VirtualFile> sorter){ this.sorter = sorter; return this; } public CollectFiles limit(final long limit){ this.limit = limit; return this; } public CollectFiles omit(String pattern) { blocklistFilter.add(pattern); return this; } @Override public void execute() throws Exception { VirtualFile root = VFS.getChild(this.env.getJbossHome()); List<VirtualFile> matches = root.getChildrenRecursively(Filters.and(this.filter, this.blocklistFilter)); // order the files in some arbitrary way.. basically prep for the limiter so things like log files can // be gotten in chronological order. Keep in mind everything that might be collected per the filter for // this collector. If the filter is too broad, you may collect unrelated logs, sort them, and then // get some limit on that set, which probably would be wrong. if(sorter != null){ Collections.sort(matches, sorter); } // limit how much data we collect Limiter limiter = new Limiter(limit); Iterator<VirtualFile> iter = matches.iterator(); while(iter.hasNext() && !limiter.isDone()) { VirtualFile f = iter.next(); try (InputStream stream = limiter.limit(f)) { InputStream modifiedStream = stream; for (Sanitizer sanitizer : this.sanitizers) { if (sanitizer.accepts(f)) { modifiedStream = sanitizer.sanitize(modifiedStream); } } this.env.getZip().add(f, modifiedStream); } } } /** * A Limiter is constructed with a number, and it can be repeatedly given VirtualFiles for which it will return an * InputStream that possibly is adjusted so that the number of bytes the stream can provide, when added to what the * Limiter already has seen, won't be more than the limit. * * If the VirtualFiles's size minus the amount already seen by the Limiter is smaller than the limit, the * VirtualFiles's InputStream is simply returned and its size added to the number of bytes the Limiter has seen. * Otherwise, the VirtualFiles's InputStream is skipped ahead so that the total number of bytes it will provide * before exhaustion will make the total amount seen by the Limiter equal to its limit. */ private static class Limiter { private long amountRead = 0; private long limit = -1; private boolean done = false; public Limiter(long limit){ this.limit = limit; } public boolean isDone(){ return done; } /** * @return * @throws IOException */ public InputStream limit(VirtualFile resource) throws IOException { InputStream is = resource.openStream(); long resourceSize = resource.getSize(); // if we're limiting and know we're not going to consume the whole file, we skip // ahead so that we get the tail of the file instead of the beginning of it, and we // toggle the done switch. if(limit != -1){ long leftToRead = limit - amountRead; if(leftToRead < resourceSize){ Utils.skip(is, resourceSize - leftToRead); done = true; } else { amountRead += resourceSize; } } return is; } } }
6,071
34.928994
119
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/commands/DeploymentDependencies.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.jdr.commands; import java.lang.management.ManagementFactory; import javax.management.ObjectName; import javax.management.MBeanServer; /** * Call MBean method dumpAllModuleInformation to get module information for deployments * * @author Brad Maxwell */ public class DeploymentDependencies extends JdrCommand { private static String OUTPUT_FILE = "deployment-dependencies.txt"; @Override public void execute() throws Exception { if(!this.env.isServerRunning()) return; StringBuilder buffer = new StringBuilder(); MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer(); // see if we can get rid of the -* number // jboss.modules:type=ModuleLoader,name=LocalModuleLoader-2 - String dumpAllModuleInformation // jboss.modules:type=ModuleLoader,name=ServiceModuleLoader-3 - String dumpAllModuleInformation ObjectName base = new ObjectName("jboss.modules:type=ModuleLoader,name=ServiceModuleLoader-*"); for(ObjectName serviceModuleLoader : platformMBeanServer.queryNames(base, null)) { buffer.append( (String) platformMBeanServer.invoke(serviceModuleLoader, "dumpAllModuleInformation", null, null) ); } this.env.getZip().add(buffer.toString(), OUTPUT_FILE); } }
2,354
40.315789
126
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/commands/JarCheck.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.jdr.commands; import org.jboss.as.jdr.util.Utils; import org.jboss.vfs.VFS; import org.jboss.vfs.VirtualFile; import org.jboss.vfs.util.automount.Automounter; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import static org.jboss.as.jdr.logger.JdrLogger.ROOT_LOGGER; public class JarCheck extends JdrCommand { StringBuilder buffer; @Override public void execute() throws Exception { this.buffer = new StringBuilder(); walk(VFS.getChild(this.env.getJbossHome())); this.env.getZip().add(this.buffer.toString(), "jarcheck.txt"); } private void walk(VirtualFile root) throws NoSuchAlgorithmException { for(VirtualFile f : root.getChildren()) { if(f.isDirectory()) { walk(f); } else { check(f); } } } private void check(VirtualFile f) throws NoSuchAlgorithmException { try { MessageDigest alg = MessageDigest.getInstance("md5"); byte [] buffer = Utils.toBytes(f); alg.update(buffer); String sum = new BigInteger(1, alg.digest()).toString(16); this.buffer.append( f.getPathName().replace(this.env.getJbossHome(), "JBOSSHOME") + "\n" + sum + "\n" + getManifestString(f) + "==="); } catch( java.util.zip.ZipException ze ) { // skip } catch( java.io.FileNotFoundException fnfe ) { ROOT_LOGGER.debug(fnfe); } catch( java.io.IOException ioe ) { ROOT_LOGGER.debug(ioe); } } private String getManifestString(VirtualFile file) throws java.io.IOException { try { Automounter.mount(file); String result = Utils.toString(file.getChild(Utils.MANIFEST_NAME)); return result != null? result: ""; } catch (Exception npe) { ROOT_LOGGER.tracef("no MANIFEST present"); return ""; } finally { if(Automounter.isMounted(file)){ Automounter.cleanup(file); } } } }
3,267
33.4
88
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/commands/JdrEnvironment.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.jdr.commands; import org.jboss.as.cli.scriptsupport.CLI; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.jdr.util.JdrZipFile; /** * Value object of globally useful data. * * This object contains information that is designed to be used by Commands. It isn't thread safe. * Most commands will need to interact with the {@link JdrZipFile} zip member. */ public class JdrEnvironment { private String jbossHome = System.getenv("JBOSS_HOME"); private String username; private String password; private String host; private String port; private String outputDirectory = System.getProperty("user.dir"); private String hostControllerName; private String serverName; private ModelControllerClient client; private String productName; private String productVersion; public CLI getCli() { return cli; } public void setCli(CLI cli) { this.cli = cli; } private CLI cli; private JdrZipFile zip; private boolean isServerRunning; public JdrEnvironment() {} public JdrEnvironment(JdrEnvironment copy) { this.setJbossHome(copy.getJbossHome()); this.setUsername(copy.getUsername()); this.setPassword(copy.getPassword()); this.setHost(copy.getHost()); this.setPort(copy.getPort()); this.setOutputDirectory(copy.getOutputDirectory()); this.setHostControllerName(copy.getHostControllerName()); this.setServerName(copy.getServerName()); this.setClient(copy.getClient()); this.setCli(copy.getCli()); this.setZip(copy.getZip()); this.setServerRunning(copy.isServerRunning()); this.setProductName(copy.getProductName()); this.setProductVersion(copy.getProductVersion()); } public String getJbossHome() { return jbossHome; } public void setJbossHome(String jbossHome) { this.jbossHome = jbossHome; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public String getOutputDirectory() { return outputDirectory; } public void setOutputDirectory(String outputDirectory) { this.outputDirectory = outputDirectory; } public String getHostControllerName() { return hostControllerName; } public void setHostControllerName(String hostControllerName) { this.hostControllerName = hostControllerName; } public String getServerName() { return serverName; } public void setServerName(String serverName) { this.serverName = serverName; } public ModelControllerClient getClient() { return client; } public void setClient(ModelControllerClient client) { this.client = client; } public JdrZipFile getZip() { return zip; } public void setZip(JdrZipFile zip) { this.zip = zip; } public boolean isServerRunning() { return isServerRunning; } public void setServerRunning(boolean isServerRunning) { this.isServerRunning = isServerRunning; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getProductVersion() { return productVersion; } public void setProductVersion(String productVersion) { this.productVersion = productVersion; } }
5,009
26.679558
98
java
null
wildfly-main/jdr/src/main/java/org/jboss/as/jdr/vfs/Filters.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.jdr.vfs; import org.jboss.as.jdr.util.WildcardPattern; import org.jboss.vfs.VirtualFile; import org.jboss.vfs.VirtualFileFilter; import org.jboss.vfs.util.MatchAllVirtualFileFilter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; /** * @author [email protected] * Date: 11/23/12 */ public class Filters { public static final VirtualFileFilter TRUE = MatchAllVirtualFileFilter.INSTANCE; public static VirtualFileFilter not(final VirtualFileFilter filter) { return new VirtualFileFilter() { @Override public boolean accepts(VirtualFile file) { return !filter.accepts(file); } }; } public static VirtualFileFilter and(final VirtualFileFilter... filters) { return new VirtualFileFilter() { @Override public boolean accepts(VirtualFile file) { for(VirtualFileFilter f: filters) { if(!f.accepts(file)){ return false; } } return true; } }; } public static VirtualFileFilter or(final VirtualFileFilter... filters) { return new VirtualFileFilter() { @Override public boolean accepts(VirtualFile file) { for(VirtualFileFilter f: filters) { if(f.accepts(file)){ return true; } } return false; } }; } public static VirtualFileFilter wildcard(final String p){ return new VirtualFileFilter() { private WildcardPattern pattern = new WildcardPattern(p); @Override public boolean accepts(VirtualFile file) { return pattern.matches(file.getPathName()); } }; } public static BlocklistFilter wildcardBlockList() { return new WildcardBlocklistFilter(); } public static BlocklistFilter wildcardBlocklistFilter(final String... patterns){ return new WildcardBlocklistFilter(patterns); } public static BlocklistFilter regexBlockList() { return new RegexBlocklistFilter(); } public static BlocklistFilter regexBlockList(String... patterns) { return new RegexBlocklistFilter(patterns); } public static VirtualFileFilter suffix(final String s){ return new VirtualFileFilter() { @Override public boolean accepts(VirtualFile file) { return file.getPathName().endsWith(s); } }; } public interface BlocklistFilter extends VirtualFileFilter { void add(final String... patterns); } private static class WildcardBlocklistFilter implements BlocklistFilter { private final List<WildcardPattern> patterns; public WildcardBlocklistFilter() { patterns = new ArrayList<WildcardPattern>(); patterns.add(new WildcardPattern("*-users.properties")); } public WildcardBlocklistFilter(final String... patterns) { this.patterns = new ArrayList<WildcardPattern>(patterns.length); add(patterns); } @Override public boolean accepts(VirtualFile file) { for(WildcardPattern p: this.patterns){ if(p.matches(file.getName())){ return false; } } return true; } public void add(final String... patterns){ for(String p: patterns) { this.patterns.add(new WildcardPattern(p)); } } } private static class RegexBlocklistFilter implements BlocklistFilter { private final List<Pattern> patterns; public RegexBlocklistFilter(){ this.patterns = Arrays.asList(Pattern.compile(".*-users.properties")); } public RegexBlocklistFilter(final String... patterns){ this.patterns = new ArrayList<Pattern>(patterns.length); add(patterns); } @Override public boolean accepts(final VirtualFile file) { for(Pattern p: this.patterns){ if(p.matcher(file.getName()).matches()){ return false; } } return true; } public void add(final String... patterns){ for(String p: patterns){ this.patterns.add(Pattern.compile(p)); } } } }
5,666
30.837079
84
java
null
wildfly-main/elytron-oidc-client/src/test/java/org/wildfly/extension/elytron/oidc/ExpressionsTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import static org.wildfly.extension.elytron.oidc.ElytronOidcSubsystemDefinition.ELYTRON_CAPABILITY_NAME; import org.jboss.as.controller.RunningMode; 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.AbstractSubsystemTest; import org.jboss.as.subsystem.test.AdditionalInitialization; import org.jboss.as.subsystem.test.KernelServices; import org.junit.Assert; import org.junit.Test; /** * Subsystem parsing test case. * * <a href="mailto:[email protected]">Ashpan Raskar</a> */ public class ExpressionsTestCase extends AbstractSubsystemTest { private KernelServices services = null; public ExpressionsTestCase() { super(ElytronOidcExtension.SUBSYSTEM_NAME, new ElytronOidcExtension()); } @Test public void testExpressions() throws Throwable { if (services != null) return; String subsystemXml = "oidc-expressions.xml"; services = super.createKernelServicesBuilder(new DefaultInitializer()).setSubsystemXmlResource(subsystemXml).build(); if (! services.isSuccessfulBoot()) { Assert.fail(services.getBootError().toString()); } } private static class DefaultInitializer extends AdditionalInitialization { @Override protected void initializeExtraSubystemsAndModel(ExtensionRegistry extensionRegistry, Resource rootResource, ManagementResourceRegistration rootRegistration, RuntimeCapabilityRegistry capabilityRegistry) { super.initializeExtraSubystemsAndModel(extensionRegistry, rootResource, rootRegistration, capabilityRegistry); registerCapabilities(capabilityRegistry, ELYTRON_CAPABILITY_NAME); } @Override protected RunningMode getRunningMode() { return RunningMode.NORMAL; } } }
2,768
37.458333
212
java
null
wildfly-main/elytron-oidc-client/src/test/java/org/wildfly/extension/elytron/oidc/OidcTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import static org.junit.Assert.assertEquals; import static org.wildfly.extension.elytron.oidc.ElytronOidcSubsystemDefinition.ELYTRON_CAPABILITY_NAME; import org.jboss.as.controller.RunningMode; 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.AbstractSubsystemTest; import org.jboss.as.subsystem.test.AdditionalInitialization; import org.jboss.as.subsystem.test.KernelServices; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Subsystem parsing test case. * * <a href="mailto:[email protected]">Farah Juma</a> */ public class OidcTestCase extends AbstractSubsystemTest { private OidcConfigService configService; private KernelServices services = null; public OidcTestCase() { super(ElytronOidcExtension.SUBSYSTEM_NAME, new ElytronOidcExtension()); } @Before public void prepare() throws Throwable { if (services != null) return; String subsystemXml = "oidc.xml"; services = super.createKernelServicesBuilder(new DefaultInitializer()).setSubsystemXmlResource(subsystemXml).build(); if (! services.isSuccessfulBoot()) { Assert.fail(services.getBootError().toString()); } configService = OidcConfigService.getInstance(); } @Test public void testSecureDeploymentWithSecretCredential() throws Exception { String expectedJson = "{\"realm\" : \"main\", \"realm-public-key\" : \"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4siLKUew0WYxdtq6/rwk4Uj/4amGFFnE/yzIxQVU0PUqz3QBRVkUWpDj0K6ZnS5nzJV/y6DHLEy7hjZTdRDphyF1sq09aDOYnVpzu8o2sIlMM8q5RnUyEfIyUZqwo8pSZDJ90fS0s+IDUJNCSIrAKO3w1lqZDHL6E/YFHXyzkvQIDAQAB\", \"auth-server-url\" : \"http://localhost:8080/auth\", \"truststore\" : \"truststore.jks\", \"truststore-password\" : \"secret\", \"ssl-required\" : \"EXTERNAL\", \"confidential-port\" : 443, \"allow-any-hostname\" : false, \"disable-trust-manager\" : true, \"connection-pool-size\" : 20, \"enable-cors\" : true, \"client-keystore\" : \"keys.jks\", \"client-keystore-password\" : \"secret\", \"client-key-password\" : \"secret\", \"cors-max-age\" : 600, \"cors-allowed-headers\" : \"X-Custom\", \"cors-allowed-methods\" : \"PUT,POST,DELETE,GET\", \"expose-token\" : false, \"always-refresh-token\" : false, \"register-node-at-startup\" : true, \"register-node-period\" : 60, \"token-store\" : \"session\", \"principal-attribute\" : \"sub\", \"proxy-url\" : \"http://localhost:9000\", \"resource\" : \"myAppId\", \"use-resource-role-mappings\" : true, \"turn-off-change-session-id-on-login\" : false, \"token-minimum-time-to-live\" : 10, \"min-time-between-jwks-requests\" : 20, \"public-key-cache-ttl\" : 3600, \"verify-token-audience\" : true, \"credentials\" : {\"secret\" : \"0aa31d98-e0aa-404c-b6e0-e771dba1e798\"}, \"redirect-rewrite-rules\" : {\"^/wsmain/api/(.*)$\" : \"/api/$1/\"}}"; assertEquals(expectedJson, configService.getJSON("myAppWithSecret.war")); } @Test public void testSecureDeploymentWithJwtCredential() throws Exception { String expectedJson = "{\"realm\" : \"main\", \"realm-public-key\" : \"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4siLKUew0WYxdtq6/rwk4Uj/4amGFFnE/yzIxQVU0PUqz3QBRVkUWpDj0K6ZnS5nzJV/y6DHLEy7hjZTdRDphyF1sq09aDOYnVpzu8o2sIlMM8q5RnUyEfIyUZqwo8pSZDJ90fS0s+IDUJNCSIrAKO3w1lqZDHL6E/YFHXyzkvQIDAQAB\", \"auth-server-url\" : \"http://localhost:8080/auth\", \"truststore\" : \"truststore.jks\", \"truststore-password\" : \"secret\", \"ssl-required\" : \"EXTERNAL\", \"confidential-port\" : 443, \"allow-any-hostname\" : false, \"disable-trust-manager\" : true, \"connection-pool-size\" : 20, \"enable-cors\" : true, \"client-keystore\" : \"keys.jks\", \"client-keystore-password\" : \"secret\", \"client-key-password\" : \"secret\", \"cors-max-age\" : 600, \"cors-allowed-headers\" : \"X-Custom\", \"cors-allowed-methods\" : \"PUT,POST,DELETE,GET\", \"expose-token\" : false, \"always-refresh-token\" : false, \"register-node-at-startup\" : true, \"register-node-period\" : 60, \"token-store\" : \"session\", \"principal-attribute\" : \"sub\", \"proxy-url\" : \"http://localhost:9000\", \"resource\" : \"http-endpoint\", \"use-resource-role-mappings\" : true, \"adapter-state-cookie-path\" : \"/\", \"credentials\" : { \"jwt\" : {\"client-keystore-file\" : \"/tmp/keystore.jks\", \"client-keystore-type\" : \"jks\", \"client-keystore-password\" : \"keystorePassword\", \"client-key-password\" : \"keyPassword\", \"token-timeout\" : \"10\", \"client-key-alias\" : \"keyAlias\"} }, \"redirect-rewrite-rules\" : {\"^/wsmain/api/(.*)$\" : \"/api/$1/\"}}"; assertEquals(expectedJson, configService.getJSON("myAppWithJwt.war")); } @Test public void testSecureDeploymentWithSecretJwtCredential() throws Exception { String expectedJson = "{\"realm\" : \"main\", \"realm-public-key\" : \"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4siLKUew0WYxdtq6/rwk4Uj/4amGFFnE/yzIxQVU0PUqz3QBRVkUWpDj0K6ZnS5nzJV/y6DHLEy7hjZTdRDphyF1sq09aDOYnVpzu8o2sIlMM8q5RnUyEfIyUZqwo8pSZDJ90fS0s+IDUJNCSIrAKO3w1lqZDHL6E/YFHXyzkvQIDAQAB\", \"auth-server-url\" : \"http://localhost:8080/auth\", \"truststore\" : \"truststore.jks\", \"truststore-password\" : \"secret\", \"ssl-required\" : \"EXTERNAL\", \"confidential-port\" : 443, \"allow-any-hostname\" : false, \"disable-trust-manager\" : true, \"connection-pool-size\" : 20, \"enable-cors\" : true, \"client-keystore\" : \"keys.jks\", \"client-keystore-password\" : \"secret\", \"client-key-password\" : \"secret\", \"cors-max-age\" : 600, \"cors-allowed-headers\" : \"X-Custom\", \"cors-allowed-methods\" : \"PUT,POST,DELETE,GET\", \"expose-token\" : false, \"always-refresh-token\" : false, \"register-node-at-startup\" : true, \"register-node-period\" : 60, \"token-store\" : \"session\", \"principal-attribute\" : \"sub\", \"proxy-url\" : \"http://localhost:9000\", \"resource\" : \"some-endpoint\", \"use-resource-role-mappings\" : true, \"adapter-state-cookie-path\" : \"/\", \"credentials\" : { \"secret-jwt\" : {\"secret\" : \"fd8f54e1-6994-413a-acf8-90bc67f05412\", \"algorithm\" : \"HS512\"} }, \"redirect-rewrite-rules\" : {\"^/wsmain/api/(.*)$\" : \"/api/$1/\"}}"; assertEquals(expectedJson, configService.getJSON("myAppWithSecretJwt.war")); } @Test public void testSecureDeploymentWithRealmInlined() throws Exception { String expectedJson = "{\"realm\" : \"demo\", \"resource\" : \"customer-portal\", \"auth-server-url\" : \"http://localhost:8081/auth\", \"ssl-required\" : \"EXTERNAL\", \"credentials\" : {\"secret\" : \"password\"}}"; assertEquals(expectedJson, configService.getJSON("myAppWithRealmInline.war")); } @Test public void testSecureDeploymentWithProvider() throws Exception { String expectedJson = "{\"provider-url\" : \"https://accounts.google.com\", \"ssl-required\" : \"EXTERNAL\", \"principal-attribute\" : \"firstName\", \"client-id\" : \"customer-portal\", \"credentials\" : {\"secret\" : \"password\"}}"; assertEquals(expectedJson, configService.getJSON("myAppWithProvider.war")); } @Test public void testSecureServerWithProvider() throws Exception { String expectedJson = "{\"provider-url\" : \"http://localhost:8080/realms/WildFly\", \"client-id\" : \"wildfly-console\", \"public-client\" : true, \"ssl-required\" : \"EXTERNAL\"}"; assertEquals(expectedJson, configService.getJSON("another-wildfly-console")); } @Test public void testSecureServerWithRealm() throws Exception { String expectedJson = "{\"realm\" : \"jboss-infra\", \"realm-public-key\" : \"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqKoq+a9MgXepmsPJDmo45qswuChW9pWjanX68oIBuI4hGvhQxFHryCow230A+sr7tFdMQMt8f1l/ysmV/fYAuW29WaoY4kI4Ou1yYPuwywKSsxT6PooTs83hKyZ1h4LZMj5DkLGDDDyVRHob2WmPaYg9RGVRw3iGGsD/p+Yb+L/gnBYQnZZ7lYqmN7h36p5CkzzlgXQA1Ha8sQxL+rJNH8+sZm0vBrKsoII3Of7TqHGsm1RwFV3XCuGJ7S61AbjJMXL5DQgJl9Z5scvxGAyoRLKC294UgMnQdzyBTMPw2GybxkRKmiK2KjQKmcopmrJp/Bt6fBR6ZkGSs9qUlxGHgwIDAQAB\", \"auth-server-url\" : \"http://localhost:8180/auth\", \"resource\" : \"wildfly-console\", \"public-client\" : true, \"adapter-state-cookie-path\" : \"/\", \"ssl-required\" : \"EXTERNAL\", \"confidential-port\" : 443, \"proxy-url\" : \"http://localhost:9000\"}"; assertEquals(expectedJson, configService.getJSON("wildfly-console")); } private static class DefaultInitializer extends AdditionalInitialization { @Override protected void initializeExtraSubystemsAndModel(ExtensionRegistry extensionRegistry, Resource rootResource, ManagementResourceRegistration rootRegistration, RuntimeCapabilityRegistry capabilityRegistry) { super.initializeExtraSubystemsAndModel(extensionRegistry, rootResource, rootRegistration, capabilityRegistry); registerCapabilities(capabilityRegistry, ELYTRON_CAPABILITY_NAME); } @Override protected RunningMode getRunningMode() { return RunningMode.NORMAL; } } }
10,053
79.432
1,532
java
null
wildfly-main/elytron-oidc-client/src/test/java/org/wildfly/extension/elytron/oidc/Subsystem_2_0_ParsingTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import java.io.IOException; import java.util.Properties; import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest; /** * Subsystem parsing test case. * * <a href="mailto:[email protected]">Farah Juma</a> */ public class Subsystem_2_0_ParsingTestCase extends AbstractSubsystemBaseTest { public Subsystem_2_0_ParsingTestCase() { super(ElytronOidcExtension.SUBSYSTEM_NAME, new ElytronOidcExtension()); } @Override protected String getSubsystemXml() throws IOException { return readResource("subsystem_2_0.xml"); } @Override protected String getSubsystemXsdPath() throws IOException { return "schema/wildfly-elytron-oidc-client_2_0.xsd"; } @Override protected void compareXml(String configId, String original, String marshalled) throws Exception { // } protected Properties getResolvedProperties() { return System.getProperties(); } }
1,690
29.196429
101
java
null
wildfly-main/elytron-oidc-client/src/test/java/org/wildfly/extension/elytron/oidc/Subsystem_1_0_ParsingTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import java.io.IOException; import java.util.Properties; import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest; /** * Subsystem parsing test case. * * <a href="mailto:[email protected]">Farah Juma</a> */ public class Subsystem_1_0_ParsingTestCase extends AbstractSubsystemBaseTest { public Subsystem_1_0_ParsingTestCase() { super(ElytronOidcExtension.SUBSYSTEM_NAME, new ElytronOidcExtension()); } @Override protected String getSubsystemXml() throws IOException { return readResource("legacy_subsystem_1_0.xml"); } @Override protected String getSubsystemXsdPath() throws IOException { return "schema/wildfly-elytron-oidc-client_1_0.xsd"; } @Override protected void compareXml(String configId, String original, String marshalled) throws Exception { // } protected Properties getResolvedProperties() { return System.getProperties(); } }
1,697
29.321429
101
java
null
wildfly-main/elytron-oidc-client/src/test/java/org/wildfly/extension/elytron/oidc/OidcActivationProcessorTest.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import static org.junit.Assert.assertTrue; import java.util.List; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.registry.Resource; import org.jboss.as.server.deployment.AttachmentKey; import org.jboss.as.server.deployment.AttachmentList; import org.jboss.as.server.deployment.DelegatingSupplier; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.Phase; import org.jboss.as.web.common.WarMetaData; import org.jboss.dmr.ModelNode; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.jboss.metadata.web.spec.LoginConfigMetaData; import org.jboss.msc.inject.Injector; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceRegistry; import org.jboss.msc.service.ServiceTarget; import org.junit.Test; public class OidcActivationProcessorTest { private final class MockDeploymentPhaseContext implements DeploymentPhaseContext { private final class MockDeploymentUnit implements DeploymentUnit { @Override public boolean hasAttachment(AttachmentKey<?> key) { return false; } @Override public <T> T getAttachment(AttachmentKey<T> key) { if (WarMetaData.ATTACHMENT_KEY.equals(key)) { return (T) new NonNullRealmNullEverythingElseWarMetaData(); } return null; } @Override public <T> List<T> getAttachmentList(AttachmentKey<? extends List<T>> key) { return null; } @Override public <T> T putAttachment(AttachmentKey<T> key, T value) { return null; } @Override public <T> T removeAttachment(AttachmentKey<T> key) { return null; } @Override public <T> void addToAttachmentList(AttachmentKey<AttachmentList<T>> key, T value) { } @Override public ServiceName getServiceName() { return null; } @Override public DeploymentUnit getParent() { return null; } @Override public String getName() { return null; } @Override public ServiceRegistry getServiceRegistry() { return null; } //@Override public ModelNode getDeploymentSubsystemModel(String subsystemName) { return null; } //@Override public ModelNode createDeploymentSubModel(String subsystemName, PathElement address) { return null; } //@Override public ModelNode createDeploymentSubModel(String subsystemName, PathAddress address) { return null; } //@Override public ModelNode createDeploymentSubModel(String subsystemName, PathAddress address, Resource resource) { return null; } } @Override public <T> void addToAttachmentList(AttachmentKey<AttachmentList<T>> arg0, T arg1) { } @Override public <T> T getAttachment(AttachmentKey<T> arg0) { return null; } @Override public <T> List<T> getAttachmentList(AttachmentKey<? extends List<T>> arg0) { return null; } @Override public boolean hasAttachment(AttachmentKey<?> arg0) { return false; } @Override public <T> T putAttachment(AttachmentKey<T> arg0, T arg1) { return null; } @Override public <T> T removeAttachment(AttachmentKey<T> arg0) { return null; } @Override public <T> void addDependency(ServiceName arg0, AttachmentKey<T> arg1) { } public <T> void addDependency(ServiceName arg0, Class<T> arg1, Injector<T> arg2) { } @Override public <T> void addDeploymentDependency(ServiceName arg0, AttachmentKey<T> arg1) { } @Override public DeploymentUnit getDeploymentUnit() { return new MockDeploymentUnit(); } @Override public Phase getPhase() { return null; } @Override public ServiceName getPhaseServiceName() { return null; } @Override public ServiceRegistry getServiceRegistry() { return null; } @Override public ServiceTarget getServiceTarget() { return null; } @Override public <T> void requires(ServiceName arg0, DelegatingSupplier<T> arg1) { } } private final class NonNullRealmNullEverythingElseWarMetaData extends WarMetaData { private final class JBossWebMetaDataExtension extends JBossWebMetaData { @Override public LoginConfigMetaData getLoginConfig() { return new LoginConfigMetaDataExtension(); } } private final class LoginConfigMetaDataExtension extends LoginConfigMetaData { @Override public String getRealmName() { return "NON-NULL"; } } @Override public JBossWebMetaData getMergedJBossWebMetaData() { return new JBossWebMetaDataExtension(); } } /** * Should be able to deploy a web application that specifies a realm, but nothing else in its login-config */ @Test public void testDeployLoginConfigWithRealmAndNullAuthMethod() throws Exception { new OidcActivationProcessor().deploy(new MockDeploymentPhaseContext()); assertTrue("Expect to succeed and reach this point", true); } }
6,792
29.461883
110
java
null
wildfly-main/elytron-oidc-client/src/main/java/org/wildfly/extension/elytron/oidc/RealmDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.DISABLE_TRUST_MANAGER; import static org.wildfly.extension.elytron.oidc._private.ElytronOidcLogger.ROOT_LOGGER; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.AbstractRemoveStepHandler; 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.PathElement; import org.jboss.as.controller.ResourceDefinition; 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; /** * A {@link ResourceDefinition} for a Keycloak realm definition. * * @author <a href="mailto:[email protected]">Farah Juma</a> */ class RealmDefinition extends SimpleResourceDefinition { RealmDefinition() { super(new Parameters(PathElement.pathElement(ElytronOidcDescriptionConstants.REALM), ElytronOidcExtension.getResourceDescriptionResolver(ElytronOidcDescriptionConstants.REALM)) .setAddHandler(RealmAddHandler.INSTANCE) .setRemoveHandler(RealmRemoveHandler.INSTANCE) .setAddRestartLevel(OperationEntry.Flag.RESTART_RESOURCE_SERVICES) .setRemoveRestartLevel(OperationEntry.Flag.RESTART_RESOURCE_SERVICES)); } @Override public void registerAttributes(ManagementResourceRegistration resourceRegistration) { super.registerAttributes(resourceRegistration); for (AttributeDefinition attribute : ProviderAttributeDefinitions.ATTRIBUTES) { resourceRegistration.registerReadWriteAttribute(attribute, null, RealmWriteAttributeHandler.INSTANCE); } } static class RealmAddHandler extends AbstractAddStepHandler { public static RealmAddHandler INSTANCE = new RealmAddHandler(); private RealmAddHandler() { super(ProviderAttributeDefinitions.ATTRIBUTES); } protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { super.performRuntime(context, operation, model); boolean disableTrustManager = DISABLE_TRUST_MANAGER.resolveModelAttribute(context, model).asBoolean(); if (disableTrustManager) { ROOT_LOGGER.disableTrustManagerSetToTrue(); } OidcConfigService oidcConfigService = OidcConfigService.getInstance(); oidcConfigService.addRealm(context.getCurrentAddressValue(), context.resolveExpressions(model)); } } static class RealmWriteAttributeHandler extends AbstractWriteAttributeHandler<OidcConfigService> { public static final RealmWriteAttributeHandler INSTANCE = new RealmWriteAttributeHandler(); public RealmWriteAttributeHandler(AttributeDefinition... definitions) { super(ProviderAttributeDefinitions.ATTRIBUTES); } @Override protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<OidcConfigService> handbackHolder) throws OperationFailedException { OidcConfigService oidcConfigService = OidcConfigService.getInstance(); oidcConfigService.updateRealm(context.getCurrentAddressValue(), attributeName, resolvedValue); handbackHolder.setHandback(oidcConfigService); return false; } @Override protected void revertUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode valueToRestore, ModelNode valueToRevert, OidcConfigService oidcConfigService) throws OperationFailedException { oidcConfigService.updateRealm(context.getCurrentAddressValue(), attributeName, valueToRestore); } } static class RealmRemoveHandler extends AbstractRemoveStepHandler { public static ProviderDefinition.ProviderRemoveHandler INSTANCE = new ProviderDefinition.ProviderRemoveHandler(); RealmRemoveHandler() { } @Override protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { OidcConfigService oidcConfigService = OidcConfigService.getInstance(); oidcConfigService.removeRealm(context.getCurrentAddressValue()); } } }
5,517
46.162393
179
java
null
wildfly-main/elytron-oidc-client/src/main/java/org/wildfly/extension/elytron/oidc/ElytronOidcExtension.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import org.jboss.as.controller.Extension; import org.jboss.as.controller.ExtensionContext; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SubsystemRegistration; import org.jboss.as.controller.descriptions.ResourceDescriptionResolver; import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver; import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler; import org.jboss.as.controller.parsing.ExtensionParsingContext; import org.jboss.as.controller.registry.ManagementResourceRegistration; /** * An {@link Extension} to add support for OpenID Connect. * * @author <a href="mailto:[email protected]">Farah Juma</a> */ public class ElytronOidcExtension implements Extension { /** * The name of our subsystem within the model. */ public static final String SUBSYSTEM_NAME = "elytron-oidc-client"; protected static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME); private static final String RESOURCE_NAME = ElytronOidcExtension.class.getPackage().getName() + ".LocalDescriptions"; protected static final ModelVersion VERSION_1_0_0 = ModelVersion.create(1, 0, 0); protected static final ModelVersion VERSION_2_0_0 = ModelVersion.create(2, 0, 0); private static final ModelVersion CURRENT_MODEL_VERSION = VERSION_2_0_0; private static final ElytronOidcSubsystemParser_1_0 ELYTRON_OIDC_SUBSYSTEM_PARSER_1_0 = new ElytronOidcSubsystemParser_1_0(); private static final ElytronOidcSubsystemParser_2_0 CURRENT_PARSER = new ElytronOidcSubsystemParser_2_0(); static ResourceDescriptionResolver getResourceDescriptionResolver(final String... keyPrefixes) { StringBuilder sb = new StringBuilder(SUBSYSTEM_NAME); if (keyPrefixes != null) { for (String current : keyPrefixes) { sb.append(".").append(current); } } return new StandardResourceDescriptionResolver(sb.toString(), RESOURCE_NAME, ElytronOidcExtension.class.getClassLoader(), true, false); } @Override public void initialize(ExtensionContext context) { final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION); subsystem.registerXMLElementWriter(CURRENT_PARSER); final ManagementResourceRegistration registration = subsystem.registerSubsystemModel(new ElytronOidcSubsystemDefinition()); registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE); } public void initializeParsers(ExtensionParsingContext context) { context.setSubsystemXmlMapping(SUBSYSTEM_NAME, ElytronOidcSubsystemParser_1_0.NAMESPACE_1_0, ELYTRON_OIDC_SUBSYSTEM_PARSER_1_0); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, ElytronOidcSubsystemParser_2_0.NAMESPACE_2_0, CURRENT_PARSER); } }
3,834
45.768293
136
java
null
wildfly-main/elytron-oidc-client/src/main/java/org/wildfly/extension/elytron/oidc/ProviderAttributeDefinitions.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; 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.IntRangeValidator; import org.jboss.as.controller.operations.validation.LongRangeValidator; import org.jboss.as.controller.operations.validation.StringLengthValidator; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.wildfly.security.http.oidc.Oidc; import java.util.EnumSet; /** * The common attribute definitions for OpenID Connect provider attributes. * * @author <a href="mailto:[email protected]">Farah Juma</a> */ class ProviderAttributeDefinitions { protected static final SimpleAttributeDefinition REALM_PUBLIC_KEY = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.REALM_PUBLIC_KEY, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition AUTH_SERVER_URL = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.AUTH_SERVER_URL, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .setAlternatives(ElytronOidcDescriptionConstants.PROVIDER_URL) .build(); protected static final SimpleAttributeDefinition PROVIDER_URL = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.PROVIDER_URL, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .setAlternatives(ElytronOidcDescriptionConstants.AUTH_SERVER_URL) .build(); protected static final SimpleAttributeDefinition SSL_REQUIRED = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.SSL_REQUIRED, ModelType.STRING, true) .setAllowExpression(true) .setDefaultValue(new ModelNode("external")) .setValidator(EnumValidator.create(Oidc.SSLRequired.class, EnumSet.allOf(Oidc.SSLRequired.class))) .build(); protected static final SimpleAttributeDefinition ALLOW_ANY_HOSTNAME = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.ALLOW_ANY_HOSTNAME, ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition DISABLE_TRUST_MANAGER = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.DISABLE_TRUST_MANAGER, ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition TRUSTSTORE = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.TRUSTSTORE, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition TRUSTSTORE_PASSWORD = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.TRUSTORE_PASSWORD, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition CONNECTION_POOL_SIZE = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.CONNECTION_POOL_SIZE, ModelType.INT, true) .setAllowExpression(true) .setValidator(new IntRangeValidator(0, true)) .build(); protected static final SimpleAttributeDefinition ENABLE_CORS = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.ENABLE_CORS, ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition CLIENT_KEYSTORE = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.CLIENT_KEYSTORE, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition CLIENT_KEYSTORE_PASSWORD = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.CLIENT_KEYSTORE_PASSWORD, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition CLIENT_KEY_PASSWORD = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.CLIENT_KEY_PASSWORD, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition CORS_MAX_AGE = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.CORS_MAX_AGE, ModelType.INT, true) .setAllowExpression(true) .setValidator(new IntRangeValidator(-1, true)) .build(); protected static final SimpleAttributeDefinition CORS_ALLOWED_HEADERS = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.CORS_ALLOWED_HEADERS, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition CORS_ALLOWED_METHODS = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.CORS_ALLOWED_METHODS, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition CORS_EXPOSED_HEADERS = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.CORS_EXPOSED_HEADERS, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition EXPOSE_TOKEN = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.EXPOSE_TOKEN, ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition ALWAYS_REFRESH_TOKEN = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.ALWAYS_REFRESH_TOKEN, ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition REGISTER_NODE_AT_STARTUP = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.REGISTER_NODE_AT_STARTUP, ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition REGISTER_NODE_PERIOD = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.REGISTER_NODE_PERIOD, ModelType.INT, true) .setAllowExpression(true) .setValidator(new IntRangeValidator(-1, true)) .build(); protected static final SimpleAttributeDefinition TOKEN_STORE = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.TOKEN_STORE, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition PRINCIPAL_ATTRIBUTE = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.PRINCIPAL_ATTRIBUTE, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition AUTODETECT_BEARER_ONLY = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.AUTODETECT_BEARER_ONLY, ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition IGNORE_OAUTH_QUERY_PARAMETER = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.IGNORE_OAUTH_QUERY_PARAMTER, ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition CONFIDENTIAL_PORT = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.CONFIDENTIAL_PORT, ModelType.INT, true) .setAllowExpression(true) .setDefaultValue(new ModelNode(8443)) .build(); protected static final SimpleAttributeDefinition PROXY_URL = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.PROXY_URL, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition VERIFY_TOKEN_AUDIENCE = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.VERIFY_TOKEN_AUDIENCE, ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition SOCKET_TIMEOUT_MILLIS = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.SOCKET_TIMEOUT_MILLIS, ModelType.LONG, true) .setAllowExpression(true) .setValidator(new LongRangeValidator(-1L, true)) .build(); protected static final SimpleAttributeDefinition CONNECTION_TTL_MILLIS = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.CONNECTION_TTL_MILLIS, ModelType.LONG, true) .setAllowExpression(true) .setValidator(new LongRangeValidator(-1L, true)) .build(); protected static final SimpleAttributeDefinition CONNECTION_TIMEOUT_MILLIS = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.CONNECTION_TIMEOUT_MILLIS, ModelType.LONG, true) .setAllowExpression(true) .setValidator(new LongRangeValidator(-1L, true)) .build(); protected static final SimpleAttributeDefinition TOKEN_SIGNATURE_ALGORITHM = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.TOKEN_SIGNATURE_ALGORITHM, ModelType.STRING, true) .setAllowExpression(true) .setDefaultValue(new ModelNode("RS256")) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition[] ATTRIBUTES = { REALM_PUBLIC_KEY, AUTH_SERVER_URL, PROVIDER_URL, TRUSTSTORE, TRUSTSTORE_PASSWORD, SSL_REQUIRED, CONFIDENTIAL_PORT, ALLOW_ANY_HOSTNAME, DISABLE_TRUST_MANAGER, CONNECTION_POOL_SIZE, ENABLE_CORS, CLIENT_KEYSTORE, CLIENT_KEYSTORE_PASSWORD, CLIENT_KEY_PASSWORD, CORS_MAX_AGE, CORS_ALLOWED_HEADERS, CORS_ALLOWED_METHODS, CORS_EXPOSED_HEADERS, EXPOSE_TOKEN, ALWAYS_REFRESH_TOKEN, REGISTER_NODE_AT_STARTUP, REGISTER_NODE_PERIOD, TOKEN_STORE, PRINCIPAL_ATTRIBUTE, AUTODETECT_BEARER_ONLY, IGNORE_OAUTH_QUERY_PARAMETER, PROXY_URL, VERIFY_TOKEN_AUDIENCE, SOCKET_TIMEOUT_MILLIS, CONNECTION_TTL_MILLIS, CONNECTION_TIMEOUT_MILLIS, TOKEN_SIGNATURE_ALGORITHM}; }
13,864
56.53112
176
java
null
wildfly-main/elytron-oidc-client/src/main/java/org/wildfly/extension/elytron/oidc/OidcVirtualSecurityDomainCreationService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import org.jboss.as.server.security.VirtualSecurityDomainCreationService; import org.jboss.msc.service.Service; import org.wildfly.security.auth.permission.LoginPermission; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.http.oidc.OidcSecurityRealm; /** * Core {@link Service} handling virtual security domain creation. * * @author <a href="mailto:[email protected]">Farah Juma</a> */ public class OidcVirtualSecurityDomainCreationService extends VirtualSecurityDomainCreationService { private static final String VIRTUAL_REALM = "virtual"; @Override public SecurityDomain.Builder createVirtualSecurityDomainBuilder() { return SecurityDomain.builder() .addRealm(VIRTUAL_REALM, new OidcSecurityRealm()).build() .setDefaultRealmName(VIRTUAL_REALM) .setPermissionMapper((permissionMappable, roles) -> LoginPermission.getInstance()); } }
1,701
37.681818
100
java
null
wildfly-main/elytron-oidc-client/src/main/java/org/wildfly/extension/elytron/oidc/VirtualHttpServerMechanismFactoryNameProcessor.java
/* * Copyright 2021 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import static org.jboss.as.server.security.SecurityMetaData.ATTACHMENT_KEY; import static org.jboss.as.server.security.VirtualDomainMarkerUtility.virtualDomainName; import static org.jboss.as.server.security.VirtualDomainUtil.setTopLevelDeploymentSecurityMetaData; import static org.jboss.as.web.common.VirtualHttpServerMechanismFactoryMarkerUtility.isVirtualMechanismFactoryRequired; import static org.jboss.as.web.common.VirtualHttpServerMechanismFactoryMarkerUtility.virtualMechanismFactoryName; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.security.AdvancedSecurityMetaData; import org.jboss.as.server.security.SecurityMetaData; import org.jboss.as.web.common.WarMetaData; import org.jboss.msc.service.ServiceName; /** * A {@code DeploymentUnitProcessor} to set the {@code ServiceName} of any virtual HTTP server mechanism factory to be used * by the deployment. * * @author <a href="mailto:[email protected]">Farah Juma</a> */ public class VirtualHttpServerMechanismFactoryNameProcessor implements DeploymentUnitProcessor { @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); if (warMetaData == null) { return; } SecurityMetaData securityMetaData = deploymentUnit.getAttachment(ATTACHMENT_KEY); if (securityMetaData != null && isVirtualMechanismFactoryRequired(deploymentUnit)) { AdvancedSecurityMetaData advancedSecurityMetaData = new AdvancedSecurityMetaData(); advancedSecurityMetaData.setHttpServerAuthenticationMechanismFactory(virtualMechanismFactoryName(deploymentUnit)); ServiceName virtualDomainName = virtualDomainName(deploymentUnit); advancedSecurityMetaData.setSecurityDomain(virtualDomainName); // virtual mechanism factory implies virtual security domain deploymentUnit.putAttachment(ATTACHMENT_KEY, advancedSecurityMetaData); setTopLevelDeploymentSecurityMetaData(deploymentUnit, virtualDomainName); } } }
3,068
49.311475
135
java
null
wildfly-main/elytron-oidc-client/src/main/java/org/wildfly/extension/elytron/oidc/OidcConfigService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import static org.wildfly.extension.elytron.oidc.ElytronOidcDescriptionConstants.AUTH_SERVER_URL; import static org.wildfly.extension.elytron.oidc.ElytronOidcDescriptionConstants.CLIENT_ID; import static org.wildfly.extension.elytron.oidc.ElytronOidcDescriptionConstants.PROVIDER_URL; import static org.wildfly.extension.elytron.oidc.ElytronOidcDescriptionConstants.REALM; import static org.wildfly.extension.elytron.oidc.ElytronOidcDescriptionConstants.RESOURCE; import static org.wildfly.extension.elytron.oidc._private.ElytronOidcLogger.ROOT_LOGGER; import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.web.common.WarMetaData; import org.jboss.dmr.ModelNode; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.wildfly.security.http.oidc.Oidc; final class OidcConfigService { private static final String CREDENTIALS_JSON_NAME = "credentials"; private static final String REDIRECT_REWRITE_RULE_JSON_NAME = "redirect-rewrite-rules"; private static final OidcConfigService INSTANCE = new OidcConfigService(); public static OidcConfigService getInstance() { return INSTANCE; } private Map<String, ModelNode> realms = new HashMap<>(); private Map<String, ModelNode> providers = new HashMap<>(); // deployments secured with OpenID Connect private Map<String, ModelNode> secureDeployments = new HashMap<>(); private OidcConfigService() { } public void addRealm(String realmName, ModelNode model) { this.realms.put(realmName, model.clone()); } public void updateRealm(String realmName, String attrName, ModelNode resolvedValue) { ModelNode realm = this.realms.get(realmName); realm.get(attrName).set(resolvedValue); } public void removeRealm(String realmName) { this.realms.remove(realmName); } public void addProvider(String providerName, ModelNode model) { this.providers.put(providerName, model.clone()); } public void updateProvider(String providerName, String attrName, ModelNode resolvedValue) { ModelNode realm = this.providers.get(providerName); realm.get(attrName).set(resolvedValue); } public void removeProvider(String providerName) { this.providers.remove(providerName); } public void addSecureDeployment(String deploymentName, ModelNode model) { ModelNode deployment = model.clone(); this.secureDeployments.put(deploymentName, deployment); } public void updateSecureDeployment(String deploymentName, String attrName, ModelNode resolvedValue) { ModelNode deployment = this.secureDeployments.get(deploymentName); deployment.get(attrName).set(resolvedValue); } public void removeSecureDeployment(String deploymentName) { this.secureDeployments.remove(deploymentName); } public void addCredential(String deploymentName, String credentialName, ModelNode model) { ModelNode credentials = getCredentialsForDeployment(deploymentName); if (! credentials.isDefined()) { credentials = new ModelNode(); } setCredential(credentialName, model, credentials); ModelNode deployment = this.secureDeployments.get(deploymentName); deployment.get(CREDENTIALS_JSON_NAME).set(credentials); } private void setCredential(String credentialName, ModelNode model, ModelNode credentials) { if (credentialName.equals(ElytronOidcDescriptionConstants.SECRET)) { credentials.get(credentialName).set(model.get(ElytronOidcDescriptionConstants.SECRET).asString()); } else { credentials.set(credentialName, getCredentialValue(model)); } } private ModelNode getCredentialValue(ModelNode model) { ModelNode credential = new ModelNode(); for (SimpleAttributeDefinition attribute : CredentialDefinition.ATTRIBUTES) { String attributeName = attribute.getName(); ModelNode attributeValue = model.get(attributeName); if (attributeValue.isDefined()) { credential.get(attributeName).set(attributeValue.asString()); } } return credential; } public void removeCredential(String deploymentName, String credentialName) { ModelNode credentials = getCredentialsForDeployment(deploymentName); if (!credentials.isDefined()) { throw ROOT_LOGGER.cannotRemoveCredential(deploymentName); } credentials.remove(credentialName); } public void updateCredential(String deploymentName, String credentialName, ModelNode resolvedValue) { ModelNode credentials = getCredentialsForDeployment(deploymentName); if (!credentials.isDefined()) { throw ROOT_LOGGER.cannotUpdateCredential(deploymentName); } setCredential(credentialName, resolvedValue, credentials); } private ModelNode getCredentialsForDeployment(String deploymentName) { ModelNode deployment = this.secureDeployments.get(deploymentName); return deployment.get(CREDENTIALS_JSON_NAME); } public void addRedirectRewriteRule(String deploymentName, String redirectRewriteRuleName, ModelNode model) { ModelNode redirectRewritesRules = getRedirectRewriteRuleForDeployment(deploymentName); if (!redirectRewritesRules.isDefined()) { redirectRewritesRules = new ModelNode(); } redirectRewritesRules.get(redirectRewriteRuleName).set(model.get(ElytronOidcDescriptionConstants.REPLACEMENT).asString()); ModelNode deployment = this.secureDeployments.get(deploymentName); deployment.get(REDIRECT_REWRITE_RULE_JSON_NAME).set(redirectRewritesRules); } public void removeRedirectRewriteRule(String deploymentName, String redirectRewriteRuleName) { ModelNode redirectRewritesRules = getRedirectRewriteRuleForDeployment(deploymentName); if (!redirectRewritesRules.isDefined()) { throw ROOT_LOGGER.cannotRemoveRedirectRuntimeRule(deploymentName); } redirectRewritesRules.remove(redirectRewriteRuleName); } public void updateRedirectRewriteRule(String deploymentName, String redirectRewriteRuleName, ModelNode resolvedValue) { ModelNode redirectRewritesRules = getRedirectRewriteRuleForDeployment(deploymentName); if (!redirectRewritesRules.isDefined()) { throw ROOT_LOGGER.cannotUpdateRedirectRuntimeRule(deploymentName); } redirectRewritesRules.get(redirectRewriteRuleName).set(resolvedValue.get(ElytronOidcDescriptionConstants.REPLACEMENT).asString()); } private ModelNode getRedirectRewriteRuleForDeployment(String deploymentName) { ModelNode deployment = this.secureDeployments.get(deploymentName); return deployment.get(REDIRECT_REWRITE_RULE_JSON_NAME); } protected boolean isDeploymentConfigured(DeploymentUnit deploymentUnit) { ModelNode deployment = getSecureDeployment(deploymentUnit); if (! deployment.isDefined()) { return false; } ModelNode resource = deployment.get(SecureDeploymentDefinition.RESOURCE.getName()); ModelNode clientId = deployment.get(SecureDeploymentDefinition.CLIENT_ID.getName()); return resource.isDefined() || clientId.isDefined(); } public String getJSON(DeploymentUnit deploymentUnit) { ModelNode deployment = getSecureDeployment(deploymentUnit); return getJSON(deployment); } public String getJSON(String deploymentName) { return getJSON(deploymentName, false); } public String getJSON(String deploymentName, boolean convertToRealmConfiguration) { ModelNode deployment = this.secureDeployments.get(deploymentName); return getJSON(deployment, convertToRealmConfiguration); } public void clear() { realms = new HashMap<>(); providers = new HashMap<>(); secureDeployments = new HashMap<>(); } private String getJSON(ModelNode deployment) { return getJSON(deployment, false); } private String getJSON(ModelNode deployment, boolean convertToRealmConfiguration) { ModelNode json = new ModelNode(); ModelNode realmOrProvider = null; boolean removeProvider = false; String realmName = deployment.get(ElytronOidcDescriptionConstants.REALM).asStringOrNull(); if (realmName != null) { realmOrProvider = this.realms.get(realmName); json.get(ElytronOidcDescriptionConstants.REALM).set(realmName); } else { String providerName = deployment.get(ElytronOidcDescriptionConstants.PROVIDER).asStringOrNull(); if (providerName != null) { realmOrProvider = this.providers.get(providerName); removeProvider = true; } } // set realm/provider values first, some can be overridden by deployment values if (realmOrProvider != null) { setJSONValues(json, realmOrProvider, Stream.of(ProviderAttributeDefinitions.ATTRIBUTES).map(AttributeDefinition::getName)::iterator); } setJSONValues(json, deployment, Stream.concat(SecureDeploymentDefinition.ALL_ATTRIBUTES.stream().map(AttributeDefinition::getName), Stream.of(CREDENTIALS_JSON_NAME, REDIRECT_REWRITE_RULE_JSON_NAME))::iterator); if (removeProvider) { json.remove(ElytronOidcDescriptionConstants.PROVIDER); } if (convertToRealmConfiguration) { String clientId = json.get(CLIENT_ID).asStringOrNull(); if (clientId != null) { json.remove(CLIENT_ID); json.get(RESOURCE).set(clientId); } String providerUrl = json.get(PROVIDER_URL).asStringOrNull(); if (providerUrl != null) { String[] authServerUrlAndRealm = providerUrl.split(Oidc.SLASH + Oidc.KEYCLOAK_REALMS_PATH); json.get(AUTH_SERVER_URL).set(authServerUrlAndRealm[0]); json.get(REALM).set(authServerUrlAndRealm[1]); json.remove(PROVIDER_URL); } } return json.toJSONString(true); } private static void setJSONValues(ModelNode json, ModelNode values, Iterable<String> keys) { synchronized (values) { for (String key : keys) { if (values.hasDefined(key)) { json.get(key).set(values.get(key)); } } } } public boolean isSecureDeployment(DeploymentUnit deploymentUnit) { String deploymentName = preferredDeploymentName(deploymentUnit); return this.secureDeployments.containsKey(deploymentName); } private ModelNode getSecureDeployment(DeploymentUnit deploymentUnit) { String deploymentName = preferredDeploymentName(deploymentUnit); return this.secureDeployments.containsKey(deploymentName) ? this.secureDeployments.get(deploymentName) : new ModelNode(); } private String preferredDeploymentName(DeploymentUnit deploymentUnit) { String deploymentName = deploymentUnit.getName(); WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); if (warMetaData == null) { return deploymentName; } JBossWebMetaData webMetaData = warMetaData.getMergedJBossWebMetaData(); if (webMetaData == null) { return deploymentName; } String moduleName = webMetaData.getModuleName(); if (moduleName != null) return moduleName + ".war"; return deploymentName; } }
12,654
40.765677
218
java
null
wildfly-main/elytron-oidc-client/src/main/java/org/wildfly/extension/elytron/oidc/CredentialDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import static org.wildfly.extension.elytron.oidc.ElytronOidcDescriptionConstants.SECURE_DEPLOYMENT; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.AbstractRemoveStepHandler; import org.jboss.as.controller.AbstractWriteAttributeHandler; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.ObjectTypeAttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.ResourceDefinition; 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.StringLengthValidator; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.OperationEntry; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; /** * A {@link ResourceDefinition} for an OpenID Connect credential definition. * * @author <a href="mailto:[email protected]">Farah Juma</a> */ class CredentialDefinition extends SimpleResourceDefinition { protected static final SimpleAttributeDefinition SECRET = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.SECRET, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, false, true)) .build(); protected static final SimpleAttributeDefinition CLIENT_KEYSTORE_FILE = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.CLIENT_KEYSTORE_FILE, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, false, true)) .build(); protected static final SimpleAttributeDefinition CLIENT_KEYSTORE_TYPE = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.CLIENT_KEYSTORE_TYPE, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, false, true)) .build(); protected static final SimpleAttributeDefinition CLIENT_KEYSTORE_PASSWORD = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.CLIENT_KEYSTORE_PASSWORD, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, false, true)) .build(); protected static final SimpleAttributeDefinition CLIENT_KEY_PASSWORD = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.CLIENT_KEY_PASSWORD, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, false, true)) .build(); protected static final SimpleAttributeDefinition TOKEN_TIMEOUT = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.TOKEN_TIMEOUT, ModelType.INT, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, false, true)) .build(); protected static final SimpleAttributeDefinition CLIENT_KEY_ALIAS = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.CLIENT_KEY_ALIAS, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, false, true)) .build(); protected static final SimpleAttributeDefinition ALGORITHM = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.ALGORITHM, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, false, true)) .build(); protected static final SimpleAttributeDefinition[] ATTRIBUTES = {SECRET, CLIENT_KEYSTORE_FILE, CLIENT_KEYSTORE_TYPE, CLIENT_KEYSTORE_PASSWORD, CLIENT_KEY_PASSWORD, TOKEN_TIMEOUT, CLIENT_KEY_ALIAS, ALGORITHM}; protected static final ObjectTypeAttributeDefinition CREDENTIAL = new ObjectTypeAttributeDefinition.Builder(ElytronOidcDescriptionConstants.CREDENTIAL, ATTRIBUTES).build(); CredentialDefinition() { super(new Parameters(PathElement.pathElement(ElytronOidcDescriptionConstants.CREDENTIAL), ElytronOidcExtension.getResourceDescriptionResolver(SECURE_DEPLOYMENT, ElytronOidcDescriptionConstants.CREDENTIAL)) .setAddHandler(CredentialAddHandler.INSTANCE) .setRemoveHandler(CredentialRemoveHandler.INSTANCE) .setAddRestartLevel(OperationEntry.Flag.RESTART_RESOURCE_SERVICES) .setRemoveRestartLevel(OperationEntry.Flag.RESTART_RESOURCE_SERVICES)); } @Override public void registerAttributes(ManagementResourceRegistration resourceRegistration) { super.registerAttributes(resourceRegistration); for (AttributeDefinition attribute : ATTRIBUTES) { resourceRegistration.registerReadWriteAttribute(attribute, null, CredentialWriteAttributeHandler.INSTANCE); } } static class CredentialAddHandler extends AbstractAddStepHandler { public static CredentialAddHandler INSTANCE = new CredentialAddHandler(); private CredentialAddHandler() { super(ATTRIBUTES); } protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { super.performRuntime(context, operation, model); OidcConfigService oidcConfigService = OidcConfigService.getInstance(); oidcConfigService.addCredential(context.getCurrentAddress().getParent().getLastElement().getValue(), context.getCurrentAddressValue(), context.resolveExpressions(model)); } } static class CredentialWriteAttributeHandler extends AbstractWriteAttributeHandler<OidcConfigService> { public static final CredentialWriteAttributeHandler INSTANCE = new CredentialWriteAttributeHandler(); private CredentialWriteAttributeHandler() { super(ATTRIBUTES); } @Override protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<OidcConfigService> handbackHolder) throws OperationFailedException { OidcConfigService oidcConfigService = OidcConfigService.getInstance(); oidcConfigService.updateCredential(context.getCurrentAddress().getParent().getLastElement().getValue(), context.getCurrentAddressValue(), resolvedValue); handbackHolder.setHandback(oidcConfigService); return false; } @Override protected void revertUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode valueToRestore, ModelNode valueToRevert, OidcConfigService oidcConfigService) throws OperationFailedException { oidcConfigService.updateCredential(context.getCurrentAddress().getParent().getLastElement().getValue(), context.getCurrentAddressValue(), valueToRestore); } } static class CredentialRemoveHandler extends AbstractRemoveStepHandler { public static CredentialRemoveHandler INSTANCE = new CredentialRemoveHandler(); CredentialRemoveHandler() { } @Override protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { OidcConfigService oidcConfigService = OidcConfigService.getInstance(); oidcConfigService.removeCredential(context.getCurrentAddress().getParent().getLastElement().getValue(), context.getCurrentAddressValue()); } } }
9,075
52.076023
182
java
null
wildfly-main/elytron-oidc-client/src/main/java/org/wildfly/extension/elytron/oidc/OidcDependencyProcessor.java
/* * Copyright 2021 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.module.ModuleDependency; import org.jboss.as.server.deployment.module.ModuleSpecification; import org.jboss.modules.Module; import org.jboss.modules.ModuleLoader; /** * A {link {@link DeploymentUnitProcessor} to add the required dependencies to activate OpenID Connect. * * @author <a href="mailto:[email protected]">Farah Juma</a> */ class OidcDependencyProcessor implements DeploymentUnitProcessor { private static final String ELYTRON_HTTP_OIDC = "org.wildfly.security.elytron-http-oidc"; @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (!OidcDeploymentMarker.isOidcDeployment(deploymentUnit)) { return; } ModuleLoader moduleLoader = Module.getBootModuleLoader(); ModuleSpecification moduleSpec = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); moduleSpec.addSystemDependency(new ModuleDependency(moduleLoader, ELYTRON_HTTP_OIDC, false, false, true, false)); } }
2,077
40.56
121
java
null
wildfly-main/elytron-oidc-client/src/main/java/org/wildfly/extension/elytron/oidc/RedirectRewriteRuleDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import static org.wildfly.extension.elytron.oidc.ElytronOidcDescriptionConstants.SECURE_DEPLOYMENT; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.AbstractRemoveStepHandler; import org.jboss.as.controller.AbstractWriteAttributeHandler; import org.jboss.as.controller.ObjectTypeAttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.ResourceDefinition; 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.StringLengthValidator; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.OperationEntry; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; /** * A {@link ResourceDefinition} for an OpenID Connect rewrite rule definition. * * @author <a href="mailto:[email protected]">Farah Juma</a> */ class RedirectRewriteRuleDefinition extends SimpleResourceDefinition { protected static final SimpleAttributeDefinition REPLACEMENT = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.REPLACEMENT, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, false, true)) .build(); protected static final ObjectTypeAttributeDefinition REDIRECT_REWRITE_RULE = new ObjectTypeAttributeDefinition.Builder(ElytronOidcDescriptionConstants.REDIRECT_REWRITE_RULE, REPLACEMENT).build(); RedirectRewriteRuleDefinition() { super(new Parameters(PathElement.pathElement(ElytronOidcDescriptionConstants.REDIRECT_REWRITE_RULE), ElytronOidcExtension.getResourceDescriptionResolver(SECURE_DEPLOYMENT, ElytronOidcDescriptionConstants.REDIRECT_REWRITE_RULE)) .setAddHandler(RedirectRewriteRuleAddHandler.INSTANCE) .setRemoveHandler(RedirectRewriteRuleRemoveHandler.INSTANCE) .setAddRestartLevel(OperationEntry.Flag.RESTART_RESOURCE_SERVICES) .setRemoveRestartLevel(OperationEntry.Flag.RESTART_RESOURCE_SERVICES)); } @Override public void registerAttributes(ManagementResourceRegistration resourceRegistration) { super.registerAttributes(resourceRegistration); resourceRegistration.registerReadWriteAttribute(REPLACEMENT, null, RedirectRewriteRuleWriteHandler.INSTANCE); } static class RedirectRewriteRuleAddHandler extends AbstractAddStepHandler { public static RedirectRewriteRuleAddHandler INSTANCE = new RedirectRewriteRuleAddHandler(); private RedirectRewriteRuleAddHandler() { super(REPLACEMENT); } @Override protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { OidcConfigService oidcConfigService = OidcConfigService.getInstance(); oidcConfigService.addRedirectRewriteRule(context.getCurrentAddress().getParent().getLastElement().getValue(), context.getCurrentAddressValue(), context.resolveExpressions(model)); } } static class RedirectRewriteRuleWriteHandler extends AbstractWriteAttributeHandler<OidcConfigService> { public static final RedirectRewriteRuleWriteHandler INSTANCE = new RedirectRewriteRuleWriteHandler(); private RedirectRewriteRuleWriteHandler() { super(REPLACEMENT); } @Override protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<OidcConfigService> handbackHolder) throws OperationFailedException { OidcConfigService oidcConfigService = OidcConfigService.getInstance(); oidcConfigService.updateRedirectRewriteRule(context.getCurrentAddress().getParent().getLastElement().getValue(), context.getCurrentAddressValue(), resolvedValue); handbackHolder.setHandback(oidcConfigService); return false; } @Override protected void revertUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode valueToRestore, ModelNode valueToRevert, OidcConfigService oidcConfigService) throws OperationFailedException { oidcConfigService.updateRedirectRewriteRule(context.getCurrentAddress().getParent().getLastElement().getValue(), context.getCurrentAddressValue(), valueToRestore); } } static class RedirectRewriteRuleRemoveHandler extends AbstractRemoveStepHandler { public static RedirectRewriteRuleRemoveHandler INSTANCE = new RedirectRewriteRuleRemoveHandler(); RedirectRewriteRuleRemoveHandler() { } @Override protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { OidcConfigService oidcConfigService = OidcConfigService.getInstance(); oidcConfigService.removeRedirectRewriteRule(context.getCurrentAddress().getParent().getLastElement().getValue(), context.getCurrentAddressValue()); } } }
6,296
49.782258
191
java
null
wildfly-main/elytron-oidc-client/src/main/java/org/wildfly/extension/elytron/oidc/VirtualHttpServerMechanismFactoryProcessor.java
/* * Copyright 2021 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import static org.jboss.as.server.security.VirtualDomainUtil.clearVirtualDomainMetaDataSecurityDomain; import static org.jboss.as.server.security.VirtualDomainUtil.configureVirtualDomain; import static org.jboss.as.server.security.VirtualDomainUtil.getVirtualDomainMetaData; import static org.jboss.as.server.security.VirtualDomainUtil.isVirtualDomainCreated; import static org.jboss.as.web.common.VirtualHttpServerMechanismFactoryMarkerUtility.isVirtualMechanismFactoryRequired; import static org.jboss.as.web.common.VirtualHttpServerMechanismFactoryMarkerUtility.virtualMechanismFactoryName; import java.util.function.Consumer; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.security.VirtualDomainMarkerUtility; import org.jboss.as.server.security.VirtualDomainMetaData; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController.Mode; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.wildfly.security.auth.permission.LoginPermission; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.http.HttpServerAuthenticationMechanismFactory; import org.wildfly.security.http.oidc.OidcMechanismFactory; import org.wildfly.security.http.oidc.OidcSecurityRealm; /** * A {@link DeploymentUnitProcessor} to install a virtual HTTP server authentication mechanism factory if required. * * @author <a href="mailto:[email protected]">Farah Juma</a> */ class VirtualHttpServerMechanismFactoryProcessor implements DeploymentUnitProcessor { private static final String VIRTUAL_REALM = "virtual"; @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (deploymentUnit.getParent() != null || !isVirtualMechanismFactoryRequired(deploymentUnit)) { return; // Only interested in installation if this is really the root deployment. } ServiceName virtualMechanismFactoryName = virtualMechanismFactoryName(deploymentUnit); ServiceTarget serviceTarget = phaseContext.getServiceTarget(); ServiceBuilder<?> serviceBuilder = serviceTarget.addService(virtualMechanismFactoryName); final HttpServerAuthenticationMechanismFactory virtualMechanismFactory = new OidcMechanismFactory(); final Consumer<HttpServerAuthenticationMechanismFactory> mechanismFactoryConsumer = serviceBuilder.provides(virtualMechanismFactoryName); serviceBuilder.setInstance(Service.newInstance(mechanismFactoryConsumer, virtualMechanismFactory)); serviceBuilder.setInitialMode(Mode.ON_DEMAND); serviceBuilder.install(); if (! isVirtualDomainCreated(deploymentUnit)) { ServiceName virtualDomainName = VirtualDomainMarkerUtility.virtualDomainName(deploymentUnit); VirtualDomainMetaData virtualDomainMetaData = getVirtualDomainMetaData(deploymentUnit); serviceBuilder = serviceTarget.addService(virtualDomainName); SecurityDomain.Builder virtualDomainBuilder = SecurityDomain.builder() .addRealm(VIRTUAL_REALM, new OidcSecurityRealm()).build() .setDefaultRealmName(VIRTUAL_REALM) .setPermissionMapper((permissionMappable, roles) -> LoginPermission.getInstance()); configureVirtualDomain(virtualDomainMetaData, virtualDomainBuilder); SecurityDomain virtualDomain = virtualDomainBuilder.build(); if (virtualDomainMetaData != null) { virtualDomainMetaData.setSecurityDomain(virtualDomain); } Consumer<SecurityDomain> securityDomainConsumer = serviceBuilder.provides(new ServiceName[]{virtualDomainName}); serviceBuilder.setInstance(Service.newInstance(securityDomainConsumer, virtualDomain)); serviceBuilder.setInitialMode(Mode.ON_DEMAND); serviceBuilder.install(); } } @Override public void undeploy(DeploymentUnit deploymentUnit) { clearVirtualDomainMetaDataSecurityDomain(deploymentUnit); } }
5,058
50.622449
145
java
null
wildfly-main/elytron-oidc-client/src/main/java/org/wildfly/extension/elytron/oidc/SecureServerDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import static org.wildfly.extension.elytron.oidc.ElytronOidcDescriptionConstants.SECURE_SERVER; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.DISABLE_TRUST_MANAGER; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.ALL_ATTRIBUTES; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.CLIENT_ID; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.RESOURCE; import static org.wildfly.extension.elytron.oidc._private.ElytronOidcLogger.ROOT_LOGGER; import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.file.Path; import java.util.Collections; import java.util.Date; import java.util.List; import io.undertow.io.IoCallback; import io.undertow.io.Sender; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.resource.Resource; import io.undertow.server.handlers.resource.ResourceChangeListener; import io.undertow.server.handlers.resource.ResourceManager; import io.undertow.util.ETag; import io.undertow.util.MimeMappings; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.AbstractRemoveStepHandler; 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.PathElement; import org.jboss.as.controller.ResourceDefinition; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.OperationEntry; import org.jboss.as.server.mgmt.domain.ExtensibleHttpManagement; import org.jboss.dmr.ModelNode; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.jboss.msc.value.InjectedValue; import org.wildfly.security.http.oidc.Oidc; /** * A {@link ResourceDefinition} for securing deployments via OpenID Connect. * * @author <a href="mailto:[email protected]">Farah Juma</a> */ class SecureServerDefinition extends SimpleResourceDefinition { private static String HTTP_MANAGEMENT_CONTEXT = "http-management-context"; SecureServerDefinition() { super(new Parameters(PathElement.pathElement(SECURE_SERVER), ElytronOidcExtension.getResourceDescriptionResolver(SECURE_SERVER)) .setAddHandler(SecureServerDefinition.SecureServerAddHandler.INSTANCE) .setRemoveHandler(SecureServerDefinition.SecureServerRemoveHandler.INSTANCE) .setAddRestartLevel(OperationEntry.Flag.RESTART_RESOURCE_SERVICES) .setRemoveRestartLevel(OperationEntry.Flag.RESTART_RESOURCE_SERVICES)); } @Override public void registerAttributes(ManagementResourceRegistration resourceRegistration) { super.registerAttributes(resourceRegistration); for (AttributeDefinition attribute : ALL_ATTRIBUTES) { resourceRegistration.registerReadWriteAttribute(attribute, null, SecureServerDefinition.SecureServerWriteAttributeHandler.INSTANCE); } } @Override public void registerChildren(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerSubModel(new CredentialDefinition()); resourceRegistration.registerSubModel(new RedirectRewriteRuleDefinition()); } static class SecureServerAddHandler extends AbstractAddStepHandler { public static SecureServerDefinition.SecureServerAddHandler INSTANCE = new SecureServerDefinition.SecureServerAddHandler(); static final String HTTP_MANAGEMENT_HTTP_EXTENSIBLE_CAPABILITY = "org.wildfly.management.http.extensible"; private SecureServerAddHandler() { super(ALL_ATTRIBUTES); } @Override protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { super.performRuntime(context, operation, model); String clientId = CLIENT_ID.resolveModelAttribute(context, model).asStringOrNull(); String resource = RESOURCE.resolveModelAttribute(context, model).asStringOrNull(); if (clientId == null && resource == null) { throw ROOT_LOGGER.resourceOrClientIdMustBeConfigured(); } boolean disableTrustManager = DISABLE_TRUST_MANAGER.resolveModelAttribute(context, model).asBoolean(); if (disableTrustManager) { ROOT_LOGGER.disableTrustManagerSetToTrue(); } OidcConfigService oidcConfigService = OidcConfigService.getInstance(); oidcConfigService.addSecureDeployment(context.getCurrentAddressValue(), context.resolveExpressions(model)); ServiceTarget serviceTarget = context.getServiceTarget(); InjectedValue<ExtensibleHttpManagement> extensibleHttpManagement = new InjectedValue<>(); String secureServerName = context.getCurrentAddressValue(); ServiceName serviceName = ServiceName.of(SECURE_SERVER, secureServerName); serviceTarget.addService(serviceName.append(HTTP_MANAGEMENT_CONTEXT), createHttpManagementConfigContextService(secureServerName, extensibleHttpManagement)) .addDependency(context.getCapabilityServiceName(HTTP_MANAGEMENT_HTTP_EXTENSIBLE_CAPABILITY, ExtensibleHttpManagement.class), ExtensibleHttpManagement.class, extensibleHttpManagement).setInitialMode(ServiceController.Mode.ACTIVE).install(); } } static class SecureServerWriteAttributeHandler extends AbstractWriteAttributeHandler<OidcConfigService> { public static final SecureServerDefinition.SecureServerWriteAttributeHandler INSTANCE = new SecureServerDefinition.SecureServerWriteAttributeHandler(); SecureServerWriteAttributeHandler() { super(ALL_ATTRIBUTES.toArray(new SimpleAttributeDefinition[ALL_ATTRIBUTES.size()])); } @Override protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<OidcConfigService> handbackHolder) throws OperationFailedException { OidcConfigService oidcConfigService = OidcConfigService.getInstance(); oidcConfigService.updateSecureDeployment(context.getCurrentAddressValue(), attributeName, resolvedValue); handbackHolder.setHandback(oidcConfigService); return false; } @Override protected void revertUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode valueToRestore, ModelNode valueToRevert, OidcConfigService oidcConfigService) throws OperationFailedException { oidcConfigService.updateSecureDeployment(context.getCurrentAddressValue(), attributeName, valueToRestore); } } static class SecureServerRemoveHandler extends AbstractRemoveStepHandler { public static SecureServerDefinition.SecureServerRemoveHandler INSTANCE = new SecureServerDefinition.SecureServerRemoveHandler(); SecureServerRemoveHandler() { } @Override protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { OidcConfigService oidcConfigService = OidcConfigService.getInstance(); oidcConfigService.removeSecureDeployment(context.getCurrentAddressValue()); } } private static Service<Void> createHttpManagementConfigContextService(final String secureServerName, final InjectedValue<ExtensibleHttpManagement> httpConfigContext) { final String contextName = "/oidc/" + secureServerName + "/"; return new Service<Void>() { public void start(StartContext startContext) throws StartException { ExtensibleHttpManagement extensibleHttpManagement = (ExtensibleHttpManagement)httpConfigContext.getValue(); extensibleHttpManagement.addStaticContext(contextName, new ResourceManager() { public Resource getResource(final String path) throws IOException { OidcConfigService oidcConfigService = OidcConfigService.getInstance(); // need to convert to realm configuration to work with the Keycloak JavaScript adapter that HAL uses final String config = oidcConfigService.getJSON(secureServerName, true); if (config == null) { return null; } return new Resource() { public String getPath() { return null; } public Date getLastModified() { return null; } public String getLastModifiedString() { return null; } public ETag getETag() { return null; } public String getName() { return null; } public boolean isDirectory() { return false; } public List<Resource> list() { return Collections.emptyList(); } public String getContentType(MimeMappings mimeMappings) { return Oidc.JSON_CONTENT_TYPE; } public void serve(Sender sender, HttpServerExchange exchange, IoCallback completionCallback) { sender.send(config); } public Long getContentLength() { return Long.valueOf((long)config.length()); } public String getCacheKey() { return null; } public File getFile() { return null; } public Path getFilePath() { return null; } public File getResourceManagerRoot() { return null; } public Path getResourceManagerRootPath() { return null; } public URL getUrl() { return null; } }; } public boolean isResourceChangeListenerSupported() { return false; } public void registerResourceChangeListener(ResourceChangeListener listener) { } public void removeResourceChangeListener(ResourceChangeListener listener) { } public void close() throws IOException { } }); } public void stop(StopContext stopContext) { ((ExtensibleHttpManagement)httpConfigContext.getValue()).removeContext(contextName); } public Void getValue() throws IllegalStateException, IllegalArgumentException { return null; } }; } }
13,099
45.953405
179
java
null
wildfly-main/elytron-oidc-client/src/main/java/org/wildfly/extension/elytron/oidc/ElytronOidcSubsystemDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import static org.jboss.as.server.security.VirtualDomainUtil.OIDC_VIRTUAL_SECURITY_DOMAIN_CREATION_SERVICE; import static org.jboss.as.server.security.VirtualDomainUtil.VIRTUAL_SECURITY_DOMAIN_CREATION_SERVICE; import java.util.Collection; import java.util.Collections; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.ReloadRequiredRemoveStepHandler; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.server.security.VirtualSecurityDomainCreationService; import org.jboss.dmr.ModelNode; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; /** * Root subsystem definition for the Elytron OpenID Connect subsystem. * * @author <a href="mailto:[email protected]">Farah Juma</a> */ class ElytronOidcSubsystemDefinition extends PersistentResourceDefinition { static final String CONFIG_CAPABILITY_NAME = "org.wildlfly.elytron.oidc"; static final String ELYTRON_CAPABILITY_NAME = "org.wildfly.security.elytron"; static final RuntimeCapability<Void> CONFIG_CAPABILITY = RuntimeCapability.Builder.of(CONFIG_CAPABILITY_NAME) .setServiceType(Void.class) .addRequirements(ELYTRON_CAPABILITY_NAME) .build(); protected ElytronOidcSubsystemDefinition() { super(new SimpleResourceDefinition.Parameters(ElytronOidcExtension.SUBSYSTEM_PATH, ElytronOidcExtension.getResourceDescriptionResolver()) .setAddHandler(new ElytronOidcSubsystemAdd()) .setRemoveHandler(ElytronOidcSubsystemRemove.INSTANCE) .setCapabilities(CONFIG_CAPABILITY) ); } @Override public Collection<AttributeDefinition> getAttributes() { return Collections.emptySet(); } @Override public void registerAttributes(ManagementResourceRegistration resourceRegistration) { } @Override public void registerChildren(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerSubModel(new RealmDefinition()); resourceRegistration.registerSubModel(new ProviderDefinition()); resourceRegistration.registerSubModel(new SecureDeploymentDefinition()); resourceRegistration.registerSubModel(new SecureServerDefinition()); } private static class ElytronOidcSubsystemRemove extends ReloadRequiredRemoveStepHandler { static final ElytronOidcSubsystemRemove INSTANCE = new ElytronOidcSubsystemRemove(); private ElytronOidcSubsystemRemove() { } @Override protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { if (context.isResourceServiceRestartAllowed()) { context.removeService(OIDC_VIRTUAL_SECURITY_DOMAIN_CREATION_SERVICE); } else { context.reloadRequired(); } } @Override protected void recoverServices(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { ServiceTarget target = context.getServiceTarget(); installService(VIRTUAL_SECURITY_DOMAIN_CREATION_SERVICE, new VirtualSecurityDomainCreationService(), target); } } static void installService(ServiceName serviceName, Service<?> service, ServiceTarget serviceTarget) { serviceTarget.addService(serviceName, service) .setInitialMode(ServiceController.Mode.ACTIVE) .install(); } }
4,749
41.035398
135
java
null
wildfly-main/elytron-oidc-client/src/main/java/org/wildfly/extension/elytron/oidc/ElytronOidcDescriptionConstants.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; /** * Constants used in the Elytron OpenID Connect subsystem. * * @author <a href="mailto:[email protected]">Farah Juma</a> */ interface ElytronOidcDescriptionConstants { String ADAPTER_STATE_COOKIE_PATH = "adapter-state-cookie-path"; String ALGORITHM = "algorithm"; String ALLOW_ANY_HOSTNAME = "allow-any-hostname"; String ALWAYS_REFRESH_TOKEN = "always-refresh-token"; String AUTH_SERVER_URL = "auth-server-url"; String AUTODETECT_BEARER_ONLY = "autodetect-bearer-only"; String BEARER_ONLY = "bearer-only"; String CLIENT_ID = "client-id"; String CLIENT_KEY_ALIAS = "client-key-alias"; String CLIENT_KEY_PASSWORD = "client-key-password"; String CLIENT_KEYSTORE = "client-keystore"; String CLIENT_KEYSTORE_FILE = "client-keystore-file"; String CLIENT_KEYSTORE_PASSWORD = "client-keystore-password"; String CLIENT_KEYSTORE_TYPE = "client-keystore-type"; String CONFIDENTIAL_PORT = "confidential-port"; String CONNECTION_POOL_SIZE = "connection-pool-size"; String CONNECTION_TIMEOUT_MILLIS = "connection-timeout-millis"; String CONNECTION_TTL_MILLIS = "connection-ttl-millis"; String CORS_MAX_AGE = "cors-max-age"; String CORS_ALLOWED_HEADERS = "cors-allowed-headers"; String CORS_ALLOWED_METHODS = "cors-allowed-methods"; String CORS_EXPOSED_HEADERS = "cors-exposed-headers"; String CREDENTIAL = "credential"; String CREDENTIALS = "credentials"; String DISABLE_TRUST_MANAGER = "disable-trust-manager"; String ENABLE_BASIC_AUTH = "enable-basic-auth"; String ENABLE_CORS = "enable-cors"; String EXPOSE_TOKEN = "expose-token"; String IGNORE_OAUTH_QUERY_PARAMTER = "ignore-oauth-query-parameter"; String MIN_TIME_BETWEEN_JWKS_REQUESTS = "min-time-between-jwks-requests"; String PATTERN = "pattern"; String PRINCIPAL_ATTRIBUTE = "principal-attribute"; String PROVIDER = "provider"; String PROVIDER_URL = "provider-url"; String PROXY_URL = "proxy-url"; String PUBLIC_CLIENT = "public-client"; String PUBLIC_KEY_CACHE_TTL = "public-key-cache-ttl"; String REALM = "realm"; String REALM_PUBLIC_KEY = "realm-public-key"; String REDIRECT_REWRITE_RULE = "redirect-rewrite-rule"; String REGISTER_NODE_AT_STARTUP = "register-node-at-startup"; String REGISTER_NODE_PERIOD = "register-node-period"; String REPLACEMENT = "replacement"; String RESOURCE = "resource"; String SECRET = "secret"; String SECURE_DEPLOYMENT = "secure-deployment"; String SECURE_SERVER = "secure-server"; String SOCKET_TIMEOUT_MILLIS = "socket-timeout-millis"; String SSL_REQUIRED = "ssl-required"; String TOKEN_MINIMUM_TIME_TO_LIVE = "token-minimum-time-to-live"; String TOKEN_SIGNATURE_ALGORITHM = "token-signature-algorithm"; String TOKEN_STORE = "token-store"; String TOKEN_TIMEOUT = "token-timeout"; String TRUSTSTORE = "truststore"; String TRUSTORE_PASSWORD = "truststore-password"; String TURN_OFF_CHANGE_SESSION_ID_ON_LOGIN = "turn-off-change-session-id-on-login"; String USE_RESOURCE_ROLE_MAPPINGS = "use-resource-role-mappings"; String VERIFY_TOKEN_AUDIENCE = "verify-token-audience"; }
3,943
44.333333
87
java
null
wildfly-main/elytron-oidc-client/src/main/java/org/wildfly/extension/elytron/oidc/ElytronOidcSubsystemParser_1_0.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import static org.wildfly.extension.elytron.oidc.CredentialDefinition.ALGORITHM; import static org.wildfly.extension.elytron.oidc.CredentialDefinition.CLIENT_KEYSTORE_FILE; import static org.wildfly.extension.elytron.oidc.CredentialDefinition.CLIENT_KEYSTORE_TYPE; import static org.wildfly.extension.elytron.oidc.CredentialDefinition.CLIENT_KEY_ALIAS; import static org.wildfly.extension.elytron.oidc.CredentialDefinition.SECRET; import static org.wildfly.extension.elytron.oidc.CredentialDefinition.TOKEN_TIMEOUT; import static org.wildfly.extension.elytron.oidc.ElytronOidcDescriptionConstants.CREDENTIAL; import static org.wildfly.extension.elytron.oidc.ElytronOidcDescriptionConstants.PROVIDER; import static org.wildfly.extension.elytron.oidc.ElytronOidcDescriptionConstants.REALM; import static org.wildfly.extension.elytron.oidc.ElytronOidcDescriptionConstants.REDIRECT_REWRITE_RULE; import static org.wildfly.extension.elytron.oidc.ElytronOidcDescriptionConstants.SECURE_DEPLOYMENT; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.ALLOW_ANY_HOSTNAME; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.ALWAYS_REFRESH_TOKEN; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.AUTH_SERVER_URL; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.AUTODETECT_BEARER_ONLY; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.CLIENT_KEYSTORE; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.CLIENT_KEYSTORE_PASSWORD; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.CLIENT_KEY_PASSWORD; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.CONFIDENTIAL_PORT; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.CONNECTION_POOL_SIZE; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.CONNECTION_TIMEOUT_MILLIS; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.CONNECTION_TTL_MILLIS; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.CORS_ALLOWED_HEADERS; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.CORS_ALLOWED_METHODS; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.CORS_EXPOSED_HEADERS; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.CORS_MAX_AGE; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.DISABLE_TRUST_MANAGER; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.ENABLE_CORS; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.EXPOSE_TOKEN; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.IGNORE_OAUTH_QUERY_PARAMETER; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.PRINCIPAL_ATTRIBUTE; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.PROVIDER_URL; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.PROXY_URL; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.REALM_PUBLIC_KEY; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.REGISTER_NODE_AT_STARTUP; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.REGISTER_NODE_PERIOD; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.SOCKET_TIMEOUT_MILLIS; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.SSL_REQUIRED; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.TOKEN_SIGNATURE_ALGORITHM; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.TOKEN_STORE; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.TRUSTSTORE; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.TRUSTSTORE_PASSWORD; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.VERIFY_TOKEN_AUDIENCE; import static org.wildfly.extension.elytron.oidc.RedirectRewriteRuleDefinition.REPLACEMENT; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.ADAPTER_STATE_COOKIE_PATH; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.BEARER_ONLY; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.CLIENT_ID; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.ENABLE_BASIC_AUTH; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.MIN_TIME_BETWEEN_JWKS_REQUESTS; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.PUBLIC_CLIENT; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.PUBLIC_KEY_CACHE_TTL; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.RESOURCE; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.TOKEN_MINIMUM_TIME_TO_LIVE; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.TURN_OFF_CHANGE_SESSION_ID_ON_LOGIN; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.USE_RESOURCE_ROLE_MAPPINGS; import java.util.Collections; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.AttributeMarshaller; import org.jboss.as.controller.AttributeParser; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PersistentResourceXMLDescription; import org.jboss.as.controller.PersistentResourceXMLParser; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.parsing.ParseUtils; import org.jboss.dmr.ModelNode; import org.jboss.staxmapper.XMLExtendedStreamReader; /** * Subsystem parser for the Elytron OpenID Connect subsystem. * * @author <a href="mailto:[email protected]">Farah Juma</a> */ public class ElytronOidcSubsystemParser_1_0 extends PersistentResourceXMLParser { /** * The name space used for the {@code subsystem} element */ public static final String NAMESPACE_1_0 = "urn:wildfly:elytron-oidc-client:1.0"; static final AttributeParser SIMPLE_ATTRIBUTE_PARSER = new AttributeElementParser(); static final AttributeMarshaller SIMPLE_ATTRIBUTE_MARSHALLER = new AttributeElementMarshaller(); final PersistentResourceXMLDescription realmParser = PersistentResourceXMLDescription.builder(PathElement.pathElement(REALM)) .addAttribute(REALM_PUBLIC_KEY, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(AUTH_SERVER_URL, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(PROVIDER_URL, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(TRUSTSTORE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(TRUSTSTORE_PASSWORD, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(SSL_REQUIRED, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CONFIDENTIAL_PORT, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(ALLOW_ANY_HOSTNAME, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(DISABLE_TRUST_MANAGER, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CONNECTION_POOL_SIZE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(ENABLE_CORS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CLIENT_KEYSTORE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CLIENT_KEYSTORE_PASSWORD, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CLIENT_KEY_PASSWORD, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CORS_MAX_AGE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CORS_ALLOWED_HEADERS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CORS_ALLOWED_METHODS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CORS_EXPOSED_HEADERS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(EXPOSE_TOKEN, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(ALWAYS_REFRESH_TOKEN, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(REGISTER_NODE_AT_STARTUP, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(REGISTER_NODE_PERIOD, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(TOKEN_STORE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(PRINCIPAL_ATTRIBUTE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(AUTODETECT_BEARER_ONLY, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(IGNORE_OAUTH_QUERY_PARAMETER, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(PROXY_URL, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(VERIFY_TOKEN_AUDIENCE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(SOCKET_TIMEOUT_MILLIS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CONNECTION_TTL_MILLIS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CONNECTION_TIMEOUT_MILLIS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(TOKEN_SIGNATURE_ALGORITHM, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .build(); final PersistentResourceXMLDescription providerParser = PersistentResourceXMLDescription.builder(PathElement.pathElement(PROVIDER)) .addAttribute(REALM_PUBLIC_KEY, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(AUTH_SERVER_URL, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(PROVIDER_URL, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(TRUSTSTORE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(TRUSTSTORE_PASSWORD, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(SSL_REQUIRED, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CONFIDENTIAL_PORT, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(ALLOW_ANY_HOSTNAME, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(DISABLE_TRUST_MANAGER, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CONNECTION_POOL_SIZE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(ENABLE_CORS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CLIENT_KEYSTORE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CLIENT_KEYSTORE_PASSWORD, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CLIENT_KEY_PASSWORD, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CORS_MAX_AGE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CORS_ALLOWED_HEADERS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CORS_ALLOWED_METHODS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CORS_EXPOSED_HEADERS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(EXPOSE_TOKEN, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(ALWAYS_REFRESH_TOKEN, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(REGISTER_NODE_AT_STARTUP, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(REGISTER_NODE_PERIOD, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(TOKEN_STORE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(PRINCIPAL_ATTRIBUTE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(AUTODETECT_BEARER_ONLY, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(IGNORE_OAUTH_QUERY_PARAMETER, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(PROXY_URL, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(VERIFY_TOKEN_AUDIENCE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(SOCKET_TIMEOUT_MILLIS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CONNECTION_TTL_MILLIS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CONNECTION_TIMEOUT_MILLIS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(TOKEN_SIGNATURE_ALGORITHM, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .build(); final PersistentResourceXMLDescription credentialParser = PersistentResourceXMLDescription.builder(PathElement.pathElement(CREDENTIAL)) .addAttribute(SECRET) .addAttribute(CLIENT_KEYSTORE_FILE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(CLIENT_KEYSTORE_TYPE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(CredentialDefinition.CLIENT_KEYSTORE_PASSWORD, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(CredentialDefinition.CLIENT_KEY_PASSWORD, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(TOKEN_TIMEOUT, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(CLIENT_KEY_ALIAS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(ALGORITHM, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .build(); final PersistentResourceXMLDescription redirectRewriteRuleParser = PersistentResourceXMLDescription.builder(PathElement.pathElement(REDIRECT_REWRITE_RULE)) .addAttribute(REPLACEMENT) .build(); final PersistentResourceXMLDescription.PersistentResourceXMLBuilder secureDeploymentParserBuilder = PersistentResourceXMLDescription.builder(PathElement.pathElement(SECURE_DEPLOYMENT)) .addAttribute(REALM_PUBLIC_KEY, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(AUTH_SERVER_URL, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(PROVIDER_URL, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(TRUSTSTORE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(TRUSTSTORE_PASSWORD, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(SSL_REQUIRED, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CONFIDENTIAL_PORT, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(ALLOW_ANY_HOSTNAME, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(DISABLE_TRUST_MANAGER, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CONNECTION_POOL_SIZE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(ENABLE_CORS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CLIENT_KEYSTORE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CLIENT_KEYSTORE_PASSWORD, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CLIENT_KEY_PASSWORD, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CORS_MAX_AGE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CORS_ALLOWED_HEADERS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CORS_ALLOWED_METHODS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CORS_EXPOSED_HEADERS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(EXPOSE_TOKEN, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(ALWAYS_REFRESH_TOKEN, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(REGISTER_NODE_AT_STARTUP, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(REGISTER_NODE_PERIOD, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(TOKEN_STORE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(PRINCIPAL_ATTRIBUTE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(AUTODETECT_BEARER_ONLY, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(IGNORE_OAUTH_QUERY_PARAMETER, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(PROXY_URL, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(VERIFY_TOKEN_AUDIENCE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(SOCKET_TIMEOUT_MILLIS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CONNECTION_TTL_MILLIS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CONNECTION_TIMEOUT_MILLIS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(TOKEN_SIGNATURE_ALGORITHM, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER); final PersistentResourceXMLDescription secureDeploymentParser = secureDeploymentParserBuilder .addAttribute(SecureDeploymentDefinition.REALM, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(SecureDeploymentDefinition.PROVIDER, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(RESOURCE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(CLIENT_ID, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(USE_RESOURCE_ROLE_MAPPINGS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(BEARER_ONLY, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(ENABLE_BASIC_AUTH, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(PUBLIC_CLIENT, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(TURN_OFF_CHANGE_SESSION_ID_ON_LOGIN, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(TOKEN_MINIMUM_TIME_TO_LIVE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(MIN_TIME_BETWEEN_JWKS_REQUESTS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(PUBLIC_KEY_CACHE_TTL, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(ADAPTER_STATE_COOKIE_PATH, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addChild(redirectRewriteRuleParser) .addChild(credentialParser) .setUseElementsForGroups(true) .build(); PersistentResourceXMLDescription getRealmParser() { return realmParser; } PersistentResourceXMLDescription getProviderParser() { return providerParser; } PersistentResourceXMLDescription getSecureDeploymentParser() { return secureDeploymentParser; } @Override public PersistentResourceXMLDescription getParserDescription() { return PersistentResourceXMLDescription.builder(ElytronOidcExtension.SUBSYSTEM_PATH, getNameSpace()) .addChild(getRealmParser()) .addChild(getProviderParser()) .addChild(getSecureDeploymentParser()) .build(); } static class AttributeElementParser extends AttributeParser { @Override public boolean isParseAsElement() { return true; } @Override public void parseElement(AttributeDefinition attribute, XMLExtendedStreamReader reader, ModelNode operation) throws XMLStreamException { assert attribute instanceof SimpleAttributeDefinition; if (operation.hasDefined(attribute.getName())) { throw ParseUtils.unexpectedElement(reader); } else if (attribute.getXmlName().equals(reader.getLocalName())) { ((SimpleAttributeDefinition) attribute).parseAndSetParameter(reader.getElementText(), operation, reader); } else { throw ParseUtils.unexpectedElement(reader, Collections.singleton(attribute.getXmlName())); } } } static class AttributeElementMarshaller extends AttributeMarshaller.AttributeElementMarshaller { @Override public void marshallAsElement(AttributeDefinition attribute, ModelNode resourceModel, boolean marshallDefault, XMLStreamWriter writer) throws XMLStreamException { writer.writeStartElement(attribute.getXmlName()); marshallElementContent(resourceModel.get(attribute.getName()).asString(), writer); writer.writeEndElement(); } } String getNameSpace() { return NAMESPACE_1_0; } }
22,270
72.990033
188
java
null
wildfly-main/elytron-oidc-client/src/main/java/org/wildfly/extension/elytron/oidc/ElytronOidcSubsystemParser_2_0.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import static org.wildfly.extension.elytron.oidc.ElytronOidcDescriptionConstants.SECURE_SERVER; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.ALLOW_ANY_HOSTNAME; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.ALWAYS_REFRESH_TOKEN; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.AUTH_SERVER_URL; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.AUTODETECT_BEARER_ONLY; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.CLIENT_KEYSTORE; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.CLIENT_KEYSTORE_PASSWORD; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.CLIENT_KEY_PASSWORD; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.CONFIDENTIAL_PORT; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.CONNECTION_POOL_SIZE; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.CONNECTION_TIMEOUT_MILLIS; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.CONNECTION_TTL_MILLIS; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.CORS_ALLOWED_HEADERS; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.CORS_ALLOWED_METHODS; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.CORS_EXPOSED_HEADERS; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.CORS_MAX_AGE; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.DISABLE_TRUST_MANAGER; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.ENABLE_CORS; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.EXPOSE_TOKEN; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.IGNORE_OAUTH_QUERY_PARAMETER; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.PRINCIPAL_ATTRIBUTE; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.PROVIDER_URL; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.PROXY_URL; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.REALM_PUBLIC_KEY; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.REGISTER_NODE_AT_STARTUP; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.REGISTER_NODE_PERIOD; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.SOCKET_TIMEOUT_MILLIS; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.SSL_REQUIRED; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.TOKEN_SIGNATURE_ALGORITHM; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.TOKEN_STORE; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.TRUSTSTORE; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.TRUSTSTORE_PASSWORD; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.VERIFY_TOKEN_AUDIENCE; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.ADAPTER_STATE_COOKIE_PATH; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.BEARER_ONLY; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.CLIENT_ID; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.ENABLE_BASIC_AUTH; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.MIN_TIME_BETWEEN_JWKS_REQUESTS; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.PUBLIC_CLIENT; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.PUBLIC_KEY_CACHE_TTL; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.RESOURCE; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.TOKEN_MINIMUM_TIME_TO_LIVE; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.TURN_OFF_CHANGE_SESSION_ID_ON_LOGIN; import static org.wildfly.extension.elytron.oidc.SecureDeploymentDefinition.USE_RESOURCE_ROLE_MAPPINGS; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PersistentResourceXMLDescription; /** * Subsystem parser for the Elytron OpenID Connect subsystem. * * @author <a href="mailto:[email protected]">Farah Juma</a> */ public class ElytronOidcSubsystemParser_2_0 extends ElytronOidcSubsystemParser_1_0 { /** * The name space used for the {@code subsystem} element */ public static final String NAMESPACE_2_0 = "urn:wildfly:elytron-oidc-client:2.0"; @Override String getNameSpace() { return NAMESPACE_2_0; } final PersistentResourceXMLDescription.PersistentResourceXMLBuilder secureServerParserBuilder = PersistentResourceXMLDescription.builder(PathElement.pathElement(SECURE_SERVER)) .addAttribute(REALM_PUBLIC_KEY, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(AUTH_SERVER_URL, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(PROVIDER_URL, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(TRUSTSTORE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(TRUSTSTORE_PASSWORD, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(SSL_REQUIRED, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CONFIDENTIAL_PORT, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(ALLOW_ANY_HOSTNAME, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(DISABLE_TRUST_MANAGER, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CONNECTION_POOL_SIZE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(ENABLE_CORS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CLIENT_KEYSTORE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CLIENT_KEYSTORE_PASSWORD, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CLIENT_KEY_PASSWORD, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CORS_MAX_AGE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CORS_ALLOWED_HEADERS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CORS_ALLOWED_METHODS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CORS_EXPOSED_HEADERS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(EXPOSE_TOKEN, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(ALWAYS_REFRESH_TOKEN, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(REGISTER_NODE_AT_STARTUP, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(REGISTER_NODE_PERIOD, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(TOKEN_STORE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(PRINCIPAL_ATTRIBUTE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(AUTODETECT_BEARER_ONLY, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(IGNORE_OAUTH_QUERY_PARAMETER, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(PROXY_URL, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(VERIFY_TOKEN_AUDIENCE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(SOCKET_TIMEOUT_MILLIS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CONNECTION_TTL_MILLIS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(CONNECTION_TIMEOUT_MILLIS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER) .addAttribute(TOKEN_SIGNATURE_ALGORITHM, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER); final PersistentResourceXMLDescription secureServerParser = secureServerParserBuilder .addAttribute(SecureDeploymentDefinition.REALM, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(SecureDeploymentDefinition.PROVIDER, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(RESOURCE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(CLIENT_ID, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(USE_RESOURCE_ROLE_MAPPINGS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(BEARER_ONLY, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(ENABLE_BASIC_AUTH, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(PUBLIC_CLIENT, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(TURN_OFF_CHANGE_SESSION_ID_ON_LOGIN, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(TOKEN_MINIMUM_TIME_TO_LIVE, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(MIN_TIME_BETWEEN_JWKS_REQUESTS, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(PUBLIC_KEY_CACHE_TTL, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addAttribute(ADAPTER_STATE_COOKIE_PATH, SIMPLE_ATTRIBUTE_PARSER, SIMPLE_ATTRIBUTE_MARSHALLER ) .addChild(redirectRewriteRuleParser) .addChild(credentialParser) .setUseElementsForGroups(true) .build(); PersistentResourceXMLDescription getSecureServerParser() { return secureServerParser; } @Override public PersistentResourceXMLDescription getParserDescription() { return PersistentResourceXMLDescription.builder(ElytronOidcExtension.SUBSYSTEM_PATH, getNameSpace()) .addChild(getRealmParser()) .addChild(getProviderParser()) .addChild(getSecureDeploymentParser()) .addChild(getSecureServerParser()) // new in 2.0 .build(); } }
11,179
71.597403
180
java
null
wildfly-main/elytron-oidc-client/src/main/java/org/wildfly/extension/elytron/oidc/ElytronOidcSubsystemAdd.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import static org.jboss.as.server.security.VirtualDomainUtil.OIDC_VIRTUAL_SECURITY_DOMAIN_CREATION_SERVICE; import static org.wildfly.extension.elytron.oidc.ElytronOidcSubsystemDefinition.installService; import static org.wildfly.extension.elytron.oidc._private.ElytronOidcLogger.ROOT_LOGGER; import org.jboss.as.controller.AbstractBoottimeAddStepHandler; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.registry.Resource; 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.jboss.msc.service.ServiceTarget; /** * Add handler for the Elytron OpenID Connect subsystem. * * @author <a href="mailto:[email protected]">Farah Juma</a> */ class ElytronOidcSubsystemAdd extends AbstractBoottimeAddStepHandler { private static final int PARSE_OIDC_DETECTION = 0x4C0E; private static final int PARSE_DEFINE_VIRTUAL_HTTP_SERVER_MECHANISM_FACTORY_NAME = 0x4C18; private static final int DEPENDENCIES_OIDC = 0x1910; private static final int INSTALL_VIRTUAL_HTTP_SERVER_MECHANISM_FACTORY = 0x3100; ElytronOidcSubsystemAdd() { } @Override public void performBoottime(OperationContext context, ModelNode operation, ModelNode model) { ROOT_LOGGER.activatingSubsystem(); OidcConfigService.getInstance().clear(); ServiceTarget target = context.getServiceTarget(); installService(OIDC_VIRTUAL_SECURITY_DOMAIN_CREATION_SERVICE, new OidcVirtualSecurityDomainCreationService(), target); if (context.isNormalServer()) { context.addStep(new AbstractDeploymentChainStep() { @Override protected void execute(DeploymentProcessorTarget processorTarget) { processorTarget.addDeploymentProcessor(ElytronOidcExtension.SUBSYSTEM_NAME, Phase.PARSE, PARSE_OIDC_DETECTION, new OidcActivationProcessor()); processorTarget.addDeploymentProcessor(ElytronOidcExtension.SUBSYSTEM_NAME, Phase.PARSE, PARSE_DEFINE_VIRTUAL_HTTP_SERVER_MECHANISM_FACTORY_NAME, new VirtualHttpServerMechanismFactoryNameProcessor()); processorTarget.addDeploymentProcessor(ElytronOidcExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, DEPENDENCIES_OIDC, new OidcDependencyProcessor()); processorTarget.addDeploymentProcessor(ElytronOidcExtension.SUBSYSTEM_NAME, Phase.INSTALL, INSTALL_VIRTUAL_HTTP_SERVER_MECHANISM_FACTORY, new VirtualHttpServerMechanismFactoryProcessor()); } }, OperationContext.Stage.RUNTIME); } } @Override protected void rollbackRuntime(OperationContext context, ModelNode operation, Resource resource) { context.removeService(OIDC_VIRTUAL_SECURITY_DOMAIN_CREATION_SERVICE); } }
3,633
45.589744
220
java
null
wildfly-main/elytron-oidc-client/src/main/java/org/wildfly/extension/elytron/oidc/OidcActivationProcessor.java
/* * Copyright 2021 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import static org.wildfly.extension.elytron.oidc._private.ElytronOidcLogger.ROOT_LOGGER; import static org.wildfly.security.http.oidc.Oidc.JSON_CONFIG_CONTEXT_PARAM; import java.util.ArrayList; import java.util.List; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.web.common.VirtualHttpServerMechanismFactoryMarkerUtility; import org.jboss.as.web.common.WarMetaData; import org.jboss.metadata.javaee.spec.ParamValueMetaData; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.jboss.metadata.web.spec.ListenerMetaData; import org.jboss.metadata.web.spec.LoginConfigMetaData; import org.wildfly.security.http.oidc.OidcConfigurationServletListener; /** * A {@link DeploymentUnitProcessor} to detect if Elytron OIDC should be activated. * * @author <a href="mailto:[email protected]">Farah Juma</a> */ class OidcActivationProcessor implements DeploymentUnitProcessor { private static final String OIDC_AUTH_METHOD = "OIDC"; @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); if (warMetaData == null) { return; } JBossWebMetaData webMetaData = warMetaData.getMergedJBossWebMetaData(); if (webMetaData == null) { webMetaData = new JBossWebMetaData(); warMetaData.setMergedJBossWebMetaData(webMetaData); } OidcConfigService configService = OidcConfigService.getInstance(); if (configService.isSecureDeployment(deploymentUnit) && configService.isDeploymentConfigured(deploymentUnit)) { addOidcAuthDataAndConfig(phaseContext, configService, webMetaData); } LoginConfigMetaData loginConfig = webMetaData.getLoginConfig(); if (loginConfig != null && OIDC_AUTH_METHOD.equals(loginConfig.getAuthMethod())) { ListenerMetaData listenerMetaData = new ListenerMetaData(); listenerMetaData.setListenerClass(OidcConfigurationServletListener.class.getName()); webMetaData.getListeners().add(listenerMetaData); ROOT_LOGGER.tracef("Activating OIDC for deployment %s.", deploymentUnit.getName()); OidcDeploymentMarker.mark(deploymentUnit); VirtualHttpServerMechanismFactoryMarkerUtility.virtualMechanismFactoryRequired(deploymentUnit); } } private void addOidcAuthDataAndConfig(DeploymentPhaseContext phaseContext, OidcConfigService service, JBossWebMetaData webMetaData) { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); addJSONDataAsContextParam(service.getJSON(deploymentUnit), webMetaData); LoginConfigMetaData loginConfig = webMetaData.getLoginConfig(); if (loginConfig == null) { loginConfig = new LoginConfigMetaData(); webMetaData.setLoginConfig(loginConfig); } loginConfig.setAuthMethod(OIDC_AUTH_METHOD); ROOT_LOGGER.deploymentSecured(deploymentUnit.getName()); } private void addJSONDataAsContextParam(String json, JBossWebMetaData webMetaData) { List<ParamValueMetaData> contextParams = webMetaData.getContextParams(); if (contextParams == null) { contextParams = new ArrayList<>(); } ParamValueMetaData param = new ParamValueMetaData(); param.setParamName(JSON_CONFIG_CONTEXT_PARAM); param.setParamValue(json); contextParams.add(param); webMetaData.setContextParams(contextParams); } }
4,509
43.215686
137
java
null
wildfly-main/elytron-oidc-client/src/main/java/org/wildfly/extension/elytron/oidc/ElytronOidcSubsystemTransformers.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import static org.wildfly.extension.elytron.oidc.ElytronOidcDescriptionConstants.SECURE_SERVER; import static org.wildfly.extension.elytron.oidc.ElytronOidcExtension.VERSION_1_0_0; import static org.wildfly.extension.elytron.oidc.ElytronOidcExtension.VERSION_2_0_0; 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.ChainedTransformationDescriptionBuilder; import org.jboss.as.controller.transform.description.ResourceTransformationDescriptionBuilder; import org.jboss.as.controller.transform.description.TransformationDescriptionBuilder; public class ElytronOidcSubsystemTransformers implements ExtensionTransformerRegistration { @Override public String getSubsystemName() { return ElytronOidcExtension.SUBSYSTEM_NAME; } @Override public void registerTransformers(SubsystemTransformerRegistration registration) { ChainedTransformationDescriptionBuilder chainedBuilder = TransformationDescriptionBuilder.Factory.createChainedSubystemInstance(registration.getCurrentSubsystemVersion()); // 2.0.0 (WildFly 29) to 1.0.0 (WildFly 28) from2(chainedBuilder); chainedBuilder.buildAndRegister(registration, new ModelVersion[] { VERSION_1_0_0 }); } private static void from2(ChainedTransformationDescriptionBuilder chainedBuilder) { ResourceTransformationDescriptionBuilder builder = chainedBuilder.createBuilder(VERSION_2_0_0, VERSION_1_0_0); builder.rejectChildResource(PathElement.pathElement(SECURE_SERVER)); } }
2,498
44.436364
179
java
null
wildfly-main/elytron-oidc-client/src/main/java/org/wildfly/extension/elytron/oidc/OidcDeploymentMarker.java
/* * Copyright 2021 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import org.jboss.as.server.deployment.AttachmentKey; import org.jboss.as.server.deployment.DeploymentUnit; /** * Utility class for marking a deployment as an OIDC deployment. * * @author <a href="mailto:[email protected]">Farah Juma</a> */ class OidcDeploymentMarker { private static final AttachmentKey<Boolean> ATTACHMENT_KEY = AttachmentKey.create(Boolean.class); public static void mark(DeploymentUnit deployment) { toRoot(deployment).putAttachment(ATTACHMENT_KEY, true); } public static boolean isOidcDeployment(DeploymentUnit deployment) { Boolean val = toRoot(deployment).getAttachment(ATTACHMENT_KEY); return val != null && val; } private static DeploymentUnit toRoot(final DeploymentUnit deployment) { DeploymentUnit result = deployment; DeploymentUnit parent = result.getParent(); while (parent != null) { result = parent; parent = result.getParent(); } return result; } }
1,649
31.352941
101
java
null
wildfly-main/elytron-oidc-client/src/main/java/org/wildfly/extension/elytron/oidc/SecureDeploymentDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import static org.jboss.as.server.security.SecurityMetaData.OPERATION_CONTEXT_ATTACHMENT_KEY; import static org.jboss.as.server.security.VirtualDomainMarkerUtility.virtualDomainName; import static org.jboss.as.server.security.VirtualDomainUtil.VIRTUAL; import static org.jboss.as.web.common.VirtualHttpServerMechanismFactoryMarkerUtility.virtualMechanismFactoryName; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.DISABLE_TRUST_MANAGER; import static org.wildfly.extension.elytron.oidc._private.ElytronOidcLogger.ROOT_LOGGER; import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.AbstractRemoveStepHandler; 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.PathElement; import org.jboss.as.controller.ResourceDefinition; 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.IntRangeValidator; import org.jboss.as.controller.operations.validation.StringLengthValidator; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.OperationEntry; import org.jboss.as.controller.registry.Resource; import org.jboss.as.server.security.AdvancedSecurityMetaData; import org.jboss.as.server.security.VirtualDomainMarkerUtility; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.wildfly.security.auth.permission.LoginPermission; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.http.HttpServerAuthenticationMechanismFactory; import org.wildfly.security.http.oidc.OidcClientConfigurationBuilder; import org.wildfly.security.http.oidc.OidcClientContext; import org.wildfly.security.http.oidc.OidcMechanismFactory; import org.wildfly.security.http.oidc.OidcSecurityRealm; /** * A {@link ResourceDefinition} for securing deployments via OpenID Connect. * * @author <a href="mailto:[email protected]">Farah Juma</a> */ class SecureDeploymentDefinition extends SimpleResourceDefinition { protected static final SimpleAttributeDefinition REALM = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.REALM, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition PROVIDER = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.PROVIDER, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); protected static final SimpleAttributeDefinition RESOURCE = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.RESOURCE, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .setAlternatives(ElytronOidcDescriptionConstants.CLIENT_ID) .build(); protected static final SimpleAttributeDefinition CLIENT_ID = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.CLIENT_ID, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .setAlternatives(ElytronOidcDescriptionConstants.RESOURCE) .build(); protected static final SimpleAttributeDefinition USE_RESOURCE_ROLE_MAPPINGS = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.USE_RESOURCE_ROLE_MAPPINGS, ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition BEARER_ONLY = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.BEARER_ONLY, ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition ENABLE_BASIC_AUTH = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.ENABLE_BASIC_AUTH, ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition PUBLIC_CLIENT = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.PUBLIC_CLIENT, ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition TURN_OFF_CHANGE_SESSION_ID_ON_LOGIN = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.TURN_OFF_CHANGE_SESSION_ID_ON_LOGIN, ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition TOKEN_MINIMUM_TIME_TO_LIVE = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.TOKEN_MINIMUM_TIME_TO_LIVE, ModelType.INT, true) .setValidator(new IntRangeValidator(-1, true)) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition MIN_TIME_BETWEEN_JWKS_REQUESTS = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.MIN_TIME_BETWEEN_JWKS_REQUESTS, ModelType.INT, true) .setValidator(new IntRangeValidator(-1, true)) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition PUBLIC_KEY_CACHE_TTL = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.PUBLIC_KEY_CACHE_TTL, ModelType.INT, true) .setAllowExpression(true) .setValidator(new IntRangeValidator(-1, true)) .build(); protected static final SimpleAttributeDefinition ADAPTER_STATE_COOKIE_PATH = new SimpleAttributeDefinitionBuilder(ElytronOidcDescriptionConstants.ADAPTER_STATE_COOKIE_PATH, ModelType.STRING, true) .setAllowExpression(true) .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) .build(); static final List<SimpleAttributeDefinition> ALL_ATTRIBUTES = new ArrayList(); static { ALL_ATTRIBUTES.add(REALM); ALL_ATTRIBUTES.add(PROVIDER); ALL_ATTRIBUTES.add(RESOURCE); ALL_ATTRIBUTES.add(CLIENT_ID); ALL_ATTRIBUTES.add(USE_RESOURCE_ROLE_MAPPINGS); ALL_ATTRIBUTES.add(BEARER_ONLY); ALL_ATTRIBUTES.add(ENABLE_BASIC_AUTH); ALL_ATTRIBUTES.add(PUBLIC_CLIENT); ALL_ATTRIBUTES.add(TURN_OFF_CHANGE_SESSION_ID_ON_LOGIN); ALL_ATTRIBUTES.add(TOKEN_MINIMUM_TIME_TO_LIVE); ALL_ATTRIBUTES.add(MIN_TIME_BETWEEN_JWKS_REQUESTS); ALL_ATTRIBUTES.add(PUBLIC_KEY_CACHE_TTL); ALL_ATTRIBUTES.add(ADAPTER_STATE_COOKIE_PATH); ALL_ATTRIBUTES.add(CredentialDefinition.CREDENTIAL); ALL_ATTRIBUTES.add(RedirectRewriteRuleDefinition.REDIRECT_REWRITE_RULE); for (SimpleAttributeDefinition attribute : ProviderAttributeDefinitions.ATTRIBUTES) { ALL_ATTRIBUTES.add(attribute); } } private static final String WAR_FILE_EXTENSION = ".war"; SecureDeploymentDefinition() { super(new Parameters(PathElement.pathElement(ElytronOidcDescriptionConstants.SECURE_DEPLOYMENT), ElytronOidcExtension.getResourceDescriptionResolver(ElytronOidcDescriptionConstants.SECURE_DEPLOYMENT)) .setAddHandler(SecureDeploymentAddHandler.INSTANCE) .setRemoveHandler(SecureDeploymentRemoveHandler.INSTANCE) .setAddRestartLevel(OperationEntry.Flag.RESTART_RESOURCE_SERVICES) .setRemoveRestartLevel(OperationEntry.Flag.RESTART_RESOURCE_SERVICES)); } @Override public void registerAttributes(ManagementResourceRegistration resourceRegistration) { super.registerAttributes(resourceRegistration); for (AttributeDefinition attribute : ALL_ATTRIBUTES) { resourceRegistration.registerReadWriteAttribute(attribute, null, SecureDeploymentWriteAttributeHandler.INSTANCE); } } @Override public void registerChildren(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerSubModel(new CredentialDefinition()); resourceRegistration.registerSubModel(new RedirectRewriteRuleDefinition()); } static class SecureDeploymentAddHandler extends AbstractAddStepHandler { public static SecureDeploymentAddHandler INSTANCE = new SecureDeploymentAddHandler(); private SecureDeploymentAddHandler() { super(ALL_ATTRIBUTES); } @Override protected void populateModel(final OperationContext context, final ModelNode operation, final Resource resource) throws OperationFailedException { super.populateModel(context, operation, resource); if (! isWarDeployment(context)) { VirtualDomainMarkerUtility.virtualDomainRequired(context); AdvancedSecurityMetaData advancedSecurityMetaData = new AdvancedSecurityMetaData(); advancedSecurityMetaData.setHttpServerAuthenticationMechanismFactory(virtualMechanismFactoryName(context)); advancedSecurityMetaData.setSecurityDomain(virtualDomainName(context)); context.attach(OPERATION_CONTEXT_ATTACHMENT_KEY, advancedSecurityMetaData); } } @Override protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { super.performRuntime(context, operation, model); String clientId = CLIENT_ID.resolveModelAttribute(context, model).asStringOrNull(); String resource = RESOURCE.resolveModelAttribute(context, model).asStringOrNull(); if (clientId == null && resource == null) { throw ROOT_LOGGER.resourceOrClientIdMustBeConfigured(); } boolean disableTrustManager = DISABLE_TRUST_MANAGER.resolveModelAttribute(context, model).asBoolean(); if (disableTrustManager) { ROOT_LOGGER.disableTrustManagerSetToTrue(); } String secureDeploymentName = context.getCurrentAddressValue(); OidcConfigService oidcConfigService = OidcConfigService.getInstance(); oidcConfigService.addSecureDeployment(secureDeploymentName, context.resolveExpressions(model)); if (! isWarDeployment(context)) { ServiceTarget serviceTarget = context.getServiceTarget(); ServiceName virtualMechanismFactoryName = virtualMechanismFactoryName(context); ServiceBuilder<?> serviceBuilder = serviceTarget.addService(virtualMechanismFactoryName); final OidcClientContext oidcClientContext = new OidcClientContext(OidcClientConfigurationBuilder .build(new ByteArrayInputStream(oidcConfigService.getJSON(secureDeploymentName).getBytes()))); final HttpServerAuthenticationMechanismFactory virtualMechanismFactory = new OidcMechanismFactory(oidcClientContext); final Consumer<HttpServerAuthenticationMechanismFactory> mechanismFactoryConsumer = serviceBuilder.provides(virtualMechanismFactoryName); serviceBuilder.setInstance(Service.newInstance(mechanismFactoryConsumer, virtualMechanismFactory)); serviceBuilder.setInitialMode(ServiceController.Mode.ON_DEMAND); serviceBuilder.install(); ServiceName virtualDomainName = VirtualDomainMarkerUtility.virtualDomainName(context); serviceBuilder = serviceTarget.addService(virtualDomainName); SecurityDomain virtualDomain = SecurityDomain.builder() .addRealm(VIRTUAL, new OidcSecurityRealm()).build() .setDefaultRealmName(VIRTUAL) .setPermissionMapper((permissionMappable, roles) -> LoginPermission.getInstance()) .build(); Consumer<SecurityDomain> securityDomainConsumer = serviceBuilder.provides(new ServiceName[]{virtualDomainName}); serviceBuilder.setInstance(Service.newInstance(securityDomainConsumer, virtualDomain)); serviceBuilder.setInitialMode(ServiceController.Mode.ON_DEMAND); serviceBuilder.install(); if (! context.isBooting()) { context.reloadRequired(); } } } } static class SecureDeploymentWriteAttributeHandler extends AbstractWriteAttributeHandler<OidcConfigService> { public static final SecureDeploymentWriteAttributeHandler INSTANCE = new SecureDeploymentWriteAttributeHandler(); SecureDeploymentWriteAttributeHandler() { super(ALL_ATTRIBUTES.toArray(new SimpleAttributeDefinition[ALL_ATTRIBUTES.size()])); } @Override protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<OidcConfigService> handbackHolder) throws OperationFailedException { OidcConfigService oidcConfigService = OidcConfigService.getInstance(); oidcConfigService.updateSecureDeployment(context.getCurrentAddressValue(), attributeName, resolvedValue); handbackHolder.setHandback(oidcConfigService); return ! isWarDeployment(context); } @Override protected void revertUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode valueToRestore, ModelNode valueToRevert, OidcConfigService oidcConfigService) throws OperationFailedException { oidcConfigService.updateSecureDeployment(context.getCurrentAddressValue(), attributeName, valueToRestore); } } static class SecureDeploymentRemoveHandler extends AbstractRemoveStepHandler { public static SecureDeploymentRemoveHandler INSTANCE = new SecureDeploymentRemoveHandler(); SecureDeploymentRemoveHandler() { } @Override protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { OidcConfigService oidcConfigService = OidcConfigService.getInstance(); oidcConfigService.removeSecureDeployment(context.getCurrentAddressValue()); if (! isWarDeployment(context)) { context.reloadRequired(); } } } static boolean isWarDeployment(OperationContext context) { return context.getCurrentAddressValue().endsWith(WAR_FILE_EXTENSION); } }
16,898
52.647619
179
java
null
wildfly-main/elytron-oidc-client/src/main/java/org/wildfly/extension/elytron/oidc/ProviderDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc; import static org.wildfly.extension.elytron.oidc.ProviderAttributeDefinitions.DISABLE_TRUST_MANAGER; import static org.wildfly.extension.elytron.oidc._private.ElytronOidcLogger.ROOT_LOGGER; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.AbstractRemoveStepHandler; 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.PathElement; import org.jboss.as.controller.ResourceDefinition; 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; /** * A {@link ResourceDefinition} for an OpenID Connect provider definition. * * @author <a href="mailto:[email protected]">Farah Juma</a> */ class ProviderDefinition extends SimpleResourceDefinition { ProviderDefinition() { super(new Parameters(PathElement.pathElement(ElytronOidcDescriptionConstants.PROVIDER), ElytronOidcExtension.getResourceDescriptionResolver(ElytronOidcDescriptionConstants.PROVIDER)) .setAddHandler(ProviderAddHandler.INSTANCE) .setRemoveHandler(ProviderRemoveHandler.INSTANCE) .setAddRestartLevel(OperationEntry.Flag.RESTART_RESOURCE_SERVICES) .setRemoveRestartLevel(OperationEntry.Flag.RESTART_RESOURCE_SERVICES)); } @Override public void registerAttributes(ManagementResourceRegistration resourceRegistration) { super.registerAttributes(resourceRegistration); for (AttributeDefinition attribute : ProviderAttributeDefinitions.ATTRIBUTES) { resourceRegistration.registerReadWriteAttribute(attribute, null, ProviderWriteAttributeHandler.INSTANCE); } } static class ProviderAddHandler extends AbstractAddStepHandler { public static ProviderAddHandler INSTANCE = new ProviderAddHandler(); private ProviderAddHandler() { super(ProviderAttributeDefinitions.ATTRIBUTES); } protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { super.performRuntime(context, operation, model); boolean disableTrustManager = DISABLE_TRUST_MANAGER.resolveModelAttribute(context, model).asBoolean(); if (disableTrustManager) { ROOT_LOGGER.disableTrustManagerSetToTrue(); } OidcConfigService oidcConfigService = OidcConfigService.getInstance(); oidcConfigService.addProvider(context.getCurrentAddressValue(), context.resolveExpressions(model)); } } static class ProviderWriteAttributeHandler extends AbstractWriteAttributeHandler<OidcConfigService> { public static final ProviderWriteAttributeHandler INSTANCE = new ProviderWriteAttributeHandler(); private ProviderWriteAttributeHandler() { super(ProviderAttributeDefinitions.ATTRIBUTES); } @Override protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<OidcConfigService> handbackHolder) throws OperationFailedException { OidcConfigService oidcConfigService = OidcConfigService.getInstance(); oidcConfigService.updateProvider(context.getCurrentAddressValue(), attributeName, resolvedValue); handbackHolder.setHandback(oidcConfigService); return false; } @Override protected void revertUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode valueToRestore, ModelNode valueToRevert, OidcConfigService oidcConfigService) throws OperationFailedException { oidcConfigService.updateProvider(context.getCurrentAddressValue(), attributeName, valueToRestore); } } static class ProviderRemoveHandler extends AbstractRemoveStepHandler { public static ProviderRemoveHandler INSTANCE = new ProviderRemoveHandler(); ProviderRemoveHandler() { } @Override protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { OidcConfigService oidcConfigService = OidcConfigService.getInstance(); oidcConfigService.removeProvider(context.getCurrentAddressValue()); } } }
5,519
46.179487
179
java
null
wildfly-main/elytron-oidc-client/src/main/java/org/wildfly/extension/elytron/oidc/_private/ElytronOidcLogger.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.elytron.oidc._private; import static org.jboss.logging.Logger.Level.INFO; import static org.jboss.logging.Logger.Level.WARN; import org.jboss.as.controller.OperationFailedException; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * * <a href="mailto:[email protected]">Farah Juma</a> */ @MessageLogger(projectCode = "WFLYOIDC", length = 4) public interface ElytronOidcLogger extends BasicLogger { /** * The root logger with a category of the package name. */ ElytronOidcLogger ROOT_LOGGER = Logger.getMessageLogger(ElytronOidcLogger.class, ElytronOidcLogger.class.getPackage().getName()); /** * Logs an informational message indicating the naming subsystem is being activated. */ @LogMessage(level = INFO) @Message(id = 1, value = "Activating WildFly Elytron OIDC Subsystem") void activatingSubsystem(); @LogMessage(level = INFO) @Message(id = 2, value = "Elytron OIDC Client subsystem override for deployment '%s'") void deploymentSecured(String deploymentName); @Message(id = 3, value = "Cannot remove credential. No credential defined for deployment '%s'") RuntimeException cannotRemoveCredential(String deploymentName); @Message(id = 4, value = "Cannot update credential. No credential defined for deployment '%s'") RuntimeException cannotUpdateCredential(String deploymentName); @Message(id = 5, value = "Cannot remove redirect rewrite rule. No redirect rewrite defined for deployment '%s'") RuntimeException cannotRemoveRedirectRuntimeRule(String deploymentName); @Message(id = 6, value = "Cannot update redirect rewrite. No redirect rewrite defined for deployment '%s'") RuntimeException cannotUpdateRedirectRuntimeRule(String deploymentName); @Message(id = 7, value = "Must set 'resource' or 'client-id'") OperationFailedException resourceOrClientIdMustBeConfigured(); @LogMessage(level = WARN) @Message(id = 8, value = "The 'disable-trust-manager' attribute has been set to 'true' so no trust manager will be used when communicating with the OpenID provider over HTTPS. This value should always be set to 'false' in a production environment.") void disableTrustManagerSetToTrue(); }
3,125
42.416667
253
java
null
wildfly-main/mod_cluster/extension/src/test/java/org/wildfly/extension/mod_cluster/ModClusterAdditionalInitialization.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.mod_cluster; import java.io.Serializable; import org.jboss.as.controller.RunningMode; import org.jboss.as.controller.capability.registry.RuntimeCapabilityRegistry; import org.jboss.as.controller.extension.ExtensionRegistry; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.Resource; import org.jboss.as.subsystem.test.AdditionalInitialization; import org.jboss.as.subsystem.test.ControllerInitializer; import org.jboss.as.subsystem.test.LegacyKernelServicesInitializer; /** * Static simplistic {@link AdditionalInitialization} implementation which registers undertow capabilities and socket bindings. * To avoid class loading problems ensure that this is a standalone {@link Serializable} class and {@link LegacyKernelServicesInitializer#addSingleChildFirstClass(java.lang.Class[])} is called. * Also, this class is only usable on capability-enabled containers (EAP 7.0 and newer). * * @author Radoslav Husar */ public class ModClusterAdditionalInitialization extends AdditionalInitialization implements Serializable { private static final long serialVersionUID = 776664289594803865L; @Override protected RunningMode getRunningMode() { return RunningMode.ADMIN_ONLY; } @Override protected void initializeExtraSubystemsAndModel(ExtensionRegistry extensionRegistry, Resource rootResource, ManagementResourceRegistration rootRegistration, RuntimeCapabilityRegistry capabilityRegistry) { registerCapabilities(capabilityRegistry, "org.wildfly.undertow.listener.ajp"); registerCapabilities(capabilityRegistry, "org.wildfly.undertow.listener.default"); } @Override protected void setupController(ControllerInitializer controllerInitializer) { super.setupController(controllerInitializer); controllerInitializer.addSocketBinding("modcluster", 0); // "224.0.1.105", "23364" controllerInitializer.addRemoteOutboundSocketBinding("proxy1", "localhost", 6666); controllerInitializer.addRemoteOutboundSocketBinding("proxy2", "localhost", 6766); controllerInitializer.addRemoteOutboundSocketBinding("proxy3", "localhost", 6866); } }
3,253
46.852941
208
java
null
wildfly-main/mod_cluster/extension/src/test/java/org/wildfly/extension/mod_cluster/ModClusterSubsystemTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.mod_cluster; import java.util.EnumSet; import org.jboss.as.subsystem.test.AbstractSubsystemSchemaTest; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * @author <a href="[email protected]">Kabir Khan</a> * @author Jean-Frederic Clere * @author Radoslav Husar */ @RunWith(Parameterized.class) public class ModClusterSubsystemTestCase extends AbstractSubsystemSchemaTest<ModClusterSubsystemSchema> { @Parameters public static Iterable<ModClusterSubsystemSchema> parameters() { return EnumSet.allOf(ModClusterSubsystemSchema.class); } public ModClusterSubsystemTestCase(ModClusterSubsystemSchema schema) { super(ModClusterExtension.SUBSYSTEM_NAME, new ModClusterExtension(), schema, ModClusterSubsystemSchema.CURRENT); } @Override protected String getSubsystemXmlPathPattern() { // N.B. Exclude the subsystem name from pattern return "subsystem_%2$d_%3$d.xml"; } @Override protected String getSubsystemXsdPathPattern() { // N.B. the schema name does not correspond to the subsystem name, so exclude this parameter from pattern return "schema/jboss-as-mod-cluster_%2$d_%3$d.xsd"; } }
2,320
37.04918
120
java
null
wildfly-main/mod_cluster/extension/src/test/java/org/wildfly/extension/mod_cluster/ModClusterOperationsTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.mod_cluster; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_OPERATION_NAMES_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS; import java.io.IOException; import org.jboss.as.clustering.controller.CommonUnaryRequirement; import org.jboss.as.clustering.subsystem.AdditionalInitialization; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.operations.common.Util; 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; /** * Test case for testing proxy operations. * * @author Radoslav Husar */ public class ModClusterOperationsTestCase extends AbstractSubsystemTest { public ModClusterOperationsTestCase() { super(ModClusterExtension.SUBSYSTEM_NAME, new ModClusterExtension()); } @Test public void testProxyOperations() throws Exception { KernelServices services = this.buildKernelServices(); ModelNode op = Util.createOperation(READ_OPERATION_NAMES_OPERATION, getProxyAddress("default")); ModelNode result = services.executeOperation(op); Assert.assertEquals(result.get(FAILURE_DESCRIPTION).asString(), SUCCESS, result.get(OUTCOME).asString()); for (ProxyOperation proxyOperation : ProxyOperation.values()) { String operationName = proxyOperation.getDefinition().getName(); Assert.assertTrue(String.format("'%s' operation is not registered at the proxy address", operationName), result.get(RESULT).asList().contains(new ModelNode(operationName))); } } // Addresses private static PathAddress getSubsystemAddress() { return PathAddress.pathAddress(ModClusterSubsystemResourceDefinition.PATH); } private static PathAddress getProxyAddress(String proxyName) { return getSubsystemAddress().append(ProxyConfigurationResourceDefinition.pathElement(proxyName)); } // Setup private String getSubsystemXml() throws IOException { return readResource("subsystem-operations.xml"); } private KernelServices buildKernelServices() throws Exception { return createKernelServicesBuilder(new AdditionalInitialization().require(CommonUnaryRequirement.OUTBOUND_SOCKET_BINDING, "proxy1")).setSubsystemXml(this.getSubsystemXml()).build(); } }
3,773
42.37931
189
java
null
wildfly-main/mod_cluster/extension/src/test/java/org/wildfly/extension/mod_cluster/ModClusterTransformersTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.mod_cluster; import java.util.EnumSet; import java.util.HashSet; import java.util.Set; import org.jboss.as.controller.ModelVersion; import org.jboss.as.model.test.FailedOperationTransformationConfig; import org.jboss.as.model.test.ModelFixer; import org.jboss.as.model.test.ModelTestControllerVersion; import org.jboss.as.model.test.ModelTestUtils; import org.jboss.as.subsystem.test.AbstractSubsystemTest; 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.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * @author Radoslav Husar */ @RunWith(Parameterized.class) public class ModClusterTransformersTestCase extends AbstractSubsystemTest { @Parameters public static Iterable<ModelTestControllerVersion> parameters() { return EnumSet.of(ModelTestControllerVersion.EAP_7_4_0); } ModelTestControllerVersion version; public ModClusterTransformersTestCase(ModelTestControllerVersion version) { super(ModClusterExtension.SUBSYSTEM_NAME, new ModClusterExtension()); this.version = version; } private static String formatArtifact(String pattern, ModelTestControllerVersion version) { return String.format(pattern, version.getMavenGavVersion()); } private static ModClusterSubsystemModel getModelVersion(ModelTestControllerVersion controllerVersion) { switch (controllerVersion) { case EAP_7_4_0: return ModClusterSubsystemModel.VERSION_7_0_0; } throw new IllegalArgumentException(); } private static String[] getDependencies(ModelTestControllerVersion version) { switch (version) { case EAP_7_4_0: return new String[] { formatArtifact("org.jboss.eap:wildfly-mod_cluster-extension:%s", version), "org.jboss.mod_cluster:mod_cluster-core:1.4.3.Final-redhat-00002", formatArtifact("org.jboss.eap:wildfly-clustering-common:%s", version), }; } throw new IllegalArgumentException(); } @Test public void testTransformations() throws Exception { this.testTransformations(version); } private void testTransformations(ModelTestControllerVersion controllerVersion) throws Exception { ModClusterSubsystemModel model = getModelVersion(controllerVersion); ModelVersion modelVersion = model.getVersion(); String[] dependencies = getDependencies(controllerVersion); Set<String> resources = new HashSet<>(); resources.add(String.format("subsystem-transform-%d_%d_%d.xml", modelVersion.getMajor(), modelVersion.getMinor(), modelVersion.getMicro())); for (String resource : resources) { String subsystemXml = readResource(resource); KernelServicesBuilder builder = createKernelServicesBuilder(new ModClusterAdditionalInitialization()) .setSubsystemXml(subsystemXml); builder.createLegacyKernelServicesBuilder(null, controllerVersion, modelVersion) .addMavenResourceURL(dependencies) .skipReverseControllerCheck() .dontPersistXml(); KernelServices mainServices = builder.build(); KernelServices legacyServices = mainServices.getLegacyServices(modelVersion); Assert.assertNotNull(legacyServices); Assert.assertTrue(mainServices.isSuccessfulBoot()); Assert.assertTrue(legacyServices.isSuccessfulBoot()); checkSubsystemModelTransformation(mainServices, modelVersion, createModelFixer(modelVersion), false); } } private static ModelFixer createModelFixer(ModelVersion version) { return model -> { if (ModClusterSubsystemModel.VERSION_8_0_0.requiresTransformation(version)) { Set.of("default", "with-floating-decay-load-provider").forEach( proxy -> model.get(ProxyConfigurationResourceDefinition.pathElement(proxy).getKeyValuePair()).get("connector").set(new ModelNode()) ); } return model; }; } @Test public void testRejections() throws Exception { this.testRejections(version); } private void testRejections(ModelTestControllerVersion controllerVersion) throws Exception { String[] dependencies = getDependencies(controllerVersion); String subsystemXml = readResource("subsystem-reject.xml"); ModClusterSubsystemModel model = getModelVersion(controllerVersion); ModelVersion modelVersion = model.getVersion(); KernelServicesBuilder builder = createKernelServicesBuilder(new ModClusterAdditionalInitialization()); builder.createLegacyKernelServicesBuilder(model.getVersion().getMajor() >= 4 ? new ModClusterAdditionalInitialization() : null, controllerVersion, modelVersion) .addSingleChildFirstClass(ModClusterAdditionalInitialization.class) .addMavenResourceURL(dependencies) .skipReverseControllerCheck(); KernelServices mainServices = builder.build(); KernelServices legacyServices = mainServices.getLegacyServices(modelVersion); Assert.assertNotNull(legacyServices); Assert.assertTrue(mainServices.isSuccessfulBoot()); Assert.assertTrue(legacyServices.isSuccessfulBoot()); ModelTestUtils.checkFailedTransformedBootOperations(mainServices, modelVersion, parse(subsystemXml), createFailedOperationConfig(modelVersion)); } private static FailedOperationTransformationConfig createFailedOperationConfig(ModelVersion version) { return new FailedOperationTransformationConfig(); } }
6,999
41.424242
168
java
null
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/SimpleLoadProviderResourceDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.mod_cluster; import org.jboss.as.clustering.controller.ChildResourceDefinition; import org.jboss.as.clustering.controller.ReloadRequiredResourceRegistrar; import org.jboss.as.clustering.controller.ResourceDescriptor; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.operations.validation.IntRangeValidator; import org.jboss.as.controller.operations.validation.ParameterValidator; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; /** * Definition for resource at address /subsystem=modcluster/proxy=X/load-provider=simple * * @author Radoslav Husar */ public class SimpleLoadProviderResourceDefinition extends ChildResourceDefinition<ManagementResourceRegistration> { public static final PathElement PATH = PathElement.pathElement("load-provider", "simple"); enum Attribute implements org.jboss.as.clustering.controller.Attribute { FACTOR("factor", ModelType.INT, new ModelNode(1), new IntRangeValidator(0, 100, true, true)), ; private final AttributeDefinition definition; Attribute(String name, ModelType type, ModelNode defaultValue, ParameterValidator validator) { this.definition = new SimpleAttributeDefinitionBuilder(name, type) .setAllowExpression(true) .setRequired(defaultValue == null) .setDefaultValue(defaultValue) .setValidator(validator) .setRestartAllServices() .build(); } @Override public AttributeDefinition getDefinition() { return this.definition; } } SimpleLoadProviderResourceDefinition() { super(PATH, ModClusterExtension.SUBSYSTEM_RESOLVER.createChildResolver(PATH)); } @Override public ManagementResourceRegistration register(ManagementResourceRegistration parent) { ManagementResourceRegistration registration = parent.registerSubModel(this); ResourceDescriptor descriptor = new ResourceDescriptor(this.getResourceDescriptionResolver()) .addAttributes(Attribute.class) ; new ReloadRequiredResourceRegistrar(descriptor).register(registration); return registration; } }
3,507
39.790698
115
java
null
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/XMLElement.java
/* * JBoss, Home of Professional Open Source * Copyright 2011, 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.wildfly.extension.mod_cluster; import java.util.HashMap; import java.util.Map; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; /** * Enumeration of XML elements used by {@link ModClusterSubsystemXMLReader} and {@link ModClusterSubsystemXMLWriter}. * * @author Jean-Frederic Clere * @author Radoslav Husar */ enum XMLElement { UNKNOWN((String) null), MOD_CLUSTER_CONFIG("mod-cluster-config"), PROXY(ProxyConfigurationResourceDefinition.WILDCARD_PATH), SIMPLE_LOAD_PROVIDER("simple-load-provider"), DYNAMIC_LOAD_PROVIDER("dynamic-load-provider"), CUSTOM_LOAD_METRIC(CustomLoadMetricResourceDefinition.WILDCARD_PATH), LOAD_METRIC(LoadMetricResourceDefinition.WILDCARD_PATH), PROPERTY(ModelDescriptionConstants.PROPERTY), SSL("ssl"), ; private final String name; XMLElement(final String name) { this.name = name; } XMLElement(PathElement path) { this.name = path.getKey(); } /** * Get the local name of this element. * * @return the local name */ public String getLocalName() { return name; } private static final Map<String, XMLElement> MAP; static { Map<String, XMLElement> map = new HashMap<>(); for (XMLElement element : values()) { final String name = element.getLocalName(); if (name != null) { map.put(name, element); } } MAP = map; } public static XMLElement forName(String localName) { XMLElement element = MAP.get(localName); return element == null ? UNKNOWN : element; } }
2,731
29.355556
117
java
null
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ModClusterSubsystemResourceTransformer.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.mod_cluster; import java.util.function.Function; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.transform.description.ResourceTransformationDescriptionBuilder; import org.jboss.as.controller.transform.description.TransformationDescription; import org.jboss.as.controller.transform.description.TransformationDescriptionBuilder; /** * Transformer logic for {@link ModClusterSubsystemResourceDefinition}. * * @author Radoslav Husar */ public class ModClusterSubsystemResourceTransformer implements Function<ModelVersion, TransformationDescription> { private final ResourceTransformationDescriptionBuilder builder = TransformationDescriptionBuilder.Factory.createSubsystemInstance(); @Override public TransformationDescription apply(ModelVersion version) { new ProxyConfigurationResourceTransformer(this.builder).accept(version); return this.builder.build(); } }
1,985
39.530612
136
java
null
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ModClusterSubsystemXMLReader.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.mod_cluster; import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; 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.wildfly.extension.mod_cluster.ModClusterLogger.ROOT_LOGGER; import static org.wildfly.extension.mod_cluster.XMLAttribute.CLASS; import static org.wildfly.extension.mod_cluster.XMLAttribute.TYPE; import java.util.List; import javax.xml.stream.XMLStreamException; import org.jboss.as.clustering.controller.Attribute; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.controller.parsing.ParseUtils; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; import org.jboss.staxmapper.XMLElementReader; import org.jboss.staxmapper.XMLExtendedStreamReader; /** * @author Jean-Frederic Clere * @author Radoslav Husar */ final class ModClusterSubsystemXMLReader implements XMLElementReader<List<ModelNode>> { private final ModClusterSubsystemSchema schema; ModClusterSubsystemXMLReader(ModClusterSubsystemSchema schema) { this.schema = schema; } @Override public void readElement(XMLExtendedStreamReader reader, List<ModelNode> list) throws XMLStreamException { ParseUtils.requireNoAttributes(reader); PathAddress subsystemAddress = PathAddress.pathAddress(ModClusterSubsystemResourceDefinition.PATH); ModelNode subsystemAddOp = Util.createAddOperation(subsystemAddress); list.add(subsystemAddOp); while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { XMLElement element = XMLElement.forName(reader.getLocalName()); switch (element) { case MOD_CLUSTER_CONFIG: { if (!schema.since(ModClusterSubsystemSchema.MODCLUSTER_4_0)) { this.parseProxy(reader, list, subsystemAddress); break; } } case PROXY: { if (schema.since(ModClusterSubsystemSchema.MODCLUSTER_4_0)) { this.parseProxy(reader, list, subsystemAddress); break; } } default: { throw unexpectedElement(reader); } } } } private void parseProxy(XMLExtendedStreamReader reader, List<ModelNode> list, PathAddress parent) throws XMLStreamException { String name = schema.since(ModClusterSubsystemSchema.MODCLUSTER_4_0) ? require(reader, XMLAttribute.NAME) : "default"; PathAddress address = parent.append(ProxyConfigurationResourceDefinition.pathElement(name)); ModelNode operation = Util.createAddOperation(address); list.add(operation); int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); XMLAttribute attribute = XMLAttribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case ADVERTISE_SOCKET: { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.ADVERTISE_SOCKET); break; } case PROXY_URL: { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.PROXY_URL); break; } case ADVERTISE: { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.ADVERTISE); break; } case ADVERTISE_SECURITY_KEY: { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.ADVERTISE_SECURITY_KEY); break; } case EXCLUDED_CONTEXTS: { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.EXCLUDED_CONTEXTS); break; } case AUTO_ENABLE_CONTEXTS: { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.AUTO_ENABLE_CONTEXTS); break; } case STOP_CONTEXT_TIMEOUT: { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.STOP_CONTEXT_TIMEOUT); break; } case SOCKET_TIMEOUT: { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.SOCKET_TIMEOUT); break; } case STICKY_SESSION: { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.STICKY_SESSION); break; } case STICKY_SESSION_REMOVE: { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.STICKY_SESSION_REMOVE); break; } case STICKY_SESSION_FORCE: { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.STICKY_SESSION_FORCE); break; } case WORKER_TIMEOUT: { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.WORKER_TIMEOUT); break; } case MAX_ATTEMPTS: { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.MAX_ATTEMPTS); break; } case FLUSH_PACKETS: { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.FLUSH_PACKETS); break; } case FLUSH_WAIT: { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.FLUSH_WAIT); break; } case PING: { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.PING); break; } case SMAX: { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.SMAX); break; } case TTL: { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.TTL); break; } case NODE_TIMEOUT: { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.NODE_TIMEOUT); break; } case BALANCER: { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.BALANCER); break; } case PROXY_LIST: { if (this.schema.since(ModClusterSubsystemSchema.MODCLUSTER_6_0)) { throw ParseUtils.unexpectedAttribute(reader, i); } ROOT_LOGGER.ignoredAttribute(attribute.getLocalName(), reader.getLocalName()); break; } // 1.0 case DOMAIN: { if (schema == ModClusterSubsystemSchema.MODCLUSTER_1_0) { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.LOAD_BALANCING_GROUP); break; } } // 1.1 case LOAD_BALANCING_GROUP: { if (schema.since(ModClusterSubsystemSchema.MODCLUSTER_1_1)) { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.LOAD_BALANCING_GROUP); break; } } case CONNECTOR: { if (schema.since(ModClusterSubsystemSchema.MODCLUSTER_1_1) && !schema.since(ModClusterSubsystemSchema.MODCLUSTER_4_0)) { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.LISTENER); break; } else { throw unexpectedAttribute(reader, i); } } // 1.2 case SESSION_DRAINING_STRATEGY: { if (schema.since(ModClusterSubsystemSchema.MODCLUSTER_1_2)) { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.SESSION_DRAINING_STRATEGY); break; } } // 2.0 case STATUS_INTERVAL: { if (schema.since(ModClusterSubsystemSchema.MODCLUSTER_2_0)) { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.STATUS_INTERVAL); break; } } case PROXIES: { if (schema.since(ModClusterSubsystemSchema.MODCLUSTER_2_0)) { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.PROXIES); break; } } // 3.0 case SSL_CONTEXT: { if (schema.since(ModClusterSubsystemSchema.MODCLUSTER_3_0)) { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.SSL_CONTEXT); break; } } // 4.0 case NAME: { if (schema.since(ModClusterSubsystemSchema.MODCLUSTER_4_0)) { // Ignore -- already parsed. break; } } case LISTENER: { if (schema.since(ModClusterSubsystemSchema.MODCLUSTER_4_0)) { readAttribute(reader, i, operation, ProxyConfigurationResourceDefinition.Attribute.LISTENER); break; } } default: { throw unexpectedAttribute(reader, i); } } } if (schema == ModClusterSubsystemSchema.MODCLUSTER_1_0) { // This is a required attribute - so set it to something reasonable setAttribute(reader, "ajp", operation, ProxyConfigurationResourceDefinition.Attribute.LISTENER); } while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { XMLElement element = XMLElement.forName(reader.getLocalName()); switch (element) { case SIMPLE_LOAD_PROVIDER: { this.parseSimpleLoadProvider(reader, list, address); break; } case DYNAMIC_LOAD_PROVIDER: { this.parseDynamicLoadProvider(reader, list, address); break; } case SSL: { ROOT_LOGGER.ignoredElement(element.getLocalName()); ParseUtils.requireNoContent(reader); break; } default: { throw unexpectedElement(reader); } } } } private void parseSimpleLoadProvider(XMLExtendedStreamReader reader, List<ModelNode> list, PathAddress parent) throws XMLStreamException { PathAddress address = parent.append(SimpleLoadProviderResourceDefinition.PATH); ModelNode operation = Util.createAddOperation(address); int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); XMLAttribute attribute = XMLAttribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case FACTOR: { readAttribute(reader, i, operation, SimpleLoadProviderResourceDefinition.Attribute.FACTOR); break; } default: { throw unexpectedAttribute(reader, i); } } } ParseUtils.requireNoContent(reader); list.add(operation); } private void parseDynamicLoadProvider(XMLExtendedStreamReader reader, List<ModelNode> list, PathAddress parent) throws XMLStreamException { PathAddress address = parent.append(DynamicLoadProviderResourceDefinition.PATH); ModelNode operation = Util.createAddOperation(address); int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); XMLAttribute attribute = XMLAttribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case DECAY: { readAttribute(reader, i, operation, DynamicLoadProviderResourceDefinition.Attribute.DECAY); break; } case HISTORY: { readAttribute(reader, i, operation, DynamicLoadProviderResourceDefinition.Attribute.HISTORY); break; } case INITIAL_LOAD: { if (schema.since(ModClusterSubsystemSchema.MODCLUSTER_5_0)) { readAttribute(reader, i, operation, DynamicLoadProviderResourceDefinition.Attribute.INITIAL_LOAD); break; } } default: { throw unexpectedAttribute(reader, i); } } } list.add(operation); while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { XMLElement element = XMLElement.forName(reader.getLocalName()); switch (element) { case LOAD_METRIC: { this.parseLoadMetric(reader, list, address); break; } case CUSTOM_LOAD_METRIC: { this.parseCustomLoadMetric(reader, list, address); break; } default: { throw unexpectedElement(reader); } } } } private void parseLoadMetric(XMLExtendedStreamReader reader, List<ModelNode> list, PathAddress address) throws XMLStreamException { String type = require(reader, TYPE); if ("mem".equalsIgnoreCase(type)) { ROOT_LOGGER.ignoredElement(type); ParseUtils.requireNoContent(reader); return; } PathAddress opAddress = address.append(LoadMetricResourceDefinition.pathElement(type)); ModelNode operation = Util.createAddOperation(opAddress); int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); XMLAttribute attribute = XMLAttribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case TYPE: { // TODO polish this being both path and required attribute readAttribute(reader, i, operation, LoadMetricResourceDefinition.Attribute.TYPE); break; } case CAPACITY: { readAttribute(reader, i, operation, LoadMetricResourceDefinition.SharedAttribute.CAPACITY); break; } case WEIGHT: { readAttribute(reader, i, operation, LoadMetricResourceDefinition.SharedAttribute.WEIGHT); break; } default: { throw unexpectedAttribute(reader, i); } } } readProperties(reader, operation); list.add(operation); } private void parseCustomLoadMetric(XMLExtendedStreamReader reader, List<ModelNode> list, PathAddress address) throws XMLStreamException { String type = require(reader, CLASS); PathAddress opAddress = address.append(CustomLoadMetricResourceDefinition.pathElement(type)); ModelNode operation = Util.createAddOperation(opAddress); int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); XMLAttribute attribute = XMLAttribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case CLASS: { // TODO polish this being both path and required attribute readAttribute(reader, i, operation, CustomLoadMetricResourceDefinition.Attribute.CLASS); break; } case CAPACITY: { readAttribute(reader, i, operation, LoadMetricResourceDefinition.SharedAttribute.CAPACITY); break; } case MODULE: { readAttribute(reader, i, operation, CustomLoadMetricResourceDefinition.Attribute.MODULE); break; } case WEIGHT: { readAttribute(reader, i, operation, LoadMetricResourceDefinition.SharedAttribute.WEIGHT); break; } default: { throw unexpectedAttribute(reader, i); } } } readProperties(reader, operation); list.add(operation); } private static String require(XMLExtendedStreamReader reader, XMLAttribute attribute) throws XMLStreamException { String value = reader.getAttributeValue(null, attribute.getLocalName()); if (value == null) { throw ParseUtils.missingRequired(reader, attribute.getLocalName()); } return value; } private static void readProperties(XMLExtendedStreamReader reader, ModelNode operation) throws XMLStreamException { while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { XMLElement element = XMLElement.forName(reader.getLocalName()); switch (element) { case PROPERTY: { Property property = ParseUtils.readProperty(reader, true); operation.get(LoadMetricResourceDefinition.SharedAttribute.PROPERTY.getName()).get(property.getName()).set(property.getValue()); break; } default: { throw unexpectedElement(reader); } } } } private static void readAttribute(XMLExtendedStreamReader reader, int index, ModelNode operation, Attribute attribute) throws XMLStreamException { setAttribute(reader, reader.getAttributeValue(index), operation, attribute); } private static void setAttribute(XMLExtendedStreamReader reader, String value, ModelNode operation, Attribute attribute) throws XMLStreamException { AttributeDefinition definition = attribute.getDefinition(); definition.getParser().parseAndSetParameter(definition, value, operation, reader); } }
20,905
44.056034
152
java
null
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ModClusterExtensionTransformerRegistration.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.mod_cluster; import java.util.EnumSet; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.transform.ExtensionTransformerRegistration; import org.jboss.as.controller.transform.SubsystemTransformerRegistration; import org.jboss.as.controller.transform.description.TransformationDescription; import org.kohsuke.MetaInfServices; /** * @author Radoslav Husar */ @MetaInfServices(ExtensionTransformerRegistration.class) public class ModClusterExtensionTransformerRegistration implements ExtensionTransformerRegistration { @Override public String getSubsystemName() { return ModClusterExtension.SUBSYSTEM_NAME; } @Override public void registerTransformers(SubsystemTransformerRegistration registration) { // Register transformers for all but the current model for (ModClusterSubsystemModel model : EnumSet.complementOf(EnumSet.of(ModClusterSubsystemModel.CURRENT))) { ModelVersion version = model.getVersion(); TransformationDescription.Tools.register(new ModClusterSubsystemResourceTransformer().apply(version), registration, version); } } }
2,202
40.566038
137
java
null
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/XMLAttribute.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.mod_cluster; import java.util.HashMap; import java.util.Map; import org.jboss.as.clustering.controller.Attribute; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; /** * Enumeration of XML attributes used solely by {@link ModClusterSubsystemXMLReader}. * * @author Emanuel Muckenhuber * @author Jean-Frederic Clere * @author Radoslav Husar */ enum XMLAttribute { UNKNOWN((String) null), // Proxy configuration ADVERTISE(ProxyConfigurationResourceDefinition.Attribute.ADVERTISE), ADVERTISE_SECURITY_KEY(ProxyConfigurationResourceDefinition.Attribute.ADVERTISE_SECURITY_KEY), ADVERTISE_SOCKET(ProxyConfigurationResourceDefinition.Attribute.ADVERTISE_SOCKET), AUTO_ENABLE_CONTEXTS(ProxyConfigurationResourceDefinition.Attribute.AUTO_ENABLE_CONTEXTS), BALANCER(ProxyConfigurationResourceDefinition.Attribute.BALANCER), CONNECTOR("connector"), DOMAIN("domain"), EXCLUDED_CONTEXTS(ProxyConfigurationResourceDefinition.Attribute.EXCLUDED_CONTEXTS), FLUSH_PACKETS(ProxyConfigurationResourceDefinition.Attribute.FLUSH_PACKETS), FLUSH_WAIT(ProxyConfigurationResourceDefinition.Attribute.FLUSH_WAIT), LISTENER(ProxyConfigurationResourceDefinition.Attribute.LISTENER), LOAD_BALANCING_GROUP(ProxyConfigurationResourceDefinition.Attribute.LOAD_BALANCING_GROUP), MAX_ATTEMPTS(ProxyConfigurationResourceDefinition.Attribute.MAX_ATTEMPTS), NAME(ModelDescriptionConstants.NAME), NODE_TIMEOUT(ProxyConfigurationResourceDefinition.Attribute.NODE_TIMEOUT), PING(ProxyConfigurationResourceDefinition.Attribute.PING), PROXIES(ProxyConfigurationResourceDefinition.Attribute.PROXIES), PROXY_LIST("proxy-list"), PROXY_URL(ProxyConfigurationResourceDefinition.Attribute.PROXY_URL), SESSION_DRAINING_STRATEGY(ProxyConfigurationResourceDefinition.Attribute.SESSION_DRAINING_STRATEGY), SMAX(ProxyConfigurationResourceDefinition.Attribute.SMAX), SOCKET_TIMEOUT(ProxyConfigurationResourceDefinition.Attribute.SOCKET_TIMEOUT), SSL_CONTEXT(ProxyConfigurationResourceDefinition.Attribute.SSL_CONTEXT), STATUS_INTERVAL(ProxyConfigurationResourceDefinition.Attribute.STATUS_INTERVAL), STICKY_SESSION(ProxyConfigurationResourceDefinition.Attribute.STICKY_SESSION), STICKY_SESSION_FORCE(ProxyConfigurationResourceDefinition.Attribute.STICKY_SESSION_FORCE), STICKY_SESSION_REMOVE(ProxyConfigurationResourceDefinition.Attribute.STICKY_SESSION_REMOVE), STOP_CONTEXT_TIMEOUT(ProxyConfigurationResourceDefinition.Attribute.STOP_CONTEXT_TIMEOUT), TTL(ProxyConfigurationResourceDefinition.Attribute.TTL), WORKER_TIMEOUT(ProxyConfigurationResourceDefinition.Attribute.WORKER_TIMEOUT), // Load provider DECAY(DynamicLoadProviderResourceDefinition.Attribute.DECAY), FACTOR(SimpleLoadProviderResourceDefinition.Attribute.FACTOR), HISTORY(DynamicLoadProviderResourceDefinition.Attribute.HISTORY), INITIAL_LOAD(DynamicLoadProviderResourceDefinition.Attribute.INITIAL_LOAD), // Load metrics CAPACITY(LoadMetricResourceDefinition.SharedAttribute.CAPACITY), CLASS(CustomLoadMetricResourceDefinition.Attribute.CLASS), MODULE(CustomLoadMetricResourceDefinition.Attribute.MODULE), TYPE(LoadMetricResourceDefinition.Attribute.TYPE), WEIGHT(LoadMetricResourceDefinition.SharedAttribute.WEIGHT), ; private final String name; XMLAttribute(String name) { this.name = name; } XMLAttribute(Attribute attribute) { this.name = attribute.getName(); } public String getLocalName() { return name; } private static final Map<String, XMLAttribute> MAP; static { Map<String, XMLAttribute> map = new HashMap<>(XMLAttribute.values().length); for (XMLAttribute element : values()) { String name = element.getLocalName(); if (name != null) { map.put(name, element); } } MAP = map; } public static XMLAttribute forName(String localName) { XMLAttribute element = MAP.get(localName); return element == null ? UNKNOWN : element; } @Override public String toString() { return this.getLocalName(); } }
5,274
41.886179
104
java
null
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ModClusterSubsystemServiceHandler.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.mod_cluster; import static org.wildfly.extension.mod_cluster.ModClusterLogger.ROOT_LOGGER; import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.LISTENER; import static org.wildfly.extension.mod_cluster.ProxyConfigurationResourceDefinition.Attribute.STATUS_INTERVAL; import java.time.Duration; import java.util.HashSet; import java.util.Properties; import java.util.ServiceLoader; import java.util.Set; import org.jboss.as.clustering.controller.ResourceServiceHandler; import org.jboss.as.clustering.controller.ServiceValueCaptorServiceConfigurator; import org.jboss.as.clustering.controller.ServiceValueRegistry; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.registry.Resource; import org.jboss.common.beans.property.BeanUtils; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; import org.jboss.modcluster.ModClusterServiceMBean; import org.jboss.modcluster.load.LoadBalanceFactorProvider; import org.jboss.modcluster.load.impl.DynamicLoadBalanceFactorProvider; import org.jboss.modcluster.load.impl.SimpleLoadBalanceFactorProvider; import org.jboss.modcluster.load.metric.LoadMetric; import org.jboss.modules.Module; import org.jboss.modules.ModuleLoadException; import org.jboss.msc.service.ServiceController.Mode; import org.jboss.msc.service.ServiceTarget; import org.wildfly.clustering.service.ServiceConfigurator; /** * Resource service handler implementation that handles installation of mod_cluster services. Since mod_cluster requires certain * boot time handling, all operations on the subsystem leave the server in the 'reload required' state. This makes the service * installation a one time endeavour which is handled here. * * @author Radoslav Husar */ class ModClusterSubsystemServiceHandler implements ResourceServiceHandler { private final ServiceValueRegistry<ModClusterServiceMBean> registry; ModClusterSubsystemServiceHandler(ServiceValueRegistry<ModClusterServiceMBean> registry) { this.registry = registry; } @Override public void installServices(OperationContext context, ModelNode model) throws OperationFailedException { if (!context.isBooting()) return; Resource subsystemResource = context.readResource(PathAddress.EMPTY_ADDRESS); if (subsystemResource.hasChildren(ProxyConfigurationResourceDefinition.WILDCARD_PATH.getKey())) { Set<String> adapterNames = new HashSet<>(); Set<LoadMetric> enabledMetrics = new HashSet<>(); for (Resource.ResourceEntry proxyResource : subsystemResource.getChildren(ProxyConfigurationResourceDefinition.WILDCARD_PATH.getKey())) { String proxyName = proxyResource.getName(); PathAddress proxyAddress = context.getCurrentAddress().append(ProxyConfigurationResourceDefinition.pathElement(proxyName)); adapterNames.add(proxyName); ModelNode proxyModel = Resource.Tools.readModel(proxyResource); ServiceTarget target = context.getServiceTarget(); ProxyConfigurationServiceConfigurator configurationBuilder = new ProxyConfigurationServiceConfigurator(proxyAddress); configurationBuilder.configure(context, proxyModel).build(target).install(); // Construct LoadBalanceFactorProvider and call pluggable boot time metric Set<LoadMetric> metrics = new HashSet<>(); LoadBalanceFactorProvider loadProvider = this.getLoadProvider(proxyName, metrics, context, proxyModel); enabledMetrics.addAll(metrics); String listenerName = LISTENER.resolveModelAttribute(context, proxyModel).asString(); int statusInterval = STATUS_INTERVAL.resolveModelAttribute(context, proxyModel).asInt(); ServiceConfigurator configurator = new ContainerEventHandlerServiceConfigurator(proxyAddress, loadProvider); configurator.build(target).install(); new ServiceValueCaptorServiceConfigurator<>(this.registry.add(configurator.getServiceName())).build(target).install(); // Install services for web container integration for (ContainerEventHandlerAdapterServiceConfiguratorProvider provider : ServiceLoader.load(ContainerEventHandlerAdapterServiceConfiguratorProvider.class, ContainerEventHandlerAdapterServiceConfiguratorProvider.class.getClassLoader())) { provider.getServiceConfigurator(proxyName, listenerName, Duration.ofSeconds(statusInterval)).configure(context).build(target).setInitialMode(Mode.PASSIVE).install(); } } for (BoottimeHandlerProvider handler : ServiceLoader.load(BoottimeHandlerProvider.class, BoottimeHandlerProvider.class.getClassLoader())) { handler.performBoottime(context, adapterNames, enabledMetrics); } } } private LoadBalanceFactorProvider getLoadProvider(String proxyName, final Set<LoadMetric> metrics, final OperationContext context, ModelNode model) throws OperationFailedException { LoadBalanceFactorProvider load = null; if (model.get(SimpleLoadProviderResourceDefinition.PATH.getKeyValuePair()).isDefined()) { ModelNode simpleProviderModel = model.get(SimpleLoadProviderResourceDefinition.PATH.getKeyValuePair()); int value = SimpleLoadProviderResourceDefinition.Attribute.FACTOR.resolveModelAttribute(context, simpleProviderModel).asInt(); SimpleLoadBalanceFactorProvider simpleLoadProvider = new SimpleLoadBalanceFactorProvider(); simpleLoadProvider.setLoadBalanceFactor(value); load = simpleLoadProvider; } if (model.get(DynamicLoadProviderResourceDefinition.PATH.getKeyValuePair()).isDefined()) { ModelNode node = model.get(DynamicLoadProviderResourceDefinition.PATH.getKeyValuePair()); float decayFactor = (float) DynamicLoadProviderResourceDefinition.Attribute.DECAY.resolveModelAttribute(context, node).asDouble(); int history = DynamicLoadProviderResourceDefinition.Attribute.HISTORY.resolveModelAttribute(context, node).asInt(); int initialLoad = DynamicLoadProviderResourceDefinition.Attribute.INITIAL_LOAD.resolveModelAttribute(context, node).asInt(); if (node.hasDefined(LoadMetricResourceDefinition.WILDCARD_PATH.getKey())) { this.addLoadMetrics(metrics, node.get(LoadMetricResourceDefinition.WILDCARD_PATH.getKey()), context); } if (node.hasDefined(CustomLoadMetricResourceDefinition.WILDCARD_PATH.getKey())) { this.addLoadMetrics(metrics, node.get(CustomLoadMetricResourceDefinition.WILDCARD_PATH.getKey()), context); } if (!metrics.isEmpty()) { DynamicLoadBalanceFactorProvider loadBalanceFactorProvider = new DynamicLoadBalanceFactorProvider(metrics, initialLoad); loadBalanceFactorProvider.setDecayFactor(decayFactor); loadBalanceFactorProvider.setHistory(history); load = loadBalanceFactorProvider; } } if (load == null) { ROOT_LOGGER.usingSimpleLoadProvider(proxyName); load = new SimpleLoadBalanceFactorProvider(); } return load; } private void addLoadMetrics(Set<LoadMetric> metrics, ModelNode nodes, final OperationContext context) throws OperationFailedException { for (Property property1 : nodes.asPropertyList()) { ModelNode node = property1.getValue(); double capacity = LoadMetricResourceDefinition.SharedAttribute.CAPACITY.resolveModelAttribute(context, node).asDouble(); int weight = LoadMetricResourceDefinition.SharedAttribute.WEIGHT.resolveModelAttribute(context, node).asInt(); Class<? extends LoadMetric> loadMetricClass = null; if (node.hasDefined(LoadMetricResourceDefinition.Attribute.TYPE.getName())) { String type = LoadMetricResourceDefinition.Attribute.TYPE.resolveModelAttribute(context, node).asString(); LoadMetricEnum metric = LoadMetricEnum.forType(type); loadMetricClass = (metric != null) ? metric.getLoadMetricClass() : null; } else { String className = CustomLoadMetricResourceDefinition.Attribute.CLASS.resolveModelAttribute(context, node).asString(); String moduleName = CustomLoadMetricResourceDefinition.Attribute.MODULE.resolveModelAttribute(context, node).asString(); try { Module module = Module.getContextModuleLoader().loadModule(moduleName); loadMetricClass = module.getClassLoader().loadClass(className).asSubclass(LoadMetric.class); } catch (ModuleLoadException e) { ROOT_LOGGER.errorLoadingModuleForCustomMetric(moduleName, e); } catch (ClassNotFoundException e) { ROOT_LOGGER.errorAddingMetrics(e); } } if (loadMetricClass != null) { try { LoadMetric metric = loadMetricClass.newInstance(); metric.setCapacity(capacity); metric.setWeight(weight); Properties props = new Properties(); for (Property property : LoadMetricResourceDefinition.SharedAttribute.PROPERTY.resolveModelAttribute(context, node).asPropertyListOrEmpty()) { props.put(property.getName(), property.getValue().asString()); } // Apply Java Bean properties if any are set if (!props.isEmpty()) { try { BeanUtils.mapJavaBeanProperties(metric, props, true); } catch (Exception ex) { ROOT_LOGGER.errorApplyingMetricProperties(ex, loadMetricClass.getCanonicalName()); // Do not add this incomplete metric. continue; } } metrics.add(metric); } catch (InstantiationException | IllegalAccessException e) { ROOT_LOGGER.errorAddingMetrics(e); } } } } @Override public void removeServices(OperationContext context, ModelNode model) { // Ignore -- the server is now in reload-required state. } }
11,753
53.925234
252
java
null
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ModClusterSubsystemXMLWriter.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.mod_cluster; import javax.xml.stream.XMLStreamException; import java.util.EnumSet; import org.jboss.as.clustering.controller.Attribute; 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; /** * @author Radoslav Husar */ public final class ModClusterSubsystemXMLWriter implements XMLElementWriter<SubsystemMarshallingContext> { @Override public void writeContent(final XMLExtendedStreamWriter writer, final SubsystemMarshallingContext context) throws XMLStreamException { context.startSubsystemElement(ModClusterSubsystemSchema.CURRENT.getNamespace().getUri(), false); ModelNode subsystemModel = context.getModelNode(); if (subsystemModel.hasDefined(ProxyConfigurationResourceDefinition.WILDCARD_PATH.getKey())) { for (Property property : subsystemModel.get(ProxyConfigurationResourceDefinition.WILDCARD_PATH.getKey()).asPropertyList()) { String name = property.getName(); ModelNode proxy = property.getValue(); writeProxy(writer, name, proxy); } } writer.writeEndElement(); } private static void writeProxy(XMLExtendedStreamWriter writer, String name, ModelNode model) throws XMLStreamException { writer.writeStartElement(XMLElement.PROXY.getLocalName()); writer.writeAttribute(XMLAttribute.NAME.getLocalName(), name); writeAttributes(writer, model, ProxyConfigurationResourceDefinition.Attribute.class); if (model.get(SimpleLoadProviderResourceDefinition.PATH.getKeyValuePair()).isDefined()) { ModelNode loadProviderModel = model.get(SimpleLoadProviderResourceDefinition.PATH.getKeyValuePair()); writer.writeStartElement(XMLElement.SIMPLE_LOAD_PROVIDER.getLocalName()); writeAttributes(writer, loadProviderModel, SimpleLoadProviderResourceDefinition.Attribute.class); writer.writeEndElement(); } if (model.get(DynamicLoadProviderResourceDefinition.PATH.getKeyValuePair()).isDefined()) { ModelNode loadProviderModel = model.get(DynamicLoadProviderResourceDefinition.PATH.getKeyValuePair()); writer.writeStartElement(XMLElement.DYNAMIC_LOAD_PROVIDER.getLocalName()); writeAttributes(writer, loadProviderModel, DynamicLoadProviderResourceDefinition.Attribute.class); if (loadProviderModel.hasDefined(LoadMetricResourceDefinition.WILDCARD_PATH.getKey())) { for (Property prop : loadProviderModel.get(LoadMetricResourceDefinition.WILDCARD_PATH.getKey()).asPropertyList()) { ModelNode metricModel = prop.getValue(); writer.writeStartElement(XMLElement.LOAD_METRIC.getLocalName()); writeAttributes(writer, metricModel, LoadMetricResourceDefinition.Attribute.class); writeAttributes(writer, metricModel, LoadMetricResourceDefinition.SharedAttribute.class); writer.writeEndElement(); } } if (loadProviderModel.hasDefined(CustomLoadMetricResourceDefinition.WILDCARD_PATH.getKey())) { for (Property prop : loadProviderModel.get(CustomLoadMetricResourceDefinition.WILDCARD_PATH.getKey()).asPropertyList()) { ModelNode customMetricModel = prop.getValue(); writer.writeStartElement(XMLElement.CUSTOM_LOAD_METRIC.getLocalName()); writeAttributes(writer, customMetricModel, CustomLoadMetricResourceDefinition.Attribute.class); writeAttributes(writer, customMetricModel, LoadMetricResourceDefinition.SharedAttribute.class); writer.writeEndElement(); } } writer.writeEndElement(); } writer.writeEndElement(); } private static <A extends Enum<A> & Attribute> void writeAttributes(XMLExtendedStreamWriter writer, ModelNode model, Class<A> attributeClass) throws XMLStreamException { writeAttributes(writer, model, EnumSet.allOf(attributeClass)); } private static void writeAttributes(XMLExtendedStreamWriter writer, ModelNode model, Iterable<? extends Attribute> attributes) throws XMLStreamException { for (Attribute attribute : attributes) { writeAttribute(writer, model, attribute); } } private static void writeAttribute(XMLExtendedStreamWriter writer, ModelNode model, Attribute attribute) throws XMLStreamException { attribute.getDefinition().getMarshaller().marshallAsAttribute(attribute.getDefinition(), model, true, writer); } }
5,843
51.648649
173
java
null
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/BoottimeHandlerProvider.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.mod_cluster; import java.util.Set; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.modcluster.load.metric.LoadMetric; /** * Mechanism to plug in {@link org.jboss.as.server.deployment.DeploymentUnitProcessor} on boot time, e.g. Undertow * {@link io.undertow.server.HttpHandler}. Passes on a reference to sets with enabled {@link LoadMetric}s and event handler * adapters. * * @author Radoslav Husar * @since 8.0 */ public interface BoottimeHandlerProvider { void performBoottime(OperationContext context, Set<String> adapterNames, Set<LoadMetric> enabledMetrics) throws OperationFailedException; }
1,740
40.452381
141
java
null
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ContainerEventHandlerAdapterServiceConfiguratorProvider.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.mod_cluster; import java.time.Duration; import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; /** * Creates builder of a service that triggers container events for use by {@link org.jboss.modcluster.container.ContainerEventHandler}. * * @author Paul Ferraro * @author Radoslav Husar */ public interface ContainerEventHandlerAdapterServiceConfiguratorProvider { CapabilityServiceConfigurator getServiceConfigurator(String adapterName, String listenerName, Duration statusInterval); }
1,568
40.289474
135
java
null
wildfly-main/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ProxyConfigurationResourceDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.mod_cluster; import java.util.function.UnaryOperator; import org.jboss.as.clustering.controller.ChildResourceDefinition; import org.jboss.as.clustering.controller.CommonUnaryRequirement; import org.jboss.as.clustering.controller.FunctionExecutorRegistry; import org.jboss.as.clustering.controller.ManagementResourceRegistration; import org.jboss.as.clustering.controller.OperationHandler; import org.jboss.as.clustering.controller.ReloadRequiredResourceRegistrar; import org.jboss.as.clustering.controller.ResourceDescriptor; import org.jboss.as.clustering.controller.UnaryCapabilityNameResolver; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.AttributeMarshaller; import org.jboss.as.controller.ParameterCorrector; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.StringListAttributeDefinition; import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition; import org.jboss.as.controller.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.StringLengthValidator; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.modcluster.ModClusterServiceMBean; import org.jboss.modcluster.config.impl.SessionDrainingStrategyEnum; /** * {@link org.jboss.as.controller.ResourceDefinition} implementation for the core mod_cluster configuration resource. * * @author Radoslav Husar */ public class ProxyConfigurationResourceDefinition extends ChildResourceDefinition<ManagementResourceRegistration> { private static final String UNDERTOW_LISTENER_CAPABILITY_NAME = "org.wildfly.undertow.listener"; static final PathElement WILDCARD_PATH = pathElement(PathElement.WILDCARD_VALUE); static PathElement pathElement(String name) { return PathElement.pathElement("proxy", name); } public enum Capability implements org.jboss.as.clustering.controller.Capability { SERVICE("org.wildfly.mod_cluster.service", ModClusterServiceMBean.class), ; private final RuntimeCapability<Void> definition; Capability(String name, Class<?> type) { this.definition = RuntimeCapability.Builder.of(name, true, type).setDynamicNameMapper(UnaryCapabilityNameResolver.DEFAULT).build(); } @Override public RuntimeCapability<Void> getDefinition() { return this.definition; } } enum Attribute implements org.jboss.as.clustering.controller.Attribute, UnaryOperator<SimpleAttributeDefinitionBuilder> { ADVERTISE("advertise", ModelType.BOOLEAN, ModelNode.TRUE), ADVERTISE_SECURITY_KEY("advertise-security-key", ModelType.STRING, null) { @Override public SimpleAttributeDefinitionBuilder apply(SimpleAttributeDefinitionBuilder builder) { return builder .addAccessConstraint(SensitiveTargetAccessConstraintDefinition.CREDENTIAL) .addAccessConstraint(ModClusterExtension.MOD_CLUSTER_SECURITY_DEF) ; } }, ADVERTISE_SOCKET("advertise-socket", ModelType.STRING, null) { @Override public SimpleAttributeDefinitionBuilder apply(SimpleAttributeDefinitionBuilder builder) { return builder .addAccessConstraint(SensitiveTargetAccessConstraintDefinition.SOCKET_BINDING_REF) .setCapabilityReference(CommonUnaryRequirement.SOCKET_BINDING.getName()) ; } }, AUTO_ENABLE_CONTEXTS("auto-enable-contexts", ModelType.BOOLEAN, ModelNode.TRUE), BALANCER("balancer", ModelType.STRING, null), EXCLUDED_CONTEXTS("excluded-contexts", ModelType.STRING, null), FLUSH_PACKETS("flush-packets", ModelType.BOOLEAN, ModelNode.FALSE), FLUSH_WAIT("flush-wait", ModelType.INT, null) { @Override public SimpleAttributeDefinitionBuilder apply(SimpleAttributeDefinitionBuilder builder) { return builder .setMeasurementUnit(MeasurementUnit.SECONDS) .setValidator(new IntRangeValidator(1, true, true)) ; } }, LISTENER("listener", ModelType.STRING, null) { @Override public SimpleAttributeDefinitionBuilder apply(SimpleAttributeDefinitionBuilder builder) { return builder .setCapabilityReference(UNDERTOW_LISTENER_CAPABILITY_NAME) .setRequired(true) ; } }, LOAD_BALANCING_GROUP("load-balancing-group", ModelType.STRING, null), MAX_ATTEMPTS("max-attempts", ModelType.INT, new ModelNode(1)) { @Override public SimpleAttributeDefinitionBuilder apply(SimpleAttributeDefinitionBuilder builder) { return builder .setValidator(new IntRangeValidator(0, true, true)) .setCorrector(new ParameterCorrector() { @Override public ModelNode correct(ModelNode newValue, ModelNode currentValue) { return (newValue.getType().equals(ModelType.INT) && newValue.asInt() == -1) ? new ModelNode(1) : newValue; } }) ; } }, NODE_TIMEOUT("node-timeout", ModelType.INT, null) { @Override public SimpleAttributeDefinitionBuilder apply(SimpleAttributeDefinitionBuilder builder) { return builder .setMeasurementUnit(MeasurementUnit.SECONDS) .setValidator(new IntRangeValidator(1, true, true)) ; } }, PING("ping", ModelType.INT, new ModelNode(10)) { @Override public SimpleAttributeDefinitionBuilder apply(SimpleAttributeDefinitionBuilder builder) { return builder.setMeasurementUnit(MeasurementUnit.SECONDS); } }, PROXIES("proxies"), PROXY_URL("proxy-url", ModelType.STRING, new ModelNode("/")) { @Override public SimpleAttributeDefinitionBuilder apply(SimpleAttributeDefinitionBuilder builder) { return builder .addAccessConstraint(ModClusterExtension.MOD_CLUSTER_PROXIES_DEF); } }, SESSION_DRAINING_STRATEGY("session-draining-strategy", ModelType.STRING, new ModelNode(SessionDrainingStrategyEnum.DEFAULT.name())) { @Override public SimpleAttributeDefinitionBuilder apply(SimpleAttributeDefinitionBuilder builder) { return builder.setValidator(new EnumValidator<>(SessionDrainingStrategyEnum.class, SessionDrainingStrategyEnum.values())); } }, SMAX("smax", ModelType.INT, null) { @Override public SimpleAttributeDefinitionBuilder apply(SimpleAttributeDefinitionBuilder builder) { return builder .setValidator(new IntRangeValidator(1, true, true)) ; } }, SOCKET_TIMEOUT("socket-timeout", ModelType.INT, new ModelNode(20)) { @Override public SimpleAttributeDefinitionBuilder apply(SimpleAttributeDefinitionBuilder builder) { return builder.setMeasurementUnit(MeasurementUnit.SECONDS) .setValidator(new IntRangeValidator(1, true, true)); } }, SSL_CONTEXT("ssl-context", ModelType.STRING, null) { @Override public SimpleAttributeDefinitionBuilder apply(SimpleAttributeDefinitionBuilder builder) { return builder .setCapabilityReference(CommonUnaryRequirement.SSL_CONTEXT.getName()) .setValidator(new StringLengthValidator(1)) .setAccessConstraints(SensitiveTargetAccessConstraintDefinition.SSL_REF) ; } }, STATUS_INTERVAL("status-interval", ModelType.INT, new ModelNode(10)) { @Override public SimpleAttributeDefinitionBuilder apply(SimpleAttributeDefinitionBuilder builder) { return builder .setMeasurementUnit(MeasurementUnit.SECONDS) .setValidator(new IntRangeValidator(1, true, true)); } }, STICKY_SESSION("sticky-session", ModelType.BOOLEAN, ModelNode.TRUE), STICKY_SESSION_REMOVE("sticky-session-remove", ModelType.BOOLEAN, ModelNode.FALSE), STICKY_SESSION_FORCE("sticky-session-force", ModelType.BOOLEAN, ModelNode.FALSE), STOP_CONTEXT_TIMEOUT("stop-context-timeout", ModelType.INT, new ModelNode(10)) { @Override public SimpleAttributeDefinitionBuilder apply(SimpleAttributeDefinitionBuilder builder) { return builder.setMeasurementUnit(MeasurementUnit.SECONDS) .setValidator(new IntRangeValidator(1, true, true)); } }, TTL("ttl", ModelType.INT, null) { @Override public SimpleAttributeDefinitionBuilder apply(SimpleAttributeDefinitionBuilder builder) { return builder .setMeasurementUnit(MeasurementUnit.SECONDS) .setValidator(new IntRangeValidator(1, true, true)) ; } }, WORKER_TIMEOUT("worker-timeout", ModelType.INT, null) { @Override public SimpleAttributeDefinitionBuilder apply(SimpleAttributeDefinitionBuilder builder) { return builder .setMeasurementUnit(MeasurementUnit.SECONDS) .setValidator(new IntRangeValidator(1, true, true)) ; } }, ; private final AttributeDefinition definition; Attribute(String name, ModelType type, ModelNode defaultValue) { this.definition = this.apply(new SimpleAttributeDefinitionBuilder(name, type) .setAllowExpression(true) .setRequired(false) .setDefaultValue(defaultValue) .setRestartAllServices() ).build(); } // proxies Attribute(String name) { this.definition = new StringListAttributeDefinition.Builder(name) .setRequired(false) .setAllowExpression(false) // expressions are not allowed for model references .setRestartAllServices() .setCapabilityReference(CommonUnaryRequirement.OUTBOUND_SOCKET_BINDING.getName()) .setAttributeMarshaller(AttributeMarshaller.STRING_LIST) .addAccessConstraint(ModClusterExtension.MOD_CLUSTER_PROXIES_DEF) .build(); } @Override public AttributeDefinition getDefinition() { return this.definition; } @Override public SimpleAttributeDefinitionBuilder apply(SimpleAttributeDefinitionBuilder builder) { return builder; } } private final FunctionExecutorRegistry<ModClusterServiceMBean> executors; public ProxyConfigurationResourceDefinition(FunctionExecutorRegistry<ModClusterServiceMBean> executors) { super(WILDCARD_PATH, ModClusterExtension.SUBSYSTEM_RESOLVER.createChildResolver(WILDCARD_PATH)); this.executors = executors; } @Override public ManagementResourceRegistration register(ManagementResourceRegistration parent) { ManagementResourceRegistration registration = parent.registerSubModel(this); ResourceDescriptor descriptor = new ResourceDescriptor(this.getResourceDescriptionResolver()) .addAttributes(Attribute.class) .addRequiredSingletonChildren(SimpleLoadProviderResourceDefinition.PATH) .addCapabilities(Capability.class) ; if (registration.isRuntimeOnlyRegistrationValid()) { new OperationHandler<>(new ProxyOperationExecutor(this.executors), ProxyOperation.class).register(registration); } new ReloadRequiredResourceRegistrar(descriptor).register(registration); new SimpleLoadProviderResourceDefinition().register(registration); new DynamicLoadProviderResourceDefinition().register(registration); return registration; } }
14,044
46.289562
143
java