Search in sources :

Example 41 with ProceedingJoinPoint

use of org.aspectj.lang.ProceedingJoinPoint in project cuba by cuba-platform.

the class ServiceInterceptor method validateMethodParameters.

protected void validateMethodParameters(ProceedingJoinPoint ctx, @Nullable ValidateServiceMethodContext validatedContext) {
    if (validatedContext != null) {
        log.trace("Validating service call params: {}", ctx.getSignature());
        ExecutableValidator validator = validatedContext.getValidator();
        Class[] constraintGroups = validatedContext.getGroups();
        if (constraintGroups.length == 0) {
            constraintGroups = new Class[] { Default.class, ServiceParametersChecks.class };
        }
        Set<ConstraintViolation<Object>> violations = validator.validateParameters(validatedContext.getTarget(), validatedContext.getMethod(), validatedContext.getArgs(), constraintGroups);
        if (!violations.isEmpty()) {
            Class serviceInterface = ctx.getSignature().getDeclaringType();
            Set<ConstraintViolation<Object>> resultViolations = violations.stream().map(violation -> new ServiceMethodConstraintViolation(serviceInterface, violation)).collect(Collectors.toSet());
            throw new MethodParametersValidationException("Service method parameters validation failed", resultViolations);
        }
    }
}
Also used : ServiceParametersChecks(com.haulmont.cuba.core.global.validation.groups.ServiceParametersChecks) Persistence(com.haulmont.cuba.core.Persistence) ServiceResultChecks(com.haulmont.cuba.core.global.validation.groups.ServiceResultChecks) LoggerFactory(org.slf4j.LoggerFactory) MethodResultValidationException(com.haulmont.cuba.core.global.validation.MethodResultValidationException) ServerConfig(com.haulmont.cuba.core.app.ServerConfig) ExecutableValidator(javax.validation.executable.ExecutableValidator) com.haulmont.cuba.core.global(com.haulmont.cuba.core.global) UserSession(com.haulmont.cuba.security.global.UserSession) ServiceMethodConstraintViolation(com.haulmont.cuba.core.global.validation.ServiceMethodConstraintViolation) MiddlewareStatisticsAccumulator(com.haulmont.cuba.core.app.MiddlewareStatisticsAccumulator) ConstraintViolation(javax.validation.ConstraintViolation) Method(java.lang.reflect.Method) Nullable(javax.annotation.Nullable) Default(javax.validation.groups.Default) MethodInvocationProceedingJoinPoint(org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint) Validated(org.springframework.validation.annotation.Validated) Logger(org.slf4j.Logger) AnnotationUtils(org.springframework.core.annotation.AnnotationUtils) Set(java.util.Set) MethodParametersValidationException(com.haulmont.cuba.core.global.validation.MethodParametersValidationException) Collectors(java.util.stream.Collectors) NoUserSessionException(com.haulmont.cuba.security.global.NoUserSessionException) UserSessionsAPI(com.haulmont.cuba.security.app.UserSessionsAPI) MethodSignature(org.aspectj.lang.reflect.MethodSignature) ProceedingJoinPoint(org.aspectj.lang.ProceedingJoinPoint) ServiceMethodConstraintViolation(com.haulmont.cuba.core.global.validation.ServiceMethodConstraintViolation) ExecutableValidator(javax.validation.executable.ExecutableValidator) ServiceMethodConstraintViolation(com.haulmont.cuba.core.global.validation.ServiceMethodConstraintViolation) ConstraintViolation(javax.validation.ConstraintViolation) MethodParametersValidationException(com.haulmont.cuba.core.global.validation.MethodParametersValidationException)

Example 42 with ProceedingJoinPoint

use of org.aspectj.lang.ProceedingJoinPoint in project nifi by apache.

the class ControllerAuditor method updateControllerEventDrivenThreadsAdvice.

