Java Code Examples for com.fasterxml.jackson.databind.SerializationFeature

The following examples show how to use com.fasterxml.jackson.databind.SerializationFeature. These examples are extracted from open source projects. 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 Project: datacollector   Author: streamsets   File: SnapshotDataCommand.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
  if(pipelineRev == null) {
    pipelineRev = "0";
  }

  try {
    ManagerApi managerApi = new ManagerApi(getApiClient());
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    System.out.println(mapper.writeValueAsString(managerApi.getSnapshot(pipelineId, snapshotName,
      pipelineRev)));
  } catch (Exception ex) {
    if(printStackTrace) {
      ex.printStackTrace();
    } else {
      System.out.println(ex.getMessage());
    }
  }
}
 
Example #2
Source Project: find   Author: microfocus-idol   File: DashboardConfigService.java    License: MIT License 6 votes vote down vote up
@Autowired
public DashboardConfigService(final JsonDeserializer<TagName> tagNameDeserializer) {
    super(
        "dashboards.json",
        "defaultDashboardsConfigFile.json",
        DashboardConfig.class,
        DashboardConfig.builder().build(),
        new Jackson2ObjectMapperBuilder()
            .mixIn(Widget.class, WidgetMixins.class)
            .mixIn(WidgetDatasource.class, WidgetDatasourceMixins.class)
            .deserializersByType(ImmutableMap.of(TagName.class, tagNameDeserializer))
            .serializersByType(ImmutableMap.of(TagName.class, new TagNameSerializer()))
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,
                               DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
    );
}
 
Example #3
Source Project: timbuctoo   Author: HuygensING   File: TypeTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void isSerializable() throws IOException {
  Type type = new Type("http://example.org/myType");
  type.getOrCreatePredicate("http://example.org/myPredicate", Direction.OUT);
  type.getOrCreatePredicate("http://example.org/myPredicate", Direction.IN);

  ObjectMapper mapper = new ObjectMapper()
    .registerModule(new Jdk8Module())
    .registerModule(new GuavaModule())
    .registerModule(new TimbuctooCustomSerializers())
    .enable(SerializationFeature.INDENT_OUTPUT);
  String result = mapper.writeValueAsString(type);

  Type loadedType = mapper.readValue(result, Type.class);

  assertThat(loadedType, is(type));
}
 
Example #4
Source Project: soundwave   Author: pinterest   File: EsInstanceStore.java    License: Apache License 2.0 6 votes vote down vote up
public EsInstanceStore(String host, int port) {
  super(host, port);
  //This is required to let ES create the mapping of Date instead of long
  insertMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

  updateMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
      .addMixIn(getInstanceClass(), IgnoreCreatedTimeMixin.class);

  //Specific mapper to read EsDailySnapshotInstance from the index
  essnapshotinstanceMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
      .setPropertyNamingStrategy(new EsPropertyNamingStrategy(
          EsDailySnapshotInstance.class, EsInstanceStore.class))
      .configure(MapperFeature.ALLOW_EXPLICIT_PROPERTY_RENAMING, true);

}
 
Example #5
Source Project: spring-cloud-dataflow   Author: spring-cloud   File: JdbcDataflowTaskExecutionMetadataDao.java    License: Apache License 2.0 6 votes vote down vote up
public JdbcDataflowTaskExecutionMetadataDao(DataSource dataSource,
		DataFieldMaxValueIncrementer incrementer) {

	this.incrementer = incrementer;

	this.jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

	this.objectMapper = new ObjectMapper();
	SimpleModule module = new SimpleModule();
	module.addDeserializer(Resource.class,
			new ResourceDeserializer(new AppResourceCommon(new MavenProperties(), new DefaultResourceLoader())));
	this.objectMapper.registerModule(module);
	this.objectMapper.addMixIn(Resource.class, ResourceMixin.class);
	this.objectMapper.addMixIn(AppDefinition.class, AppDefinitionMixin.class);
	this.objectMapper.addMixIn(AppDeploymentRequest.class, AppDeploymentRequestMixin.class);
	this.objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

	this.dataSource = dataSource;
}
 
