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

The following are top voted examples for showing how to use com.fasterxml.jackson.databind.ObjectMapper. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: athena   File: ObjectMapperUtil.java   View source code 8 votes vote down vote up
/**
 * convert Object into String.
 * @param obj Object
 * @return String
 */
public static String convertToString(Object obj) {
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        return objectMapper.writeValueAsString(obj);
    } catch (JsonProcessingException e) {
        log.error("JsonProcessingException while converting Entity into string", e);
    }
    return null;
}
 
Example 2
Project: PepSIIrup-2017   File: EventController.java   View source code 8 votes vote down vote up
/**
 * method to get all the events
 * @param id
 * @return
 * @throws JsonProcessingException
 */
@RabbitListener(queues = "#{getAllEventQueue.name}")
public String getAllEvent(byte[] id){
	String res = "";
	List<Event> events = repository.findAll();
	ObjectMapper mapper = new ObjectMapper();
	Log
	.forContext("MemberName", "getAllEvent")
	.forContext("Service", appName)
	.information("RabbitMQ : getAllEvent");
	try {
		res = mapper.writeValueAsString(events);
	} catch (JsonProcessingException e1) {
		Log
		.forContext("MemberName", "getAllEvent")
		.forContext("Service", appName)
		.error(e1,"JsonProcessingException");
	}
	return res;
}
 
Example 3
Project: Apache-Spark-2x-for-Java-Developers   File: TweetText.java   View source code 6 votes vote down vote up
@Override
public String call(String tweet) throws Exception {

  	 ObjectMapper mapper = new ObjectMapper();
      try
      {
          JsonNode root = mapper.readValue(tweet, JsonNode.class);
          if (root.get("lang") != null &&
              "en".equals(root.get("lang").textValue()))
          {
              if (root.get("id") != null && root.get("text") != null)
              {   System.out.println("the text is ::"+root.get("text").textValue());                            
                  return root.get("text").textValue();
              }
              return null;
          }
          return null;
      }
      catch (IOException ex)
      {
         ex.printStackTrace();
      }
      return null;
}
 
Example 4
Project: board-server   File: GameLobby.java   View source code 6 votes vote down vote up
public JsonNode getState() {
	ObjectMapper mapper = new ObjectMapper();

	ObjectNode state = mapper.createObjectNode();

	state.put("name", this.gameClass.getSimpleName());

	ArrayNode rooms = state.putArray("rooms");
	for (GameRoom room : this.rooms.values()) {
		rooms.add(room.getState(false));
	}

	ArrayNode players = state.putArray("players");
	for (GamePlayer player : this.players.values()) {
		players.add(player.getState());
	}
	return state;
}
 
Example 5
Project: metagraph-auth   File: PasswordTest.java   View source code 6 votes vote down vote up
@Test
public void testPassword() throws IOException {
    String tokenUrl = authUrlPrefix + "/oauth/token?client_id=" + clientId + "&client_secret=" + clientSecret + "&grant_type=password&username=" + username + "&password=" + password;
    HttpHeaders headers1 = null;
    //headers1   =    AuthorizationUtil.basic("admin","admin");
    ResponseEntity<String> response = new TestRestTemplate().postForEntity(tokenUrl, null, String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    HashMap map = new ObjectMapper().readValue(response.getBody(), HashMap.class);
    String accessToken = (String) map.get("access_token");
    String refreshToken = (String) map.get("refresh_token");
    System.out.println("Token Info:" + map.toString());

    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Bearer " + accessToken);
    response = new TestRestTemplate().exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertEquals("secure", new ObjectMapper().readValue(response.getBody(), HashMap.class).get("content"));

    refreshToken(refreshToken);


}
 
Example 6
Project: server-vot   File: HttpResponseTest.java   View source code 6 votes vote down vote up
@Test
public void ok() throws Exception {
    String OK = "OK";
    int STATUS = 200;
    String generated = (String) generator.ok(OK).handle(req, res);

    verify(res, times(1)).status(STATUS);
    verify(res, times(1)).type(CONTENT_TYPE);

    ObjectMapper om = new ObjectMapper();
    RESTResult wrapper = om.readValue(generated, RESTResult.class);

    assertTrue(wrapper.getSuccess());
    assertEquals(OK, wrapper.getData());
    assertNull(wrapper.getError());
}
 
Example 7
Project: devops-cstack   File: CloudUnitApplicationContext.java   View source code 6 votes vote down vote up
private MappingJackson2HttpMessageConverter jacksonMessageConverter() {
    MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new Hibernate4Module().enable(Hibernate4Module.Feature.USE_TRANSIENT_ANNOTATION));
    messageConverter.setObjectMapper(mapper);
    return messageConverter;
}
 
