com.fasterxml.jackson.databind.JsonMappingException Java Examples

The following examples show how to use com.fasterxml.jackson.databind.JsonMappingException. 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: singleton   Author: vmware   File: ReadCompJsonFile.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public static DBI18nDocument Json2DBDoc(TransCompDocFile compDoc)
		throws JsonParseException, JsonMappingException, IOException {

	ObjectMapper mapper = new ObjectMapper();

	logger.info(compDoc.getDocFile().getAbsolutePath());

	StringBuilder strBuilder = file2String(compDoc.getDocFile(), StandardCharsets.UTF_8);
	logger.debug(strBuilder.toString());

	DBI18nDocument doc = mapper.readValue(strBuilder.toString(), DBI18nDocument.class);
	logger.debug("bundle doc component:" + doc.getComponent());
	logger.debug("bundle doc locale:" + doc.getComponent());
	doc.setProduct(compDoc.getProduct());
	doc.setVersion(compDoc.getVersion());
	doc.setComponent(compDoc.getComponent());
	doc.setLocale(compDoc.getLocale());
	return doc;
}
 
Example #2
Source Project: syndesis   Author: syndesisio   File: JsonDBRawMetrics.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * If Integrations get deleted we should also delete their metrics
 */
@Override
public void curate(Set<String> activeIntegrationIds) throws IOException, JsonMappingException {

    //1. Loop over all RawMetrics
    String json = jsonDB.getAsString(path(), new GetOptions().depth(1));
    if (json != null) {
        Map<String,Boolean> metricsMap = JsonUtils.reader().forType(TYPE_REFERENCE).readValue(json);
        Set<String> rawIntegrationIds = metricsMap.keySet();
        for (String rawIntId : rawIntegrationIds) {
            if (! activeIntegrationIds.contains(rawIntId)) {
                jsonDB.delete(path(rawIntId));
            }
        }
    }
}
 
Example #3
Source Project: spring-analysis-note   Author: Vip-Augus   File: AbstractJackson2HttpMessageConverter.java    License: MIT License 6 votes vote down vote up
/**
 * Determine whether to log the given exception coming from a
 * {@link ObjectMapper#canDeserialize} / {@link ObjectMapper#canSerialize} check.
 * @param type the class that Jackson tested for (de-)serializability
 * @param cause the Jackson-thrown exception to evaluate
 * (typically a {@link JsonMappingException})
 * @since 4.3
 */
protected void logWarningIfNecessary(Type type, @Nullable Throwable cause) {
	if (cause == null) {
		return;
	}

	// Do not log warning for serializer not found (note: different message wording on Jackson 2.9)
	boolean debugLevel = (cause instanceof JsonMappingException && cause.getMessage().startsWith("Cannot find"));

	if (debugLevel ? logger.isDebugEnabled() : logger.isWarnEnabled()) {
		String msg = "Failed to evaluate Jackson " + (type instanceof JavaType ? "de" : "") +
				"serialization for type [" + type + "]";
		if (debugLevel) {
			logger.debug(msg, cause);
		}
		else if (logger.isDebugEnabled()) {
			logger.warn(msg, cause);
		}
		else {
			logger.warn(msg + ": " + cause);
		}
	}
}
 
Example #4
Source Project: open-Autoscaler   Author: cfibmers   File: BeanValidation.java    License: Apache License 2.0 6 votes vote down vote up
public static JsonNode parseScalingHistory(String jsonString, HttpServletRequest httpServletRequest) throws JsonParseException, JsonMappingException, IOException{
	 List<String> violation_message = new ArrayList<String>();
	 ObjectNode result = new_mapper.createObjectNode();
	 result.put("valid", false);
	 JavaType javaType = getCollectionType(ArrayList.class, ArrayList.class, HistoryData.class);
	 new_mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
	 List<HistoryData> scalinghistory = (List<HistoryData>)new_mapper.readValue(jsonString, javaType);
	 ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
	 Locale locale = LocaleUtil.getLocale(httpServletRequest);
	 MessageInterpolator interpolator = new LocaleSpecificMessageInterpolator(vf.getMessageInterpolator(), locale);
	 Validator validator = vf.usingContext().messageInterpolator(interpolator).getValidator();
	 Set<ConstraintViolation<List<HistoryData>>> set = validator.validate(scalinghistory);
	 if (set.size() > 0 ){
		 for (ConstraintViolation<List<HistoryData>> constraintViolation : set) {
			 violation_message.add(constraintViolation.getMessage());
		 }
		 result.set("violation_message", new_mapper.valueToTree(violation_message));
		 return result;
	 }

	 //additional data manipulation
    	 String new_json = transformHistory(scalinghistory);
	 result.put("valid", true);
	 result.put("new_json", new_json);
	 return result;
}
 
