Example usage for org.apache.commons.lang3 SerializationUtils clone

List of usage examples for org.apache.commons.lang3 SerializationUtils clone

Introduction

In this page you can find the example usage for org.apache.commons.lang3 SerializationUtils clone.

Prototype

public static <T extends Serializable> T clone(final T object) 

Source Link

Document

Deep clone an Object using serialization.

This is many times slower than writing clone methods by hand on all objects in your object graph.

Usage

From source file:org.apache.syncope.client.console.reports.ReportDirectoryPanel.java

@Override
public ActionsPanel<ReportTO> getActions(final IModel<ReportTO> model) {
    final ActionsPanel<ReportTO> panel = super.getActions(model);

    panel.add(new ActionLink<ReportTO>() {

        private static final long serialVersionUID = -3722207913631435501L;

        @Override/*from ww w .jav  a 2  s  .  c  o m*/
        public void onClick(final AjaxRequestTarget target, final ReportTO ignore) {
            send(ReportDirectoryPanel.this, Broadcast.EXACT,
                    new AjaxWizard.EditItemActionEvent<>(restClient.read(model.getObject().getKey()), target));
        }
    }, ActionLink.ActionType.EDIT, StandardEntitlement.REPORT_UPDATE);

    panel.add(new ActionLink<ReportTO>() {

        private static final long serialVersionUID = -3722207913631435501L;

        @Override
        public void onClick(final AjaxRequestTarget target, final ReportTO ignore) {
            final ReportTO clone = SerializationUtils.clone(model.getObject());
            clone.setKey(null);
            send(ReportDirectoryPanel.this, Broadcast.EXACT,
                    new AjaxWizard.EditItemActionEvent<>(clone, target));
        }
    }, ActionLink.ActionType.CLONE, StandardEntitlement.REPORT_CREATE);

    panel.add(new ActionLink<ReportTO>() {

        private static final long serialVersionUID = -3722207913631435501L;

        @Override
        public void onClick(final AjaxRequestTarget target, final ReportTO ignore) {
            target.add(
                    modal.setContent(new ReportletDirectoryPanel(modal, model.getObject().getKey(), pageRef)));

            modal.header(new StringResourceModel("reportlet.conf", ReportDirectoryPanel.this,
                    Model.of(model.getObject())));

            MetaDataRoleAuthorizationStrategy.authorize(modal.getForm(), ENABLE,
                    StandardEntitlement.RESOURCE_UPDATE);

            modal.show(true);
        }
    }, ActionLink.ActionType.COMPOSE, StandardEntitlement.REPORT_UPDATE);

    panel.add(new ActionLink<ReportTO>() {

        private static final long serialVersionUID = -3722207913631435501L;

        @Override
        public void onClick(final AjaxRequestTarget target, final ReportTO ignore) {
            viewTask(model.getObject(), target);
        }
    }, ActionLink.ActionType.VIEW, StandardEntitlement.REPORT_READ);

    panel.add(new ActionLink<ReportTO>() {

        private static final long serialVersionUID = -3722207913631435501L;

        @Override
        public void onClick(final AjaxRequestTarget target, final ReportTO ignore) {
            startAt.setExecutionDetail(model.getObject().getKey(), model.getObject().getName(), target);
            startAt.toggle(target, true);
        }
    }, ActionLink.ActionType.EXECUTE, StandardEntitlement.REPORT_EXECUTE);

    panel.add(new ActionLink<ReportTO>() {

        private static final long serialVersionUID = -3722207913631435501L;

        @Override
        public void onClick(final AjaxRequestTarget target, final ReportTO ignore) {
            final ReportTO reportTO = model.getObject();
            try {
                restClient.delete(reportTO.getKey());
                SyncopeConsoleSession.get().info(getString(Constants.OPERATION_SUCCEEDED));
                target.add(container);
            } catch (SyncopeClientException e) {
                LOG.error("While deleting {}", reportTO.getKey(), e);
                SyncopeConsoleSession.get()
                        .error(StringUtils.isBlank(e.getMessage()) ? e.getClass().getName() : e.getMessage());
            }
            ((BasePage) pageRef.getPage()).getNotificationPanel().refresh(target);
        }
    }, ActionLink.ActionType.DELETE, StandardEntitlement.REPORT_DELETE, true);
    return panel;
}