Example 8
Project: athena   File: PortPairGroupWebResource.java   View source code 6 votes vote down vote up
/**
 * Update details of a specified port pair group id.
 *
 * @param id port pair group id
 * @param stream port pair group from json
 * @return 200 OK, 404 if given identifier does not exist
 */
@PUT
@Path("{group_id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response updatePortPairGroup(@PathParam("group_id") String id,
                                    final InputStream stream) {
    try {
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode jsonTree = (ObjectNode) mapper.readTree(stream);
        JsonNode port = jsonTree.get("port_pair_group");
        PortPairGroup portPairGroup = codec(PortPairGroup.class).decode((ObjectNode) port, this);
        Boolean isSuccess = nullIsNotFound(get(PortPairGroupService.class).updatePortPairGroup(portPairGroup),
                                           PORT_PAIR_GROUP_NOT_FOUND);
        return Response.status(OK).entity(isSuccess.toString()).build();
    } catch (IOException e) {
        log.error("Update port pair group failed because of exception {}.", e.toString());
        throw new IllegalArgumentException(e);
    }
}
 
Example 9
Project: microservice-cloudfoundry   File: CatalogClient.java   View source code 6 votes vote down vote up
protected RestTemplate getRestTemplate() {
	ObjectMapper mapper = new ObjectMapper();
	mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	mapper.registerModule(new Jackson2HalModule());

	MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
	converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
	converter.setObjectMapper(mapper);

	return new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));
}
 
Example 10
Project: jersey-jwt-springsecurity   File: ObjectMapperProvider.java   View source code 6 votes vote down vote up
private static ObjectMapper createObjectMapper() {

        ObjectMapper mapper = new ObjectMapper();

        mapper.registerModule(new Jdk8Module());
        mapper.registerModule(new JavaTimeModule());
        mapper.registerModule(new ParameterNamesModule());

        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

        return mapper;
    }
 
Example 11
Project: GitHub   File: ArrayRuleTest.java   View source code 6 votes vote down vote up
@Test
public void arrayWithUniqueItemsProducesSet() {
    JCodeModel codeModel = new JCodeModel();
    JPackage jpackage = codeModel._package(getClass().getPackage().getName());

    ObjectMapper mapper = new ObjectMapper();

    ObjectNode itemsNode = mapper.createObjectNode();
    itemsNode.put("type", "integer");

    ObjectNode propertyNode = mapper.createObjectNode();
    propertyNode.set("uniqueItems", BooleanNode.TRUE);
    propertyNode.set("items", itemsNode);

    JClass propertyType = rule.apply("fooBars", propertyNode, jpackage, mock(Schema.class));

    assertThat(propertyType, notNullValue());
    assertThat(propertyType.erasure(), is(codeModel.ref(Set.class)));
    assertThat(propertyType.getTypeParameters().get(0).fullName(), is(Integer.class.getName()));
}
 
Example 12
Project: ares   File: ControllerSerializationTest.java   View source code 6 votes vote down vote up
/**
 * Tests {@link Controller} serialization/deserialization.
 * @throws IOException when command cannot be serialized/deserialized.
 */
@Test
public void test_complex() throws IOException, ParseException {
  Controller ctrlExpected = new Controller(
      "initCustom3", "cmdCustom3", "logCustom3",
      new Interval(10, 15, TimeUnit.SECONDS),
      10L,
      new Interval(10, 15, TimeUnit.SECONDS),
      new HttpProxy("192.168.0.1", 8080),
      "* * * ? * SAT,SUN",
      new HashMap<String,String>(){{put("User-Agent", "CustomUserAgent");}});
  ObjectMapper mapper = new ControllerJsonMapper();
  String jsonActual = mapper.writeValueAsString(ctrlExpected);
  Controller ctrlActual = mapper.readValue(jsonActual, Controller.class);
  Assert.assertEquals(ctrlExpected.getSleep(), ctrlActual.getSleep());
  Assert.assertEquals(ctrlExpected, ctrlActual);
}
 
