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.core.workflow.user.activiti.task.Update.java

@Override
protected void doExecute(final String executionId) {
    SyncopeUser user = (SyncopeUser) runtimeService.getVariable(executionId,
            ActivitiUserWorkflowAdapter.SYNCOPE_USER);
    UserMod userMod = (UserMod) runtimeService.getVariable(executionId, ActivitiUserWorkflowAdapter.USER_MOD);

    // update password internally only if required
    UserMod actualMod = SerializationUtils.clone(userMod);
    if (actualMod.getPwdPropRequest() != null && !actualMod.getPwdPropRequest().isOnSyncope()) {
        actualMod.setPassword(null);//www .ja v  a2  s  .  c  om
    }
    // update SyncopeUser
    PropagationByResource propByRes = dataBinder.update(user, actualMod);

    // report updated user and propagation by resource as result
    runtimeService.setVariable(executionId, ActivitiUserWorkflowAdapter.SYNCOPE_USER, user);
    runtimeService.setVariable(executionId, ActivitiUserWorkflowAdapter.PROP_BY_RESOURCE, propByRes);
}

From source file:org.apache.syncope.core.workflow.user.NoOpUserWorkflowAdapter.java

@Override
protected WorkflowResult<Map.Entry<UserMod, Boolean>> doUpdate(final SyncopeUser user, final UserMod userMod)
        throws WorkflowException {

    // update password internally only if required
    UserMod actualMod = SerializationUtils.clone(userMod);
    if (actualMod.getPwdPropRequest() != null && !actualMod.getPwdPropRequest().isOnSyncope()) {
        actualMod.setPassword(null);/*from   ww w  .ja  v a 2s . c o  m*/
    }
    // update SyncopeUser
    PropagationByResource propByRes = dataBinder.update(user, actualMod);

    SyncopeUser updated = userDAO.save(user);

    userMod.setId(updated.getId());
    return new WorkflowResult<Map.Entry<UserMod, Boolean>>(
            new AbstractMap.SimpleEntry<UserMod, Boolean>(userMod, !user.isSuspended()), propByRes, "update");
}

From source file:org.apache.syncope.fit.core.ConnectorITCase.java

@Test
public void history() {
    List<ConnInstanceHistoryConfTO> history = connectorHistoryService
            .list("74141a3b-0762-4720-a4aa-fc3e374ef3ef");
    assertNotNull(history);/*w  ww.  j  a  v a2  s .  c om*/
    int pre = history.size();

    ConnInstanceTO ldapConn = connectorService.read("74141a3b-0762-4720-a4aa-fc3e374ef3ef", null);
    String originalDisplayName = ldapConn.getDisplayName();
    Set<ConnectorCapability> originalCapabilities = new HashSet<>(ldapConn.getCapabilities());
    ConnConfProperty originalConfProp = SerializationUtils
            .clone(ldapConn.getConf("maintainPosixGroupMembership").get());
    assertEquals(1, originalConfProp.getValues().size());
    assertEquals("false", originalConfProp.getValues().get(0));

    ldapConn.setDisplayName(originalDisplayName + " modified");
    ldapConn.getCapabilities().clear();
    ldapConn.getConf("maintainPosixGroupMembership").get().getValues().set(0, "true");
    connectorService.update(ldapConn);

    ldapConn = connectorService.read("74141a3b-0762-4720-a4aa-fc3e374ef3ef", null);
    assertNotEquals(originalDisplayName, ldapConn.getDisplayName());
    assertNotEquals(originalCapabilities, ldapConn.getCapabilities());
    assertNotEquals(originalConfProp, ldapConn.getConf("maintainPosixGroupMembership"));

    history = connectorHistoryService.list("74141a3b-0762-4720-a4aa-fc3e374ef3ef");
    assertEquals(pre + 1, history.size());

    connectorHistoryService.restore(history.get(0).getKey());

    ldapConn = connectorService.read("74141a3b-0762-4720-a4aa-fc3e374ef3ef", null);
    assertEquals(originalDisplayName, ldapConn.getDisplayName());
    assertEquals(originalCapabilities, ldapConn.getCapabilities());
    assertEquals(originalConfProp, ldapConn.getConf("maintainPosixGroupMembership").get());
}