Example #5
Source Project: wecube-platform   Author: WeBankPartners   File: UmAuthenticationChecker.java    License: Apache License 2.0 6 votes vote down vote up
private UmUserAuthResultDto performUserAuthentication(UmAuthContext authCtx, UmSubSystemAuthResultDto subSystemAuthResult,
		UsernamePasswordAuthenticationToken userToken) throws JsonParseException, JsonMappingException, IOException
		 {
	String host = authCtx.getHost();
	int port = authCtx.getPort();
	String userId = userToken.getName();
	String pwd = (String) userToken.getCredentials();
	String appid = subSystemAuthResult.getId();
	String tmp = generatePwd(userId, pwd);
	String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
	String sign = md5(userId + tmp + timeStamp);
	String token = subSystemAuthResult.getTok();
	String auth = subSystemAuthResult.getAuth();

	String url = String.format(
			"http://%s:%s/um_service?style=6&appid=%s&id=%s&sign=%s&timeStamp=%s&token=%s&auth=%s", host, port,
			appid, userId, sign, timeStamp, token, auth);

	HttpHeaders headers = new HttpHeaders();
	ResponseEntity<String> resp = sendGetRequestWithUrlParamMap(restTemplate, url, headers, String.class);

	UmUserAuthResultDto authResult = objectMapper.readValue(resp.getBody(), UmUserAuthResultDto.class);
	
	return authResult;
}
 
Example #6
Source Project: pulsar   Author: apache   File: PoliciesDataTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void bundlesData() throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper jsonMapper = ObjectMapperFactory.create();
    String newJsonPolicy = "{\"auth_policies\":{\"namespace_auth\":{},\"destination_auth\":{}},\"replication_clusters\":[],\"bundles\":{\"boundaries\":[\"0x00000000\",\"0xffffffff\"]},\"backlog_quota_map\":{},\"persistence\":null,\"latency_stats_sample_rate\":{}}";

    List<String> bundleSet = Lists.newArrayList();
    bundleSet.add("0x00000000");
    bundleSet.add("0xffffffff");

    String newBundlesDataString = "{\"boundaries\":[\"0x00000000\",\"0xffffffff\"]}";
    BundlesData data = jsonMapper.readValue(newBundlesDataString.getBytes(), BundlesData.class);
    assertEquals(data.getBoundaries(), bundleSet);

    Policies policies = jsonMapper.readValue(newJsonPolicy.getBytes(), Policies.class);
    Policies expected = new Policies();
    expected.bundles = data;
    assertEquals(policies, expected);
}
 
Example #7
Source Project: milkman   Author: warmuuh   File: DiffTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldMergeCorrectlyAddCollection() throws JsonParseException, JsonMappingException, IOException {
	String colId = UUID.randomUUID().toString();
	String colId2 = UUID.randomUUID().toString();
	
	List<Collection> base = new LinkedList<Collection>();
	base.add(new Collection(colId, "collection1", false, new LinkedList<>(), Collections.emptyList()));
	
	List<Collection> working = new LinkedList<Collection>();
	working.add(new Collection(colId, "collection1", false, new LinkedList<>(), Collections.emptyList()));
	working.add(new Collection(colId2, "collection2", false, new LinkedList<>(), Collections.emptyList()));
	
	CollectionDiffer collectionDiffer = new CollectionDiffer();
	DiffNode diffNode = collectionDiffer.compare(working, base);
	
	collectionDiffer.mergeDiffs(working, base, diffNode);
	
	assertThat(base.size()).isEqualTo(2);
	assertThat(base.get(0).getId()).isEqualTo(colId);
	assertThat(base.get(0).getName()).isEqualTo("collection1");

	assertThat(base.get(1).getId()).isEqualTo(colId2);
	assertThat(base.get(1).getName()).isEqualTo("collection2");
	
}
 