Example #6
Source Project: soundwave   Author: pinterest   File: EsPropertyNamingStrategyTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void deserializeWithStrategy() throws Exception {
  ObjectMapper
      mapper =
      new ObjectMapper().configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
          .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
          .setPropertyNamingStrategy(new EsPropertyNamingStrategy(
              EsDailySnapshotInstance.class, EsInstanceStore.class))
          .configure(MapperFeature.ALLOW_EXPLICIT_PROPERTY_RENAMING, true);

  EsDailySnapshotInstance inst = mapper.readValue(doc, EsDailySnapshotInstance.class);
  Assert.assertEquals("coreapp-webapp-prod-0a018ef5", inst.getName());
  Assert.assertEquals("fixed", inst.getLifecycle());
  Assert.assertTrue(inst.getLaunchTime() != null);

}
 
Example #7
Source Project: qpid-broker-j   Author: apache   File: ObjectMapperFactory.java    License: Apache License 2.0 6 votes vote down vote up
public ObjectMapper createObjectMapper()
{
    SimpleModule module = new SimpleModule();
    module.addDeserializer(PropertyValue.class, new PropertyValueDeserializer());
    module.addSerializer(SimplePropertyValue.class, new SimplePropertyValueSerializer());

    ObjectMapper objectMapper = new ObjectMapper();

    objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);

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

    objectMapper.configure(MapperFeature.AUTO_DETECT_GETTERS, false);
    objectMapper.registerModule(module);

    objectMapper.registerModule(module);

    return objectMapper;
}
 
Example #8
Source Project: openapi-generator   Author: OpenAPITools   File: ApiClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Ctor.
 */
public ApiClient() {
  builder = HttpClient.newBuilder();
  mapper = new ObjectMapper();
  mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);
  mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
  mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
  mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
  mapper.registerModule(new JavaTimeModule());
  JsonNullableModule jnm = new JsonNullableModule();
  mapper.registerModule(jnm);
  URI baseURI = URI.create("http://petstore.swagger.io:80/v2");
  scheme = baseURI.getScheme();
  host = baseURI.getHost();
  port = baseURI.getPort();
  basePath = baseURI.getRawPath();
  interceptor = null;
  readTimeout = null;
  responseInterceptor = null;
}
 
Example #9
Source Project: terracotta-platform   Author: Terracotta-OSS   File: AbstractTest.java    License: Apache License 2.0 6 votes vote down vote up
protected final void commonSetUp(Cluster cluster) throws Exception {
  this.cluster = cluster;

  mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
  mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
  mapper.addMixIn(CapabilityContext.class, CapabilityContextMixin.class);
  mapper.addMixIn(Statistic.class, StatisticMixin.class);
  mapper.addMixIn(ContextualStatistics.class, ContextualStatisticsMixin.class);
  mapper.addMixIn(ConstantValueStatistic.class, ConstantValueStatisticMixin.class);

  connectManagementClient(cluster.getConnectionURI());

  addWebappNode(cluster.getConnectionURI(), "pet-clinic");
  addWebappNode(cluster.getConnectionURI(), "pet-clinic");

  getCaches("pets");
  getCaches("clients");
}
 
Example #10
Source Project: onetwo   Author: wayshall   File: JsonMapper.java    License: Apache License 2.0 6 votes vote down vote up
public JsonMapper(ObjectMapper objectMapper, Include include, boolean fieldVisibility){
		objectMapper.setSerializationInclusion(include);
//		objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
//		setDateFormat(DateUtils.DATE_TIME);
		objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
		objectMapper.configure(Feature.ALLOW_COMMENTS, true);
//		objectMapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
		objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		if(fieldVisibility)
			objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
		objectMapper.setFilterProvider(filterProvider);
//		objectMapper.addMixIn(target, mixinSource);
		this.objectMapper = objectMapper;
		this.typeFactory = this.objectMapper.getTypeFactory();
	}
 
Example #11
Source Project: datacollector   Author: streamsets   File: GetCommittedOffsetsCommand.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
  if(pipelineRev == null) {
    pipelineRev = "0";
  }
  try {
    ManagerApi managerApi = new ManagerApi(getApiClient());
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    System.out.println(mapper.writeValueAsString(managerApi.getCommittedOffsets(pipelineId, pipelineRev)));
  } catch (Exception ex) {
    if(printStackTrace) {
      ex.printStackTrace();
    } else {
      System.out.println(ex.getMessage());
    }
  }
}
 
Example #12
Source Project: autorest-clientruntime-for-java   Author: Azure   File: PollingState.java    License: MIT License 6 votes vote down vote up
/**
 * Initializes an object mapper.
 *
 * @param mapper the mapper to initialize
 * @return the initialized mapper
 */