From source file:org.apache.syncope.client.console.tasks.SchedTaskDirectoryPanel.java

@Override
public ActionsPanel<T> getActions(final IModel<T> model) {
    final ActionsPanel<T> panel = super.getActions(model);
    final T taskTO = model.getObject();

    panel.add(new ActionLink<T>() {

        private static final long serialVersionUID = -3722207913631435501L;

        @Override/*from w w w. ja  v  a2  s. c om*/
        public void onClick(final AjaxRequestTarget target, final T ignore) {
            SchedTaskDirectoryPanel.this.getTogglePanel().close(target);
            viewTask(taskTO, target);
        }
    }, ActionLink.ActionType.VIEW, StandardEntitlement.TASK_READ);

    panel.add(new ActionLink<T>() {

        private static final long serialVersionUID = -3722207913631435501L;

        @Override
        public void onClick(final AjaxRequestTarget target, final T ignore) {
            SchedTaskDirectoryPanel.this.getTogglePanel().close(target);
            send(SchedTaskDirectoryPanel.this, Broadcast.EXACT,
                    new AjaxWizard.EditItemActionEvent<>(
                            restClient.readSchedTask(reference, model.getObject().getKey()), target)
                                    .setResourceModel(new StringResourceModel("inner.task.edit",
                                            SchedTaskDirectoryPanel.this,
                                            Model.of(Pair.of(ActionLink.ActionType.EDIT, model.getObject())))));
        }
    }, ActionLink.ActionType.EDIT, StandardEntitlement.TASK_UPDATE);

    panel.add(new ActionLink<T>() {

        private static final long serialVersionUID = -3722207913631435501L;

        @Override
        public void onClick(final AjaxRequestTarget target, final T ignore) {
            SchedTaskDirectoryPanel.this.getTogglePanel().close(target);
            final T clone = SerializationUtils.clone(model.getObject());
            clone.setKey(null);
            send(SchedTaskDirectoryPanel.this, Broadcast.EXACT,
                    new AjaxWizard.EditItemActionEvent<>(clone, target).setResourceModel(
                            new StringResourceModel("inner.task.clone", SchedTaskDirectoryPanel.this,
                                    Model.of(Pair.of(ActionLink.ActionType.CLONE, model.getObject())))));
        }
    }, ActionLink.ActionType.CLONE, StandardEntitlement.TASK_CREATE);

    panel.add(new ActionLink<T>() {

        private static final long serialVersionUID = -3722207913631435501L;

        @Override
        public void onClick(final AjaxRequestTarget target, final T ignore) {
            SchedTaskDirectoryPanel.this.getTogglePanel().close(target);
            startAt.setExecutionDetail(model.getObject().getKey(), model.getObject().getName(), target);
            startAt.toggle(target, true);
        }
    }, ActionLink.ActionType.EXECUTE, StandardEntitlement.TASK_EXECUTE);

    addFurtherActions(panel, model);

    panel.add(new ActionLink<T>() {

        private static final long serialVersionUID = -3722207913631435501L;

        @Override
        public void onClick(final AjaxRequestTarget target, final T ignore) {
            try {
                restClient.delete(taskTO.getKey(), reference);
                SyncopeConsoleSession.get().info(getString(Constants.OPERATION_SUCCEEDED));
                target.add(container);
                SchedTaskDirectoryPanel.this.getTogglePanel().close(target);
            } catch (SyncopeClientException e) {
                SyncopeConsoleSession.get()
                        .error(StringUtils.isBlank(e.getMessage()) ? e.getClass().getName() : e.getMessage());
                LOG.error("While deleting propagation task {}", taskTO.getKey(), e);
            }
            ((BasePage) pageRef.getPage()).getNotificationPanel().refresh(target);
        }
    }, ActionLink.ActionType.DELETE, StandardEntitlement.TASK_DELETE, true);

    return panel;
}

