Java Code Examples for net.minidev.json.JSONObject#toJSONString()

The following examples show how to use net.minidev.json.JSONObject#toJSONString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CertificateSetAndRegenerateTest.java    From credhub with Apache License 2.0 7 votes vote down vote up
@Test
public void certificateSetRequest_whenProvidedACertificateValueThatIsTooLong_returnsAValidationError()
        throws Exception {
    final int repetitionCount = 7001 - TEST_CERTIFICATE.length();
    final String setJson = JSONObject.toJSONString(
            ImmutableMap.<String, String>builder()
                    .put("ca_name", "")
                    .put("certificate", TEST_CERTIFICATE + StringUtils.repeat("a", repetitionCount))
                    .put("private_key", TEST_PRIVATE_KEY)
                    .build());

    final MockHttpServletRequestBuilder certificateSetRequest = put("/api/v1/data")
            .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
            .accept(APPLICATION_JSON)
            .contentType(APPLICATION_JSON)
            //language=JSON
            .content("{\n"
                    + "  \"name\" : \"/crusher\",\n"
                    + "  \"type\" : \"certificate\",\n"
                    + "  \"value\" : " + setJson + "}");

    this.mockMvc.perform(certificateSetRequest)
            .andExpect(status().isBadRequest())
            .andExpect(jsonPath("$.error", equalTo(
                    "The provided certificate value is too long. Certificate lengths must be less than 7000 characters.")));
}
 
Example 2
Source File: CertificateSetAndRegenerateTest.java    From credhub with Apache License 2.0 6 votes vote down vote up
@Test
public void certificateSetRequest_withTransitionalTrue_shouldGenerateAVersionWithTransitionalTrue() throws Exception {
    final String setJson = JSONObject.toJSONString(
            ImmutableMap.<String, String>builder()
                    .put("ca", TEST_CA)
                    .put("certificate", TEST_CERTIFICATE)
                    .put("private_key", TEST_PRIVATE_KEY)
                    .build());

    final MockHttpServletRequestBuilder certificateSetRequest = post("/api/v1/certificates/" + caCredentialUuid + "/versions")
            .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
            .accept(APPLICATION_JSON)
            .contentType(APPLICATION_JSON)
            .content("{\"value\" : " + setJson + ", \"transitional\": true}");

    this.mockMvc.perform(certificateSetRequest)
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.transitional", equalTo(true)));
}
 
Example 3
Source File: CertificateSetAndRegenerateTest.java    From credhub with Apache License 2.0 6 votes vote down vote up
@Test
public void certificateSetRequest_returnsWithGenerated() throws Exception {
    final String setJson = JSONObject.toJSONString(
            ImmutableMap.<String, String>builder()
                    .put("ca_name", "")
                    .put("certificate", TEST_CERTIFICATE)
                    .put("private_key", TEST_PRIVATE_KEY)
                    .build());

    final MockHttpServletRequestBuilder certificateSetRequest = put("/api/v1/data")
            .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
            .accept(APPLICATION_JSON)
            .contentType(APPLICATION_JSON)
            //language=JSON
            .content("{\n"
                    + "  \"name\" : \"/certificate\",\n"
                    + "  \"type\" : \"certificate\",\n"
                    + "  \"value\" : " + setJson + "}");

    this.mockMvc.perform(certificateSetRequest)
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.generated", equalTo(false)));
}
 
Example 4
Source File: CertificateSetRequestTest.java    From credhub with Apache License 2.0 6 votes vote down vote up
@Test
public void whenTheValueIsValid_doesNotRequireTheCA() {
  final String setJson = JSONObject.toJSONString(
    ImmutableMap.<String, String>builder()
      .put("certificate", TEST_CERTIFICATE)
      .put("private_key", TEST_PRIVATE_KEY)
      .build());
  final String json = "{"
    + "\"name\": \"/example/certificate\","
    + "\"type\": \"certificate\","
    + "\"value\": " + setJson
    + "}";

  final Set<ConstraintViolation<CertificateSetRequest>> violations = deserializeAndValidate(json,
    CertificateSetRequest.class);
  assertThat(violations.size(), equalTo(0));

  final CertificateSetRequest certificateSetRequest = deserialize(json, CertificateSetRequest.class);
  assertNull(certificateSetRequest.getCertificateValue().getCa());
}
 
