Search in sources :

Example 6 with JSONObject

use of com.unboundid.util.json.JSONObject in project ldapsdk by pingidentity.

the class PasswordPolicyStateJSON method getPasswordQualityRequirements.

/**
 * Retrieves a list of the password quality requirements that are contained in
 * the JSON object in which the indicated Boolean field is present and set to
 * {@code true}.
 *
 * @param  booleanFieldName  The name of the field that is expected to be
 *                           present with a Boolean value of true for each
 *                           requirement to be included in the list that is
 *                           returned.
 *
 * @return  The appropriate list of password quality requirements, or an empty
 *          list if no requirements will be imposed.
 */
@NotNull()
private List<PasswordQualityRequirement> getPasswordQualityRequirements(@NotNull final String booleanFieldName) {
    final List<JSONValue> requirementObjectLst = passwordPolicyStateObject.getFieldAsArray(PASSWORD_QUALITY_REQUIREMENTS.getFieldName());
    if ((requirementObjectLst == null) || requirementObjectLst.isEmpty()) {
        return Collections.emptyList();
    }
    final List<PasswordQualityRequirement> requirements = new ArrayList<>(requirementObjectLst.size());
    for (final JSONValue requirementObjectValue : requirementObjectLst) {
        if (!(requirementObjectValue instanceof JSONObject)) {
            continue;
        }
        final JSONObject requirementObject = (JSONObject) requirementObjectValue;
        final Boolean include = requirementObject.getFieldAsBoolean(booleanFieldName);
        if ((include == null) || (!include.booleanValue())) {
            continue;
        }
        final String description = requirementObject.getFieldAsString(REQUIREMENT_FIELD_DESCRIPTION);
        if (description == null) {
            continue;
        }
        final String clientSideValidationType = requirementObject.getFieldAsString(REQUIREMENT_FIELD_CLIENT_SIDE_VALIDATION_TYPE);
        final Map<String, String> clientSideValidationProperties = new LinkedHashMap<>();
        final List<JSONValue> propertyValues = requirementObject.getFieldAsArray(REQUIREMENT_FIELD_CLIENT_SIDE_VALIDATION_PROPERTIES);
        if (propertyValues != null) {
            for (final JSONValue propertyValue : propertyValues) {
                if (!(propertyValue instanceof JSONObject)) {
                    continue;
                }
                final JSONObject propertyObject = (JSONObject) propertyValue;
                final String name = propertyObject.getFieldAsString(REQUIREMENT_FIELD_CLIENT_SIDE_VALIDATION_PROPERTY_NAME);
                final String value = propertyObject.getFieldAsString(REQUIREMENT_FIELD_CLIENT_SIDE_VALIDATION_PROPERTY_VALUE);
                if ((name != null) && (value != null)) {
                    clientSideValidationProperties.put(name, value);
                }
            }
        }
        requirements.add(new PasswordQualityRequirement(description, clientSideValidationType, clientSideValidationProperties));
    }
    return requirements;
}
Also used : JSONValue(com.unboundid.util.json.JSONValue) PasswordQualityRequirement(com.unboundid.ldap.sdk.unboundidds.extensions.PasswordQualityRequirement) JSONObject(com.unboundid.util.json.JSONObject) ArrayList(java.util.ArrayList) JSONString(com.unboundid.util.json.JSONString) LinkedHashMap(java.util.LinkedHashMap) NotNull(com.unboundid.util.NotNull)

Example 7 with JSONObject

use of com.unboundid.util.json.JSONObject in project ldapsdk by pingidentity.

the class LDAPResultCode method doToolProcessing.

/**
 * {@inheritDoc}
 */