/**
 * Audits updating the max number of event driven threads for the controller.
 *
 * @param proceedingJoinPoint join point
 * @param maxEventDrivenThreadCount thread count
 * @param controllerFacade facade
 * @throws java.lang.Throwable ex
 */
@Around("within(org.apache.nifi.web.controller.ControllerFacade) && " + "execution(void setMaxEventDrivenThreadCount(int)) && " + "args(maxEventDrivenThreadCount) && " + "target(controllerFacade)")
public void updateControllerEventDrivenThreadsAdvice(ProceedingJoinPoint proceedingJoinPoint, int maxEventDrivenThreadCount, ControllerFacade controllerFacade) throws Throwable {
    // get the current max thread count
    int previousMaxEventDrivenThreadCount = controllerFacade.getMaxEventDrivenThreadCount();
    // update the processors state
    proceedingJoinPoint.proceed();
    // ensure the value changed
    if (previousMaxEventDrivenThreadCount != maxEventDrivenThreadCount) {
        // get the current user
        NiFiUser user = NiFiUserUtils.getNiFiUser();
        // ensure the user was found
        if (user != null) {
            Collection<Action> actions = new ArrayList<>();
            // create the configure details
            FlowChangeConfigureDetails configDetails = new FlowChangeConfigureDetails();
            configDetails.setName("Controller Max Event Driven Thread Count");
            configDetails.setValue(String.valueOf(maxEventDrivenThreadCount));
            configDetails.setPreviousValue(String.valueOf(previousMaxEventDrivenThreadCount));
            // create the config action
            FlowChangeAction configAction = new FlowChangeAction();
            configAction.setUserIdentity(user.getIdentity());
            configAction.setOperation(Operation.Configure);
            configAction.setTimestamp(new Date());
            configAction.setSourceId("Flow Controller");
            configAction.setSourceName("Flow Controller");
            configAction.setSourceType(Component.Controller);
            configAction.setActionDetails(configDetails);
            actions.add(configAction);
            // record the action
            saveActions(actions, logger);
        }
    }
}
Also used : FlowChangeAction(org.apache.nifi.action.FlowChangeAction) Action(org.apache.nifi.action.Action) NiFiUser(org.apache.nifi.authorization.user.NiFiUser) FlowChangeConfigureDetails(org.apache.nifi.action.details.FlowChangeConfigureDetails) ArrayList(java.util.ArrayList) ProceedingJoinPoint(org.aspectj.lang.ProceedingJoinPoint) Date(java.util.Date) FlowChangeAction(org.apache.nifi.action.FlowChangeAction) Around(org.aspectj.lang.annotation.Around)

Example 43 with ProceedingJoinPoint

use of org.aspectj.lang.ProceedingJoinPoint in project nifi by apache.

the class ControllerAuditor method updateControllerTimerDrivenThreadsAdvice.

/**
 * Audits updating the max number of timer driven threads for the controller.
 *
 * @param proceedingJoinPoint joint point
 * @param maxTimerDrivenThreadCount thread count
 * @param controllerFacade facade
 * @throws java.lang.Throwable ex
 */