Example 5
Source File: CertificateSetRequestTest.java    From credhub with Apache License 2.0 6 votes vote down vote up
@Test
public void whenCertificateValueIsLongerThan7000Chars_isInvalid() {
  final int repetitionCount = 7001 - TEST_CERTIFICATE.length();
  final String setJson = JSONObject.toJSONString(
    ImmutableMap.<String, String>builder()
      .put("ca_name", "CA_NAME")
      .put("certificate", TEST_CERTIFICATE + StringUtils.repeat("a", repetitionCount))
      .put("private_key", TEST_PRIVATE_KEY)
      .build()
  );

  final String json = "{\n"
    + "  \"name\": \"/example/certificate\",\n"
    + "  \"type\": \"certificate\",\n"
    + "  \"value\": " + setJson
    + "}";
  final Set<ConstraintViolation<CertificateSetRequest>> violations = deserializeAndValidate(
    json,
    CertificateSetRequest.class
  );

  assertThat(violations, hasItem(hasViolationWithMessage(ErrorMessages.INVALID_CERTIFICATE_LENGTH)));
}
 
Example 6
Source File: CertificateSetAndRegenerateTest.java    From credhub with Apache License 2.0 6 votes vote down vote up
@Test
public void certificateSetRequest_whenProvidedACAValueThatIsTooLong_returnsAValidationError() throws Exception {
    final int repetitionCount = 7001 - TEST_CA.length();
    final String setJson = JSONObject.toJSONString(
            ImmutableMap.<String, String>builder()
                    .put("ca", TEST_CA + StringUtils.repeat("a", repetitionCount))
                    .put("certificate", TEST_CERTIFICATE)
                    .put("private_key", TEST_PRIVATE_KEY)
                    .build());

    final MockHttpServletRequestBuilder certificateSetRequest = put("/api/v1/data")
            .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
            .accept(APPLICATION_JSON)
            .contentType(APPLICATION_JSON)
            //language=JSON
            .content("{\n"
                    + "  \"name\" : \"/crusher\",\n"
                    + "  \"type\" : \"certificate\",\n"
                    + "  \"value\" : " + setJson + "}");

    this.mockMvc.perform(certificateSetRequest)
            .andExpect(status().isBadRequest())
            .andExpect(jsonPath("$.error", equalTo(
                    "The provided certificate value is too long. Certificate lengths must be less than 7000 characters.")));
}
 
Example 7
Source File: CertificateSetAndRegenerateTest.java    From credhub with Apache License 2.0 6 votes vote down vote up
@Test
public void certificateSetRequest_whenSettingAMalformedCertificateAndMalformedKey_returnsAValidationError() throws Exception {
    final String setJson = JSONObject.toJSONString(
            ImmutableMap.<String, String>builder()
                    .put("certificate", "-----BEGIN CERTIFICATE-----") // missing END CERTIFICATE tag
                    .put("private_key", "not a key")
                    .build());

    final MockHttpServletRequestBuilder certificateSetRequest = put("/api/v1/data")
            .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
            .accept(APPLICATION_JSON)
            .contentType(APPLICATION_JSON)
            .content("{\n"
                    + "  \"name\" : \"/crusher\",\n"
                    + "  \"type\" : \"certificate\",\n"
                    + "  \"value\" : " + setJson + "}");

    this.mockMvc.perform(certificateSetRequest)
            .andExpect(status().isBadRequest())
            .andExpect(jsonPath("$.error", equalTo("The provided certificate value is not a valid X509 certificate.")));
}
 
Example 8
Source File: CertificateSetAndRegenerateTest.java    From credhub with Apache License 2.0 6 votes vote down vote up
@Test
public void certificateSetRequest_whenOmittingACertificate_returnsAValidationError() throws Exception {
    final String setJson = JSONObject.toJSONString(
            ImmutableMap.<String, String>builder()
                    .put("private_key", TEST_PRIVATE_KEY)
                    .build());

    final MockHttpServletRequestBuilder certificateSetRequest = put("/api/v1/data")
            .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
            .accept(APPLICATION_JSON)
            .contentType(APPLICATION_JSON)
            .content("{\n"
                    + "  \"name\" : \"/crusher\",\n"
                    + "  \"type\" : \"certificate\",\n"
                    + "  \"value\" : " + setJson + "}");

    this.mockMvc.perform(certificateSetRequest)
            .andExpect(status().isBadRequest())
            .andExpect(jsonPath("$.error", equalTo("You must provide a certificate.")));
}
 