From source file:org.apache.syncope.client.console.tasks.SchedTaskSearchResultPanel.java

@Override
protected final List<IColumn<T, String>> getColumns() {
    final List<IColumn<T, String>> columns = new ArrayList<>();

    columns.addAll(getFieldColumns());/*w  ww.  j ava 2s  .co  m*/

    columns.add(new ActionColumn<T, String>(new ResourceModel("actions", "")) {

        private static final long serialVersionUID = 2054811145491901166L;

        @Override
        public String getCssClass() {
            return "action";
        }

        @Override
        public ActionLinksPanel<T> getActions(final String componentId, final IModel<T> model) {

            final T taskTO = model.getObject();

            final ActionLinksPanel<T> panel = ActionLinksPanel.<T>builder(pageRef).add(new ActionLink<T>() {

                private static final long serialVersionUID = -3722207913631435501L;

                @Override
                public void onClick(final AjaxRequestTarget target, final T ignore) {
                    viewTask(taskTO, target);
                }
            }, ActionLink.ActionType.SEARCH, StandardEntitlement.TASK_READ).add(new ActionLink<T>() {

                private static final long serialVersionUID = -3722207913631435501L;

                @Override
                public void onClick(final AjaxRequestTarget target, final T ignore) {
                    send(SchedTaskSearchResultPanel.this, Broadcast.EXACT, new AjaxWizard.EditItemActionEvent<>(
                            restClient.readSchedTask(reference, model.getObject().getKey()), target));
                }
            }, ActionLink.ActionType.EDIT, StandardEntitlement.TASK_UPDATE).add(new ActionLink<T>() {

                private static final long serialVersionUID = -3722207913631435501L;

                @Override
                public void onClick(final AjaxRequestTarget target, final T ignore) {
                    final T clone = SerializationUtils.clone(model.getObject());
                    clone.setKey(0L);
                    send(SchedTaskSearchResultPanel.this, Broadcast.EXACT,
                            new AjaxWizard.EditItemActionEvent<>(clone, target));
                }
            }, ActionLink.ActionType.CLONE, StandardEntitlement.TASK_CREATE).add(new ActionLink<T>() {

                private static final long serialVersionUID = -3722207913631435501L;

                @Override
                public void onClick(final AjaxRequestTarget target, final T ignore) {
                    startAt.setTaskTO(target, model.getObject());
                    startAt.toggle(target, true);
                }
            }, ActionLink.ActionType.EXECUTE, StandardEntitlement.TASK_EXECUTE).add(new ActionLink<T>() {

                private static final long serialVersionUID = -3722207913631435501L;

                @Override
                public void onClick(final AjaxRequestTarget target, final T ignore) {
                    try {
                        restClient.startExecution(taskTO.getKey(), null, true);
                        info(getString(Constants.OPERATION_SUCCEEDED));
                        target.add(container);
                    } catch (SyncopeClientException e) {
                        error(getString(Constants.ERROR) + ": " + e.getMessage());
                        LOG.error("While running propagation task {}", taskTO.getKey(), e);
                    }
                    SyncopeConsoleSession.get().getNotificationPanel().refresh(target);
                }
            }, ActionLink.ActionType.DRYRUN, StandardEntitlement.TASK_EXECUTE).add(new ActionLink<T>() {

                private static final long serialVersionUID = -3722207913631435501L;

                @Override
                public void onClick(final AjaxRequestTarget target, final T ignore) {
                    try {
                        restClient.delete(taskTO.getKey(), reference);
                        info(getString(Constants.OPERATION_SUCCEEDED));
                        target.add(container);
                    } catch (SyncopeClientException e) {
                        error(getString(Constants.ERROR) + ": " + e.getMessage());
                        LOG.error("While deleting propagation task {}", taskTO.getKey(), e);
                    }
                    SyncopeConsoleSession.get().getNotificationPanel().refresh(target);
                }
            }, ActionLink.ActionType.DELETE, StandardEntitlement.TASK_DELETE).build(componentId);

            return panel;
        }

        @Override
        public ActionLinksPanel<T> getHeader(final String componentId) {
            final ActionLinksPanel.Builder<T> panel = ActionLinksPanel.builder(page.getPageReference());

            return panel.add(new ActionLink<T>() {

                private static final long serialVersionUID = -7978723352517770644L;

                @Override
                public void onClick(final AjaxRequestTarget target, final T ignore) {
                    if (target != null) {
                        target.add(container);
                    }
                }
            }, ActionLink.ActionType.RELOAD, StandardEntitlement.TASK_LIST).build(componentId);
        }
    });

    return columns;
}