@Around("within(org.apache.nifi.web.controller.ControllerFacade) && " + "execution(void setMaxTimerDrivenThreadCount(int)) && " + "args(maxTimerDrivenThreadCount) && " + "target(controllerFacade)")
public void updateControllerTimerDrivenThreadsAdvice(ProceedingJoinPoint proceedingJoinPoint, int maxTimerDrivenThreadCount, ControllerFacade controllerFacade) throws Throwable {
    // get the current max thread count
    int previousMaxTimerDrivenThreadCount = controllerFacade.getMaxTimerDrivenThreadCount();
    // update the processors state
    proceedingJoinPoint.proceed();
    // ensure the value changed
    if (previousMaxTimerDrivenThreadCount != maxTimerDrivenThreadCount) {
        // get the current user
        NiFiUser user = NiFiUserUtils.getNiFiUser();
        // ensure the user was found
        if (user != null) {
            Collection<Action> actions = new ArrayList<>();
            // create the configure details
            FlowChangeConfigureDetails configDetails = new FlowChangeConfigureDetails();
            configDetails.setName("Controller Max Timer Driven Thread Count");
            configDetails.setValue(String.valueOf(maxTimerDrivenThreadCount));
            configDetails.setPreviousValue(String.valueOf(previousMaxTimerDrivenThreadCount));
            // create the config action
            FlowChangeAction configAction = new FlowChangeAction();
            configAction.setUserIdentity(user.getIdentity());
            configAction.setOperation(Operation.Configure);
            configAction.setTimestamp(new Date());
            configAction.setSourceId("Flow Controller");
            configAction.setSourceName("Flow Controller");
            configAction.setSourceType(Component.Controller);
            configAction.setActionDetails(configDetails);
            actions.add(configAction);
            // record the action
            saveActions(actions, logger);
        }
    }
}
Also used : FlowChangeAction(org.apache.nifi.action.FlowChangeAction) Action(org.apache.nifi.action.Action) NiFiUser(org.apache.nifi.authorization.user.NiFiUser) FlowChangeConfigureDetails(org.apache.nifi.action.details.FlowChangeConfigureDetails) ArrayList(java.util.ArrayList) ProceedingJoinPoint(org.aspectj.lang.ProceedingJoinPoint) Date(java.util.Date) FlowChangeAction(org.apache.nifi.action.FlowChangeAction) Around(org.aspectj.lang.annotation.Around)

Example 44 with ProceedingJoinPoint

use of org.aspectj.lang.ProceedingJoinPoint in project nifi by apache.

the class PortAuditor method updatePortAdvice.

/**
 * Audits the update of a port.
 *
 * @param proceedingJoinPoint join point
 * @param portDTO port dto
 * @param portDAO port dao
 * @return port
 * @throws Throwable ex
 */