Example #8
Source Project: levelup-java-examples   Author: leveluplunch   File: JsonToGuavaMultimap.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void convert() throws JsonParseException, JsonMappingException,
		JsonProcessingException, IOException {

	ObjectMapper objectMapper = new ObjectMapper();
	objectMapper.registerModule(new GuavaModule());

	Multimap<String, NavItem> navs = objectMapper.readValue(
			objectMapper.treeAsTokens(objectMapper.readTree(jsonString)),
			objectMapper.getTypeFactory().constructMapLikeType(
					Multimap.class, String.class, NavItem.class));

	logger.info(navs);
	
    assertThat(navs.keys(), hasItems("123455", "999999"));
}
 
Example #9
Source Project: arctic-sea   Author: 52North   File: KibanaImporter.java    License: Apache License 2.0 6 votes vote down vote up
public void importJson(String jsonString) throws JsonParseException, JsonMappingException, IOException {
    Objects.requireNonNull(jsonString);

    // delete .kibana index
    try {
        client.delete(new DeleteRequest(kibanaIndexName), RequestOptions.DEFAULT);
    } catch (ElasticsearchException ex) {
        LOG.debug("Tried to delete kibana index " + kibanaIndexName + " but it is not exists", ex);
    }

    ObjectMapper mapper = new ObjectMapper();
    KibanaConfigHolderDto holder = mapper.readValue(jsonString, KibanaConfigHolderDto.class);

    for (KibanaConfigEntryDto dto : holder.getEntries()) {
        processDto(dto);
        LOG.debug("Importing {}", dto);
        CreateIndexResponse response =
                client.indices().create(new CreateIndexRequest(kibanaIndexName), RequestOptions.DEFAULT);
        // client.prepareIndex(kibanaIndexName, dto.getType(), dto.getId())
        // .setSource(dto.getSource()).get();
    }
}
 
Example #10
Source Project: ogham   Author: groupe-sii   File: SendGridHttpTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void authenticationFailed() throws MessagingException, JsonParseException, JsonMappingException, IOException {
	// @formatter:off
	server.stubFor(post("/api/mail.send.json")
		.willReturn(aResponse()
				.withStatus(400)
				.withBody(loadJson("/stubs/responses/authenticationFailed.json"))));
	// @formatter:on
	// @formatter:off
	Email email = new Email()
		.subject(SUBJECT)
		.content(CONTENT_TEXT)
		.from(FROM_ADDRESS)
		.to(TO_ADDRESS_1);
	// @formatter:on
	
	MessagingException e = assertThrows(MessagingException.class, () -> {
		messagingService.send(email);
	}, "throws message exception");
	assertThat("sendgrid exception", e.getCause(), allOf(notNullValue(), instanceOf(SendGridException.class)));
	assertThat("root cause", e.getCause().getCause(), allOf(notNullValue(), instanceOf(IOException.class)));
	assertThat("sendgrid message", e.getCause().getCause().getMessage(), Matchers.equalTo("Sending to SendGrid failed: (400) {\n" + 
			"	\"errors\": [\"The provided authorization grant is invalid, expired, or revoked\"],\n" + 
			"	\"message\": \"error\"\n" + 
			"}"));
}
 
Example #11
Source Project: conductor   Author: Netflix   File: JsonMapperProviderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleMapping() throws JsonGenerationException, JsonMappingException, IOException {
    ObjectMapper m = new JsonMapperProvider().get();
    assertTrue(m.canSerialize(Any.class));

    Struct struct1 = Struct.newBuilder().putFields(
            "some-key", Value.newBuilder().setStringValue("some-value").build()
    ).build();

    Any source = Any.pack(struct1);

    StringWriter buf = new StringWriter();
    m.writer().writeValue(buf, source);

    Any dest = m.reader().forType(Any.class).readValue(buf.toString());
    assertEquals(source.getTypeUrl(), dest.getTypeUrl());

    Struct struct2 = dest.unpack(Struct.class);
    assertTrue(struct2.containsFields("some-key"));
    assertEquals(
            struct1.getFieldsOrThrow("some-key").getStringValue(),
            struct2.getFieldsOrThrow("some-key").getStringValue()
    );
}
 
