com.fasterxml.jackson.databind.util.StdDateFormat Java Examples

The following examples show how to use com.fasterxml.jackson.databind.util.StdDateFormat. 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: JacksonDateUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenSerializingDateToISO8601_thenSerializedToText() throws JsonProcessingException, ParseException {
    final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm");
    df.setTimeZone(TimeZone.getTimeZone("UTC"));

    final String toParse = "01-01-1970 02:30";
    final Date date = df.parse(toParse);
    final Event event = new Event("party", date);

    final ObjectMapper mapper = new ObjectMapper();
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    // StdDateFormat is ISO8601 since jackson 2.9
    mapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true));

    final String result = mapper.writeValueAsString(event);
    assertThat(result, containsString("1970-01-01T02:30:00.000+00:00"));
}
 
Example #2
Source File: AwsSessionCredentialClient.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
public AwsSessionCredentials retrieveSessionCredentials(AwsCredentialView awsCredential) {
    String externalId = awsCredential.getExternalId();
    AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest()
            .withDurationSeconds(DEFAULT_SESSION_CREDENTIALS_DURATION)
            .withExternalId(StringUtils.isEmpty(externalId) ? deprecatedExternalId : externalId)
            .withRoleArn(awsCredential.getRoleArn())
            .withRoleSessionName(roleSessionName);
    LOGGER.debug("Trying to assume role with role arn {}", awsCredential.getRoleArn());
    try {
        AssumeRoleResult result = awsSecurityTokenServiceClient(awsCredential).assumeRole(assumeRoleRequest);
        Credentials credentialsResponse = result.getCredentials();

        String formattedExpirationDate = "";
        Date expirationTime = credentialsResponse.getExpiration();
        if (expirationTime != null) {
            formattedExpirationDate = new StdDateFormat().format(expirationTime);
        }
        LOGGER.debug("Assume role result credential: role arn: {}, expiration date: {}",
                awsCredential.getRoleArn(), formattedExpirationDate);

        return new AwsSessionCredentials(
                credentialsResponse.getAccessKeyId(),
                credentialsResponse.getSecretAccessKey(),
                credentialsResponse.getSessionToken(),
                credentialsResponse.getExpiration());
    } catch (SdkClientException e) {
        LOGGER.error("Unable to assume role. Check exception for details.", e);
        throw e;
    }
}
 
Example #3
Source File: BlobMetadataJsonTest.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Test
public void testRoundTrip() {
    Date timestamp = new Date();
    String timestampString = StdDateFormat.getISO8601Format(TimeZone.getTimeZone(ZoneOffset.UTC), Locale.ENGLISH).format(timestamp).replaceFirst("Z$", "+0000");

    BlobMetadata expected = new DefaultBlobMetadata("id", timestamp,
            1234, "1e00d0c82221522ce2cf80365dc1fbfc",
            "6c4ebe94eb98c9c790ed89e48e581428d1b65b0f", ImmutableMap.of("contentType", "image/jpeg"));
    String string = JsonHelper.asJson(expected);

    assertEquals(string, "{\"id\":\"id\",\"timestamp\":\"" + timestampString + "\",\"length\":1234," +
            "\"md5\":\"1e00d0c82221522ce2cf80365dc1fbfc\",\"sha1\":\"6c4ebe94eb98c9c790ed89e48e581428d1b65b0f\"," +
            "\"attributes\":{\"contentType\":\"image/jpeg\"}}");

    BlobMetadata actual = JsonHelper.fromJson(string, DefaultBlobMetadata.class);

    assertEquals(actual.getId(), expected.getId());
    assertEquals(actual.getLength(), expected.getLength());
    assertEquals(actual.getMD5(), expected.getMD5());
    assertEquals(actual.getSHA1(), expected.getSHA1());
    assertEquals(actual.getAttributes(), expected.getAttributes());
}
 