Example 13
Project: pandemie   File: Jeu.java   View source code 6 votes vote down vote up
private String lesCartesToJson(){
    ObjectMapper obj = new ObjectMapper();
    StringBuilder tmpJson = new StringBuilder();
    tmpJson.append("lesCartes [ "); 

  
    
    for (Map.Entry<ETypeCarte, List<Carte>> entry : LesCartes.entrySet()) {
        ETypeCarte key = entry.getKey();
        List<Carte> value = entry.getValue();
        tmpJson.append(key.toString()).append(" [ ");
        
        for (Carte carte : value) {
            tmpJson.append(carte.toString());
        }
        tmpJson.append(" ],");
    }
    tmpJson.append(" ]");
            
    return tmpJson.toString();
}
 
Example 14
Project: elastic-apm-java-agent-poc   File: ApmAgent.java   View source code 6 votes vote down vote up
protected <T> T createApiClient (Class<T> type) {
  final HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
  logging.setLevel(HttpLoggingInterceptor.Level.BODY);

  final ObjectMapper mapper = new ObjectMapper ();
  final JacksonConverterFactory jacksonConverterFactory = JacksonConverterFactory.create (mapper);
  final OkHttpClient httpClient = new OkHttpClient.Builder()
      .addNetworkInterceptor (new FixedContentTypeInterceptor ())
      .addInterceptor (logging).build ();

  final Retrofit retrofit = new Retrofit.Builder()
      .baseUrl(getApmHost ())
      .addConverterFactory (jacksonConverterFactory)
      .client (httpClient)
      .build();

  return retrofit.create(type);
}
 
Example 15
Project: sf-java-ui   File: NumberFormTest.java   View source code 6 votes vote down vote up
@Test
public void testGenerate_Number_For_Long() throws JsonProcessingException {
	UiForm ui = UiFormSchemaGenerator.get().generate(LongNumberForm.class);
	String json = new ObjectMapper().writeValueAsString(ui);
	Assert.assertThat(json, hasJsonPath("$.schema.properties.number.title", equalTo("Long Number")));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='number')]", hasSize(1)));
	Assert.assertThat(json,
			hasJsonPath("$.form[?(@.key=='number')].description", hasItem("This is a long number")));
	Assert.assertThat(json,
			hasJsonPath("$.form[?(@.key=='number')].placeholder", hasItem("Long Number PlaceHolder")));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='number')].validationMessage",
			hasItem("this is a validation msg for long value")));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='number')].type", hasItem("number")));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='number')].notitle", hasItem(true)));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='number')].readonly", hasItem(true)));

}
 
Example 16
Project: creacoinj   File: ScriptTest.java   View source code 6 votes vote down vote up
@Test
public void dataDrivenValidScripts() throws Exception {
    JsonNode json = new ObjectMapper().readTree(new InputStreamReader(getClass().getResourceAsStream(
            "script_valid.json"), Charsets.UTF_8));
    for (JsonNode test : json) {
        Script scriptSig = parseScriptString(test.get(0).asText());
        Script scriptPubKey = parseScriptString(test.get(1).asText());
        Set<VerifyFlag> verifyFlags = parseVerifyFlags(test.get(2).asText());
        try {
            scriptSig.correctlySpends(new Transaction(PARAMS), 0, scriptPubKey, verifyFlags);
        } catch (ScriptException e) {
            System.err.println(test);
            System.err.flush();
            throw e;
        }
    }
}
 