@Override()
@NotNull()
public ResultCode doToolProcessing() {
    // Get all result codes that should be included in the output.
    final Map<Integer, ResultCode> resultCodesByIntValue = new TreeMap<>();
    final Map<String, ResultCode> resultCodesByName = new TreeMap<>();
    if ((intValueArg != null) && intValueArg.isPresent()) {
        final int intValue = intValueArg.getValue();
        final ResultCode rc = ResultCode.valueOf(intValue, null, false);
        if (rc != null) {
            resultCodesByIntValue.put(intValue, rc);
            resultCodesByName.put(StaticUtils.toLowerCase(rc.getName()), rc);
        }
    } else {
        final String searchString;
        if ((searchArg != null) && searchArg.isPresent()) {
            searchString = StaticUtils.toLowerCase(searchArg.getValue());
        } else {
            searchString = null;
        }
        for (final ResultCode rc : ResultCode.values()) {
            final String name = rc.getName();
            final String lowerName = StaticUtils.toLowerCase(name);
            if (searchString != null) {
                if (!lowerName.contains(searchString)) {
                    continue;
                }
            }
            resultCodesByIntValue.put(rc.intValue(), rc);
            resultCodesByName.put(lowerName, rc);
        }
    }
    // exit with an error.
    if (resultCodesByIntValue.isEmpty()) {
        wrapErr(0, WRAP_COLUMN, ERR_LDAP_RC_NO_RESULTS.get());
        return ResultCode.NO_RESULTS_RETURNED;
    }
    // Iterate through the matching result codes and figure out how many
    // characters are in the longest name and
    final String nameLabel = INFO_LDAP_RC_NAME_LABEL.get();
    final String intValueLabel = INFO_LDAP_RC_INT_VALUE_LABEL.get();
    int numCharsInLongestName = nameLabel.length();
    int numCharsInLongestIntValue = intValueLabel.length();
    for (final Map.Entry<Integer, ResultCode> e : resultCodesByIntValue.entrySet()) {
        final String intValueString = String.valueOf(e.getKey());
        numCharsInLongestIntValue = Math.max(numCharsInLongestIntValue, intValueString.length());
        final String name = e.getValue().getName();
        numCharsInLongestName = Math.max(numCharsInLongestName, name.length());
    }
    // Construct the column formatter that will be used to generate the output.
    final boolean json;
    final OutputFormat outputFormat;
    final boolean scriptFriendly = ((scriptFriendlyArg != null) && scriptFriendlyArg.isPresent());
    if (scriptFriendly) {
        json = false;
        outputFormat = OutputFormat.TAB_DELIMITED_TEXT;
    } else if ((outputFormatArg != null) && outputFormatArg.isPresent()) {
        final String outputFormatValue = StaticUtils.toLowerCase(outputFormatArg.getValue());
        if (outputFormatValue.equals(OUTPUT_FORMAT_CSV)) {
            json = false;
            outputFormat = OutputFormat.CSV;
        } else if (outputFormatValue.equals(OUTPUT_FORMAT_JSON)) {
            json = true;
            outputFormat = null;
        } else if (outputFormatValue.equals(OUTPUT_FORMAT_TAB_DELIMITED)) {
            json = false;
            outputFormat = OutputFormat.TAB_DELIMITED_TEXT;
        } else {
            json = false;
            outputFormat = OutputFormat.COLUMNS;
        }
    } else {
        json = false;
        outputFormat = OutputFormat.COLUMNS;
    }
    final ColumnFormatter formatter;
    if (json) {
        formatter = null;
    } else {
        formatter = new ColumnFormatter(false, null, outputFormat, " | ", new FormattableColumn(numCharsInLongestName, HorizontalAlignment.LEFT, nameLabel), new FormattableColumn(numCharsInLongestIntValue, HorizontalAlignment.LEFT, intValueLabel));
    }
    // Display the table header, if appropriate.
    if ((formatter != null) && (outputFormat == OutputFormat.COLUMNS)) {
        for (final String line : formatter.getHeaderLines(true)) {
            out(line);
        }
    }
    // Display the main output.
    final Collection<ResultCode> resultCodes;
    if ((alphabeticOrderArg != null) && alphabeticOrderArg.isPresent()) {
        resultCodes = resultCodesByName.values();
    } else {
        resultCodes = resultCodesByIntValue.values();
    }
    for (final ResultCode rc : resultCodes) {
        if (formatter == null) {
            final JSONObject jsonObject = new JSONObject(new JSONField(JSON_FIELD_NAME, rc.getName()), new JSONField(JSON_FIELD_INT_VALUE, rc.intValue()));
            out(jsonObject.toSingleLineString());
        } else {
            out(formatter.formatRow(rc.getName(), rc.intValue()));
        }
    }
    return ResultCode.SUCCESS;
}
Also used : OutputFormat(com.unboundid.util.OutputFormat) JSONField(com.unboundid.util.json.JSONField) TreeMap(java.util.TreeMap) FormattableColumn(com.unboundid.util.FormattableColumn) JSONObject(com.unboundid.util.json.JSONObject) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) ResultCode(com.unboundid.ldap.sdk.ResultCode) ColumnFormatter(com.unboundid.util.ColumnFormatter) NotNull(com.unboundid.util.NotNull)

Example 8 with JSONObject

use of com.unboundid.util.json.JSONObject in project ldapsdk by pingidentity.

the class FilterTestCase method testMatchesEntryJSONObjectExtensibleMatch.