From source file:org.apache.syncope.fit.core.GroupITCase.java

@Test
public void issueSYNCOPE632() {
    DerSchemaTO orig = schemaService.read(SchemaType.DERIVED, "displayProperty");
    DerSchemaTO modified = SerializationUtils.clone(orig);
    modified.setExpression("icon + '_' + show");

    GroupTO groupTO = GroupITCase.getSampleTO("lastGroup");
    try {/*w  w w . jav a  2  s  . c o m*/
        schemaService.update(SchemaType.DERIVED, modified);

        // 0. create group
        groupTO.getPlainAttrs().add(attrTO("icon", "anIcon"));
        groupTO.getPlainAttrs().add(attrTO("show", "true"));
        groupTO.getResources().clear();

        groupTO = createGroup(groupTO).getEntity();
        assertNotNull(groupTO);

        // 1. create new LDAP resource having ConnObjectKey mapped to a derived attribute
        ResourceTO newLDAP = resourceService.read(RESOURCE_NAME_LDAP);
        newLDAP.setKey("new-ldap");
        newLDAP.setPropagationPriority(0);

        for (ProvisionTO provision : newLDAP.getProvisions()) {
            provision.getVirSchemas().clear();
        }

        MappingTO mapping = newLDAP.getProvision(AnyTypeKind.GROUP.name()).get().getMapping();

        ItemTO connObjectKey = mapping.getConnObjectKeyItem();
        connObjectKey.setIntAttrName("displayProperty");
        connObjectKey.setPurpose(MappingPurpose.PROPAGATION);
        mapping.setConnObjectKeyItem(connObjectKey);
        mapping.setConnObjectLink("'cn=' + displayProperty + ',ou=groups,o=isp'");

        ItemTO description = new ItemTO();
        description.setIntAttrName("key");
        description.setExtAttrName("description");
        description.setPurpose(MappingPurpose.PROPAGATION);
        mapping.add(description);

        newLDAP = createResource(newLDAP);
        assertNotNull(newLDAP);

        // 2. update group and give the resource created above
        GroupPatch patch = new GroupPatch();
        patch.setKey(groupTO.getKey());
        patch.getResources().add(
                new StringPatchItem.Builder().operation(PatchOperation.ADD_REPLACE).value("new-ldap").build());

        groupTO = updateGroup(patch).getEntity();
        assertNotNull(groupTO);

        // 3. update the group
        GroupPatch groupPatch = new GroupPatch();
        groupPatch.setKey(groupTO.getKey());
        groupPatch.getPlainAttrs().add(attrAddReplacePatch("icon", "anotherIcon"));

        groupTO = updateGroup(groupPatch).getEntity();
        assertNotNull(groupTO);

        // 4. check that a single group exists in LDAP for the group created and updated above
        int entries = 0;
        DirContext ctx = null;
        try {
            ctx = getLdapResourceDirContext(null, null);

            SearchControls ctls = new SearchControls();
            ctls.setReturningAttributes(new String[] { "*", "+" });
            ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            NamingEnumeration<SearchResult> result = ctx.search("ou=groups,o=isp",
                    "(description=" + groupTO.getKey() + ")", ctls);
            while (result.hasMore()) {
                result.next();
                entries++;
            }
        } catch (Exception e) {
            // ignore
        } finally {
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (NamingException e) {
                    // ignore
                }
            }
        }

        assertEquals(1, entries);
    } finally {
        schemaService.update(SchemaType.DERIVED, orig);
        if (groupTO.getKey() != null) {
            groupService.delete(groupTO.getKey());
        }
        resourceService.delete("new-ldap");
    }
}