Example 17
Project: rskj   File: GenesisJsonTest.java   View source code 6 votes vote down vote up
@Test
public void generateGenesisJson() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    JavaType type = mapper.getTypeFactory().constructType(GenesisJson.class);

    GenesisJson genesisJson = new ObjectMapper().readValue(GENESIS_JSON, type);

    Assert.assertTrue(StringUtils.isNotBlank(genesisJson.getMinimumGasPrice()));
    Assert.assertTrue(StringUtils.isNotBlank(genesisJson.getParentHash()));
    Assert.assertTrue(genesisJson.getAlloc().size() > 0);
    Assert.assertTrue(StringUtils.isNotBlank(genesisJson.getBitcoinMergedMiningCoinbaseTransaction()));
    Assert.assertTrue(StringUtils.isNotBlank(genesisJson.getBitcoinMergedMiningHeader()));
    Assert.assertTrue(StringUtils.isNotBlank(genesisJson.getBitcoinMergedMiningMerkleProof()));
    Assert.assertTrue(StringUtils.isNotBlank(genesisJson.getCoinbase()));
    Assert.assertTrue(StringUtils.isNotBlank(genesisJson.getDifficulty()));
    Assert.assertTrue(StringUtils.isNotBlank(genesisJson.getExtraData()));
    Assert.assertTrue(StringUtils.isNotBlank(genesisJson.getMixhash()));
    Assert.assertTrue(StringUtils.isNotBlank(genesisJson.getTimestamp()));

}
 
Example 18
Project: microcks-jenkins-plugin   File: IMicrocksTesterTest.java   View source code 6 votes vote down vote up
@Test
public void testResponseParsing() {
   String response = "{\"id\":\"59947684b2799d34d12fb189\",\"testNumber\":null,\"testDate\":1502901892216,\"testedEndpoint\":\"http://localhost:8088/mockHelloServiceSoapBinding\",\"serviceId\":\"57f4dacc6588793c093f94a5\",\"elapsedTime\":0,\"success\":false,\"inProgress\":true,\"runnerType\":\"HTTP\",\"testCaseResults\":[]}";
   // Convert response to Node using Jackson object mapper.
   ObjectMapper mapper = new ObjectMapper();

   try {
      JsonNode responseNode = mapper.readTree(response);
      String testResultId = responseNode.path("id").asText();

      assertEquals("59947684b2799d34d12fb189", testResultId);
   } catch (Exception e) {
      e.printStackTrace();
      fail("No exception should be thrown");
   }
}
 
Example 19
Project: bruxelas   File: TalkerRestController.java   View source code 6 votes vote down vote up
@RequestMapping(value="/languages", produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<String> getLanguages(){
	logger.info( "getLanguages()..." );
	ResponseEntity<String> responseEntity = null;
	try {
		List<Language> languages = this.talkerService.findAllLanguages();			
		
		HttpHeaders responseHeaders = new HttpHeaders();
		String talkerJson = new ObjectMapper().writeValueAsString(languages);
		responseEntity = new ResponseEntity<String>(talkerJson, responseHeaders, HttpStatus.OK);
	} catch (Exception e) {
		logger.error(e.getMessage());
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
	}
	return responseEntity;
}
 
Example 20
Project: SensorThingsManager   File: ControllerScene.java   View source code 5 votes vote down vote up
private void saveServerList() {
    try {
        File serversFile = new File("servers.json");
        final ObjectMapper mapper = ObjectMapperFactory.get();
        mapper.writeValue(serversFile, servers);
    } catch (IOException ex) {
        LOGGER.error("Failed to save server list.", ex);
    }
}
 
Example 21
Project: SensorThingsManager   File: EntityGuiController.java   View source code 5 votes vote down vote up
@Override
public void saveFields() {
    entity.setName(textName.getText());
    entity.setDescription(textDescription.getText());
    entity.setEncodingType(textEncodingType.getText());
    final ObjectMapper mapper = ObjectMapperFactory.get();
    try {
        JsonNode json = mapper.readTree(textMetadata.getText());
        entity.setMetadata(json);
    } catch (IOException ex) {
        LOGGER.error("Not valid json.", ex);
    }
}
 
Example 22
Project: devops-cstack   File: JsonConverter.java   View source code 5 votes vote down vote up
public static List<Image> getImages(String response) {
	List<Image> images = new ArrayList<>();
	ObjectMapper mapper = new ObjectMapper();
	try {
		images = mapper.readValue(response, new TypeReference<List<Image>>() {
		});
	} catch (IOException e) {
		e.printStackTrace();
	}
	return images;
}
 
Example 23
Project: xm-ms-entity   File: XmEntitySpecUnitTest.java   View source code 5 votes vote down vote up
@Test
public void testParseXmEntitySpecFromYmlForSeveralTenants() throws IOException {
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    String[] tenants = {"test", "resinttest"};
    String configName;

    for (String tenant : tenants) {
        configName = "config/specs/xmentityspec-" + tenant.toLowerCase() + ".yml";
        InputStream cfgInputStream = new ClassPathResource(configName).getInputStream();
        XmEntitySpec xmEntitySpec = mapper.readValue(cfgInputStream, XmEntitySpec.class);
        assertNotNull(xmEntitySpec);
    }
}
 
Example 24
Project: dragoman   File: HttpServerSimulatorVerticle.java   View source code 5 votes vote down vote up
private ObjectMapper createObjectMapper() {
  ObjectMapper objectMapper = new ObjectMapper();
  objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
  objectMapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false);

  return objectMapper;
}
 