Example 9
Source File: CertificateSetAndRegenerateTest.java    From credhub with Apache License 2.0 6 votes vote down vote up
@Test
public void certificateSetRequest_whenProvidedAMalformedCertificate_returnsAValidationError() throws Exception {
    final String setJson = JSONObject.toJSONString(
            ImmutableMap.<String, String>builder()
                    .put("certificate", "-----BEGIN CERTIFICATE-----") // missing END CERTIFICATE tag
                    .build());

    final MockHttpServletRequestBuilder certificateSetRequest = put("/api/v1/data")
            .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
            .accept(APPLICATION_JSON)
            .contentType(APPLICATION_JSON)
            .content("{\n"
                    + "  \"name\" : \"/crusher\",\n"
                    + "  \"type\" : \"certificate\",\n"
                    + "  \"value\" : " + setJson + "}");

    this.mockMvc.perform(certificateSetRequest)
            .andExpect(status().isBadRequest())
            .andExpect(jsonPath("$.error", equalTo("The provided certificate value is not a valid X509 certificate.")));
}
 
Example 10
Source File: CertificateSetRequestTest.java    From credhub with Apache License 2.0 6 votes vote down vote up
@Test
public void whenCertificateValueIsNotValidX509Certificate_isInvalid() {
  final String setJson = JSONObject.toJSONString(
    ImmutableMap.<String, String>builder()
      .put("ca_name", "CA_NAME")
      .put("certificate", "invalid x509 certificate")
      .put("private_key", TEST_PRIVATE_KEY)
      .build()
  );

  final String json = "{\n"
    + "  \"name\": \"/example/certificate\",\n"
    + "  \"type\": \"certificate\",\n"
    + "  \"value\": " + setJson
    + "}";

  assertThatThrownBy(() -> {
    deserializeAndValidate(
      json,
      CertificateSetRequest.class
    );
  }).isInstanceOf(ValidationException.class);
}
 
Example 11
Source File: CertificateSetRequestTest.java    From credhub with Apache License 2.0 6 votes vote down vote up
@Test
public void whenCAValueIsNotACertificateAuthority_isInvalid() {
  final String setJson = JSONObject.toJSONString(
    ImmutableMap.<String, String>builder()
      .put("ca", TEST_CERTIFICATE)
      .put("certificate", TEST_CERTIFICATE)
      .put("private_key", TEST_PRIVATE_KEY)
      .build()
  );

  final String json = "{\n"
    + "  \"name\": \"/example/certificate\",\n"
    + "  \"type\": \"certificate\",\n"
    + "  \"value\": " + setJson
    + "}";
  final Set<ConstraintViolation<CertificateSetRequest>> violations = deserializeAndValidate(
    json,
    CertificateSetRequest.class
  );

  assertThat(violations, hasItem(hasViolationWithMessage(ErrorMessages.INVALID_CA_VALUE)));
}
 
Example 12
Source File: CertificateSetRequestTest.java    From credhub with Apache License 2.0 6 votes vote down vote up
@Test
public void whenCAValueIsLongerThan7000Chars_isInvalid() {
  final int repetitionCount = 7001 - TEST_CA.length();
  final String setJson = JSONObject.toJSONString(
    ImmutableMap.<String, String>builder()
      .put("ca", TEST_CA + StringUtils.repeat("a", repetitionCount))
      .put("certificate", TEST_CERTIFICATE)
      .put("private_key", TEST_PRIVATE_KEY)
      .build()
  );

  final String json = "{\n"
    + "  \"name\": \"/example/certificate\",\n"
    + "  \"type\": \"certificate\",\n"
    + "  \"value\": " + setJson
    + "}";
  final Set<ConstraintViolation<CertificateSetRequest>> violations = deserializeAndValidate(
    json,
    CertificateSetRequest.class
  );

  assertThat(violations, hasItem(hasViolationWithMessage(ErrorMessages.INVALID_CERTIFICATE_LENGTH)));
}
 
Example 13
Source File: WebSocketPushEventsListener.java    From citrus-admin with Apache License 2.0 6 votes vote down vote up
/**
 * Construct JSON test result from given test data.
 * @param test
 * @param cause
 * @param success
 * @return
 */