@Around("within(org.apache.nifi.web.dao.PortDAO+) && " + "execution(org.apache.nifi.connectable.Port updatePort(org.apache.nifi.web.api.dto.PortDTO)) && " + "args(portDTO) && " + "target(portDAO)")
public Port updatePortAdvice(ProceedingJoinPoint proceedingJoinPoint, PortDTO portDTO, PortDAO portDAO) throws Throwable {
    final Port port = portDAO.getPort(portDTO.getId());
    final ScheduledState scheduledState = port.getScheduledState();
    final String name = port.getName();
    final String comments = port.getComments();
    final int maxConcurrentTasks = port.getMaxConcurrentTasks();
    final Set<String> existingUsers = new HashSet<>();
    final Set<String> existingGroups = new HashSet<>();
    boolean isRootGroupPort = false;
    if (port instanceof RootGroupPort) {
        isRootGroupPort = true;
        existingUsers.addAll(((RootGroupPort) port).getUserAccessControl());
        existingGroups.addAll(((RootGroupPort) port).getGroupAccessControl());
    }
    // perform the underlying operation
    final Port updatedPort = (Port) proceedingJoinPoint.proceed();
    // get the current user
    NiFiUser user = NiFiUserUtils.getNiFiUser();
    // ensure the user was found
    if (user != null) {
        Collection<ActionDetails> configurationDetails = new ArrayList<>();
        // see if the name has changed
        if (name != null && portDTO.getName() != null && !name.equals(updatedPort.getName())) {
            // create the config details
            FlowChangeConfigureDetails configDetails = new FlowChangeConfigureDetails();
            configDetails.setName("Name");
            configDetails.setValue(updatedPort.getName());
            configDetails.setPreviousValue(name);
            configurationDetails.add(configDetails);
        }
        // see if the comments has changed
        if (comments != null && portDTO.getComments() != null && !comments.equals(updatedPort.getComments())) {
            // create the config details
            FlowChangeConfigureDetails configDetails = new FlowChangeConfigureDetails();
            configDetails.setName("Comments");
            configDetails.setValue(updatedPort.getComments());
            configDetails.setPreviousValue(comments);
            configurationDetails.add(configDetails);
        }
        // if this is a root group port, consider concurrent tasks
        if (isRootGroupPort) {
            if (portDTO.getConcurrentlySchedulableTaskCount() != null && updatedPort.getMaxConcurrentTasks() != maxConcurrentTasks) {
                // create the config details
                FlowChangeConfigureDetails configDetails = new FlowChangeConfigureDetails();
                configDetails.setName("Concurrent Tasks");
                configDetails.setValue(String.valueOf(updatedPort.getMaxConcurrentTasks()));
                configDetails.setPreviousValue(String.valueOf(maxConcurrentTasks));
                configurationDetails.add(configDetails);
            }
            // if user access control was specified in the request
            if (portDTO.getUserAccessControl() != null) {
                final Set<String> newUsers = new HashSet<>(portDTO.getUserAccessControl());
                newUsers.removeAll(existingUsers);
                final Set<String> removedUsers = new HashSet<>(existingUsers);
                removedUsers.removeAll(portDTO.getUserAccessControl());
                // if users were added/removed
                if (newUsers.size() > 0 || removedUsers.size() > 0) {
                    // create the config details
                    FlowChangeConfigureDetails configDetails = new FlowChangeConfigureDetails();
                    configDetails.setName("User Access Control");
                    configDetails.setValue(StringUtils.join(portDTO.getUserAccessControl(), ", "));
                    configDetails.setPreviousValue(StringUtils.join(existingUsers, ", "));
                    configurationDetails.add(configDetails);
                }
            }
            // if group access control was specified in the request
            if (portDTO.getGroupAccessControl() != null) {
                final Set<String> newGroups = new HashSet<>(portDTO.getGroupAccessControl());
                newGroups.removeAll(existingGroups);
                final Set<String> removedGroups = new HashSet<>(existingGroups);
                removedGroups.removeAll(portDTO.getGroupAccessControl());
                // if groups were added/removed
                if (newGroups.size() > 0 || removedGroups.size() > 0) {
                    // create the config details
                    FlowChangeConfigureDetails configDetails = new FlowChangeConfigureDetails();
                    configDetails.setName("Group Access Control");
                    configDetails.setValue(StringUtils.join(portDTO.getGroupAccessControl(), ", "));
                    configDetails.setPreviousValue(StringUtils.join(existingGroups, ", "));
                    configurationDetails.add(configDetails);
                }
            }
        }
        final Collection<Action> actions = new ArrayList<>();
        // determine the type of port
        Component componentType = Component.OutputPort;
        if (ConnectableType.INPUT_PORT == updatedPort.getConnectableType()) {
            componentType = Component.InputPort;
        }
        // add each configuration detail
        if (!configurationDetails.isEmpty()) {
            // create the timestamp for the update
            Date timestamp = new Date();
            // create the actions
            for (ActionDetails detail : configurationDetails) {
                // create the port action for updating the name
                FlowChangeAction portAction = new FlowChangeAction();
                portAction.setUserIdentity(user.getIdentity());
                portAction.setOperation(Operation.Configure);
                portAction.setTimestamp(timestamp);
                portAction.setSourceId(updatedPort.getIdentifier());
                portAction.setSourceName(updatedPort.getName());
                portAction.setSourceType(componentType);
                portAction.setActionDetails(detail);
                actions.add(portAction);
            }
        }
        // determine the new executing state
        final ScheduledState updatedScheduledState = updatedPort.getScheduledState();
        // determine if the running state has changed
        if (scheduledState != updatedScheduledState) {
            // create a processor action
            FlowChangeAction processorAction = new FlowChangeAction();
            processorAction.setUserIdentity(user.getIdentity());
            processorAction.setTimestamp(new Date());
            processorAction.setSourceId(updatedPort.getIdentifier());
            processorAction.setSourceName(updatedPort.getName());
            processorAction.setSourceType(componentType);
            // set the operation accordingly
            if (ScheduledState.RUNNING.equals(updatedScheduledState)) {
                processorAction.setOperation(Operation.Start);
            } else if (ScheduledState.DISABLED.equals(updatedScheduledState)) {
                processorAction.setOperation(Operation.Disable);
            } else {
                // state is now stopped... consider the previous state
                if (ScheduledState.RUNNING.equals(scheduledState)) {
                    processorAction.setOperation(Operation.Stop);
                } else if (ScheduledState.DISABLED.equals(scheduledState)) {
                    processorAction.setOperation(Operation.Enable);
                }
            }
            actions.add(processorAction);
        }
        // ensure there are actions to record
        if (!actions.isEmpty()) {
            // save the actions
            saveActions(actions, logger);
        }
    }
    return updatedPort;
}
Also used : FlowChangeAction(org.apache.nifi.action.FlowChangeAction) Action(org.apache.nifi.action.Action) NiFiUser(org.apache.nifi.authorization.user.NiFiUser) RootGroupPort(org.apache.nifi.remote.RootGroupPort) Port(org.apache.nifi.connectable.Port) RootGroupPort(org.apache.nifi.remote.RootGroupPort) ArrayList(java.util.ArrayList) ProceedingJoinPoint(org.aspectj.lang.ProceedingJoinPoint) Date(java.util.Date) ScheduledState(org.apache.nifi.controller.ScheduledState) FlowChangeConfigureDetails(org.apache.nifi.action.details.FlowChangeConfigureDetails) ActionDetails(org.apache.nifi.action.details.ActionDetails) Component(org.apache.nifi.action.Component) HashSet(java.util.HashSet) FlowChangeAction(org.apache.nifi.action.FlowChangeAction) Around(org.aspectj.lang.annotation.Around)