Example 25
Project: CS6310O01   File: Instructor.java   View source code 5 votes vote down vote up
/**
 * Serialize a list of objects with a particular set of attributes
 * @param view
 * @return
 * @throws IOException 
 */
public JsonNode jsonSerialization(Class view) throws IOException
{
    ObjectMapper mapper = new ObjectMapper();
    
    DateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
    mapper.setDateFormat(myDateFormat); 
    mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
    
    ObjectWriter writer = mapper.writerWithView(view);
    JsonNode response = mapper.readTree(writer.writeValueAsString(this));
    return response;
}
 
Example 26
Project: streamsx.jmxclients   File: RootResource.java   View source code 5 votes vote down vote up
@Path("instance/resourceMetrics")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getInstanceResourceMetrics() throws StreamsTrackerException, WebApplicationException, JsonProcessingException {
    StreamsInstanceTracker jobTracker = StreamsInstanceTracker.getInstance();
    ObjectMapper om = new ObjectMapper();

    return Response.status(Response.Status.OK).entity(
               om.writeValueAsString(jobTracker.getInstanceResourceMetrics())).build();
}
 
Example 27
Project: swordfish-service   File: JsonTransformConfig.java   View source code 5 votes vote down vote up
@Bean
public ResourceConverter resourceConverter() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE);

    return new ResourceConverter(objectMapper,
            User.class,
            Team.class,
            Notification.class
    );
}
 
Example 28
Project: databricks-client-java   File: ListResponseDTO.java   View source code 5 votes vote down vote up
@Override
public String toString() {
    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    try {
        return ow.writeValueAsString(this);
    } catch (JsonProcessingException e) {
        return "Could Not Marshal Object to JSON";
    }
}
 
Example 29
Project: spring-cloud-skipper   File: AppDeployerData.java   View source code 5 votes vote down vote up
public void setDeploymentDataUsingMap(Map<String, String> appNameDeploymentIdMap) {
	ObjectMapper objectMapper = new ObjectMapper();
	try {
		setDeploymentData(objectMapper.writeValueAsString(appNameDeploymentIdMap));
	}
	catch (JsonProcessingException e) {
		throw new SkipperException("Could not serialize appNameDeploymentIdMap", e);
	}
}
 
Example 30
Project: flowing-retail   File: MessageListener.java   View source code 5 votes vote down vote up
/**
 * Very generic listener for simplicity. It takes all events and checks, if a 
 * flow instance is interested. If yes, they are correlated, 
 * otherwise they are just discarded.
 *  
 * It might make more sense to handle each and every message type individually.
 */
@StreamListener(target = Sink.INPUT, 
    condition="payload.messageType.toString().endsWith('Event')")
@Transactional
public void messageReceived(String messageJson) throws Exception {
  Message<JsonNode> message = new ObjectMapper().readValue( //
      messageJson, //
      new TypeReference<Message<JsonNode>>() {});
  
  long correlatingInstances = camunda.getRuntimeService().createExecutionQuery() //
    .messageEventSubscriptionName(message.getMessageType()) //
    .processInstanceBusinessKey(message.getTraceId()) //
    .count();
  
  if (correlatingInstances==1) {
    System.out.println("Correlating " + message + " to waiting flow instance");
    
    camunda.getRuntimeService().createMessageCorrelation(message.getMessageType())
      .processInstanceBusinessKey(message.getTraceId())
      .setVariable(//
          "PAYLOAD_" + message.getMessageType(), // 
          SpinValues.jsonValue(message.getPayload().toString()).create())//
      .correlateWithResult();
  } else {
    // ignoring event, not interested
    System.out.println("Order context ignores event '" + message.getMessageType() + "'");
  }
  
}
 