From source file:org.apache.syncope.fit.core.PlainSchemaITCase.java

@Test
public void issue259() {
    PlainSchemaTO schemaTO = buildPlainSchemaTO("schema_issue259", AttrSchemaType.Double);
    schemaTO.setUniqueConstraint(true);//from ww  w  .ja v a  2 s . c o  m

    schemaTO = createSchema(SchemaType.PLAIN, schemaTO);
    assertNotNull(schemaTO);

    AnyTypeClassTO typeClass = new AnyTypeClassTO();
    typeClass.setKey("issue259");
    typeClass.getPlainSchemas().add(schemaTO.getKey());
    anyTypeClassService.create(typeClass);

    UserTO userTO = UserITCase.getUniqueSampleTO("issue259@syncope.apache.org");
    userTO.getAuxClasses().add(typeClass.getKey());
    userTO.getPlainAttrs().add(attrTO(schemaTO.getKey(), "1"));
    userTO = createUser(userTO).getEntity();
    assertNotNull(userTO);

    UserTO newUserTO = SerializationUtils.clone(userTO);
    newUserTO.getMemberships()
            .add(new MembershipTO.Builder().group("b1f7c12d-ec83-441f-a50e-1691daaedf3b").build());

    userTO = userService.update(newUserTO).readEntity(new GenericType<ProvisioningResult<UserTO>>() {
    }).getEntity();
    assertNotNull(userTO);
}

From source file:org.apache.syncope.fit.core.PolicyITCase.java

@Test
public void update() {
    PasswordPolicyTO globalPolicy = policyService.read("ce93fcda-dc3a-4369-a7b0-a6108c261c85");

    PasswordPolicyTO policy = SerializationUtils.clone(globalPolicy);
    policy.setDescription("A simple password policy");

    // create a new password policy using the former as a template
    policy = createPolicy(policy);//from  w ww.j  av  a  2s.co  m
    assertNotNull(policy);
    assertNotEquals("ce93fcda-dc3a-4369-a7b0-a6108c261c85", policy.getKey());

    ImplementationTO rule = implementationService.read(policy.getRules().get(0));
    assertNotNull(rule);

    DefaultPasswordRuleConf ruleConf = POJOHelper.deserialize(rule.getBody(), DefaultPasswordRuleConf.class);
    ruleConf.setMaxLength(22);
    rule.setBody(POJOHelper.serialize(ruleConf));

    // update new password policy
    policyService.update(policy);
    policy = policyService.read(policy.getKey());
    assertNotNull(policy);

    ruleConf = POJOHelper.deserialize(rule.getBody(), DefaultPasswordRuleConf.class);
    assertEquals(22, ruleConf.getMaxLength());
    assertEquals(8, ruleConf.getMinLength());
}

From source file:org.apache.syncope.fit.core.PropagationTaskITCase.java

@Test
public void propagationJEXLTransformer() {
    // 0. Set propagation JEXL MappingItemTransformer
    ResourceTO resource = resourceService.read(RESOURCE_NAME_DBSCRIPTED);
    ResourceTO originalResource = SerializationUtils.clone(resource);
    ProvisionTO provision = resource.getProvision("PRINTER").get();
    assertNotNull(provision);// w  w w .ja v  a2  s .  c o  m

    Optional<ItemTO> mappingItem = provision.getMapping().getItems().stream()
            .filter(item -> "location".equals(item.getIntAttrName())).findFirst();
    assertTrue(mappingItem.isPresent());
    assertTrue(mappingItem.get().getTransformers().isEmpty());

    String suffix = getUUIDString();
    mappingItem.get().setPropagationJEXLTransformer("value + '" + suffix + "'");

    try {
        resourceService.update(resource);

        // 1. create printer on external resource
        AnyObjectTO anyObjectTO = AnyObjectITCase.getSampleTO("propagationJEXLTransformer");
        String originalLocation = anyObjectTO.getPlainAttr("location").get().getValues().get(0);
        assertFalse(originalLocation.endsWith(suffix));

        anyObjectTO = createAnyObject(anyObjectTO).getEntity();
        assertNotNull(anyObjectTO);

        // 2. verify that JEXL MappingItemTransformer was applied during propagation
        // (location ends with given suffix on external resource)
        ConnObjectTO connObjectTO = resourceService.readConnObject(RESOURCE_NAME_DBSCRIPTED,
                anyObjectTO.getType(), anyObjectTO.getKey());
        assertFalse(anyObjectTO.getPlainAttr("location").get().getValues().get(0).endsWith(suffix));
        assertTrue(connObjectTO.getAttr("LOCATION").get().getValues().get(0).endsWith(suffix));
    } finally {
        resourceService.update(originalResource);
    }
}