From source file:org.apache.syncope.client.console.wicket.markup.html.form.FieldPanel.java

@Override
@SuppressWarnings("unchecked")
public FieldPanel<T> clone() {
    final FieldPanel<T> panel = SerializationUtils.clone(this);
    panel.setModelObject(null);//  w  w  w  .  ja v  a2s.  c o  m
    panel.addLabel();
    return panel;
}

From source file:org.apache.syncope.client.console.wizards.AbstractModalPanelBuilder.java

protected T newModelObject() {
    if (item == null) {
        // keep the original item: the which one before the changes performed during wizard browsing
        item = SerializationUtils.clone(defaultItem);
    }/*  w ww.  j a  v a2 s. c o m*/

    // instantiate a new model object and return it
    return SerializationUtils.clone(item);
}

From source file:org.apache.syncope.client.enduser.resources.UserSelfCreateResource.java

@Override
protected ResourceResponse newResourceResponse(final Attributes attributes) {
    ResourceResponse response = new ResourceResponse();
    response.setContentType(MediaType.TEXT_PLAIN);
    try {//from  ww  w.  j  a  va2  s. co  m
        HttpServletRequest request = (HttpServletRequest) attributes.getRequest().getContainerRequest();

        if (!xsrfCheck(request)) {
            LOG.error("XSRF TOKEN is not matching");
            response.setError(Response.Status.BAD_REQUEST.getStatusCode(), "XSRF TOKEN is not matching");
            return response;
        }

        String jsonString = request.getReader().readLine();
        final UserTO userTO = MAPPER.readValue(jsonString, UserTO.class);

        if (!captchaCheck(request.getHeader("captcha"),
                request.getSession().getAttribute(SyncopeEnduserConstants.CAPTCHA_SESSION_KEY))) {

            throw new IllegalArgumentException("Entered captcha is not matching");
        }

        if (isSelfRegistrationAllowed() && userTO != null) {
            LOG.debug("User self registration request for [{}]", userTO.getUsername());
            LOG.trace("Request is [{}]", userTO);

            // check if request is compliant with customization form rules
            if (UserRequestValidator.compliant(userTO, SyncopeEnduserApplication.get().getCustomForm(), true)) {

                // 1. membership attributes management
                Set<AttrTO> membAttrs = new HashSet<>();
                userTO.getPlainAttrs().stream().filter(
                        attr -> (attr.getSchema().contains(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR)))
                        .forEachOrdered(attr -> {
                            String[] simpleAttrs = attr.getSchema()
                                    .split(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR);
                            MembershipTO membership = userTO.getMemberships().stream()
                                    .filter(memb -> simpleAttrs[0].equals(memb.getGroupName())).findFirst()
                                    .orElse(null);
                            if (membership == null) {
                                membership = new MembershipTO.Builder().group(null, simpleAttrs[0]).build();
                                userTO.getMemberships().add(membership);
                            }

                            AttrTO clone = SerializationUtils.clone(attr);
                            clone.setSchema(simpleAttrs[1]);
                            membership.getPlainAttrs().add(clone);
                            membAttrs.add(attr);
                        });
                userTO.getPlainAttrs().removeAll(membAttrs);

                // 2. millis -> Date conversion for PLAIN attributes of USER and its MEMBERSHIPS
                SyncopeEnduserSession.get().getDatePlainSchemas().stream().map(plainSchema -> {
                    millisToDate(userTO.getPlainAttrs(), plainSchema);
                    return plainSchema;
                }).forEachOrdered(plainSchema -> {
                    userTO.getMemberships().forEach(membership -> {
                        millisToDate(membership.getPlainAttrs(), plainSchema);
                    });
                });

                membAttrs.clear();
                userTO.getDerAttrs().stream().filter(
                        attr -> (attr.getSchema().contains(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR)))
                        .forEachOrdered(attr -> {
                            String[] simpleAttrs = attr.getSchema()
                                    .split(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR);
                            MembershipTO membership = userTO.getMemberships().stream()
                                    .filter(memb -> simpleAttrs[0].equals(memb.getGroupName())).findFirst()
                                    .orElse(null);
                            if (membership == null) {
                                membership = new MembershipTO.Builder().group(null, simpleAttrs[0]).build();
                                userTO.getMemberships().add(membership);
                            }

                            AttrTO clone = SerializationUtils.clone(attr);
                            clone.setSchema(simpleAttrs[1]);
                            membership.getDerAttrs().add(clone);
                            membAttrs.add(attr);
                        });
                userTO.getDerAttrs().removeAll(membAttrs);

                membAttrs.clear();
                userTO.getVirAttrs().stream().filter(
                        attr -> (attr.getSchema().contains(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR)))
                        .forEachOrdered(attr -> {
                            String[] simpleAttrs = attr.getSchema()
                                    .split(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR);
                            MembershipTO membership = userTO.getMemberships().stream()
                                    .filter(memb -> simpleAttrs[0].equals(memb.getGroupName())).findFirst()
                                    .orElse(null);
                            if (membership == null) {
                                membership = new MembershipTO.Builder().group(null, simpleAttrs[0]).build();
                                userTO.getMemberships().add(membership);
                            }

                            AttrTO clone = SerializationUtils.clone(attr);
                            clone.setSchema(simpleAttrs[1]);
                            membership.getVirAttrs().add(clone);
                            membAttrs.add(attr);
                        });
                userTO.getVirAttrs().removeAll(membAttrs);

                LOG.debug("Received user self registration request for user: [{}]", userTO.getUsername());
                LOG.trace("Received user self registration request is: [{}]", userTO);

                // adapt request and create user
                final Response res = SyncopeEnduserSession.get().getService(UserSelfService.class)
                        .create(userTO, true);

                buildResponse(response, res.getStatus(),
                        Response.Status.Family.SUCCESSFUL.equals(res.getStatusInfo().getFamily())
                                ? "User[ " + userTO.getUsername() + "] successfully created"
                                : "ErrorMessage{{ " + res.getStatusInfo().getReasonPhrase() + " }}");
            } else {
                LOG.warn("Incoming create request [{}] is not compliant with form customization rules. "
                        + "Create NOT allowed", userTO.getUsername());
                buildResponse(response, Response.Status.OK.getStatusCode(),
                        "User: " + userTO.getUsername() + " successfully created");
            }
        } else {
            response.setError(Response.Status.FORBIDDEN.getStatusCode(),
                    new StringBuilder().append("ErrorMessage{{")
                            .append(userTO == null ? "Request received is not valid }}"
                                    : "Self registration not allowed }}")
                            .toString());
        }
    } catch (Exception e) {
        LOG.error("Unable to create userTO", e);
        response.setError(Response.Status.BAD_REQUEST.getStatusCode(),
                new StringBuilder().append("ErrorMessage{{ ").append(e.getMessage()).append(" }}").toString());
    }
    return response;
}

