Search in sources :

Example 1 with Attribute

use of org.gluu.oxtrust.model.scim2.annotations.Attribute in project oxTrust by GluuFederation.

the class BaseScimWebService method search.

public <T> List<T> search(String dn, Class<T> entryClass, String filterString, int startIndex, int count, String sortBy, String sortOrder, VirtualListViewResponse vlvResponse, String attributesArray) throws Exception {
    log.info("----------");
    log.info(" ### RAW PARAMS ###");
    log.info(" filter string = " + filterString);
    log.info(" startIndex = " + startIndex);
    log.info(" count = " + count);
    log.info(" sortBy = " + sortBy);
    log.info(" sortOrder = " + sortOrder);
    log.info(" attributes = " + attributesArray);
    Filter filter = null;
    if (filterString == null || (filterString != null && filterString.isEmpty())) {
        filter = Filter.create("inum=*");
    } else {
        Class clazz = null;
        if (entryClass.getName().equals(GluuCustomPerson.class.getName())) {
            clazz = ScimPerson.class;
        } else if (entryClass.getName().equals(GluuGroup.class.getName())) {
            clazz = ScimGroup.class;
        }
        filter = scimFilterParserService.createFilter(filterString, clazz);
    }
    startIndex = (startIndex < 1) ? 1 : startIndex;
    count = (count < 1) ? DEFAULT_COUNT : count;
    count = (count > getMaxCount()) ? getMaxCount() : count;
    sortBy = (sortBy != null && !sortBy.isEmpty()) ? sortBy : "displayName";
    if (entryClass.getName().equals(GluuCustomPerson.class.getName())) {
        sortBy = getUserLdapAttributeName(sortBy);
    } else if (entryClass.getName().equals(GluuGroup.class.getName())) {
        sortBy = getGroupLdapAttributeName(sortBy);
    }
    SortOrder sortOrderEnum = null;
    if (sortOrder != null && !sortOrder.isEmpty()) {
        sortOrderEnum = SortOrder.getByValue(sortOrder);
    } else if (sortBy != null && (sortOrder == null || (sortOrder != null && sortOrder.isEmpty()))) {
        sortOrderEnum = SortOrder.ASCENDING;
    } else {
        sortOrderEnum = SortOrder.ASCENDING;
    }
    // String[] attributes = (attributesArray != null && !attributesArray.isEmpty()) ? mapper.readValue(attributesArray, String[].class) : null;
    String[] attributes = (attributesArray != null && !attributesArray.isEmpty()) ? attributesArray.split("\\,") : null;
    if (attributes != null && attributes.length > 0) {
        // Add the attributes which are returned by default
        List<String> attributesList = new ArrayList<String>(Arrays.asList(attributes));
        Set<String> attributesSet = new LinkedHashSet<String>();
        for (String attribute : attributesList) {
            if (attribute != null && !attribute.isEmpty()) {
                attribute = FilterUtil.stripScim1Schema(attribute);
                if (entryClass.getName().equals(GluuCustomPerson.class.getName()) && attribute.toLowerCase().startsWith("name.")) {
                    if (!attributesSet.contains("name.familyName")) {
                        attributesSet.add("name.familyName");
                        attributesSet.add("name.middleName");
                        attributesSet.add("name.givenName");
                        attributesSet.add("name.honorificPrefix");
                        attributesSet.add("name.honorificSuffix");
                    }
                } else {
                    attributesSet.add(attribute);
                }
            }
        }
        attributesSet.add("id");
        if (entryClass.getName().equals(GluuCustomPerson.class.getName())) {
            attributesSet.add("userName");
        }
        if (entryClass.getName().equals(GluuGroup.class.getName())) {
            attributesSet.add("displayName");
        }
        /*
			attributesSet.add("meta.created");
			attributesSet.add("meta.lastModified");
			attributesSet.add("meta.location");
			attributesSet.add("meta.version");
			*/
        attributes = attributesSet.toArray(new String[attributesSet.size()]);
        for (int i = 0; i < attributes.length; i++) {
            if (attributes[i] != null && !attributes[i].isEmpty()) {
                if (entryClass.getName().equals(GluuCustomPerson.class.getName())) {
                    attributes[i] = getUserLdapAttributeName(attributes[i].trim());
                } else if (entryClass.getName().equals(GluuGroup.class.getName())) {
                    attributes[i] = getGroupLdapAttributeName(attributes[i].trim());
                }
            }
        }
    }
    log.info(" ### CONVERTED PARAMS ###");
    log.info(" parsed filter = " + filter.toString());
    log.info(" startIndex = " + startIndex);
    log.info(" count = " + count);
    log.info(" sortBy = " + sortBy);
    log.info(" sortOrder = " + sortOrderEnum.getValue());
    log.info(" attributes = " + ((attributes != null && attributes.length > 0) ? new ObjectMapper().writeValueAsString(attributes) : null));
    // List<T> result = ldapEntryManager.findEntriesVirtualListView(dn, entryClass, filter, startIndex, count, sortBy, sortOrderEnum, vlvResponse, attributes);
    List<T> result = ldapEntryManager.findEntriesSearchSearchResult(dn, entryClass, filter, startIndex, count, getMaxCount(), sortBy, sortOrderEnum, vlvResponse, attributes);
    log.info(" ### RESULTS INFO ###");
    log.info(" totalResults = " + vlvResponse.getTotalResults());
    log.info(" itemsPerPage = " + vlvResponse.getItemsPerPage());
    log.info(" startIndex = " + vlvResponse.getStartIndex());
    log.info("----------");
    return result;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ArrayList(java.util.ArrayList) SortOrder(org.xdi.ldap.model.SortOrder) GluuGroup(org.gluu.oxtrust.model.GluuGroup) GluuCustomPerson(org.gluu.oxtrust.model.GluuCustomPerson) DEFAULT_COUNT(org.gluu.oxtrust.model.scim2.Constants.DEFAULT_COUNT) Filter(com.unboundid.ldap.sdk.Filter) ScimGroup(org.gluu.oxtrust.model.scim.ScimGroup) ObjectMapper(org.codehaus.jackson.map.ObjectMapper)

Example 2 with Attribute

use of org.gluu.oxtrust.model.scim2.annotations.Attribute in project oxTrust by GluuFederation.

the class UserExtensionsTest method testCreatePersonFromUserObject.

@Test(dependsOnMethods = "testCreatePersonFromJsonString")
@Parameters
public void testCreatePersonFromUserObject() throws Exception {
    System.out.println(" testCreatePersonFromUserObject() ");
    // Create custom attributes
    // String, not
    GluuAttribute scimCustomFirst = null;
    // multi-valued
    if (attributeService.getAttributeByName("scimCustomFirst") == null) {
        scimCustomFirst = createCustomAttribute(attributeService, schemaService, appConfiguration, "scimCustomFirst", "Custom First", "First custom attribute", GluuAttributeDataType.STRING, OxMultivalued.FALSE);
    }
    // Date, multi-valued
    GluuAttribute scimCustomSecond = null;
    if (attributeService.getAttributeByName("scimCustomSecond") == null) {
        scimCustomSecond = createCustomAttribute(attributeService, schemaService, appConfiguration, "scimCustomSecond", "Custom Second", "Second custom attribute", GluuAttributeDataType.DATE, OxMultivalued.TRUE);
    }
    // Numeric, not
    GluuAttribute scimCustomThird = null;
    // multi-valued
    if (attributeService.getAttributeByName("scimCustomThird") == null) {
        scimCustomThird = createCustomAttribute(attributeService, schemaService, appConfiguration, "scimCustomThird", "Custom Third", "Third custom attribute", GluuAttributeDataType.NUMERIC, OxMultivalued.FALSE);
    }
    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
    User user = createUserObject();
    // Create Person
    GluuCustomPerson gluuPerson = copyUtils2.copy(user, null, false);
    assertNotNull(gluuPerson, "gluuPerson is null!");
    System.out.println(">>>>>>>>>> gluuPerson.getUid() = " + gluuPerson.getUid());
    String inum = personService.generateInumForNewPerson();
    String dn = personService.getDnForPerson(inum);
    String iname = personService.generateInameForNewPerson(user.getUserName());
    gluuPerson.setDn(dn);
    gluuPerson.setInum(inum);
    gluuPerson.setIname(iname);
    gluuPerson.setCommonName(gluuPerson.getGivenName() + " " + gluuPerson.getSurname());
    personService.addPerson(gluuPerson);
    // Retrieve Person
    GluuCustomPerson retrievedPerson = personService.getPersonByUid(gluuPerson.getUid());
    assertNotNull(retrievedPerson, "Failed to find person.");
    User newPerson = copyUtils2.copy(retrievedPerson, null);
    Extension extension = newPerson.getExtension(Constants.USER_EXT_SCHEMA_ID);
    assertNotNull(extension, "(Persistence) Custom extension not persisted.");
    Extension.Field customFirstField = extension.getFields().get("scimCustomFirst");
    assertNotNull(customFirstField, "(Persistence) \"scimCustomFirst\" field not persisted.");
    assertEquals(customFirstField.getValue(), "customFirstValue");
    System.out.println("##### (Persistence) customFirstField.getValue() = " + customFirstField.getValue());
    Extension.Field customSecondField = extension.getFields().get("scimCustomSecond");
    assertNotNull(customSecondField, "(Persistence) \"scimCustomSecond\" field not persisted.");
    List<Date> dateList = Arrays.asList(mapper.readValue(customSecondField.getValue(), Date[].class));
    assertEquals(dateList.size(), 2);
    System.out.println("##### (Persistence) dateList.get(0) = " + dateList.get(0));
    System.out.println("##### (Persistence) dateList.get(1) = " + dateList.get(1));
    Extension.Field customThirdField = extension.getFields().get("scimCustomThird");
    assertNotNull(customThirdField, "(Persistence) \"scimCustomThird\" field not persisted.");
    assertEquals(new BigDecimal(customThirdField.getValue()), new BigDecimal(3000));
    System.out.println("##### (Persistence) customThirdField.getValue() = " + customThirdField.getValue());
    // Remove Person
    memberService.removePerson(retrievedPerson);
// Remove custom attributes
// schemaService.removeAttributeTypeFromObjectClass(scimCustomFirst.getOrigin(),
// scimCustomFirst.getName());
// schemaService.removeStringAttribute(scimCustomFirst.getName());
// attributeService.removeAttribute(scimCustomFirst);
// schemaService.removeAttributeTypeFromObjectClass(scimCustomSecond.getOrigin(),
// scimCustomSecond.getName());
// schemaService.removeStringAttribute(scimCustomSecond.getName());
// attributeService.removeAttribute(scimCustomSecond);
// schemaService.removeAttributeTypeFromObjectClass(scimCustomThird.getOrigin(),
// scimCustomThird.getName());
// schemaService.removeStringAttribute(scimCustomThird.getName());
// attributeService.removeAttribute(scimCustomThird);
}
Also used : Extension(org.gluu.oxtrust.model.scim2.Extension) GluuCustomPerson(org.gluu.oxtrust.model.GluuCustomPerson) User(org.gluu.oxtrust.model.scim2.User) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) Date(java.util.Date) BigDecimal(java.math.BigDecimal) GluuAttribute(org.xdi.model.GluuAttribute) Parameters(org.testng.annotations.Parameters) Test(org.testng.annotations.Test) BaseTest(org.gluu.oxtrust.action.test.BaseTest)