From source file:org.apache.syncope.fit.core.PullTaskITCase.java

@Test
public void reconcileFromScriptedSQL() throws IOException {
    // 0. reset sync token and set MappingItemTransformer
    ResourceTO resource = resourceService.read(RESOURCE_NAME_DBSCRIPTED);
    ResourceTO originalResource = SerializationUtils.clone(resource);
    ProvisionTO provision = resource.getProvision("PRINTER").get();
    assertNotNull(provision);//from w  w  w.ja  v  a2  s .  com

    ItemTO mappingItem = provision.getMapping().getItems().stream()
            .filter(object -> "location".equals(object.getIntAttrName())).findFirst().get();
    assertNotNull(mappingItem);

    final String prefix = "PREFIX_";

    ImplementationTO transformer = new ImplementationTO();
    transformer.setKey("PrefixItemTransformer");
    transformer.setEngine(ImplementationEngine.GROOVY);
    transformer.setType(ImplementationType.ITEM_TRANSFORMER);
    transformer.setBody(IOUtils.toString(getClass().getResourceAsStream("/PrefixItemTransformer.groovy"),
            StandardCharsets.UTF_8));
    Response response = implementationService.create(transformer);
    transformer = getObject(response.getLocation(), ImplementationService.class, ImplementationTO.class);
    assertNotNull(transformer);

    mappingItem.getTransformers().clear();
    mappingItem.getTransformers().add(transformer.getKey());

    try {
        resourceService.update(resource);
        resourceService.removeSyncToken(resource.getKey(), provision.getAnyType());

        // insert a deleted record in the external resource (SYNCOPE-923), which will be returned
        // as sync event prior to the CREATE_OR_UPDATE events generated by the actions below (before pull)
        JdbcTemplate jdbcTemplate = new JdbcTemplate(testDataSource);
        jdbcTemplate.update(
                "INSERT INTO TESTPRINTER (id, printername, location, deleted, lastmodification) VALUES (?,?,?,?,?)",
                UUID.randomUUID().toString(), "Mysterious Printer", "Nowhere", true, new Date());

        // 1. create printer on external resource
        AnyObjectTO anyObjectTO = AnyObjectITCase.getSampleTO("pull");
        String originalLocation = anyObjectTO.getPlainAttr("location").get().getValues().get(0);
        assertFalse(originalLocation.startsWith(prefix));

        anyObjectTO = createAnyObject(anyObjectTO).getEntity();
        assertNotNull(anyObjectTO);

        // 2. verify that PrefixMappingItemTransformer was applied during propagation
        // (location starts with given prefix on external resource)
        ConnObjectTO connObjectTO = resourceService.readConnObject(RESOURCE_NAME_DBSCRIPTED,
                anyObjectTO.getType(), anyObjectTO.getKey());
        assertFalse(anyObjectTO.getPlainAttr("location").get().getValues().get(0).startsWith(prefix));
        assertTrue(connObjectTO.getAttr("LOCATION").get().getValues().get(0).startsWith(prefix));

        // 3. unlink any existing printer and delete from Syncope (printer is now only on external resource)
        PagedResult<AnyObjectTO> matchingPrinters = anyObjectService.search(new AnyQuery.Builder()
                .realm(SyncopeConstants.ROOT_REALM).fiql(SyncopeClient
                        .getAnyObjectSearchConditionBuilder("PRINTER").is("location").equalTo("pull*").query())
                .build());
        assertTrue(matchingPrinters.getSize() > 0);
        for (AnyObjectTO printer : matchingPrinters.getResult()) {
            anyObjectService.deassociate(new DeassociationPatch.Builder().key(printer.getKey())
                    .action(ResourceDeassociationAction.UNLINK).resource(RESOURCE_NAME_DBSCRIPTED).build());
            anyObjectService.delete(printer.getKey());
        }

        // ensure that the pull task does not have the DELETE capability (SYNCOPE-923)
        PullTaskTO pullTask = taskService.read("30cfd653-257b-495f-8665-281281dbcb3d", false);
        assertNotNull(pullTask);
        assertFalse(pullTask.isPerformDelete());

        // 4. pull
        execProvisioningTask(taskService, pullTask.getKey(), 50, false);

        // 5. verify that printer was re-created in Syncope (implies that location does not start with given prefix,
        // hence PrefixItemTransformer was applied during pull)
        matchingPrinters = anyObjectService.search(new AnyQuery.Builder()
                .realm(SyncopeConstants.ROOT_REALM).fiql(SyncopeClient
                        .getAnyObjectSearchConditionBuilder("PRINTER").is("location").equalTo("pull*").query())
                .build());
        assertTrue(matchingPrinters.getSize() > 0);

        // 6. verify that synctoken was updated
        assertNotNull(resourceService.read(RESOURCE_NAME_DBSCRIPTED).getProvision(anyObjectTO.getType()).get()
                .getSyncToken());
    } finally {
        resourceService.update(originalResource);
    }
}