Example #4
Source File: JacksonObjectMapper.java    From frostmourne with MIT License 6 votes vote down vote up
public static ObjectMapper settingCommonObjectMapper(ObjectMapper objectMapper) {
    objectMapper.setDateFormat(new StdDateFormat());
    objectMapper.setTimeZone(TimeZone.getDefault());

    objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);

    objectMapper.configure(SerializationFeature.INDENT_OUTPUT, false);
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    objectMapper.configure(MapperFeature.INFER_PROPERTY_MUTATORS, false);
    objectMapper.configure(MapperFeature.ALLOW_FINAL_FIELDS_AS_MUTATORS, false);

    return objectMapper;
}
 
Example #5
Source File: TestCookieProcessor.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetValueDate() throws Exception {
  Date date = new Date();

  String strDate =  new StdDateFormat().format(date);

  createClientRequest();

  CookieProcessor processor = createProcessor("h1", Date.class);
  processor.setValue(clientRequest, date);
  Assert.assertEquals(strDate, cookies.get("h1"));
}
 
Example #6
Source File: Zendesk.java    From zendesk-java-client with Apache License 2.0 5 votes vote down vote up
public static ObjectMapper createMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
    mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    mapper.setDateFormat(new StdDateFormat());
    return mapper;
}
 
Example #7
Source File: JSONMapper.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
private static ObjectMapper createObjectMapper() {
    return JsonMapper.builder()
                     .addModule(timeModule())
                     // disable value class loader to avoid jdk illegal reflection warning, requires JSON class/fields must be public
                     .addModule(new AfterburnerModule().setUseValueClassLoader(false))
                     .defaultDateFormat(new StdDateFormat())
                     // only auto detect field, and default visibility is public_only, refer to com.fasterxml.jackson.databind.introspect.VisibilityChecker.Std
                     .visibility(new VisibilityChecker.Std(NONE, NONE, NONE, NONE, PUBLIC_ONLY))
                     .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
                     .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
                     .annotationIntrospector(new JSONAnnotationIntrospector())
                     .deactivateDefaultTyping()
                     .build();
}
 
Example #8
Source File: TransformationDataOutputAssociation.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void evaluate(DelegateExecution execution) {
    Object value = this.transformation.getValue(execution);

    VariableTypes variableTypes = CommandContextUtil.getVariableServiceConfiguration().getVariableTypes();
    try {
        variableTypes.findVariableType(value);
    } catch (final FlowableException e) {
        // Couldn't find a variable type that is able to serialize the output value
        // Perhaps the output value is a Java bean, we try to convert it as JSon
        try {
            final ObjectMapper mapper = new ObjectMapper();

            // By default, Jackson serializes only public fields, we force to use all fields of the Java Bean
            mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

            // By default, Jackson serializes java.util.Date as timestamp, we force ISO-8601
            mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            mapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true));

            value = mapper.convertValue(value, JsonNode.class);
        } catch (final IllegalArgumentException e1) {
            throw new FlowableException("An error occurs converting output value as JSon", e1);
        }
    }

    execution.setVariable(this.getTarget(), value);
}
 
Example #9
Source File: JsonUtils.java    From spring-credhub with Apache License 2.0 5 votes vote down vote up
/**
 * Create and configure the {@link ObjectMapper} used for serializing and
 * deserializing JSON requests and responses.
 * @return a configured {@link ObjectMapper}
 */
public static ObjectMapper buildObjectMapper() {
	ObjectMapper objectMapper = new ObjectMapper();
	objectMapper.setDateFormat(new StdDateFormat());
	objectMapper.setPropertyNamingStrategy(new PropertyNamingStrategy.SnakeCaseStrategy());
	objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
	objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	objectMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);
	objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);

	configureCredentialDetailTypeMapping(objectMapper);

	return objectMapper;
}
 