From source file:org.apache.syncope.client.enduser.resources.UserSelfReadResource.java

@Override
protected ResourceResponse newResourceResponse(final IResource.Attributes attributes) {
    LOG.debug("Requested user self information");

    ResourceResponse response = new AbstractResource.ResourceResponse();
    response.setContentType(MediaType.APPLICATION_JSON);
    try {/*from  www  .  j ava  2  s  .  co  m*/
        HttpServletRequest request = (HttpServletRequest) attributes.getRequest().getContainerRequest();
        if (!xsrfCheck(request)) {
            LOG.error("XSRF TOKEN does not match");
            response.setError(Response.Status.BAD_REQUEST.getStatusCode(), "XSRF TOKEN does not match");
            return response;
        }

        UserTO userTO = SerializationUtils.clone(SyncopeEnduserSession.get().getSelfTO());

        // 1. Date -> millis conversion for PLAIN MEMBERSHIPS attributes of USER
        for (PlainSchemaTO plainSchema : SyncopeEnduserSession.get().getDatePlainSchemas()) {
            for (MembershipTO membership : userTO.getMemberships()) {
                dateToMillis(membership.getPlainAttrs(), plainSchema);
            }
        }

        // 2. membership attributes management
        for (MembershipTO membership : userTO.getMemberships()) {
            String groupName = membership.getGroupName();
            membership.getPlainAttrs().stream().map(attr -> {
                attr.setSchema(groupName.concat(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR)
                        .concat(attr.getSchema()));
                return attr;
            }).forEachOrdered(attr -> {
                userTO.getPlainAttrs().add(attr);
            });
            membership.getPlainAttrs().clear();
            membership.getDerAttrs().stream().map(attr -> {
                attr.setSchema(groupName.concat(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR)
                        .concat(attr.getSchema()));
                return attr;
            }).forEachOrdered(attr -> {
                userTO.getDerAttrs().add(attr);
            });
            membership.getDerAttrs().clear();
            membership.getVirAttrs().stream().map((attr) -> {
                attr.setSchema(groupName.concat(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR)
                        .concat(attr.getSchema()));
                return attr;
            }).forEachOrdered(attr -> {
                userTO.getVirAttrs().add(attr);
            });
            membership.getVirAttrs().clear();
        }
        // USER from customization, if empty or null ignore it, use it to filter attributes otherwise
        applyFromCustomization(userTO, SyncopeEnduserApplication.get().getCustomForm());

        // 1.1 Date -> millis conversion for PLAIN attributes of USER
        for (PlainSchemaTO plainSchema : SyncopeEnduserSession.get().getDatePlainSchemas()) {
            dateToMillis(userTO.getPlainAttrs(), plainSchema);
        }

        final String selfTOJson = MAPPER.writeValueAsString(userTO);
        response.setContentType(MediaType.APPLICATION_JSON);
        response.setTextEncoding(StandardCharsets.UTF_8.name());

        response.setWriteCallback(new WriteCallback() {

            @Override
            public void writeData(final Attributes attributes) throws IOException {
                attributes.getResponse().write(selfTOJson);
            }
        });
        response.setStatusCode(Response.Status.OK.getStatusCode());
    } catch (Exception e) {
        LOG.error("Error retrieving selfTO", e);
        response.setError(Response.Status.BAD_REQUEST.getStatusCode(),
                new StringBuilder().append("ErrorMessage{{ ").append(e.getMessage()).append(" }}").toString());
    }
    return response;
}