Example 31
Project: syndesis   File: ErrorMap.java   View source code 5 votes vote down vote up
/**
 * Performs best effort to parse the rawMsg. If all parsers fail it returns the raw message.
 *
 * @param rawMsg
 * @return the underlying error message.
 */
public static String from(String rawMsg) {
    if (rawMsg.matches("^\\s*\\<.*")) {
        return parseWith(rawMsg, new XmlMapper());
    }
    if (rawMsg.matches("^\\s*\\{.*")) {
        return parseWith(rawMsg, new ObjectMapper());
    }
    return rawMsg;
}
 
Example 32
Project: CS6310O01   File: Program.java   View source code 5 votes vote down vote up
/**
 * Des-Serialize an object who was in json format
 * @param jsonObject
 * @return
 * @throws Exception 
 */
public static Program jsonDesSerialization(JsonNode jsonObject) throws Exception
{
    Program object;
    ObjectMapper mapper = new ObjectMapper();
    DateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
    mapper.setDateFormat(myDateFormat); 
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    object = mapper.convertValue(jsonObject,Program.class);
    return object;
}
 
Example 33
Project: Apache-Spark-2x-for-Java-Developers   File: StateFulProcessingExample.java   View source code 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException {

		System.setProperty("hadoop.home.dir", "C:\\softwares\\Winutils");

		SparkSession sparkSession = SparkSession.builder().master("local[*]").appName("Stateful Streaming Example")
				.config("spark.sql.warehouse.dir", "file:////C:/Users/sgulati/spark-warehouse").getOrCreate();

		JavaStreamingContext jssc= new JavaStreamingContext(new JavaSparkContext(sparkSession.sparkContext()),
				Durations.milliseconds(1000));
		JavaReceiverInputDStream<String> inStream = jssc.socketTextStream("10.204.136.223", 9999);
		jssc.checkpoint("C:\\Users\\sgulati\\spark-checkpoint");

		JavaDStream<FlightDetails> flightDetailsStream = inStream.map(x -> {
			ObjectMapper mapper = new ObjectMapper();
			return mapper.readValue(x, FlightDetails.class);
		});
		
		

		JavaPairDStream<String, FlightDetails> flightDetailsPairStream = flightDetailsStream
				.mapToPair(f -> new Tuple2<String, FlightDetails>(f.getFlightId(), f));

		Function3<String, Optional<FlightDetails>, State<List<FlightDetails>>, Tuple2<String, Double>> mappingFunc = (
				flightId, curFlightDetail, state) -> {
			List<FlightDetails> details = state.exists() ? state.get() : new ArrayList<>();

			boolean isLanded = false;

			if (curFlightDetail.isPresent()) {
				details.add(curFlightDetail.get());
				if (curFlightDetail.get().isLanded()) {
					isLanded = true;
				}
			}
			Double avgSpeed = details.stream().mapToDouble(f -> f.getTemperature()).average().orElse(0.0);

			if (isLanded) {
				state.remove();
			} else {
				state.update(details);
			}
			return new Tuple2<String, Double>(flightId, avgSpeed);
		};

		JavaMapWithStateDStream<String, FlightDetails, List<FlightDetails>, Tuple2<String, Double>> streamWithState = flightDetailsPairStream
				.mapWithState(StateSpec.function(mappingFunc).timeout(Durations.minutes(5)));
		
		streamWithState.print();
		jssc.start();
		jssc.awaitTermination();
	}
 
Example 34
Project: device-telemetry-java   File: Rules.java   View source code 5 votes vote down vote up
public CompletionStage<RuleServiceModel> postAsync(
    RuleServiceModel ruleServiceModel) {

    ObjectNode jsonData = new ObjectMapper().createObjectNode();
    jsonData.put("Data", ruleServiceModel.toJson().toString());

    return this.prepareRequest(null)
        .post(jsonData.toString())
        .handle((result, error) -> {
            if (result.getStatus() != OK) {
                log.error("Key value storage error code {}",
                    result.getStatusText());
                throw new CompletionException(
                    new ExternalDependencyException(result.getStatusText()));
            }

            if (error != null) {
                log.error("Key value storage request error: {}",
                    error.getMessage());
                throw new CompletionException(
                    new ExternalDependencyException(
                        "Could not connect to key value storage " +
                            error.getMessage()));
            }

            try {
                return getServiceModelFromJson(
                    Json.parse(result.getBody()));
            } catch (Exception e) {
                log.error("Could not parse result from Key Value Storage: {}",
                    e.getMessage());
                throw new CompletionException(
                    new ExternalDependencyException(
                        "Could not parse result from Key Value Storage"));
            }
        });
}
 