private static ObjectMapper initMapper(ObjectMapper mapper) {
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
            .configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, true)
            .configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
            .setSerializationInclusion(JsonInclude.Include.NON_NULL)
            .registerModule(new JodaModule())
            .registerModule(ByteArraySerializer.getModule())
            .registerModule(Base64UrlSerializer.getModule())
            .registerModule(DateTimeSerializer.getModule())
            .registerModule(DateTimeRfc1123Serializer.getModule())
            .registerModule(HeadersSerializer.getModule());
    mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
            .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
            .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE));
    return mapper;
}
 
Example #13
Source Project: typescript-generator   Author: vojtechhabarta   File: ObjectAsIdTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testJacksonLists() throws JsonProcessingException {
    final TestObjectA testObjectA = new TestObjectA();
    final TestObjectB testObjectB = new TestObjectB();
    final TestObjectC<String> testObjectC = new TestObjectC<>("valueC");
    final TestObjectD testObjectD = new TestObjectD();
    final TestObjectE testObjectE = new TestObjectE();
    final WrapperWithLists wrapper = new WrapperWithLists();
    wrapper.listOfTestObjectA = Arrays.asList(testObjectA, testObjectA);
    wrapper.listOfTestObjectB = Arrays.asList(testObjectB, testObjectB);
    wrapper.listOfTestObjectC = Arrays.asList(testObjectC, testObjectC);
    wrapper.listOfTestObjectD = Arrays.asList(testObjectD, testObjectD);
    wrapper.listOfTestObjectE = Arrays.asList(testObjectE, testObjectE);
    final ObjectMapper objectMapper = Utils.getObjectMapper();
    objectMapper.disable(SerializationFeature.INDENT_OUTPUT);
    final String json = objectMapper.writeValueAsString(wrapper);
    Assert.assertTrue(json.contains("\"listOfTestObjectA\":[\"id1\""));
    Assert.assertTrue(json.contains("\"listOfTestObjectB\":[{"));
    Assert.assertTrue(json.contains("\"listOfTestObjectC\":[{"));
    Assert.assertTrue(json.contains("\"listOfTestObjectD\":[\"id4\""));
    Assert.assertTrue(json.contains("\"listOfTestObjectE\":[\"id5\""));
}
 
Example #14
Source Project: hawkular-metrics   Author: hawkular   File: ObjectMapperProducer.java    License: Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void initMapper() {
    mapper = new ObjectMapper();
    mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false);
    mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);

    SimpleModule module = new SimpleModule();
    module.addDeserializer(AvailabilityType.class, new AvailabilityTypeDeserializer());
    module.addDeserializer(MetricType.class, new MetricTypeDeserializer());
    module.addSerializer(AvailabilityType.class, new AvailabilityTypeSerializer());
    module.addKeySerializer(AvailabilityType.class, new AvailabilityTypeKeySerializer());
    mapper.registerModule(module);
}
 