Example #12
Source Project: incubator-taverna-language   Author: apache   File: WfdescAgent.java    License: Apache License 2.0 6 votes vote down vote up
public void annotateT2flows() throws JsonParseException, JsonMappingException, IOException {
	String query = "PREFIX ro: <http://purl.org/wf4ever/ro#> " +
			"" +
			" SELECT ?ro ?p ?s ?name WHERE { " +
			"?ro a ?x ;" +
			"    ?p ?s ." +
			"?s ro:name ?name ." +
			" FILTER REGEX(?name, \"t2flow$\") } ";
	
	for (JsonNode binding : sparql(query)) {
		System.out.print( binding.path("ro").path("value").asText());
		System.out.print( binding.path("p").path("value").asText());
		System.out.print( binding.path("s").path("value").asText());
		System.out.println( binding.path("name").path("value").asText());

	}
	
	
}
 
Example #13
Source Project: Kylin   Author: KylinOLAP   File: Serializer.java    License: Apache License 2.0 5 votes vote down vote up
public T deserialize(byte[] value) throws JsonParseException, JsonMappingException, IOException {
    if (null == value) {
        return null;
    }

    return JsonUtil.readValue(value, type);
}
 
Example #14
Source Project: aesh-readline   Author: aeshell   File: TaskStatusUpdateEvent.java    License: Apache License 2.0 5 votes vote down vote up
public static TaskStatusUpdateEvent fromJson(String serialized) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.readValue(serialized, TaskStatusUpdateEvent.class);
    }
    catch (JsonParseException | JsonMappingException e) {
        LOGGER.log(Level.SEVERE, "Cannot deserialize object from json", e);
        throw e;
    }
}
 
Example #15
Source Project: proctor   Author: indeedeng   File: PayloadFunctions.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * If o is a proctor Payload object, then return its type as a string, otherwise return "none".
 */
public static String printPayloadType(final Object o) throws IOException, JsonGenerationException, JsonMappingException {
    return Optional.ofNullable(o)
            .filter(ob -> ob instanceof Payload)
            .flatMap(ob -> ((Payload) ob).fetchPayloadType())
            .map(p -> p.payloadTypeName)
            .orElse("none");
}
 
Example #16
Source Project: aws-athena-query-federation   Author: awslabs   File: ObjectMapperFactoryV2.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public JsonSerializer<Object> createSerializer(SerializerProvider prov, JavaType origType)
        throws JsonMappingException
{
    for (Serializers serializers : customSerializers()) {
        JsonSerializer<?> ser = serializers.findSerializer(prov.getConfig(), origType, null);
        if (ser != null) {
            return (JsonSerializer<Object>) ser;
        }
    }
    throw new IllegalArgumentException("No explicitly configured serializer for " + origType);
}
 
Example #17
Source Project: tutorials   Author: eugenp   File: JacksonCollectionDeserializationUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public final void givenJsonArray_whenDeserializingAsListWithTypeReferenceHelp_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
    final ObjectMapper mapper = new ObjectMapper();

    final List<MyDto> listOfDtos = Lists.newArrayList(new MyDto("a", 1, true), new MyDto("bc", 3, false));
    final String jsonArray = mapper.writeValueAsString(listOfDtos);
    // [{"stringValue":"a","intValue":1,"booleanValue":true},{"stringValue":"bc","intValue":3,"booleanValue":false}]

    final List<MyDto> asList = mapper.readValue(jsonArray, new TypeReference<List<MyDto>>() {
    });
    assertThat(asList.get(0), instanceOf(MyDto.class));
}
 