protected String getTestResult(TestCase test, Throwable cause, boolean success) {
    JSONObject resultObject = new JSONObject();
    JSONObject testObject = new JSONObject();

    testObject.put("name", test.getName());
    testObject.put("type", "JAVA");
    testObject.put("className", test.getTestClass().getSimpleName());
    testObject.put("packageName", test.getPackageName());

    resultObject.put("test", testObject);
    resultObject.put("processId", test.getName());
    resultObject.put("success", success);

    if (cause != null) {
        resultObject.put("errorMessage", cause.getMessage());
        resultObject.put("errorCause", cause.getCause() != null ? cause.getCause().getClass().getName() : cause.getClass().getName());

        StringResult stackTrace = new StringResult();
        cause.printStackTrace(new PrintWriter(stackTrace.getWriter()));
        resultObject.put("stackTrace", stackTrace.toString());
    }

    return resultObject.toJSONString();
}
 
Example 14
Source File: RowOutputConverter.java    From hop with Apache License 2.0 5 votes vote down vote up
private String getStringValue( Object jo ) {
  String nodevalue = null;
  if ( jo != null ) {
    if ( jo instanceof Map ) {
      @SuppressWarnings( "unchecked" )
      Map<String, ?> asStrMap = (Map<String, ?>) jo;
      nodevalue = JSONObject.toJSONString( asStrMap );
    } else {
      nodevalue = jo.toString();
    }
  }
  return nodevalue;
}
 
Example 15
Source File: JsonLineSerializer.java    From tajo with Apache License 2.0 5 votes vote down vote up
@Override
public int serialize(OutputStream out, Tuple input) throws IOException {
  JSONObject jsonObject = new JSONObject();

  for (int i = 0; i < projectedPaths.length; i++) {
    String [] paths = projectedPaths[i].split(NestedPathUtil.PATH_DELIMITER);
    putValue(jsonObject, paths[0], paths, 0, i, input);
  }

  String jsonStr = jsonObject.toJSONString();
  byte [] jsonBytes = jsonStr.getBytes(TextDatum.DEFAULT_CHARSET);
  out.write(jsonBytes);
  return jsonBytes.length;
}
 
Example 16
Source File: CertificateSetAndRegenerateTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
@Test
public void certificateSetRequest_whenProvidedCertificateWasNotSignedByNamedCA_returnsAValidationError()
        throws Exception {
    RequestHelper.generateCa(mockMvc, "otherCa", ALL_PERMISSIONS_TOKEN);

    final String setJson = JSONObject.toJSONString(
            ImmutableMap.<String, String>builder()
                    .put("ca_name", CA_NAME)
                    .put("certificate", TEST_CERTIFICATE)
                    .put("private_key", TEST_PRIVATE_KEY)
                    .build());

    final MockHttpServletRequestBuilder certificateSetRequest = put("/api/v1/data")
            .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
            .accept(APPLICATION_JSON)
            .contentType(APPLICATION_JSON)
            //language=JSON
            .content("{\n"
                    + "  \"name\" : \"/crusher\",\n"
                    + "  \"type\" : \"certificate\",\n"
                    + "  \"value\" : " + setJson + "}");

    this.mockMvc.perform(certificateSetRequest)
            .andExpect(status().isBadRequest())
            .andExpect(jsonPath("$.error",
                    equalTo("The provided certificate was not signed by the CA specified in the 'ca_name' property.")));
}
 
Example 17
Source File: CertificateSetAndRegenerateTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
@Test
public void certificateSetRequest_whenProvidedCertificateWasNotSignedByProvidedCA_returnsAValidationError()
        throws Exception {
    RequestHelper.generateCa(mockMvc, "otherCa", ALL_PERMISSIONS_TOKEN);

    final String setJson = JSONObject.toJSONString(
            ImmutableMap.<String, String>builder()
                    .put("ca", TEST_CA)
                    .put("certificate", OTHER_TEST_CERTIFICATE)
                    .put("private_key", OTHER_TEST_PRIVATE_KEY)
                    .build());

    final MockHttpServletRequestBuilder certificateSetRequest = put("/api/v1/data")
            .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
            .accept(APPLICATION_JSON)
            .contentType(APPLICATION_JSON)
            //language=JSON
            .content("{\n"
                    + "  \"name\" : \"/crusher\",\n"
                    + "  \"type\" : \"certificate\",\n"
                    + "  \"value\" : " + setJson + "}");

    this.mockMvc.perform(certificateSetRequest)
            .andExpect(status().isBadRequest())
            .andExpect(jsonPath("$.error",
                    equalTo("The provided certificate was not signed by the CA specified in the 'ca' property.")));
}
 