Example 3 with Attribute

use of org.gluu.oxtrust.model.scim2.annotations.Attribute in project oxTrust by GluuFederation.

the class UserSerializer method serializeUserExtension.

protected void serializeUserExtension(Map.Entry<String, JsonNode> rootNodeEntry, ObjectMapper mapper, User user, JsonGenerator jsonGenerator) throws Exception {
    Extension extension = user.getExtension(rootNodeEntry.getKey());
    Map<String, Object> list = new HashMap<String, Object>();
    boolean enclosingWritten = false;
    for (Map.Entry<String, Extension.Field> extEntry : extension.getFields().entrySet()) {
        if (attributes != null && attributes.size() > 0) {
            for (String attribute : attributes) {
                attribute = FilterUtil.stripScim2Schema(attribute);
                if (extEntry.getKey().equalsIgnoreCase(attribute)) {
                    if (!enclosingWritten) {
                        jsonGenerator.writeFieldName(rootNodeEntry.getKey());
                        enclosingWritten = true;
                    }
                    break;
                }
            }
        } else {
            if (!enclosingWritten) {
                jsonGenerator.writeFieldName(rootNodeEntry.getKey());
                enclosingWritten = true;
            }
        }
        if (enclosingWritten) {
            GluuAttribute gluuAttribute = attributeService.getAttributeByName(extEntry.getKey());
            GluuAttributeDataType attributeDataType = gluuAttribute.getDataType();
            if ((gluuAttribute.getOxMultivaluedAttribute() != null) && gluuAttribute.getOxMultivaluedAttribute().equals(OxMultivalued.TRUE)) {
                if (attributeDataType.equals(GluuAttributeDataType.STRING) || attributeDataType.equals(GluuAttributeDataType.PHOTO)) {
                    List<String> stringList = Arrays.asList(mapper.readValue(extEntry.getValue().getValue(), String[].class));
                    list.put(extEntry.getKey(), stringList);
                } else if (attributeDataType.equals(GluuAttributeDataType.DATE)) {
                    List<Date> dateList = Arrays.asList(mapper.readValue(extEntry.getValue().getValue(), Date[].class));
                    List<String> stringList = new ArrayList<String>();
                    DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTime().withZoneUTC();
                    for (Date date : dateList) {
                        String dateString = dateTimeFormatter.print(date.getTime());
                        stringList.add(dateString);
                    }
                    list.put(extEntry.getKey(), stringList);
                } else if (attributeDataType.equals(GluuAttributeDataType.NUMERIC)) {
                    List<BigDecimal> numberList = Arrays.asList(mapper.readValue(extEntry.getValue().getValue(), BigDecimal[].class));
                    list.put(extEntry.getKey(), numberList);
                }
            } else {
                list.put(extEntry.getKey(), extEntry.getValue().getValue());
            }
        }
    }
    if (enclosingWritten) {
        jsonGenerator.writeObject(list);
    }
}
Also used : HashMap(java.util.HashMap) GluuAttributeDataType(org.xdi.model.GluuAttributeDataType) Date(java.util.Date) BigDecimal(java.math.BigDecimal) GluuAttribute(org.xdi.model.GluuAttribute) Extension(org.gluu.oxtrust.model.scim2.Extension) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) DateTimeFormatter(org.joda.time.format.DateTimeFormatter)