Example #18
Source Project: SciGraph   Author: SciGraph   File: CliqueConfigurationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws URISyntaxException, JsonParseException, JsonMappingException,
    IOException {
  URL url = this.getClass().getResource("/cliqueConfiguration.yaml");
  File configFile = new File(url.getFile());

  assertThat(configFile.exists(), is(true));

  OwlLoadConfigurationLoader owlLoadConfigurationLoader =
      new OwlLoadConfigurationLoader(configFile);
  loaderConfig = owlLoadConfigurationLoader.loadConfig();
  cliqueConfiguration = loaderConfig.getCliqueConfiguration().get();
}
 
Example #19
Source Project: gwt-jackson   Author: nmorel   File: RefStdDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public JsonDeserializer<?> createContextual( DeserializationContext ctxt, BeanProperty property ) throws JsonMappingException {
    if ( ctxt.getContextualType() == null || ctxt.getContextualType().containedType( 0 ) == null ) {
        throw JsonMappingException.from( ctxt, "Cannot deserialize Ref<T>. Cannot find the Generic Type T." );
    }
    return new RefStdDeserializer( ctxt.getContextualType().containedType( 0 ) );
}
 
Example #20
Source Project: mangooio   Author: svenkubiak   File: ConfigTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetCorsUrlPatternDefaultValue() throws JsonGenerationException, JsonMappingException, IOException {
    // given
    System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString());
    
    // when
    Map<String, String> configValues = new HashMap<>();
    File tempConfig = createTempConfig(configValues);
    Config config = new Config();

    // then
    assertThat(config.getCorsUrlPattern().toString(), equalTo(Pattern.compile(Default.CORS_URLPATTERN.toString()).toString()));
    assertThat(tempConfig.delete(), equalTo(true));
}
 
Example #21
Source Project: cf-butler   Author: pacphi   File: ApplicationReporter.java    License: Apache License 2.0 5 votes vote down vote up
protected AppUsageReport readAppUsageReport(String filename) throws JsonParseException, JsonMappingException, IOException {
    String content = readFile(filename);
    if (filename.endsWith(".json")) {
        return mapper.readValue(content, AppUsageReport.class);
    } else if (filename.endsWith(".csv")) {
        CsvMapper csvMapper = new CsvMapper();
        csvMapper.enable(CsvParser.Feature.WRAP_AS_ARRAY);
        File csvFile = new File(filename);
        MappingIterator<String[]> it = csvMapper.readerFor(String[].class).readValues(csvFile);
        AppUsageReportBuilder builder = AppUsageReport.builder();
        List<AppUsageMonthly> reports = new ArrayList<>();
        int rowNum = 0;
        while (it.hasNext()) {
            String[] row = it.next();
            if (rowNum > 0) {
                AppUsageMonthlyBuilder amb = AppUsageMonthly.builder();
                for (int i = 0; i < row.length; i++) {
                    if (i == 0) {
                        String[] period = row[i].split("-");
                        if (period.length == 2) {
                            amb.month(Integer.valueOf(period[1]));
                        }
                        amb.year(Integer.valueOf(period[0]));
                    }
                    if (i == 1) {
                        amb.averageAppInstances(Double.valueOf(row[i]));
                    }
                    if (i == 2) {
                        amb.maximumAppInstances(Integer.valueOf(row[i]));
                    }
                    if (i == 3) {
                        amb.appInstanceHours(Double.valueOf(row[i]));
                    }
                }
                reports.add(amb.build());
            }
            rowNum++;
        }
        builder.monthlyReports(reports);
        return builder.build();
    } else {
        return AppUsageReport.builder().build();
    }
}
 
Example #22
Source Project: tutorials   Author: eugenp   File: CustomSerializationUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public final void whenSerializingWithCustomSerializer_thenNoExceptions() throws JsonGenerationException, JsonMappingException, IOException {
    final Item myItem = new Item(1, "theItem", new User(2, "theUser"));

    final ObjectMapper mapper = new ObjectMapper();

    final SimpleModule simpleModule = new SimpleModule();
    simpleModule.addSerializer(Item.class, new ItemSerializer());
    mapper.registerModule(simpleModule);

    final String serialized = mapper.writeValueAsString(myItem);
    System.out.println(serialized);
}
 