Example #10
Source File: VerifyServiceProviderApplication.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Override
public void initialize(Bootstrap<VerifyServiceProviderConfiguration> bootstrap) {
    // Enable variable substitution with environment variables
    bootstrap.setConfigurationSourceProvider(
        new SubstitutingSourceProvider(bootstrap.getConfigurationSourceProvider(),
            new EnvironmentVariableSubstitutor(false)
        )
    );
    IdaSamlBootstrap.bootstrap();
    bootstrap.getObjectMapper().setDateFormat(StdDateFormat.getInstance());
    bootstrap.addBundle(hubMetadataBundle);
    bootstrap.addBundle(msaMetadataBundle);
    bootstrap.addCommand(new ComplianceToolMode(bootstrap.getObjectMapper(), bootstrap.getValidatorFactory().getValidator(), this));
    bootstrap.addBundle(new LogstashBundle());
}
 
Example #11
Source File: TestHeaderProcessor.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetValueDate() throws Exception {
  Date date = new Date();
  String strDate =  new StdDateFormat().format(date);
  createClientRequest();

  HeaderProcessor processor = createProcessor("h1", Date.class);
  processor.setValue(clientRequest, date);
  Assert.assertEquals(strDate, headers.get("h1"));
}
 
Example #12
Source File: JacksonScalarTypeSerialization.java    From raml-java-tools with Apache License 2.0 5 votes vote down vote up
private TypeSpec.Builder createSerialisationForDateTime(ObjectPluginContext objectPluginContext) {

    ClassName returnType = ClassName.get(Date.class);
    TypeSpec.Builder builder = TypeSpec.classBuilder("TimestampDeserializer")
            .addModifiers(Modifier.PUBLIC)
            .superclass(ParameterizedTypeName.get(ClassName.get(StdDeserializer.class), returnType))
            .addField(FieldSpec.builder(StdDateFormat.class, "DATE_PARSER", Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL).initializer("new $T()", StdDateFormat.class).build())
            .addMethod(
                    MethodSpec.constructorBuilder()
                            .addModifiers(Modifier.PUBLIC)
                            .addCode("super($T.class);", returnType).build()

            ).addModifiers(Modifier.PUBLIC);


    MethodSpec.Builder deserialize = MethodSpec.methodBuilder("deserialize")
            .addModifiers(Modifier.PUBLIC)
            .addParameter(ParameterSpec.builder(ClassName.get(JsonParser.class), "jsonParser").build())
            .addParameter(ParameterSpec.builder(ClassName.get(DeserializationContext.class), "jsonContext").build())
            .addException(IOException.class)
            .addException(JsonProcessingException.class)
            .returns(returnType)
            .addCode(
                    CodeBlock.builder().beginControlFlow("try").add(
                    CodeBlock.builder()
                      .addStatement("$T mapper  = new $T()", ObjectMapper.class, ObjectMapper.class)
                      .addStatement("$T dateString = mapper.readValue(jsonParser, String.class)", String.class)
                      .addStatement("Date date = DATE_PARSER.parse(dateString)", SimpleDateFormat.class)
                      .addStatement("return date").build()
                    ).add("} catch ($T e) {", ParseException.class).addStatement("throw new $T(e)", IOException.class).endControlFlow().build()
            );

    builder.addMethod(deserialize.build());
    objectPluginContext.createSupportClass(builder);
    return builder;
  }
 
Example #13
Source File: DiscoveredServiceWorkItemHandler.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected DiscoveredServiceWorkItemHandler(final KogitoKubeClient kubeClient) {
    LOGGER.debug("New instance of discovered service work item with kubeclient: {}", kubeClient);
    mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true));
    /*
     *  Delaying buildServiceDiscovery and buildHttpClient to avoid problems with okhttp3 dependency during GraalVM native builds. 
     *  OKHttp3 references SSLContextFactory in static fields, which lead to errors. See: https://quarkus.io/guides/writing-native-applications-tips#delaying-class-initialization
     *  We're trying to not use static fields that depends on unknown and uncontrolled dependencies to avoid errors like this.
     *  That's why we're just holding the kube reference in the constructor, thus lazy building the HTTP objects. 
     */ 
    this.kubeClient = kubeClient;
    this.serviceEndpoints = new ConcurrentHashMap<>();
}
 