Example 4 with Attribute

use of org.gluu.oxtrust.model.scim2.annotations.Attribute in project oxTrust by GluuFederation.

the class ServiceUtil method syncEmailReverse.

/**
 * One-way sync from "mail" to "oxTrustEmail". This method takes current values of "oxTrustEmail" attribute, deletes
 * those that do not match any of those in "mail", and adds new ones that are missing.
 * @param gluuCustomPerson
 * @param isScim2
 * @return
 * @throws Exception
 */
public static GluuCustomPerson syncEmailReverse(GluuCustomPerson gluuCustomPerson, boolean isScim2) throws Exception {
    /*
        Implementation of this method could not be simplified to creating a new empty list for oxTrustEmail and then do
        the respective additions based on current mail values since information such as display, primary, etc. would be lost.
        Instead, it uses set operations to know which existing entries must be removed or retained, and then apply additions
        of new data.
         */
    logger.info(" IN Utils.syncEmailReverse()...");
    GluuCustomAttribute mail = gluuCustomPerson.getGluuCustomAttribute("mail");
    GluuCustomAttribute oxTrustEmail = gluuCustomPerson.getGluuCustomAttribute("oxTrustEmail");
    if (mail == null) {
        gluuCustomPerson.setAttribute("oxTrustEmail", new String[0]);
    } else {
        ObjectMapper mapper = getObjectMapper();
        Set<String> mailSet = new HashSet<String>();
        if (mail.getValues() != null)
            mailSet.addAll(Arrays.asList(mail.getValues()));
        Set<String> mailSetCopy = new HashSet<String>(mailSet);
        Set<String> oxTrustEmailSet = new HashSet<String>();
        List<Email> oxTrustEmails = new ArrayList<Email>();
        if (oxTrustEmail != null && oxTrustEmail.getValues() != null) {
            for (String oxTrustEmailJson : oxTrustEmail.getValues()) oxTrustEmails.add(mapper.readValue(oxTrustEmailJson, Email.class));
            for (Email email : oxTrustEmails) oxTrustEmailSet.add(email.getValue());
        }
        // Keep those in "mail" and not in oxTrustEmail
        mailSetCopy.removeAll(oxTrustEmailSet);
        // Keep those in oxTrustEmail and not in "mail"
        oxTrustEmailSet.removeAll(mailSet);
        List<Integer> delIndexes = new ArrayList<Integer>();
        // Build a list of indexes that should be removed in oxTrustEmails
        for (int i = 0; i < oxTrustEmails.size(); i++) {
            if (oxTrustEmailSet.contains(oxTrustEmails.get(i).getValue()))
                delIndexes.add(0, i);
        }
        // Delete unmatched oxTrustEmail entries from highest index to lowest
        for (Integer idx : delIndexes) // must not pass an Integer directly
        oxTrustEmails.remove(idx.intValue());
        List<String> newValues = new ArrayList<String>();
        for (Email email : oxTrustEmails) newValues.add(mapper.writeValueAsString(email));
        for (String mailStr : mailSetCopy) {
            Email email = new Email();
            email.setValue(mailStr);
            email.setPrimary(false);
            newValues.add(mapper.writeValueAsString(email));
        }
        gluuCustomPerson.setAttribute("oxTrustEmail", newValues.toArray(new String[0]));
    }
    logger.info(" LEAVING Utils.syncEmailReverse()...");
    return gluuCustomPerson;
}
Also used : GluuCustomAttribute(org.gluu.oxtrust.model.GluuCustomAttribute) Email(org.gluu.oxtrust.model.scim2.user.Email) ObjectMapper(org.codehaus.jackson.map.ObjectMapper)