Example 45 with ProceedingJoinPoint

use of org.aspectj.lang.ProceedingJoinPoint in project nifi by apache.

the class TestRemoteProcessGroupAuditor method updateProcessGroupInputPortConfiguration.

@SuppressWarnings("unchecked")
private Collection<Action> updateProcessGroupInputPortConfiguration(RemoteProcessGroupPortDTO inputRPGPortDTO, RemoteGroupPort existingRPGPort) throws Throwable {
    final RemoteProcessGroup existingRPG = defaultRemoteProcessGroup();
    final RemoteProcessGroupAuditor auditor = new RemoteProcessGroupAuditor();
    final ProceedingJoinPoint joinPoint = mock(ProceedingJoinPoint.class);
    final String remoteProcessGroupId = "remote-process-group-id";
    inputRPGPortDTO.setId(remoteProcessGroupId);
    inputRPGPortDTO.setTargetId(remoteProcessGroupId);
    final String targetUrl = "http://localhost:8080/nifi";
    when(existingRPG.getIdentifier()).thenReturn(remoteProcessGroupId);
    when(existingRPG.getTargetUri()).thenReturn(targetUrl);
    final RemoteProcessGroupDAO remoteProcessGroupDAO = mock(RemoteProcessGroupDAO.class);
    when(remoteProcessGroupDAO.getRemoteProcessGroup(remoteProcessGroupId)).thenReturn(existingRPG);
    when(existingRPG.getInputPort(eq(inputRPGPortDTO.getId()))).thenReturn(existingRPGPort);
    // Setup updatedRPGPort mock based on inputRPGPortDTO.
    final RemoteGroupPort updatedRPGPort = mock(RemoteGroupPort.class);
    final String portName = existingRPGPort.getName();
    when(updatedRPGPort.getName()).thenReturn(portName);
    if (inputRPGPortDTO.isTransmitting() != null) {
        when(updatedRPGPort.isRunning()).thenReturn(inputRPGPortDTO.isTransmitting());
    }
    when(updatedRPGPort.getMaxConcurrentTasks()).thenReturn(inputRPGPortDTO.getConcurrentlySchedulableTaskCount());
    when(updatedRPGPort.isUseCompression()).thenReturn(inputRPGPortDTO.getUseCompression());
    final BatchSettingsDTO batchSettings = inputRPGPortDTO.getBatchSettings();
    if (batchSettings != null) {
        when(updatedRPGPort.getBatchCount()).thenReturn(batchSettings.getCount());
        when(updatedRPGPort.getBatchSize()).thenReturn(batchSettings.getSize());
        when(updatedRPGPort.getBatchDuration()).thenReturn(batchSettings.getDuration());
    }
    when(joinPoint.proceed()).thenReturn(updatedRPGPort);
    // Capture added actions so that those can be asserted later.
    final AuditService auditService = mock(AuditService.class);
    final AtomicReference<Collection<Action>> addedActions = new AtomicReference<>();
    doAnswer(invocation -> {
        Collection<Action> actions = invocation.getArgumentAt(0, Collection.class);
        addedActions.set(actions);
        return null;
    }).when(auditService).addActions(any());
    auditor.setAuditService(auditService);
    auditor.auditUpdateProcessGroupInputPortConfiguration(joinPoint, remoteProcessGroupId, inputRPGPortDTO, remoteProcessGroupDAO);
    final Collection<Action> actions = addedActions.get();
    // Assert common action values.
    if (actions != null) {
        actions.forEach(action -> {
            assertEquals(remoteProcessGroupId, action.getSourceId());
            assertEquals("user-id", action.getUserIdentity());
            assertEquals(targetUrl, ((RemoteProcessGroupDetails) action.getComponentDetails()).getUri());
            assertNotNull(action.getTimestamp());
        });
    }
    return actions;
}
Also used : BatchSettingsDTO(org.apache.nifi.web.api.dto.BatchSettingsDTO) RemoteProcessGroup(org.apache.nifi.groups.RemoteProcessGroup) Action(org.apache.nifi.action.Action) RemoteGroupPort(org.apache.nifi.remote.RemoteGroupPort) AtomicReference(java.util.concurrent.atomic.AtomicReference) ProceedingJoinPoint(org.aspectj.lang.ProceedingJoinPoint) Collection(java.util.Collection) RemoteProcessGroupDAO(org.apache.nifi.web.dao.RemoteProcessGroupDAO) AuditService(org.apache.nifi.admin.service.AuditService)