/**
 * Tests the behavior of the matchesEntry method when the provided filter uses
 * the jsonObjectFilterExtensibleMatch matching rule.
 *
 * @throws  Exception  If an unexpected problem occurs.
 */
@Test()
public void testMatchesEntryJSONObjectExtensibleMatch() throws Exception {
    final Entry entry = new Entry("dn: uid=test.user,ou=People,dc=example,dc=com", "objectClass: top", "objectClass: ubidPerson", "uid: test.user", "givenName: Test", "sn: User", "cn: Test User", "ubidEmailJSON: not-a-valid-json-object", "ubidEmailJSON: " + new JSONObject(new JSONField("type", "personal"), new JSONField("value", "test.user@example.com"), new JSONField("primary", true)).toSingleLineString());
    JSONObjectFilter jsonObjectFilter = new EqualsJSONObjectFilter("value", "test.user@example.com");
    Filter filter = jsonObjectFilter.toLDAPFilter("ubidEmailJSON");
    assertTrue(filter.matchesEntry(entry));
    jsonObjectFilter = new EqualsJSONObjectFilter("value", "different.user@example.com");
    filter = jsonObjectFilter.toLDAPFilter("ubidEmailJSON");
    assertFalse(filter.matchesEntry(entry));
    filter = jsonObjectFilter.toLDAPFilter("nonexistentAttribute");
    assertFalse(filter.matchesEntry(entry));
    try {
        filter = Filter.createExtensibleMatchFilter("ubidEmailJSON", "1.3.6.1.4.1.30221.2.4.13", false, "not-a-valid-json-object");
        filter.matchesEntry(entry);
        fail("Expected an exception when trying to use a JSON object filter " + "whose assertion value is not a valid JSON object");
    } catch (final LDAPException e) {
        assertEquals(e.getResultCode(), ResultCode.INAPPROPRIATE_MATCHING);
    }
    try {
        filter = Filter.createExtensibleMatchFilter("ubidEmailJSON", "1.3.6.1.4.1.30221.2.4.13", false, "{}");
        filter.matchesEntry(entry);
        fail("Expected an exception when trying to use a JSON object filter " + "whose assertion value is a valid JSON object but not a valid " + "JSON object filter");
    } catch (final LDAPException e) {
        assertEquals(e.getResultCode(), ResultCode.INAPPROPRIATE_MATCHING);
    }
}
Also used : JSONObject(com.unboundid.util.json.JSONObject) EqualsJSONObjectFilter(com.unboundid.ldap.sdk.unboundidds.jsonfilter.EqualsJSONObjectFilter) JSONObjectFilter(com.unboundid.ldap.sdk.unboundidds.jsonfilter.JSONObjectFilter) EqualsJSONObjectFilter(com.unboundid.ldap.sdk.unboundidds.jsonfilter.EqualsJSONObjectFilter) JSONField(com.unboundid.util.json.JSONField) EqualsJSONObjectFilter(com.unboundid.ldap.sdk.unboundidds.jsonfilter.EqualsJSONObjectFilter) JSONObjectFilter(com.unboundid.ldap.sdk.unboundidds.jsonfilter.JSONObjectFilter) Test(org.testng.annotations.Test)

Example 9 with JSONObject

use of com.unboundid.util.json.JSONObject in project ldapsdk by pingidentity.

the class JSONLDAPConnectionLoggerTestCase method testModifyWithAllDetailsIncluded.

/**
 * Provides coverage for the case in which a modify request log message
 * contains modifications and both names and values are to be logged.
 *
 * Tests the behavior when logging search operations.
 *
 * @throws  Exception  If an unexpected problem occurs.
 */