Example 5 with Attribute

use of org.gluu.oxtrust.model.scim2.annotations.Attribute in project oxTrust by GluuFederation.

the class BaseScimWebService method executeValidation.

protected void executeValidation(BaseScimResource resource, boolean skipRequired) throws SCIMException {
    ResourceValidator rv = new ResourceValidator(resource, extService.getResourceExtensions(resource.getClass()));
    if (!skipRequired) {
        rv.validateRequiredAttributes();
        rv.validateSchemasAttribute();
    }
    rv.validateValidableAttributes();
    // By section 7 of RFC 7643, we are not forced to constrain attribute values when they have a list of canonical values associated
    // rv.validateCanonicalizedAttributes();
    rv.validateExtendedAttributes();
}
Also used : ResourceValidator(org.gluu.oxtrust.model.scim2.util.ResourceValidator)

Aggregations

Attribute (org.gluu.oxtrust.model.scim2.annotations.Attribute)11 SCIMException (org.gluu.oxtrust.model.exception.SCIMException)9 ObjectMapper (org.codehaus.jackson.map.ObjectMapper)8 Extension (org.gluu.oxtrust.model.scim2.extensions.Extension)8 ExtensionField (org.gluu.oxtrust.model.scim2.extensions.ExtensionField)8 Field (java.lang.reflect.Field)6 InvalidAttributeValueException (javax.management.InvalidAttributeValueException)6 GluuCustomPerson (org.gluu.oxtrust.model.GluuCustomPerson)6 ArrayList (java.util.ArrayList)5 Date (java.util.Date)5 GluuAttribute (org.xdi.model.GluuAttribute)5 BigDecimal (java.math.BigDecimal)4 Response (javax.ws.rs.core.Response)4 Extension (org.gluu.oxtrust.model.scim2.Extension)4 ListResponse (org.gluu.oxtrust.model.scim2.ListResponse)4 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)3 URI (java.net.URI)3 Consumes (javax.ws.rs.Consumes)3 DefaultValue (javax.ws.rs.DefaultValue)3 HeaderParam (javax.ws.rs.HeaderParam)3