Package org.apache.syncope.core.persistence.beans

Examples of org.apache.syncope.core.persistence.beans.TaskExec


    public TaskExecTO report(@PathVariable("executionId") final Long executionId,
            @RequestParam("executionStatus") final PropagationTaskExecStatus status,
            @RequestParam("message") final String message)
            throws NotFoundException, SyncopeClientCompositeErrorException {

        TaskExec exec = taskExecDAO.find(executionId);
        if (exec == null) {
            throw new NotFoundException("Task execution " + executionId);
        }

        SyncopeClientException sce = new SyncopeClientException(
                SyncopeClientExceptionType.InvalidPropagationTaskExecReport);

        TaskUtil taskUtil = getTaskUtil(exec.getTask());
        if (TaskUtil.PROPAGATION == taskUtil) {
            PropagationTask task = (PropagationTask) exec.getTask();
            if (task.getPropagationMode() != PropagationMode.TWO_PHASES) {
                sce.addElement("Propagation mode: " + task.getPropagationMode());
            }
        } else {
            sce.addElement("Task type: " + taskUtil);
        }

        switch (status) {
            case SUCCESS:
            case FAILURE:
                break;

            case CREATED:
            case SUBMITTED:
            case UNSUBMITTED:
                sce.addElement("Execution status to be set: " + status);
                break;

            default:
        }

        if (!sce.isEmpty()) {
            SyncopeClientCompositeErrorException scce =
                    new SyncopeClientCompositeErrorException(HttpStatus.BAD_REQUEST);
            scce.addException(sce);

            auditManager.audit(Category.task, TaskSubCategory.report, Result.failure,
                    "Could not reported execution status: " + exec.getId() + "/" + taskUtil, scce);

            throw scce;
        }

        exec.setStatus(status.toString());
        exec.setMessage(message);
        exec = taskExecDAO.save(exec);

        auditManager.audit(Category.task, TaskSubCategory.report, Result.success,
                "Successfully reported execution status: " + exec.getId() + "/" + taskUtil);

        return binder.getTaskExecTO(exec);
    }
View Full Code Here


    @PreAuthorize("hasRole('TASK_DELETE')")
    @RequestMapping(method = RequestMethod.GET, value = "/execution/delete/{executionId}")
    public TaskExecTO deleteExecution(@PathVariable("executionId") final Long executionId)
            throws NotFoundException, SyncopeClientCompositeErrorException {

        TaskExec taskExec = taskExecDAO.find(executionId);
        if (taskExec == null) {
            throw new NotFoundException("Task execution " + executionId);
        }
       
        TaskExecTO taskExecutionToDelete = binder.getTaskExecTO(taskExec);

        taskExecDAO.delete(taskExec);

        auditManager.audit(Category.task, TaskSubCategory.deleteExecution, Result.success,
                "Successfully deleted task execution: " + taskExec.getId());
        return taskExecutionToDelete;
    }
View Full Code Here

        PropagationTask task = taskDAO.find(1L);
        assertNotNull(task);

        int executionNumber = task.getExecs().size();

        TaskExec execution = new TaskExec();
        execution.setTask(task);
        execution.setStatus(PropagationTaskExecStatus.CREATED.name());
        task.addExec(execution);
        execution.setStartDate(new Date());

        task = taskDAO.save(task);

        taskDAO.flush();
View Full Code Here

        SyncTask task = taskDAO.find(4L);
        assertNotNull(task);

        int executionNumber = task.getExecs().size();

        TaskExec execution = new TaskExec();
        execution.setStatus("Text-free status");
        execution.setTask(task);
        task.addExec(execution);
        execution.setMessage("A message");

        task = taskDAO.save(task);

        taskDAO.flush();