Example #15
Source Project: mall   Author: bigspiders   File: JacksonConfig.java    License: MIT License 6 votes vote down vote up
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public Jackson2ObjectMapperBuilderCustomizer customJackson() {
    return new Jackson2ObjectMapperBuilderCustomizer() {
        @Override
        public void customize(Jackson2ObjectMapperBuilder builder) {
            builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            builder.serializerByType(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            builder.serializerByType(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));

            builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            builder.deserializerByType(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            builder.deserializerByType(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
            builder.serializationInclusion(JsonInclude.Include.NON_NULL);
            builder.failOnUnknownProperties(false);
            builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        }
    };
}
 
Example #16
Source Project: kylin-on-parquet-v2   Author: Kyligence   File: CubeMetaExtractor.java    License: Apache License 2.0 6 votes vote down vote up
private void engineOverwriteInternal(File f) throws IOException {
    try {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(f);
        boolean replaced = false;
        if (engineType != null && rootNode.get("engine_type") != null) {
            ((ObjectNode) rootNode).put("engine_type", Integer.parseInt(engineType));
            replaced = true;
        }
        if (storageType != null && rootNode.get("storage_type") != null) {
            ((ObjectNode) rootNode).put("storage_type", Integer.parseInt(storageType));
            replaced = true;
        }
        if (replaced) {
            objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
            objectMapper.writeValue(f, rootNode);
        }
    } catch (JsonProcessingException ex) {
        logger.warn("cannot parse file {}", f);
    }
}
 
Example #17
Source Project: reladomo   Author: goldmansachs   File: ExampleJacksonReladomoBitemporalSerializerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
    public void testInMemoryNoRelationships() throws Exception
    {
        String serialized = "{\n" +
                "  \"_rdoClassName\" : \"com.gs.fw.common.mithra.test.domain.BitemporalOrderItem\",\n" +
//                "  \"_rdoState\" : 20,\n" +
                "  \"id\" : 70459,\n" +
                "  \"orderId\" : 1,\n" +
                "  \"productId\" : 1,\n" +
                "  \"quantity\" : 20.0,\n" +
                "  \"originalPrice\" : 10.5,\n" +
                "  \"discountPrice\" : 10.5,\n" +
                "  \"state\" : \"In-Progress\",\n" +
                "  \"businessDate\" : 1567363437186\n" +
                "}\n";
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JacksonReladomoModule());
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        JavaType customClassCollection = mapper.getTypeFactory().constructCollectionLikeType(Serialized.class, BitemporalOrderItem.class);

        Serialized<BitemporalOrderItem> back = mapper.readValue(serialized, customClassCollection);
        BitemporalOrderItem wrapped = back.getWrapped();
        Assert.assertEquals(70459, wrapped.getId());
        Assert.assertEquals("In-Progress", wrapped.getState());
        Assert.assertEquals(BitemporalOrderItemFinder.processingDate().getInfinityDate(), wrapped.getProcessingDate());
    }
 
Example #18
Source Project: rock-paper-scissors-in-java   Author: jankronquist   File: RpsConfig.java    License: MIT License 5 votes vote down vote up
public RpsConfig() throws Exception {
      mapper = new ObjectMapper();
      mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
      mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
      
GamesProjection gameProjection = new GamesProjection();
      EventStoreEventStore eventStore = new EventStoreEventStore("game", mapper);
ApplicationService applicationService = new ApplicationService(eventStore, Game.class);
eventStore.all().collect(()-> gameProjection, ReflectionUtil::invokeHandleMethod);
      
      register(new RpsResource(applicationService, gameProjection));
      register(new HandleAllExceptions());
  }
 
Example #19
Source Project: deptective   Author: moditect   File: JsonSerializer.java    License: Apache License 2.0 5 votes vote down vote up
public JsonSerializer() {
    mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    root = mapper.createObjectNode();
    components = root.putArray("components");
    whitelisted = root.putArray("whitelisted");
}
 
Example #20
protected void initObjectMapper() {
  objectMapper = new ObjectMapper();
  objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  objectMapper.configure(DeserializationFeature.FAIL_ON_UNRESOLVED_OBJECT_IDS, false);
  objectMapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);

  SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
  objectMapper.setDateFormat(sdf);
  objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
}
 
Example #21
Source Project: XS2A-Sandbox   Author: adorsys   File: TppUiBeFeignConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public Encoder feignEncoder() {
    objectMapper.addMixIn(ScaUserDataTO.class, ScaUserDataMixedIn.class)
        .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter(objectMapper);
    ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(jacksonConverter);
    return new SpringEncoder(objectFactory);
}
 
Example #22
Source Project: dss   Author: esig   File: UnmarshallingTester.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private static ObjectMapper getObjectMapper() {
	ObjectMapper om = new ObjectMapper();
	JaxbAnnotationIntrospector jai = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
	om.setAnnotationIntrospector(jai);
	om.enable(SerializationFeature.INDENT_OUTPUT);
	return om;
}
 
Example #23
Source Project: swaggy-jenkins   Author: cliffano   File: JacksonJsonProvider.java    License: MIT License 5 votes vote down vote up
public JacksonJsonProvider() {

        ObjectMapper objectMapper = new ObjectMapper()
            .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .registerModule(new JodaModule())
            .setDateFormat(new RFC3339DateFormat());

        setMapper(objectMapper);
    }
 
Example #24
Source Project: datacollector   Author: streamsets   File: StartPipelineCommand.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  if(pipelineRev == null) {
    pipelineRev = "0";
  }
  Map<String, Object> runtimeParameters = null;
  try {
    ApiClient apiClient = getApiClient();
    ManagerApi managerApi = new ManagerApi(apiClient);
    if (runtimeParametersString != null && runtimeParametersString.trim().length() > 0) {
      JSON json = apiClient.getJson();
      TypeRef returnType = new TypeRef<Map<String, Object>>() {};
      runtimeParameters = json.deserialize(runtimeParametersString, returnType);
    }
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    System.out.println(mapper.writeValueAsString(
        managerApi.startPipeline(pipelineId, pipelineRev, runtimeParameters))
    );
  } catch (Exception ex) {
    if(printStackTrace) {
      ex.printStackTrace();
    } else {
      System.out.println(ex.getMessage());
    }
  }
}
 