Example 18
Source File: CertificateSetAndRegenerateTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
@Test
public void certificateSetRequest_whenProvidedCertificateWithNonMatchingPrivateKey_returnsAValidationError()
        throws Exception {
    final String originalCertificate = RequestHelper.generateCa(mockMvc, "otherCa", ALL_PERMISSIONS_TOKEN);
    final String otherCaCertificate = RequestHelper.generateCertificateCredential(mockMvc, "otherCaCertificate", true,
            "other-ca-cert", "otherCa", ALL_PERMISSIONS_TOKEN);

    final String originalPrivateKeyValue = JsonPath.parse(originalCertificate)
            .read("$.value.private_key");
    final String otherCaCertificateValue = JsonPath.parse(otherCaCertificate)
            .read("$.value.certificate");

    final String setJson = JSONObject.toJSONString(
            ImmutableMap.<String, String>builder()
                    .put("ca_name", "otherCa")
                    .put("certificate", otherCaCertificateValue)
                    .put("private_key", originalPrivateKeyValue)
                    .build());

    final MockHttpServletRequestBuilder certificateSetRequest = put("/api/v1/data")
            .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
            .accept(APPLICATION_JSON)
            .contentType(APPLICATION_JSON)
            //language=JSON
            .content("{\n"
                    + "  \"name\" : \"/crusher\",\n"
                    + "  \"type\" : \"certificate\",\n"
                    + "  \"value\" : " + setJson + "}");

    this.mockMvc.perform(certificateSetRequest)
            .andExpect(status().isBadRequest())
            .andExpect(jsonPath("$.error", equalTo("The provided certificate does not match the private key.")));
}
 
Example 19
Source File: CertificateSetAndRegenerateTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
@Test
public void certificateSetRequest_returnsWithExpiryDate() throws Exception {
    final String setJson = JSONObject.toJSONString(
            ImmutableMap.<String, String>builder()
                    .put("ca_name", "")
                    .put("certificate", TEST_CERTIFICATE)
                    .put("private_key", TEST_PRIVATE_KEY)
                    .build());

    final MockHttpServletRequestBuilder certificateSetRequest = put("/api/v1/data")
            .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
            .accept(APPLICATION_JSON)
            .contentType(APPLICATION_JSON)
            //language=JSON
            .content("{\n"
                    + "  \"name\" : \"/certificate\",\n"
                    + "  \"type\" : \"certificate\",\n"
                    + "  \"value\" : " + setJson + "}");

    final X509Certificate certificate = (X509Certificate) CertificateFactory
            .getInstance("X.509", BouncyCastleFipsProvider.PROVIDER_NAME)
            .generateCertificate(new ByteArrayInputStream(TEST_CERTIFICATE.getBytes(UTF_8)));

    this.mockMvc.perform(certificateSetRequest)
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.expiry_date", equalTo(certificate.getNotAfter().toInstant().toString())));
}
 
Example 20
Source File: CertificateSetAndRegenerateTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
@Test
public void certificateSetRequest_whenUserCantReadCA_andCantWriteCert_shouldReturnCorrectError() throws Exception {
    final String UNAUTHORIZED_CA_NAME = "/unauthorized-ca";
    generateCa(mockMvc, UNAUTHORIZED_CA_NAME, ALL_PERMISSIONS_TOKEN);

    final String setJson = JSONObject.toJSONString(
            ImmutableMap.<String, String>builder()
                    .put("ca_name", UNAUTHORIZED_CA_NAME)
                    .put("certificate", TEST_CERTIFICATE)
                    .put("private_key", TEST_PRIVATE_KEY)
                    .build());

    String content = "{" +
            "  \"name\":\"some-name\"," +
            "  \"type\":\"certificate\"," +
            "  \"value\": " + setJson +
            "}";
    final MockHttpServletRequestBuilder request = put("/api/v1/data")
            .header("Authorization", "Bearer " + NO_PERMISSIONS_TOKEN)
            .accept(APPLICATION_JSON)
            .contentType(APPLICATION_JSON)
            .content(content);

    mockMvc.perform(request)
            .andExpect(status().isForbidden())
            .andExpect(content().contentTypeCompatibleWith(APPLICATION_JSON))
            .andExpect(jsonPath("$.error").value(ErrorMessages.Credential.INVALID_ACCESS));
}