View Full Code Here

        assertNull(taskExecDAO.find(1L));
    }

    @Test
    public void deleteTaskExecution() {
        TaskExec execution = taskExecDAO.find(1L);
        int executionNumber = execution.getTask().getExecs().size();

        taskExecDAO.delete(1L);

        taskExecDAO.flush();
View Full Code Here

        return entityManager.merge(execution);
    }

    @Override
    public void delete(final Long id) {
        TaskExec execution = find(id);
        if (execution == null) {
            return;
        }

        delete(execution);
View Full Code Here

    @Test
    public void findLatestStarted() {
        PropagationTask task = taskDAO.find(1L);
        assertNotNull(task);

        TaskExec latestStarted = taskExecDAO.findLatestStarted(task);
        assertNotNull(latestStarted);
        assertEquals(Long.valueOf(1L), latestStarted.getId());
    }
View Full Code Here

            throws PropagationException {

        for (PropagationTask task : tasks) {
            LOG.debug("Execution started for {}", task);

            TaskExec execution = execute(task, handler);

            LOG.debug("Execution finished for {}, {}", task, execution);

            // Propagation is interrupted as soon as the result of the
            // communication with a primary resource is in error
            PropagationTaskExecStatus execStatus;
            try {
                execStatus = PropagationTaskExecStatus.valueOf(execution.getStatus());
            } catch (IllegalArgumentException e) {
                LOG.error("Unexpected execution status found {}", execution.getStatus());
                execStatus = PropagationTaskExecStatus.FAILURE;
            }
            if (task.getResource().isPropagationPrimary() && !execStatus.isSuccessful()) {

                throw new PropagationException(task.getResource().getName(), execution.getMessage());
            }
        }
    }
View Full Code Here

     * @return TaskExecution.
     */
    public TaskExec execute(final PropagationTask task, final PropagationHandler handler) {
        final Date startDate = new Date();

        TaskExec execution = new TaskExec();
        execution.setStatus(PropagationTaskExecStatus.CREATED.name());

        String taskExecutionMessage = null;

        // Flag to state whether any propagation has been attempted
        Set<String> propagationAttempted = new HashSet<String>();

        ConnectorObject before = null;
        ConnectorObject after = null;

        try {
            final ConnInstance connInstance = task.getResource().getConnector();

            final ConnectorFacadeProxy connector = connLoader.getConnector(task.getResource());

            if (connector == null) {
                final String msg = String.format("Connector instance bean for resource %s and "
                        + "connInstance %s not found", task.getResource(), connInstance);

                throw new NoSuchBeanDefinitionException(msg);
            }

            // Try to read user BEFORE any actual operation
            before = getRemoteObject(connector, task, false);

            try {
                switch (task.getPropagationOperation()) {
                    case CREATE:
                    case UPDATE:
                        // set of attributes to be propagated
                        final Set<Attribute> attributes = new HashSet<Attribute>(task.getAttributes());

                        if (before != null) {

                            // 1. check if rename is really required
                            final Name newName = (Name) AttributeUtil.find(Name.NAME, attributes);

                            LOG.debug("Rename required with value {}", newName);

                            if (newName != null && newName.equals(before.getName())
                                    && !before.getUid().getUidValue().equals(newName.getNameValue())) {

                                LOG.debug("Remote object name unchanged");
                                attributes.remove(newName);
                            }

                            LOG.debug("Attributes to be replaced {}", attributes);

                            // 2. update with a new "normalized" attribute set
                            connector.update(task.getPropagationMode(), ObjectClass.ACCOUNT, before.getUid(),
                                    attributes, null, propagationAttempted);
                        } else {
                            // 1. get accountId
                            final String accountId = task.getAccountId();

                            // 2. get name
                            final Name name = (Name) AttributeUtil.find(Name.NAME, attributes);

                            // 3. check if:
                            //      * accountId is not blank;
                            //      * accountId is not equal to Name.
                            if (StringUtils.hasText(accountId)
                                    && (name == null || !accountId.equals(name.getNameValue()))) {

                                // 3.a retrieve uid
                                final Uid uid = (Uid) AttributeUtil.find(Uid.NAME, attributes);

                                // 3.b add Uid if not provided
                                if (uid == null) {
                                    attributes.add(AttributeBuilder.build(Uid.NAME, Collections.singleton(accountId)));
                                }
                            }

                            // 4. provision entry
                            connector.create(task.getPropagationMode(), ObjectClass.ACCOUNT, attributes, null,
                                    propagationAttempted);
                        }
                        break;

                    case DELETE:
                        if (before == null) {
                            LOG.debug("{} not found on external resource:" + " ignoring delete", task.getAccountId());
                        } else {
                            final SyncopeUser user = getSyncopeUser(task.getSyncopeUser().getId());

                            if (user == null || !user.getResourceNames().contains(task.getResource().getName())) {
                                // perform de-provisioning
                                LOG.debug("Perform deprovisioning on {}", task.getResource().getName());

                                connector.delete(
                                        task.getPropagationMode(),
                                        ObjectClass.ACCOUNT,
                                        before.getUid(),
                                        null,
                                        propagationAttempted);
                            } else {
                                // Update remote profile.
                                // This is absolutely needed because otherwise the resource won't be updated:
                                // resources to be deleted won't be considered by UserDataBinder.update() for the update
                                // but, often, this have to be done.
                                LOG.debug("Update remote object on {}", task.getResource().getName());

                                connector.update(
                                        task.getPropagationMode(),
                                        ObjectClass.ACCOUNT,
                                        before.getUid(),
                                        task.getAttributes(),
                                        null,
                                        propagationAttempted);
                            }
                        }

                        break;

                    default:
                }

                execution.setStatus(task.getPropagationMode() == PropagationMode.ONE_PHASE
                        ? PropagationTaskExecStatus.SUCCESS.name()
                        : PropagationTaskExecStatus.SUBMITTED.name());

                LOG.debug("Successfully propagated to {}", task.getResource());

                // Try to read user AFTER any actual operation
                after = getRemoteObject(connector, task, true);

            } catch (Exception e) {
                after = getRemoteObject(connector, task, false);
                throw e;
            }

        } catch (Exception e) {
            LOG.error("Exception during provision on resource " + task.getResource().getName(), e);

            if (e instanceof ConnectorException && e.getCause() != null) {
                taskExecutionMessage = e.getCause().getMessage();
            } else {
                StringWriter exceptionWriter = new StringWriter();
                exceptionWriter.write(e.getMessage() + "\n\n");
                e.printStackTrace(new PrintWriter(exceptionWriter));
                taskExecutionMessage = exceptionWriter.toString();
            }

            try {
                execution.setStatus(task.getPropagationMode() == PropagationMode.ONE_PHASE
                        ? PropagationTaskExecStatus.FAILURE.name()
                        : PropagationTaskExecStatus.UNSUBMITTED.name());
            } catch (Exception wft) {
                LOG.error("While executing KO action on {}", execution, wft);
            }

            propagationAttempted.add(task.getPropagationOperation().name().toLowerCase());
        } finally {
            LOG.debug("Update execution for {}", task);

            execution.setStartDate(startDate);
            execution.setMessage(taskExecutionMessage);
            execution.setEndDate(new Date());

            if (hasToBeregistered(task, execution)) {
                if (propagationAttempted.isEmpty()) {
                    LOG.debug("No propagation attempted for {}", execution);
                } else {
                    execution.setTask(task);
                    task.addExec(execution);

                    LOG.debug("Execution finished: {}", execution);
                }

                taskDAO.save(task);

                // Flush call is needed to value the id field of execution (used by deal test of TaskTestITCase).
                taskDAO.flush();

                // An alternative to the flush call could be the following statement but we should accept the risk to 
                // have a not so probable trouble coming from concurrent calls.
                //final TaskExec latestExec = taskExecDAO.findLatestStarted(taskDAO.save(task));
            }
        }

        if (handler != null) {
            handler.handle(
                    task.getResource().getName(),
                    PropagationTaskExecStatus.valueOf(execution.getStatus()),
                    before,
                    after);
        }

        return execution;
View Full Code Here

    }

    public TaskExec executeSingle(final NotificationTask task) {
        init();

        TaskExec execution = new TaskExec();
        execution.setTask(task);
        execution.setStartDate(new Date());

        if (StringUtils.isBlank(smtpHost) || StringUtils.isBlank(task.getSender())
                || StringUtils.isBlank(task.getSubject()) || task.getRecipients().isEmpty()
                || StringUtils.isBlank(task.getHtmlBody()) || StringUtils.isBlank(task.getTextBody())) {

            String message = "Could not fetch all required information for " + "sending e-mails:\n" + smtpHost + ":"
                    + smtpPort + "\n" + task.getRecipients() + "\n" + task.getSender() + "\n" + task.getSubject()
                    + "\n" + task.getHtmlBody() + "\n" + task.getTextBody();
            LOG.error(message);

            execution.setStatus(Status.NOT_SENT.name());

            if (task.getTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) {

                execution.setMessage(message);
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("About to send e-mails:\n" + smtpHost + ":" + smtpPort + "\n" + task.getRecipients() + "\n"
                        + task.getSender() + "\n" + task.getSubject() + "\n" + task.getHtmlBody() + "\n"
                        + task.getTextBody() + "\n");
            }

            for (String to : task.getRecipients()) {
                try {
                    JavaMailSenderImpl sender = new JavaMailSenderImpl();
                    sender.setHost(smtpHost);
                    sender.setPort(smtpPort);
                    sender.setDefaultEncoding("UTF-8");
                    if (StringUtils.isNotBlank(smtpUsername)) {
                        sender.setUsername(smtpUsername);
                    }
                    if (StringUtils.isNotBlank(smtpPassword)) {
                        sender.setPassword(smtpPassword);
                    }

                    MimeMessage message = sender.createMimeMessage();
                    MimeMessageHelper helper = new MimeMessageHelper(message, true);
                    helper.setTo(to);
                    helper.setFrom(task.getSender());
                    helper.setSubject(task.getSubject());
                    helper.setText(task.getTextBody(), task.getHtmlBody());

                    sender.send(message);

                    execution.setStatus(Status.SENT.name());

                    StringBuilder report = new StringBuilder();
                    switch (task.getTraceLevel()) {
                        case ALL:
                            report.append("FROM: ").append(task.getSender()).append('\n').
                                    append("TO: ").append(to).append('\n').
                                    append("SUBJECT: ").append(task.getSubject()).append('\n').append('\n').
                                    append(task.getTextBody()).append('\n').append('\n').
                                    append(task.getHtmlBody()).append('\n');
                            break;

                        case SUMMARY:
                            report.append("E-mail sent to ").append(to).append('\n');
                            break;

                        case FAILURES:
                        case NONE:
                        default:
                    }
                    if (report.length() > 0) {
                        execution.setMessage(report.toString());
                    }

                    auditManager.audit(Category.notification, NotificationSubCategory.sent, Result.success,
                            "Successfully sent notification to " + to);
                } catch (Exception e) {
                    LOG.error("Could not send e-mail", e);

                    execution.setStatus(Status.NOT_SENT.name());
                    StringWriter exceptionWriter = new StringWriter();
                    exceptionWriter.write(e.getMessage() + "\n\n");
                    e.printStackTrace(new PrintWriter(exceptionWriter));

                    if (task.getTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) {
                        execution.setMessage(exceptionWriter.toString());
                    }

                    auditManager.audit(Category.notification, NotificationSubCategory.sent, Result.failure,
                            "Could not send notification to " + to, e);
                }

                execution.setEndDate(new Date());
            }
        }

        if (hasToBeRegistered(execution)) {
            execution = notificationManager.storeExecAndUpdateLatestExecStatus(execution);
View Full Code Here

TOP

Related Classes of org.apache.syncope.core.persistence.beans.TaskExec

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.