private <T> T patch(UriTemplate template, Object body, final Class<T> modelClass) throws IOException, InterruptedException { HttpURLConnection connection = (HttpURLConnection) new URL(template.expand()).openConnection(); withAuthentication(connection); setRequestMethodViaJreBugWorkaround(connection, "PATCH"); byte[] bytes; if (body != null) { bytes = mapper.writer(new ISO8601DateFormat()).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 IOException("HTTP " + status + "/" + connection.getResponseMessage()); } finally { connection.disconnect(); } }
@Override public final void run(MatchingServiceAdapterConfiguration configuration, Environment environment) { IdaSamlBootstrap.bootstrap(); environment.getObjectMapper().setDateFormat(new ISO8601DateFormat()); environment.jersey().register(LocalMetadataResource.class); environment.jersey().register(MatchingServiceResource.class); environment.jersey().register(UnknownUserAttributeQueryResource.class); environment.jersey().register(SamlOverSoapExceptionMapper.class); environment.jersey().register(ExceptionExceptionMapper.class); MatchingServiceAdapterHealthCheck healthCheck = new MatchingServiceAdapterHealthCheck(); environment.healthChecks().register(healthCheck.getName(), healthCheck); }
@Inject public CreateCerberusBackupOperation(CerberusAdminClientFactory cerberusAdminClientFactory, ConfigStore configStore, MetricsService metricsService, EnvironmentMetadata environmentMetadata) { objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); objectMapper.enable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS); objectMapper.setDateFormat(new ISO8601DateFormat()); this.configStore = configStore; this.metricsService = metricsService; this.environmentMetadata = environmentMetadata; cerberusAdminClient = cerberusAdminClientFactory.createCerberusAdminClient( configStore.getCerberusBaseUrl()); }
@Test public void testGenerateRequest() throws Exception { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); objectMapper.setDateFormat(new ISO8601DateFormat()); BausparBerechnungsAnfrage berechnungsdaten = new BausparBerechnungsAnfrage(); berechnungsdaten.setBausparsummeInEuro(new BigDecimal("100000")); berechnungsdaten.setBerechnungsZiel(BerechnungsZiel.SPARBEITRAG); SparBeitrag sparBeitrag = new SparBeitrag(); sparBeitrag.setBeitrag(new BigDecimal("100")); sparBeitrag.setZahlungAb(LocalDate.now()); sparBeitrag.setZahlungBis(LocalDate.now().plusYears(10)); sparBeitrag.setZahlungsrhythmus(Zahlungsrhythmus.MONATLICH); berechnungsdaten.setSparBeitraege(asList(sparBeitrag)); System.out.println(objectMapper.writeValueAsString(berechnungsdaten)); }
private List<Drop> parseResponse(String responseBody) { try { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setDateFormat(new ISO8601DateFormat()); ArrayNode eventNodes = (ArrayNode) objectMapper.readTree(responseBody); List<Drop> drops = new ArrayList<>(); for (JsonNode eventNode : eventNodes) { String type = eventNode.get("type").asText(); if ("PushEvent".equals(type)) { parsePushEvent(eventNode, objectMapper) .forEach(drops::add); } } return drops; } catch (IOException e) { throw new RuntimeException("could not parse github api result: " + responseBody, e); } }
public void test_() throws Exception { JSONSerializer ser = new JSONSerializer(new SerializeConfig()); ser.setDateFormat(new ISO8601DateFormat()); Assert.assertEquals(null, ser.getDateFormatPattern()); ser.close(); }
private RestObjectMapper() { // swagger中要求date使用ISO8601格式传递,这里与之做了功能绑定,这在cse中是没有问题的 setDateFormat(new ISO8601DateFormat()); getFactory().disable(Feature.AUTO_CLOSE_SOURCE); disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); }
@Override public final void run(StubEventSinkConfiguration configuration, Environment environment) { environment.getObjectMapper().setDateFormat(new ISO8601DateFormat()); StubEventSinkHealthCheck healthCheck = new StubEventSinkHealthCheck(); environment.healthChecks().register(healthCheck.getName(), healthCheck); environment.jersey().register(EventSinkHubEventResource.class); environment.jersey().register(EventSinkHubEventTestResource.class); }
@Override public void run(PolicyConfiguration configuration, Environment environment) throws Exception { environment.getObjectMapper().setDateFormat(new ISO8601DateFormat()); registerResources(configuration, environment); registerExceptionMappers(environment); environment.jersey().register(SessionIdPathParamLoggingFilter.class); }
@Override public final void run(SamlEngineConfiguration configuration, Environment environment) { IdaSamlBootstrap.bootstrap(); environment.getObjectMapper().registerModule(new GuavaModule()); environment.getObjectMapper().setDateFormat(new ISO8601DateFormat()); // register resources registerResources(environment, configuration); // register exception mappers environment.jersey().register(SamlEngineExceptionMapper.class); environment.servlets().addFilter("Logging SessionId registration Filter", SessionIdQueryParamLoggingFilter.class).addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); }
@Override public void run(SamlSoapProxyConfiguration configuration, Environment environment) throws Exception { IdaSamlBootstrap.bootstrap(); environment.getObjectMapper().setDateFormat(new ISO8601DateFormat()); registerResources(environment); environment.servlets().addFilter("Logging SessionId registration Filter", SessionIdQueryParamLoggingFilter.class).addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); }
private <T> T post(UriTemplate template, Object body, final Class<T> modelClass) throws IOException, InterruptedException { HttpURLConnection connection = (HttpURLConnection) new URL(template.expand()).openConnection(); withAuthentication(connection); connection.setRequestMethod("POST"); byte[] bytes; if (body != null) { bytes = mapper.writer(new ISO8601DateFormat()).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 IOException( "HTTP " + status + "/" + connection.getResponseMessage() + "\n" + (bytes != null ? new String(bytes, StandardCharsets.UTF_8) : "")); } finally { connection.disconnect(); } }
public MessageUtils() { xmlMapper = new ExtendedXmlMapper(); xmlMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); xmlMapper.setDateFormat(new ISO8601DateFormat()); xmlMapper.registerModule(new JaxbAnnotationModule()); xmlMapper.setSerializationInclusion(Include.NON_NULL); }
@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(ISO8601DateFormat.getInstance()); }
@Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.findAndRegisterModules(); mapper.setDateFormat(new ISO8601DateFormat()); mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return mapper; }
@Before public void init() throws JsonParseException, JsonMappingException, UnsupportedEncodingException, IOException { ObjectMapper mapper = new ObjectMapper(); mapper.findAndRegisterModules(); mapper.setDateFormat(new ISO8601DateFormat()); Envelope envelope = mapper.readValue(MediaEventTest.MEDIA_EVENT.getBytes("UTF-8"), Envelope.class); mediaEvent = envelope.getData().get(0); }
/** * 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 ISO8601DateFormat()); 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; }
@Override public Long deserialize(JsonParser parser, DeserializationContext context) throws IOException { String value = StringDeserializer.instance.deserialize(parser, context); try { return Double.valueOf(value).longValue(); } catch (NumberFormatException e1) { try { DateFormat dateFormat = new ISO8601DateFormat(); return dateFormat.parse(value).getTime(); } catch (ParseException e2) { return 0L; } } }
public JbrickJacksonConfigurator() { // Serializzazione date in formato ISO-8601: YYYY-MM-DDThh:mm:ss.sss+hhmm // v. http://stackoverflow.com/a/5234682/1178235 // v. http://wiki.fasterxml.com/JacksonFAQDateHandling mapper.setDateFormat(new ISO8601DateFormat()); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // Registrazione del modulo dei serializzatori personalizzati mapper.registerModule(new ZefiroModule()); }
/** * Creating mapper for serialize/deserialize data to JSON. */ @NotNull public static ObjectMapper createMapper() { final ObjectMapper mapper = new ObjectMapper(); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.setDateFormat(new ISO8601DateFormat()); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return mapper; }
public ToJson() { mapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.setDateFormat(new ISO8601DateFormat()); // Adding custom writer dynamically List<WorkflowBundleWriter> writers = io.getWriters(); writers.add(jsonWriter); io.setWriters(writers); }
public JsonExport() { mapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.setDateFormat(new ISO8601DateFormat()); // Adding custom writer dynamically List<WorkflowBundleWriter> writers = io.getWriters(); writers.add(jsonWriter); io.setWriters(writers); }
public static DateFormat newUtcFormatter() { TimeZone tz = TimeZone.getTimeZone("UTC"); ISO8601DateFormat df = new ISO8601DateFormat(); df.setTimeZone(tz); return df; }
private static long parseTimeStrToMilli(String timeStr) throws ParseException { StringBuilder sb = new StringBuilder(timeStr); int snipStart = sb.indexOf("."); int snipEnd = sb.indexOf("+"); if (snipEnd == -1) snipEnd = sb.indexOf("Z"); if (snipEnd == -1) snipEnd = sb.length(); String microsString="0.0"; if (snipStart != -1) { microsString = "0"+sb.substring(snipStart,snipEnd); sb.delete(snipStart,snipEnd); timeStr = sb.toString(); } SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssX"); SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ISO8601DateFormat formatter3 = new ISO8601DateFormat(); Date dt = null; try{ dt = formatter1.parse(timeStr); }catch (Exception e){ try{ dt = formatter2.parse(timeStr); }catch (Exception e2){ dt = formatter3.parse(timeStr); } } long timeMillis = dt.getTime(); long millis = (long) (Double.parseDouble(microsString)*1000); long time = timeMillis + millis; return time; }
private static ObjectMapper createMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new ISO8601DateFormat()); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME, true); return mapper; }
public JsonResponseWriter() { this.mapper = new ObjectMapper(); this.mapper.registerModule(new ObjectIdJsonModule()); this.mapper.registerModule(new JodaModule()); this.mapper.registerModule(new JsonOrgModule()); this.mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); this.mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); this.mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); this.mapper.setSerializationInclusion(Include.NON_NULL); this.mapper.setDateFormat(new ISO8601DateFormat()); }
public void testSchemaCreation() { try { Schema schema = new SchemaBuilderJSON(jsonSchema).getSchema(); assertTrue(((DateTimeIndex) schema.getFieldIndex("dateTime")).getDateFormat() instanceof ISO8601DateFormat); } catch (SchemaConfigurationError e) { assertTrue(false); } }
public AbraidJsonObjectMapper() { super(); this.registerModule(new JodaModule()); DateFormat dateFormat = ISO8601DateFormat.getDateTimeInstance(); dateFormat.setTimeZone(TimeZone.getTimeZone(UTC)); this.setDateFormat(dateFormat); this.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true); this.setSerializationInclusion(JsonInclude.Include.NON_NULL); }
@Test public void shouldReturnSecondsInDateTime() throws ParseException { Person p = new Person(); p.set("name", "john", "last_name", "doe").saveIt(); p.refresh(); String json = p.toJson(true); System.out.println(json); @SuppressWarnings("unchecked") Map<String, String> map = JsonHelper.toMap(json); Date d = new ISO8601DateFormat().parse(map.get("created_at")); // difference between date in Json and in original model instance should be less than 1000 milliseconds a(Math.abs(d.getTime() - p.getTimestamp("created_at").getTime()) < 1000L).shouldBeTrue(); }
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 ISO8601DateFormat()); return mapper; }
@Override public void run(ConfigConfiguration configuration, Environment environment) throws Exception { environment.getObjectMapper().setDateFormat(new ISO8601DateFormat()); registerResources(environment); environment.servlets().addFilter("Logging SessionId registration Filter", SessionIdQueryParamLoggingFilter.class).addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); }
@Before public void init() throws JsonParseException, JsonMappingException, UnsupportedEncodingException, IOException { if (savedTenant == null) { Tenant tenant = new Tenant.Builder() .withId("test-tid") .withName("test") .build(); savedTenant = tenantRepository.save(tenant); } if (mongoOrg == null) { Org org = new Org.Builder() .withSourcedId("org-id") .withName("org") .build(); mongoOrg = new MongoOrg.Builder() .withOrg(org) .withTenantId(savedTenant.getId()) .withApiKey(UUID.randomUUID().toString()) .withApiSecret(UUID.randomUUID().toString()) .build(); mongoOrgRepository.save(mongoOrg); } if (event == null || mediaEvent == null) { ObjectMapper mapper = new ObjectMapper(); mapper.findAndRegisterModules(); mapper.setDateFormat(new ISO8601DateFormat()); Envelope envelope = mapper.readValue(MediaEventTest.MEDIA_EVENT.getBytes("UTF-8"), Envelope.class); mediaEvent = envelope.getData().get(0); Envelope envelope1 = mapper.readValue(MinimalEventTest.MINIMAL_VIEWED_EVENT.getBytes("UTF-8"), Envelope.class); event = envelope1.getData().get(0); } }
@Before public void setUpJsonParsing() throws Exception { objectMapper = JsonUtils.buildObjectMapper(); testDate = new ISO8601DateFormat().parse(TEST_DATE_STRING); }
@Before public void setUp() throws Exception { objectMapper = Jackson.newObjectMapper().setDateFormat(ISO8601DateFormat.getDateInstance()); }
public ChronosMapper() { this.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) .registerModule(new JodaModule()) .setDateFormat(new ISO8601DateFormat()); }
public HarEntryBuilder withStartedDateTime(Date startedDateTime) { this.startedDateTime = new ISO8601DateFormat().format(startedDateTime); return this; }
public HarPageBuilder withStartedDateTime(Date startedDateTime) { this.startedDateTime = new ISO8601DateFormat().format(startedDateTime); return this; }
/** * Dumps JVM metrics for this process. * @param incidentId incident id */ public static void dumpVmMetrics(String incidentId) { PrintWriter writer = null; try { String dumpFile = EventUtil.getDumpPathPrefix() + "/" + INC_DUMP_FILE_NAME + incidentId + INC_DUMP_FILE_EXT; final OutputStream outStream = new GZIPOutputStream(new FileOutputStream(dumpFile)); writer = new PrintWriter(outStream, true); final VirtualMachineMetrics vm = VirtualMachineMetrics.getInstance(); writer.print("\n\n\n--------------------------- METRICS " + "---------------------------\n\n"); writer.flush(); JsonFactory jf = new JsonFactory(); jf.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET); ObjectMapper mapper = new ObjectMapper(jf); mapper.registerModule(new JodaModule()); mapper.setDateFormat(new ISO8601DateFormat()); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); MetricsServlet metrics = new MetricsServlet(Clock.defaultClock(), vm, Metrics.defaultRegistry(), jf, true); final JsonGenerator json = jf.createGenerator(outStream, JsonEncoding.UTF8); json.useDefaultPrettyPrinter(); json.writeStartObject(); // JVM metrics writeVmMetrics(json, vm); // Components metrics metrics.writeRegularMetrics(json, // json generator null, // class prefix false); // include full samples json.writeEndObject(); json.close(); logger.debug("Creating full thread dump in dump file {}", dumpFile); // Thread dump next.... writer.print("\n\n\n--------------------------- THREAD DUMP " + "---------------------------\n\n"); writer.flush(); vm.threadDump(outStream); logger.debug("Dump file {} is created.", dumpFile); } catch(Exception exc) { logger.error( "Unable to write dump file, exception: {}", exc.getMessage()); } finally { if (writer != null) { writer.close(); } } }
public static Date getStashCreationTimeStamp(String stashStartTime) throws ParseException { return new ISO8601DateFormat().parse(stashStartTime); }