Example #25
Source Project: nb-springboot   Author: AlexFalappa   File: InitializrService.java    License: Apache License 2.0 5 votes vote down vote up
public JsonNode getDependencies(String bootVersion) throws Exception {
    if (!dependencyMetaMap.containsKey(bootVersion)) {
        // set connection timeouts
        timeoutFromPrefs();
        // prepare request
        final String serviceUrl = NbPreferences.forModule(PrefConstants.class).get(PREF_INITIALIZR_URL,
                PrefConstants.DEFAULT_INITIALIZR_URL);
        UriTemplate template = new UriTemplate(serviceUrl.concat("/dependencies?bootVersion={bootVersion}"));
        RequestEntity<Void> req = RequestEntity
                .get(template.expand(bootVersion))
                .accept(MediaType.valueOf("application/vnd.initializr.v2.1+json"))
                .header("User-Agent", REST_USER_AGENT)
                .build();
        // connect
        logger.log(INFO, "Getting Spring Initializr dependencies metadata from: {0}", template);
        logger.log(INFO, "Asking metadata as: {0}", REST_USER_AGENT);
        long start = System.currentTimeMillis();
        ResponseEntity<String> respEntity = rt.exchange(req, String.class);
        // analyze response
        final HttpStatus statusCode = respEntity.getStatusCode();
        if (statusCode == OK) {
            ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
            final JsonNode depMeta = mapper.readTree(respEntity.getBody());
            logger.log(INFO, "Retrieved Spring Initializr dependencies metadata for boot version {0}. Took {1} msec",
                    new Object[]{bootVersion, System.currentTimeMillis() - start});
            if (logger.isLoggable(FINE)) {
                logger.fine(mapper.writeValueAsString(depMeta));
            }
            dependencyMetaMap.put(bootVersion, depMeta);
        } else {
            // log status code
            final String errMessage = String.format("Spring initializr service connection problem. HTTP status code: %s",
                    statusCode.toString());
            logger.severe(errMessage);
            // throw exception in order to set error message
            throw new RuntimeException(errMessage);
        }
    }
    return dependencyMetaMap.get(bootVersion);
}
 
Example #26
Source Project: jackson-modules-java8   Author: FasterXML   File: LocalDateSerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSerializationAsString02() throws Exception
{
    LocalDate date = LocalDate.of(2013, Month.AUGUST, 21);
    String value = MAPPER.writer()
    		.without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
    		.writeValueAsString(date);
    assertNotNull("The value should not be null.", value);
    assertEquals("The value is not correct.", '"' + date.toString() + '"', value);
}
 
Example #27
Source Project: incubator-taverna-language   Author: apache   File: ToJson.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #28
Source Project: jackson-modules-java8   Author: FasterXML   File: InstantDeserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRoundTripOfInstantAndJavaUtilDate() throws Exception
{
    ObjectMapper mapper = newMapperBuilder()
            .configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
            .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
            .configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
            .build();

    Instant givenInstant = LocalDate.of(2016, 1, 1).atStartOfDay().atZone(ZoneOffset.UTC).toInstant();
    String json = mapper.writeValueAsString(java.util.Date.from(givenInstant));
    Instant actual = mapper.readValue(json, Instant.class);

    assertEquals(givenInstant, actual);
}
 
Example #29
Source Project: caravan   Author: ctripcorp   File: JacksonXmlSerializer.java    License: Apache License 2.0 5 votes vote down vote up
private JacksonXmlSerializer() {
    _mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    _mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    _mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
    _mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
    _mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    _mapper.configure(Feature.AUTO_CLOSE_TARGET, false);
}
 
Example #30
Source Project: katharsis-framework   Author: katharsis-project   File: AbstractMetaJerseyTest.java    License: Apache License 2.0 5 votes vote down vote up
public TestApplication() {
	property(KatharsisProperties.RESOURCE_SEARCH_PACKAGE, "io.katharsis.meta.mock.model");
	KatharsisFeature feature = new KatharsisFeature();
	ObjectMapper objectMapper = feature.getObjectMapper();
	objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
	feature.addModule(createModule());
	register(feature);
}