use of com.unboundid.util.json.JSONField in project ldapsdk by pingidentity.
the class OAUTHBEARERBindResultTestCase method testFailureResultWithCredentials.
/**
* Tests the behavior for a failure result that includes server SASL
* credentials that has all elements.
*
* @throws Exception If an unexpected problem occurs.
*/
@Test()
public void testFailureResultWithCredentials() throws Exception {
final String[] initialReferralURLs = { "ldap://ds1.example.com:389/o=initial" };
final Control[] initialControls = { new Control("1.2.3.4") };
final JSONObject initialFailureDetails = new JSONObject(new JSONField("status", "invalid_token"), new JSONField("scope", "scope1 scope2 scope3"), new JSONField("openid-configuration", "https://openid.example.com/config"), new JSONField("some-other-field", "foo"));
final ASN1OctetString initialServerSASLCredentials = new ASN1OctetString(initialFailureDetails.toSingleLineString());
final String[] finalReferralURLs = { "ldap://ds1.example.com:389/o=final" };
final Control[] finalControls = { new Control("1.2.3.5") };
final BindResult initialBindResult = new BindResult(3, ResultCode.SASL_BIND_IN_PROGRESS, "initial diagnostic message", "o=initial matched DN", initialReferralURLs, initialControls, initialServerSASLCredentials);
final BindResult finalBindResult = new BindResult(4, ResultCode.INVALID_CREDENTIALS, "final diagnostic message", "o=final matched DN", finalReferralURLs, finalControls, null);
final OAUTHBEARERBindResult bindResult = new OAUTHBEARERBindResult(initialBindResult, finalBindResult);
assertEquals(bindResult.getMessageID(), 4);
assertNotNull(bindResult.getResultCode());
assertEquals(bindResult.getResultCode(), ResultCode.INVALID_CREDENTIALS);
assertNotNull(bindResult.getDiagnosticMessage());
assertEquals(bindResult.getDiagnosticMessage(), "final diagnostic message");
assertNotNull(bindResult.getMatchedDN());
assertDNsEqual(bindResult.getMatchedDN(), "o=final matched DN");
assertNotNull(bindResult.getReferralURLs());
assertEquals(bindResult.getReferralURLs().length, 1);
assertEquals(bindResult.getReferralURLs()[0], finalReferralURLs[0]);
assertNotNull(bindResult.getResponseControls());
assertEquals(bindResult.getResponseControls().length, 1);
assertEquals(bindResult.getResponseControls()[0], finalControls[0]);
assertNotNull(bindResult.getServerSASLCredentials());
assertTrue(bindResult.getServerSASLCredentials().equalsIgnoreType(initialServerSASLCredentials));
assertNotNull(bindResult.getInitialBindResult());
assertEquals(bindResult.getInitialBindResult(), initialBindResult);
assertNotNull(bindResult.getFinalBindResult());
assertEquals(bindResult.getFinalBindResult(), finalBindResult);
assertNotNull(bindResult.getFailureDetailsObject());
assertEquals(bindResult.getFailureDetailsObject(), initialFailureDetails);
assertNotNull(bindResult.getAuthorizationErrorCode());
assertEquals(bindResult.getAuthorizationErrorCode(), "invalid_token");
assertNotNull(bindResult.getScopes());
assertFalse(bindResult.getScopes().isEmpty());
assertEquals(bindResult.getScopes(), StaticUtils.setOf("scope1", "scope2", "scope3"));
assertNotNull(bindResult.getOpenIDConfigurationURL());
assertEquals(bindResult.getOpenIDConfigurationURL(), "https://openid.example.com/config");
assertNotNull(bindResult.toString());
}
use of com.unboundid.util.json.JSONField 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;
}
use of com.unboundid.util.json.JSONField 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);
}
}
use of com.unboundid.util.json.JSONField in project ldapsdk by pingidentity.
the class JSONLogsTestCase method createPopulatedMessageObject.
/**
* Creates a JSON object with an encoded representation of a log message that
* has values populated for most of the optional common fields.
*
* @param messageType The message type for the log message. This must not
* be {@code null}.
* @param operationType The operation type for the log message. This may be
* {@code null} if it is not an operation log message.
* @param fields The set of additional fields to include in the log
* message. This must not be {@code null} but may be
* empty.
*
* @return The log message that was created.
*/
@NotNull()
protected static JSONObject createPopulatedMessageObject(@NotNull final AccessLogMessageType messageType, @Nullable final AccessLogOperationType operationType, @NotNull final JSONField... fields) {
final Map<String, JSONValue> fieldMap = createMinimalFieldMap(messageType, operationType);
fieldMap.put(PRODUCT_NAME.getFieldName(), new JSONString(DEFAULT_PRODUCT_NAME));
fieldMap.put(INSTANCE_NAME.getFieldName(), new JSONString(DEFAULT_INSTANCE_NAME));
fieldMap.put(STARTUP_ID.getFieldName(), new JSONString(DEFAULT_STARTUP_ID));
fieldMap.put(THREAD_ID.getFieldName(), new JSONNumber(DEFAULT_THREAD_ID));
fieldMap.put(CONNECTION_ID.getFieldName(), new JSONNumber(DEFAULT_CONNECTION_ID));
if (operationType != null) {
fieldMap.put(OPERATION_ID.getFieldName(), new JSONNumber(DEFAULT_OPERATION_ID));
fieldMap.put(MESSAGE_ID.getFieldName(), new JSONNumber(DEFAULT_MESSAGE_ID));
fieldMap.put(TRIGGERED_BY_CONNECTION_ID.getFieldName(), new JSONNumber(DEFAULT_TRIGGERED_BY_CONNECTION_ID));
fieldMap.put(TRIGGERED_BY_OPERATION_ID.getFieldName(), new JSONNumber(DEFAULT_TRIGGERED_BY_OPERATION_ID));
fieldMap.put(ORIGIN.getFieldName(), new JSONString(DEFAULT_ORIGIN));
fieldMap.put(REQUESTER_IP_ADDRESS.getFieldName(), new JSONString(DEFAULT_REQUESTER_IP));
fieldMap.put(REQUESTER_DN.getFieldName(), new JSONString(DEFAULT_REQUESTER_DN));
fieldMap.put(REQUEST_CONTROL_OIDS.getFieldName(), createArray(DEFAULT_REQUEST_CONTROL_OIDS));
fieldMap.put(USING_ADMIN_SESSION_WORKER_THREAD.getFieldName(), new JSONBoolean(DEFAULT_USING_ADMIN_SESSION_WORKER_THREAD));
fieldMap.put(ADMINISTRATIVE_OPERATION.getFieldName(), new JSONString(DEFAULT_ADMIN_OP_MESSAGE));
fieldMap.put(INTERMEDIATE_CLIENT_REQUEST_CONTROL.getFieldName(), DEFAULT_INTERMEDIATE_CLIENT_REQUEST.getControlObject());
fieldMap.put(OPERATION_PURPOSE.getFieldName(), DEFAULT_OPERATION_PURPOSE_REQUEST.getControlObject());
if ((messageType == AccessLogMessageType.FORWARD) || (messageType == AccessLogMessageType.FORWARD_FAILED) || (messageType == AccessLogMessageType.RESULT) || (messageType == AccessLogMessageType.ASSURANCE_COMPLETE)) {
fieldMap.put(TARGET_HOST.getFieldName(), new JSONString(DEFAULT_FORWARD_TARGET_HOST));
fieldMap.put(TARGET_PORT.getFieldName(), new JSONNumber(DEFAULT_FORWARD_TARGET_PORT));
fieldMap.put(TARGET_PROTOCOL.getFieldName(), new JSONString(DEFAULT_FORWARD_TARGET_PROTOCOL));
}
if ((messageType == AccessLogMessageType.FORWARD_FAILED) || (messageType == AccessLogMessageType.RESULT) || (messageType == AccessLogMessageType.ASSURANCE_COMPLETE)) {
fieldMap.put(RESULT_CODE_VALUE.getFieldName(), new JSONNumber(DEFAULT_RESULT_CODE.intValue()));
fieldMap.put(RESULT_CODE_NAME.getFieldName(), new JSONString(DEFAULT_RESULT_CODE.getName()));
fieldMap.put(DIAGNOSTIC_MESSAGE.getFieldName(), new JSONString(DEFAULT_DIAGNOSTIC_MESSAGE));
}
if ((messageType == AccessLogMessageType.RESULT) || (messageType == AccessLogMessageType.ASSURANCE_COMPLETE) || (messageType == AccessLogMessageType.ENTRY) || (messageType == AccessLogMessageType.REFERENCE) || (messageType == AccessLogMessageType.INTERMEDIATE_RESPONSE)) {
fieldMap.put(RESPONSE_CONTROL_OIDS.getFieldName(), createArray(DEFAULT_RESPONSE_CONTROL_OIDS));
}
if ((messageType == AccessLogMessageType.RESULT) || (messageType == AccessLogMessageType.ASSURANCE_COMPLETE)) {
fieldMap.put(ADDITIONAL_INFO.getFieldName(), new JSONString(DEFAULT_ADDITIONAL_INFO_MESSAGE));
fieldMap.put(MATCHED_DN.getFieldName(), new JSONString(DEFAULT_MATCHED_DN));
fieldMap.put(REFERRAL_URLS.getFieldName(), createArray(DEFAULT_REFERRAL_URLS));
fieldMap.put(SERVERS_ACCESSED.getFieldName(), createArray(DEFAULT_SERVERS_ACCESSED));
fieldMap.put(UNCACHED_DATA_ACCESSED.getFieldName(), new JSONBoolean(DEFAULT_UNCACHED_DATA_ACCESSED));
fieldMap.put(WORK_QUEUE_WAIT_TIME_MILLIS.getFieldName(), new JSONNumber(DEFAULT_WORK_QUEUE_WAIT_TIME_MILLIS));
fieldMap.put(PROCESSING_TIME_MILLIS.getFieldName(), new JSONNumber(DEFAULT_PROCESSING_TIME_MILLIS));
fieldMap.put(INTERMEDIATE_RESPONSES_RETURNED.getFieldName(), new JSONNumber(DEFAULT_INTERMEDIATE_RESPONSES_RETURNED));
fieldMap.put(USED_PRIVILEGES.getFieldName(), createArray(DEFAULT_USED_PRIVILEGES));
fieldMap.put(PRE_AUTHORIZATION_USED_PRIVILEGES.getFieldName(), createArray(DEFAULT_PRE_AUTHZ_USED_PRIVILEGES));
fieldMap.put(MISSING_PRIVILEGES.getFieldName(), createArray(DEFAULT_MISSING_PRIVILEGES));
if (operationType != AccessLogOperationType.ABANDON) {
fieldMap.put(INTERMEDIATE_CLIENT_RESPONSE_CONTROL.getFieldName(), DEFAULT_INTERMEDIATE_CLIENT_RESPONSE.getControlObject());
}
if ((operationType == AccessLogOperationType.ADD) || (operationType == AccessLogOperationType.COMPARE) || (operationType == AccessLogOperationType.DELETE) || (operationType == AccessLogOperationType.MODIFY) || (operationType == AccessLogOperationType.MODDN) || (operationType == AccessLogOperationType.SEARCH)) {
fieldMap.put(AUTHORIZATION_DN.getFieldName(), new JSONString(DEFAULT_AUTHZ_DN));
}
if ((operationType == AccessLogOperationType.ADD) || (operationType == AccessLogOperationType.DELETE) || (operationType == AccessLogOperationType.MODIFY) || (operationType == AccessLogOperationType.MODDN)) {
fieldMap.put(REPLICATION_CHANGE_ID.getFieldName(), new JSONString(DEFAULT_REPLICATION_CHANGE_ID));
fieldMap.put(ASSURED_REPLICATION_REQUIREMENTS.getFieldName(), createAssuredReplicationRequirements());
}
if ((operationType == AccessLogOperationType.ADD) || (operationType == AccessLogOperationType.DELETE) || (operationType == AccessLogOperationType.MODIFY) || (operationType == AccessLogOperationType.MODDN) || (operationType == AccessLogOperationType.SEARCH)) {
fieldMap.put(INDEXES_WITH_KEYS_ACCESSED_NEAR_ENTRY_LIMIT.getFieldName(), createArray(DEFAULT_INDEXES_NEAR_ENTRY_LIMIT));
fieldMap.put(INDEXES_WITH_KEYS_ACCESSED_EXCEEDING_ENTRY_LIMIT.getFieldName(), createArray(DEFAULT_INDEXES_EXCEEDING_ENTRY_LIMIT));
}
}
if (messageType == AccessLogMessageType.ASSURANCE_COMPLETE) {
fieldMap.put(LOCAL_ASSURANCE_SATISFIED.getFieldName(), new JSONBoolean(DEFAULT_LOCAL_ASSURANCE_SATISFIED));
fieldMap.put(REMOTE_ASSURANCE_SATISFIED.getFieldName(), new JSONBoolean(DEFAULT_REMOTE_ASSURANCE_SATISFIED));
fieldMap.put(SERVER_ASSURANCE_RESULTS.getFieldName(), new JSONArray(DEFAULT_ASSURED_REPLICATION_SERVER_RESULTS.get(0).getServerResultObject(), DEFAULT_ASSURED_REPLICATION_SERVER_RESULTS.get(1).getServerResultObject()));
}
}
for (final JSONField field : fields) {
fieldMap.put(field.getName(), field.getValue());
}
return new JSONObject(fieldMap);
}
use of com.unboundid.util.json.JSONField in project ldapsdk by pingidentity.
the class JSONLogFieldSyntaxTestCase method testJSONLogMethods.
/**
* Tests the methods that may be used for logging JSON-formatted messages.
*
* @throws Exception If an unexpected problem occurs.
*/
@Test()
public void testJSONLogMethods() throws Exception {
final Set<String> includeFields = StaticUtils.setOf("a");
final JSONLogFieldSyntax syntax = new JSONLogFieldSyntax(10, includeFields, null);
final JSONObject o = new JSONObject(new JSONField("a", "foo"), new JSONField("b", "ThisIsALongerValue"));
final JSONBuffer buffer = new JSONBuffer();
buffer.beginObject();
syntax.logSanitizedFieldToJSONFormattedLog("abc", o, buffer);
buffer.endObject();
assertEquals(buffer.toString(), "{ \"abc\":{ \"a\":\"foo\", " + "\"b\":\"ThisIsALon{8 more characters}\" } }");
buffer.clear();
buffer.beginObject();
syntax.logCompletelyRedactedFieldToJSONFormattedLog("def", buffer);
buffer.endObject();
assertEquals(buffer.toString(), "{ \"def\":{ \"redacted\":\"{REDACTED}\" } }");
buffer.clear();
buffer.beginObject();
syntax.logRedactedComponentsFieldToJSONFormattedLog("ghi", o, buffer);
buffer.endObject();
assertEquals(buffer.toString(), "{ \"ghi\":{ \"a\":\"{REDACTED}\", " + "\"b\":\"ThisIsALon{8 more characters}\" } }");
buffer.clear();
buffer.beginObject();
final byte[] pepper = StaticUtils.randomBytes(8, false);
syntax.logCompletelyTokenizedFieldToJSONFormattedLog("jkl", o, pepper, buffer);
buffer.endObject();
final String completelyTokenizedString = buffer.toString();
assertTrue(completelyTokenizedString.startsWith("{ \"jkl\":{ \"tokenized\":\"{TOKENIZED:"));
assertTrue(completelyTokenizedString.endsWith("}\" } }"));
buffer.clear();
buffer.beginObject();
syntax.logTokenizedComponentsFieldToJSONFormattedLog("mno", o, pepper, buffer);
buffer.endObject();
final String tokenizedComponentsString = buffer.toString();
assertTrue(tokenizedComponentsString.startsWith("{ \"mno\":{ \"a\":\"{TOKENIZED:"));
assertTrue(tokenizedComponentsString.endsWith("}\", \"b\":\"ThisIsALon{8 more characters}\" } }"));
}
Aggregations