Aggregations

ProceedingJoinPoint (org.aspectj.lang.ProceedingJoinPoint)78 Around (org.aspectj.lang.annotation.Around)33 MethodSignature (org.aspectj.lang.reflect.MethodSignature)16 Method (java.lang.reflect.Method)14 Test (org.junit.Test)14 AbstractServiceTest (org.finra.herd.service.AbstractServiceTest)10 SimpleDateFormat (java.text.SimpleDateFormat)8 ArrayList (java.util.ArrayList)8 JoinPoint (org.aspectj.lang.JoinPoint)8 FaseDTO (com.tomasio.projects.trainning.dto.FaseDTO)7 OrganizacaoDTO (com.tomasio.projects.trainning.dto.OrganizacaoDTO)7 PessoaDTO (com.tomasio.projects.trainning.dto.PessoaDTO)7 MockProceedingJoinPoint (org.finra.herd.core.MockProceedingJoinPoint)7 Annotation (java.lang.annotation.Annotation)5 CancelamentoMatriculaDTO (com.tomasio.projects.trainning.dto.CancelamentoMatriculaDTO)4 MatriculaDTO (com.tomasio.projects.trainning.dto.MatriculaDTO)4 Date (java.util.Date)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 Action (org.apache.nifi.action.Action)4 MessageHeader (org.finra.herd.model.dto.MessageHeader)4