Example #23
Source Project: Cheddar   Author: travel-cloud   File: JsonMappingExceptionMapper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Response toResponse(final JsonMappingException exception) {
    if (logger.isDebugEnabled()) {
        logger.debug(exception.getMessage(), exception);
    }
    return Response.status(Response.Status.BAD_REQUEST).entity(buildErrorResponse(exception)).build();
}
 
Example #24
Source Project: nifi   Author: apache   File: DatabaseReader.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object findInjectableValue(final Object valueId, final DeserializationContext ctxt, final BeanProperty forProperty, final Object beanInstance) throws JsonMappingException {
    if ("ip_address".equals(valueId)) {
        return ip;
    } else if ("traits".equals(valueId)) {
        return new Traits(ip);
    } else if ("locales".equals(valueId)) {
        return locales;
    }

    return null;
}
 
Example #25
Source Project: RefactoringMiner   Author: tsantalis   File: RefactoringPopulator.java    License: MIT License 5 votes vote down vote up
private static void prepareFSERefactorings(TestBuilder test, BigInteger flag)
		throws JsonParseException, JsonMappingException, IOException {
	List<Root> roots = getFSERefactorings(flag);
	
	for (Root root : roots) {
		test.project(root.repository, "master").atCommit(root.sha1)
				.containsOnly(extractRefactorings(root.refactorings));
	}
}
 
Example #26
Source Project: cloudformation-cli-java-plugin   Author: aws-cloudformation   File: AWSServiceSerdeTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void notObjectStart() {
    JsonMappingException exception = Assertions.assertThrows(JsonMappingException.class,
        () -> serializer.deserialize("[]", new TypeReference<AllPrimitives>() {
        }));
    assertThat(exception.getMessage()).contains("Expected to be in START_OBJECT got");
}
 
Example #27
Source Project: logsniffer   Author: mbok   File: ConfiguredBean.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void resolve(final DeserializationContext ctxt)
		throws JsonMappingException {
	if (defaultDeserializer instanceof ResolvableDeserializer) {
		((ResolvableDeserializer) defaultDeserializer).resolve(ctxt);
	}
}
 
Example #28
Source Project: tutorials   Author: eugenp   File: UnknownPropertiesUnitTest.java    License: MIT License 5 votes vote down vote up
@Test(expected = UnrecognizedPropertyException.class)
public final void givenJsonHasUnknownValues_whenDeserializingAJsonToAClass_thenExceptionIsThrown() throws JsonParseException, JsonMappingException, IOException {
    final String jsonAsString = "{\"stringValue\":\"a\",\"intValue\":1,\"booleanValue\":true,\"stringValue2\":\"something\"}";
    final ObjectMapper mapper = new ObjectMapper();

    final MyDto readValue = mapper.readValue(jsonAsString, MyDto.class);

    assertNotNull(readValue);
    assertThat(readValue.getStringValue(), equalTo("a"));
    assertThat(readValue.isBooleanValue(), equalTo(true));
    assertThat(readValue.getIntValue(), equalTo(1));
}
 
Example #29
Source Project: open-Autoscaler   Author: cfibmers   File: PolicyEnbale.java    License: Apache License 2.0 5 votes vote down vote up
public String transformInput() throws JsonParseException, JsonMappingException, IOException{
	Map<String, String> result = new HashMap<String, String>();
	if (this.enable == true) {
		result.put("state", "enabled");
	}
	else {
		result.put("state", "disabled");
	}
	return  BeanValidation.new_mapper.writeValueAsString(result);
}
 
Example #30
Source Project: jackson-modules-java8   Author: FasterXML   File: YearMonthSerializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void _acceptTimestampVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException
{
    SerializerProvider provider = visitor.getProvider();
    boolean useTimestamp = (provider != null) && useTimestamp(provider);
    if (useTimestamp) {
        super._acceptTimestampVisitor(visitor, typeHint);
    } else {
        JsonStringFormatVisitor v2 = visitor.expectStringFormat(typeHint);
        if (v2 != null) {
            v2.format(JsonValueFormat.DATE_TIME);
        }
    }
}