Example 35
Project: databricks-client-java   File: S3StorageInfoDTO.java   View source code 5 votes vote down vote up
@Override
public String toString() {
    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    try {
        return ow.writeValueAsString(this);
    } catch (JsonProcessingException e) {
        return "Could Not Marshal Object to JSON";
    }
}
 
Example 36
Project: crnk-framework   File: CrnkTestFeature.java   View source code 5 votes vote down vote up
public CrnkTestFeature(
		ObjectMapper objectMapper,
		QueryParamsBuilder queryParamsBuilder,
		JsonServiceLocator jsonServiceLocator) {
	super(objectMapper, queryParamsBuilder, jsonServiceLocator);
	testRequestFilter = new TestRequestFilter();
}
 
Example 37
Project: databricks-client-java   File: CronScheduleDTO.java   View source code 5 votes vote down vote up
@Override
public String toString() {
    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    try {
        return ow.writeValueAsString(this);
    } catch (JsonProcessingException e) {
        return "Could Not Marshal Object to JSON";
    }
}
 
Example 38
Project: london   File: Resources.java   View source code 5 votes vote down vote up
private Conf readConf() throws Exception {
    InputStream is = Resources.class.getResourceAsStream("/conf.json");
    try {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(is, Conf.class);
    } finally {
        try {
            is.close();
        } catch (IOException e) {

        }
    }
}
 
Example 39
Project: SpringBootStudy   File: LogAspect.java   View source code 5 votes vote down vote up
/**
 * 环绕通知 用于拦截Controller层记录用户的操作
 */
@Around("controllerAspect()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {

    logger.info("===> 执行controller - 环绕通知.");
    if(logger.isInfoEnabled()){
        logger.info("===> around: {}", pjp);
    }

    RequestAttributes ra = RequestContextHolder.getRequestAttributes();
    ServletRequestAttributes sra = (ServletRequestAttributes) ra;
    HttpServletRequest request = sra.getRequest();

    String url = request.getRequestURL().toString();
    String method = request.getMethod();
    String uri = request.getRequestURI();
    String queryString = request.getQueryString();
    logger.info("===> 请求开始:");
    logger.info("===> 请求参数: url: {}, method: {}, uri: {}, params: {}", url, method, uri, queryString);

    // result的值就是被拦截方法的返回值
    Object result = pjp.proceed();
    ObjectMapper mapper = new ObjectMapper();
    String resutlStr = mapper.writeValueAsString(result);
    logger.info("===> 请求结束:");
    logger.info("===> 请求结束: Controller返回值是:{}", resutlStr);

    return result;
}
 
Example 40
Project: rest-modeling-framework   File: CollectionGenerator.java   View source code 5 votes vote down vote up
public List<File> generate(final File outputPath, Api api) throws IOException {
    final URL resourcePath = Resources.getResource("templates/postman/");
    final List<URL> files = Helper.getTemplatesFromDirectory("templates/postman/");
    final ObjectMapper mapper = new ObjectMapper();

    final List<File> f = Lists.newArrayList();
    for (URL staticFile : files) {
        final String content = generateContent(staticFile, api);
        final String outputFileName = staticFile.toString()
                .replace(".stg", "")
                .replace(resourcePath.toString(), "");
        final File outputFile = new File(
                outputPath,
                outputFileName
        );
        f.add(generateFile(content, outputFile));
        if (outputFileName.endsWith("json")) {
            try {
                mapper.readTree(content);
            } catch (JsonParseException e) {
                System.out.println("Error generating " + outputFileName + ": Invalid JSON");
                System.out.println(e);
            }
        }
    }
    f.add(copyFile(Resources.getResource("templates/postman/connection_settings.png").openStream(), new File(outputPath, "connection_settings.png")));

    return f;
}