From source file:org.apache.syncope.fit.core.PullTaskITCase.java

@Test
public void syncTokenWithErrors() {
    ResourceTO origResource = resourceService.read(RESOURCE_NAME_DBPULL);
    ConnInstanceTO origConnector = connectorService.read(origResource.getConnector(), null);

    ResourceTO resForTest = SerializationUtils.clone(origResource);
    resForTest.setKey("syncTokenWithErrors");
    resForTest.setConnector(null);//from  w  w w  . j  a  va 2s .  c om
    ConnInstanceTO connForTest = SerializationUtils.clone(origConnector);
    connForTest.setKey(null);
    connForTest.setDisplayName("For syncTokenWithErrors");

    JdbcTemplate jdbcTemplate = new JdbcTemplate(testDataSource);
    try {
        connForTest.getCapabilities().add(ConnectorCapability.SYNC);

        ConnConfProperty changeLogColumn = connForTest.getConf("changeLogColumn").get();
        assertNotNull(changeLogColumn);
        assertTrue(changeLogColumn.getValues().isEmpty());
        changeLogColumn.getValues().add("lastModification");

        Response response = connectorService.create(connForTest);
        if (response.getStatusInfo().getStatusCode() != Response.Status.CREATED.getStatusCode()) {
            throw (RuntimeException) clientFactory.getExceptionMapper().fromResponse(response);
        }
        connForTest = getObject(response.getLocation(), ConnectorService.class, ConnInstanceTO.class);
        assertNotNull(connForTest);

        resForTest.setConnector(connForTest.getKey());
        resForTest = createResource(resForTest);
        assertNotNull(resForTest);

        PullTaskTO pullTask = new PullTaskTO();
        pullTask.setActive(true);
        pullTask.setName("For syncTokenWithErrors");
        pullTask.setResource(resForTest.getKey());
        pullTask.setDestinationRealm(SyncopeConstants.ROOT_REALM);
        pullTask.setPullMode(PullMode.INCREMENTAL);
        pullTask.setPerformCreate(true);
        pullTask.setPerformUpdate(true);
        pullTask.setPerformDelete(true);

        response = taskService.create(pullTask);
        if (response.getStatusInfo().getStatusCode() != Response.Status.CREATED.getStatusCode()) {
            throw (RuntimeException) clientFactory.getExceptionMapper().fromResponse(response);
        }
        pullTask = getObject(response.getLocation(), TaskService.class, PullTaskTO.class);
        assertNotNull(pullTask);

        jdbcTemplate.execute("DELETE FROM testpull");
        jdbcTemplate.execute("INSERT INTO testpull VALUES " + "(1040, 'syncTokenWithErrors1', 'Surname1', "
                + "'syncTokenWithErrors1@syncope.apache.org', '2014-05-23 13:53:24.293')");
        jdbcTemplate.execute("INSERT INTO testpull VALUES " + "(1041, 'syncTokenWithErrors2', 'Surname2', "
                + "'syncTokenWithErrors1@syncope.apache.org', '2015-05-23 13:53:24.293')");

        ExecTO exec = execProvisioningTask(taskService, pullTask.getKey(), 50, false);
        assertEquals(PropagationTaskExecStatus.SUCCESS, PropagationTaskExecStatus.valueOf(exec.getStatus()));

        resForTest = resourceService.read(resForTest.getKey());
        assertTrue(
                resForTest.getProvision(AnyTypeKind.USER.name()).get().getSyncToken().contains("2014-05-23"));

        jdbcTemplate.execute("UPDATE testpull "
                + "SET email='syncTokenWithErrors2@syncope.apache.org', lastModification='2016-05-23 13:53:24.293' "
                + "WHERE ID=1041");

        exec = execProvisioningTask(taskService, pullTask.getKey(), 50, false);
        assertEquals(PropagationTaskExecStatus.SUCCESS, PropagationTaskExecStatus.valueOf(exec.getStatus()));

        resForTest = resourceService.read(resForTest.getKey());
        assertTrue(
                resForTest.getProvision(AnyTypeKind.USER.name()).get().getSyncToken().contains("2016-05-23"));
    } finally {
        if (resForTest.getConnector() != null) {
            resourceService.delete(resForTest.getKey());
            connectorService.delete(connForTest.getKey());
        }

        jdbcTemplate.execute("DELETE FROM testpull WHERE ID=1040");
        jdbcTemplate.execute("DELETE FROM testpull WHERE ID=1041");
    }
}