@Test()
public void testModifyWithAllDetailsIncluded() throws Exception {
    // Get the in-memory directory server instance.
    final InMemoryDirectoryServer ds = getTestDS(false, false);
    // Create a logger to use for the test.
    final TestLogHandler logHandler = new TestLogHandler();
    final JSONLDAPConnectionLoggerProperties properties = new JSONLDAPConnectionLoggerProperties();
    properties.setIncludeModifyAttributeNames(true);
    properties.setIncludeModifyAttributeValues(true);
    final JSONLDAPConnectionLogger logger = new JSONLDAPConnectionLogger(logHandler, properties);
    final LDAPConnectionOptions options = new LDAPConnectionOptions();
    options.setConnectionLogger(logger);
    // Generate a log message.
    try (LDAPConnection connection = ds.getConnection()) {
        connection.setConnectionName("The connection name");
        connection.setConnectionPoolName("The connection pool name");
        final ModifyRequest modifyRequest = new ModifyRequest("dn: uid=test.user,ou=People,dc=example,dc=com", "changetype: modify", "replace: userPassword", "userPassword: newPassword", "-", "replace: authpassword", "authpassword: anotherNewPassword", "-", "replace: description", "-", "delete: givenName", "-", "add: givenName", "givenName: Foo", "-", "delete: givenName", "givenName: Foo", "-", "add: givenName", "givenName: Test", "-", "increment: intValueAttr", "intValueAttr: 1", "-");
        logger.logModifyRequest(connection, 1, modifyRequest);
    }
    // Make sure that we can decode the message.
    assertEquals(logHandler.getMessageCount(), 1, logHandler.getMessagesString());
    final List<JSONObject> logMessages = parseLogMessages(logHandler);
    assertMessageIs(logMessages.get(0), "request", OperationType.MODIFY);
}
Also used : TestLogHandler(com.unboundid.util.TestLogHandler) JSONObject(com.unboundid.util.json.JSONObject) InMemoryDirectoryServer(com.unboundid.ldap.listener.InMemoryDirectoryServer) Test(org.testng.annotations.Test)

Example 10 with JSONObject

use of com.unboundid.util.json.JSONObject in project ldapsdk by pingidentity.

the class JSONLDAPConnectionLoggerTestCase method testModifyLogging.

/**
 * Tests the behavior when logging modify operations.
 *
 * @throws  Exception  If an unexpected problem occurs.
 */
@Test()
public void testModifyLogging() throws Exception {
    // Get the in-memory directory server instance.
    final InMemoryDirectoryServer ds = getTestDS(true, false);
    // Create a logger to use for the test.
    final TestLogHandler logHandler = new TestLogHandler();
    final JSONLDAPConnectionLoggerProperties properties = new JSONLDAPConnectionLoggerProperties();
    final JSONLDAPConnectionLogger logger = new JSONLDAPConnectionLogger(logHandler, properties);
    final LDAPConnectionOptions options = new LDAPConnectionOptions();
    options.setConnectionLogger(logger);
    // Establish a connection and send a modify request on it.
    try (LDAPConnection connection = new LDAPConnection(options, "localhost", ds.getListenPort())) {
        connection.modify("dn: dc=example,dc=com", "changetype: modify", "replace: description", "description: foo");
    }
    // Make sure that there were five log messages:
    // - Connect
    // - Modify request
    // - Modify result
    // - Unbind
    // - Disconnect
    assertEquals(logHandler.getMessageCount(), 5, logHandler.getMessagesString());
    final List<JSONObject> logMessages = parseLogMessages(logHandler);
    assertMessageIs(logMessages.get(0), "connect", null);
    assertMessageIs(logMessages.get(1), "request", OperationType.MODIFY);
    assertMessageIs(logMessages.get(2), "result", OperationType.MODIFY);
    assertMessageIs(logMessages.get(3), "request", OperationType.UNBIND);
    assertMessageIs(logMessages.get(4), "disconnect", null);
}
Also used : TestLogHandler(com.unboundid.util.TestLogHandler) JSONObject(com.unboundid.util.json.JSONObject) InMemoryDirectoryServer(com.unboundid.ldap.listener.InMemoryDirectoryServer) Test(org.testng.annotations.Test)

Aggregations

JSONObject (com.unboundid.util.json.JSONObject)253 Test (org.testng.annotations.Test)205 JSONString (com.unboundid.util.json.JSONString)105 JSONField (com.unboundid.util.json.JSONField)97 JSONArray (com.unboundid.util.json.JSONArray)89 File (java.io.File)67 JSONValue (com.unboundid.util.json.JSONValue)40 LinkedHashMap (java.util.LinkedHashMap)32 NotNull (com.unboundid.util.NotNull)27 ArrayList (java.util.ArrayList)26 JSONNumber (com.unboundid.util.json.JSONNumber)23 InMemoryDirectoryServer (com.unboundid.ldap.listener.InMemoryDirectoryServer)22 TestLogHandler (com.unboundid.util.TestLogHandler)21 LogException (com.unboundid.ldap.sdk.unboundidds.logs.LogException)20 LDAPConnection (com.unboundid.ldap.sdk.LDAPConnection)11 PasswordPolicyStateJSONField (com.unboundid.ldap.sdk.unboundidds.PasswordPolicyStateJSONField)11 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)10 Entry (com.unboundid.ldap.sdk.Entry)9 JSONException (com.unboundid.util.json.JSONException)9 Date (java.util.Date)9