From source file:org.apache.syncope.client.enduser.resources.UserSelfUpdateResource.java

@Override
protected ResourceResponse newResourceResponse(final IResource.Attributes attributes) {
    ResourceResponse response = new AbstractResource.ResourceResponse();
    response.setContentType(MediaType.TEXT_PLAIN);
    try {//from w  w  w .  java  2  s. c o m
        HttpServletRequest request = (HttpServletRequest) attributes.getRequest().getContainerRequest();
        if (!xsrfCheck(request)) {
            LOG.error("XSRF TOKEN does not match");
            response.setError(Response.Status.BAD_REQUEST.getStatusCode(), "XSRF TOKEN does not match");
            return response;
        }

        if (!captchaCheck(request.getHeader("captcha"),
                request.getSession().getAttribute(SyncopeEnduserConstants.CAPTCHA_SESSION_KEY))) {

            throw new IllegalArgumentException("Entered captcha is not matching");
        }

        UserTO userTO = MAPPER.readValue(request.getReader().readLine(), UserTO.class);
        Map<String, CustomAttributesInfo> customForm = SyncopeEnduserApplication.get().getCustomForm();

        // check if request is compliant with customization form rules
        if (UserRequestValidator.compliant(userTO, customForm, false)) {
            // 1. membership attributes management
            Set<AttrTO> membAttrs = new HashSet<>();
            userTO.getPlainAttrs().stream().filter(
                    attr -> (attr.getSchema().contains(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR)))
                    .forEachOrdered((attr) -> {
                        String[] simpleAttrs = attr.getSchema()
                                .split(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR);
                        MembershipTO membership = userTO.getMemberships().stream()
                                .filter(item -> simpleAttrs[0].equals(item.getGroupName())).findFirst()
                                .orElse(null);
                        if (membership == null) {
                            membership = new MembershipTO.Builder().group(null, simpleAttrs[0]).build();
                            userTO.getMemberships().add(membership);
                        }
                        AttrTO clone = SerializationUtils.clone(attr);
                        clone.setSchema(simpleAttrs[1]);
                        membership.getPlainAttrs().add(clone);
                        membAttrs.add(attr);
                    });
            userTO.getPlainAttrs().removeAll(membAttrs);

            // 2. millis -> Date conversion for PLAIN attributes of USER and its MEMBERSHIPS
            SyncopeEnduserSession.get().getDatePlainSchemas().stream().map(plainSchema -> {
                millisToDate(userTO.getPlainAttrs(), plainSchema);
                return plainSchema;
            }).forEachOrdered(plainSchema -> {
                userTO.getMemberships().forEach(membership -> {
                    millisToDate(membership.getPlainAttrs(), plainSchema);
                });
            });

            membAttrs.clear();
            userTO.getDerAttrs().stream().filter(
                    attr -> (attr.getSchema().contains(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR)))
                    .forEachOrdered(attr -> {
                        String[] simpleAttrs = attr.getSchema()
                                .split(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR);
                        MembershipTO membership = userTO.getMemberships().stream()
                                .filter(item -> simpleAttrs[0].equals(item.getGroupName())).findFirst()
                                .orElse(null);
                        if (membership == null) {
                            membership = new MembershipTO.Builder().group(null, simpleAttrs[0]).build();
                            userTO.getMemberships().add(membership);
                        }
                        AttrTO clone = SerializationUtils.clone(attr);
                        clone.setSchema(simpleAttrs[1]);
                        membership.getDerAttrs().add(clone);
                        membAttrs.add(attr);
                    });
            userTO.getDerAttrs().removeAll(membAttrs);

            membAttrs.clear();
            userTO.getVirAttrs().stream().filter(
                    attr -> (attr.getSchema().contains(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR)))
                    .forEachOrdered((attr) -> {
                        String[] simpleAttrs = attr.getSchema()
                                .split(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR);
                        MembershipTO membership = userTO.getMemberships().stream()
                                .filter(item -> simpleAttrs[0].equals(item.getGroupName())).findFirst()
                                .orElse(null);
                        if (membership == null) {
                            membership = new MembershipTO.Builder().group(null, simpleAttrs[0]).build();
                            userTO.getMemberships().add(membership);

                        }
                        AttrTO clone = SerializationUtils.clone(attr);
                        clone.setSchema(simpleAttrs[1]);
                        membership.getVirAttrs().add(clone);
                        membAttrs.add(attr);
                    });
            userTO.getVirAttrs().removeAll(membAttrs);

            // get old user object from session
            UserTO selfTO = SyncopeEnduserSession.get().getSelfTO();
            // align "userTO" and "selfTO" objects
            if (customForm != null && !customForm.isEmpty()) {
                completeUserObject(userTO, selfTO);
            }
            // create diff patch
            UserPatch userPatch = AnyOperations.diff(userTO, selfTO, false);
            // update user by patch
            Response res = SyncopeEnduserSession.get().getService(userTO.getETagValue(), UserSelfService.class)
                    .update(userPatch);

            buildResponse(response, res.getStatus(),
                    res.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)
                            ? "User [" + userTO.getUsername() + "] successfully updated"
                            : "ErrorMessage{{ " + res.getStatusInfo().getReasonPhrase() + " }}");
        } else {
            LOG.warn("Incoming update request [{}] is not compliant with form customization rules."
                    + " Update NOT allowed", userTO.getUsername());
            buildResponse(response, Response.Status.OK.getStatusCode(),
                    "User: " + userTO.getUsername() + " successfully created");
        }
    } catch (final Exception e) {
        LOG.error("Error while updating user", e);
        response.setError(Response.Status.BAD_REQUEST.getStatusCode(),
                new StringBuilder().append("ErrorMessage{{ ").append(e.getMessage()).append(" }}").toString());
    }
    return response;
}