From source file:org.apache.syncope.fit.core.reference.PlainSchemaITCase.java

@Test
public void issue259() {
    PlainSchemaTO schemaTO = buildPlainSchemaTO("schema_issue259", AttrSchemaType.Double);
    schemaTO.setUniqueConstraint(true);//from ww  w  . j av  a  2s.  com

    schemaTO = createSchema(SchemaType.PLAIN, schemaTO);
    assertNotNull(schemaTO);

    AnyTypeClassTO typeClass = new AnyTypeClassTO();
    typeClass.setKey("issue259");
    typeClass.getPlainSchemas().add(schemaTO.getKey());
    anyTypeClassService.create(typeClass);

    UserTO userTO = UserITCase.getUniqueSampleTO("issue259@syncope.apache.org");
    userTO.getAuxClasses().add(typeClass.getKey());
    userTO.getPlainAttrs().add(attrTO(schemaTO.getKey(), "1"));
    userTO = createUser(userTO);
    assertNotNull(userTO);

    UserTO newUserTO = SerializationUtils.clone(userTO);
    MembershipTO membership = new MembershipTO();
    membership.setRightKey(2L);
    newUserTO.getMemberships().add(membership);

    UserMod userMod = AnyOperations.diff(newUserTO, userTO);

    userTO = userService.update(userMod).readEntity(UserTO.class);
    assertNotNull(userTO);
}