Example #14
Source File: DefaultGiteaConnection.java    From gitea-plugin with MIT License 4 votes vote down vote up
private <T> T patch(UriTemplate template, Object body, final Class<T> modelClass)
        throws IOException, InterruptedException {
    HttpURLConnection connection = openConnection(template);
    withAuthentication(connection);
    setRequestMethodViaJreBugWorkaround(connection, "PATCH");
    byte[] bytes;
    if (body != null) {
        bytes = mapper.writer(new StdDateFormat()).writeValueAsBytes(body);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Content-Length", Integer.toString(bytes.length));
        connection.setDoOutput(true);
    } else {
        bytes = null;
        connection.setDoOutput(false);
    }
    connection.setDoInput(true);

    try {
        connection.connect();
        if (bytes != null) {
            try (OutputStream os = connection.getOutputStream()) {
                os.write(bytes);
            }
        }
        int status = connection.getResponseCode();
        if (status / 100 == 2) {
            if (Void.class.equals(modelClass)) {
                return null;
            }
            try (InputStream is = connection.getInputStream()) {
                return mapper.readerFor(modelClass).readValue(is);
            }
        }
        throw new GiteaHttpStatusException(
                status,
                connection.getResponseMessage(),
                bytes != null ? new String(bytes, StandardCharsets.UTF_8) : null
        );
    } finally {
        connection.disconnect();
    }
}
 
Example #15
Source File: JsonParsingUnitTestsBase.java    From spring-credhub with Apache License 2.0 4 votes vote down vote up
@Before
public void setUpJsonParsing() throws Exception {
	this.testDate = new StdDateFormat().parse(TEST_DATE_STRING);
}
 
Example #16
Source File: DefaultGiteaConnection.java    From gitea-plugin with MIT License 4 votes vote down vote up
private <T> T post(UriTemplate template, Object body, final Class<T> modelClass)
        throws IOException, InterruptedException {
    HttpURLConnection connection = openConnection(template);
    withAuthentication(connection);
    connection.setRequestMethod("POST");
    byte[] bytes;
    if (body != null) {
        bytes = mapper.writer(new StdDateFormat()).writeValueAsBytes(body);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Content-Length", Integer.toString(bytes.length));
        connection.setDoOutput(true);
    } else {
        bytes = null;
        connection.setDoOutput(false);
    }
    connection.setDoInput(!Void.class.equals(modelClass));

    try {
        connection.connect();
        if (bytes != null) {
            try (OutputStream os = connection.getOutputStream()) {
                os.write(bytes);
            }
        }
        int status = connection.getResponseCode();
        if (status / 100 == 2) {
            if (Void.class.equals(modelClass)) {
                return null;
            }
            try (InputStream is = connection.getInputStream()) {
                return mapper.readerFor(modelClass).readValue(is);
            }
        }
        throw new GiteaHttpStatusException(
                status,
                connection.getResponseMessage(),
                bytes != null ? new String(bytes, StandardCharsets.UTF_8) : null
        );
    } finally {
        connection.disconnect();
    }
}
 
Example #17
Source File: OperationsResponseParser.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public OperationsResponseParser(final String response) {
    this.response = response;
    this.mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true));
}
 
Example #18
Source File: KafkaEventPublisher.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public KafkaEventPublisher() {
    json.setDateFormat(new StdDateFormat().withColonInTimeZone(true).withTimeZone(TimeZone.getDefault()));
}
 
Example #19
Source File: ReactiveMessagingEventPublisher.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@PostConstruct
public void configure() {
    json.setDateFormat(new StdDateFormat().withColonInTimeZone(true).withTimeZone(TimeZone.getDefault()));
}