From source file:org.apache.syncope.common.lib.AnyOperations.java

public static GroupTO patch(final GroupTO groupTO, final GroupPatch groupPatch) {
    GroupTO result = SerializationUtils.clone(groupTO);
    patch(groupTO, groupPatch, result);/*  w ww. jav  a 2 s .  c om*/

    if (groupPatch.getName() != null) {
        result.setName(groupPatch.getName().getValue());
    }

    if (groupPatch.getUserOwner() != null) {
        result.setGroupOwner(groupPatch.getUserOwner().getValue());
    }
    if (groupPatch.getGroupOwner() != null) {
        result.setGroupOwner(groupPatch.getGroupOwner().getValue());
    }

    result.setUDynMembershipCond(groupPatch.getUDynMembershipCond());
    result.getADynMembershipConds().clear();
    result.getADynMembershipConds().putAll(groupPatch.getADynMembershipConds());

    return result;
}

From source file:org.apache.syncope.common.lib.AnyOperations.java

public static AnyObjectTO patch(final AnyObjectTO anyObjectTO, final AnyObjectPatch anyObjectPatch) {
    AnyObjectTO result = SerializationUtils.clone(anyObjectTO);
    patch(anyObjectTO, anyObjectPatch, result);

    if (anyObjectPatch.getName() != null) {
        result.setName(anyObjectPatch.getName().getValue());
    }//  w w  w . ja va  2  s  .  c o m

    // 1. relationships
    anyObjectPatch.getRelationships().forEach(relPatch -> {
        if (relPatch.getRelationshipTO() == null) {
            LOG.warn("Invalid {} specified: {}", RelationshipPatch.class.getName(), relPatch);
        } else {
            result.getRelationships().remove(relPatch.getRelationshipTO());
            if (relPatch.getOperation() == PatchOperation.ADD_REPLACE) {
                result.getRelationships().add(relPatch.getRelationshipTO());
            }
        }
    });

    // 2. memberships
    anyObjectPatch.getMemberships().forEach(membPatch -> {
        if (membPatch.getGroup() == null) {
            LOG.warn("Invalid {} specified: {}", MembershipPatch.class.getName(), membPatch);
        } else {
            Optional<MembershipTO> memb = result.getMemberships().stream()
                    .filter(membership -> membPatch.getGroup().equals(membership.getGroupKey())).findFirst();
            if (memb.isPresent()) {
                result.getMemberships().remove(memb.get());
            }

            if (membPatch.getOperation() == PatchOperation.ADD_REPLACE) {
                MembershipTO newMembershipTO = new MembershipTO.Builder().group(membPatch.getGroup()).build();

                // 3. plain attributes
                newMembershipTO.getPlainAttrs().addAll(membPatch.getPlainAttrs());

                // 4. virtual attributes
                newMembershipTO.getVirAttrs().addAll(membPatch.getVirAttrs());

                result.getMemberships().add(newMembershipTO);
            }
        }
    });

    return result;
}