Java Code Examples for org.codehaus.jackson.map.ObjectMapper

The following are top voted examples for showing how to use org.codehaus.jackson.map.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: pyroclast-java   File: ReadCommitParser.java   Source Code and License 7 votes vote down vote up
@Override
public ReadCommitResult parseResponse(HttpResponse response, ObjectMapper mapper) throws IOException, PyroclastAPIException {
    int status = response.getStatusLine().getStatusCode();

    switch (status) {
        case 200:
            return new ReadCommitResult(true);
        case 400:
            throw new MalformedEventException();

        case 401:
            throw new UnauthorizedAccessException();

        default:
            throw new UnknownAPIException(response.getStatusLine().toString());
    }
}
 
Example 2
Project: chatbot   File: SpotlightService.java   Source Code and License 7 votes vote down vote up
public String search(String query) {
    try {
        String url = "?text=" + Utility.urlEncode(query) + "&confidence=" + confidence;
        HttpGet httpGet = new HttpGet(URL + url);
        httpGet.addHeader("Accept", "application/json");
        HttpResponse response = client.execute(httpGet);

        // Error Scenario
        if(response.getStatusLine().getStatusCode() >= 400) {
            logger.error("Spotlight Service could not answer due to: " + response.getStatusLine());
            return null;
        }
        else {
            String entities = EntityUtils.toString(response.getEntity());
            JsonNode entity = new ObjectMapper().readTree(entities).get("Resources").get(0);
            return entity.get("@URI").getTextValue();
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 3
Project: hadoop   File: StatePool.java   Source Code and License 7 votes vote down vote up
private void write(DataOutput out) throws IOException {
  // This is just a JSON experiment
  System.out.println("Dumping the StatePool's in JSON format.");
  ObjectMapper outMapper = new ObjectMapper();
  outMapper.configure(
      SerializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS, true);
  // define a module
  SimpleModule module = new SimpleModule("State Serializer",  
      new Version(0, 1, 1, "FINAL"));
  // add the state serializer
  //module.addSerializer(State.class, new StateSerializer());

  // register the module with the object-mapper
  outMapper.registerModule(module);

  JsonFactory outFactory = outMapper.getJsonFactory();
  JsonGenerator jGen = 
    outFactory.createJsonGenerator((DataOutputStream)out, JsonEncoding.UTF8);
  jGen.useDefaultPrettyPrinter();

  jGen.writeObject(this);
  jGen.close();
}
 
Example 4
Project: angel   File: ProtobufRpcEngine.java   Source Code and License 6 votes vote down vote up
/**
 * Logs an RPC response to the LOG file, producing valid JSON objects for client Operations.
 *
 * @param params The parameters received in the call.
 * @param methodName The name of the method invoked
 * @param call The string representation of the call
 * @param tag The tag that will be used to indicate this event in the log.
 * @param startTime The time that the call was initiated, in ms.
 * @param processingTime The duration that the call took to run, in ms.
 * @param qTime The duration that the call spent on the queue prior to being initiated, in ms.
 * @param responseSize The size in bytes of the response buffer.
 */
void logResponse(Object[] params, String methodName, String call, String tag, long startTime,
    int processingTime, int qTime, long responseSize) throws IOException {
  // for JSON encoding
  ObjectMapper mapper = new ObjectMapper();
  // base information that is reported regardless of type of call
  Map<String, Object> responseInfo = new HashMap<String, Object>();
  responseInfo.put("starttimems", startTime);
  responseInfo.put("processingtimems", processingTime);
  responseInfo.put("queuetimems", qTime);
  responseInfo.put("responsesize", responseSize);
  responseInfo.put("class", instance.getClass().getSimpleName());
  responseInfo.put("method", methodName);
  responseInfo.put("call", call);
  /*
   * LOG.warn("(response" + tag + "): " + mapper.writeValueAsString(responseInfo));
   */
}
 
Example 5
Project: ditb   File: TestTableScan.java   Source Code and License 6 votes vote down vote up
@Test
public void testScanningUnknownColumnJson() throws IOException, JAXBException {
  // Test scanning particular columns with limit.
  StringBuilder builder = new StringBuilder();
  builder.append("/*");
  builder.append("?");
  builder.append(Constants.SCAN_COLUMN + "=a:test");
  Response response = client.get("/" + TABLE  + builder.toString(),
    Constants.MIMETYPE_JSON);
  assertEquals(200, response.getCode());
  assertEquals(Constants.MIMETYPE_JSON, response.getHeader("content-type"));
  ObjectMapper mapper = new JacksonProvider().locateMapper(CellSetModel.class,
    MediaType.APPLICATION_JSON_TYPE);
  CellSetModel model = mapper.readValue(response.getStream(), CellSetModel.class);
  int count = TestScannerResource.countCellSet(model);
  assertEquals(0, count);
}
 
Example 6
Project: pyroclast-java   File: ReadAggregateParser.java   Source Code and License 6 votes vote down vote up
@Override
public ReadAggregateResult parseResponse(HttpResponse response, ObjectMapper mapper) throws IOException, PyroclastAPIException {
    int status = response.getStatusLine().getStatusCode();

    switch (status) {
        case 200:
            HttpEntity entity = response.getEntity();
            StringWriter writer = new StringWriter();
            IOUtils.copy(entity.getContent(), writer, "UTF-8");
            String json = writer.toString();

            return mapper.readValue(json, ReadAggregateResult.class);
        case 400:
            throw new MalformedEventException();

        case 401:
            throw new UnauthorizedAccessException();

        default:
            throw new UnknownAPIException(response.getStatusLine().toString());
    }
}
 
Example 7
Project: jwala   File: GroupLevelAppResourceHandler.java   Source Code and License 6 votes vote down vote up
private void updateAppTemplatesWhenDeployToJvmsChanged(final ResourceIdentifier resourceIdentifier, final String resourceName, final String previousMetaData, final String updatedMetaData) {
    try {
        ResourceTemplateMetaData oldMetaData = new ObjectMapper().readValue(previousMetaData, ResourceTemplateMetaData.class);
        ResourceTemplateMetaData newMetaData = new ObjectMapper().readValue(updatedMetaData, ResourceTemplateMetaData.class);
        boolean previousDeployToJvms = oldMetaData.getEntity().getDeployToJvms();
        boolean newDeployToJvms = newMetaData.getEntity().getDeployToJvms();
        if (previousDeployToJvms != newDeployToJvms) {
            Group group = groupPersistenceService.getGroup(resourceIdentifier.groupName);
            if (newDeployToJvms) {
                // deployToJvms was changed to true - need to create the JVM templates
                JpaGroupAppConfigTemplate appTemplate = resourceDao.getGroupLevelAppResource(resourceName, resourceIdentifier.webAppName, resourceIdentifier.groupName);
                newMetaData.setJsonData(updatedMetaData);
                createJvmTemplateFromAppResource(resourceIdentifier, appTemplate.getTemplateContent(), newMetaData, group);
            } else {
                // deployToJvms was to false - need to delete the JVM templates
                for (Jvm jvm : group.getJvms()) {
                    resourceDao.deleteAppResource(resourceName, resourceIdentifier.webAppName, jvm.getJvmName());
                }
            }
        }
    } catch (IOException ioe) {
        final String errorMsg = MessageFormat.format("Failed to parse meta data for war {0} in application {1} during an update of the meta data", resourceName, resourceIdentifier.webAppName);
        LOGGER.error(errorMsg, ioe);
        throw new GroupLevelAppResourceHandlerException(errorMsg);
    }
}
 
Example 8
Project: hadoop-oss   File: HttpExceptionUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a HTTP servlet response serializing the exception in it as JSON.
 *
 * @param response the servlet response
 * @param status the error code to set in the response
 * @param ex the exception to serialize in the response
 * @throws IOException thrown if there was an error while creating the
 * response
 */
public static void createServletExceptionResponse(
    HttpServletResponse response, int status, Throwable ex)
    throws IOException {
  response.setStatus(status);
  response.setContentType(APPLICATION_JSON_MIME);
  Map<String, Object> json = new LinkedHashMap<String, Object>();
  json.put(ERROR_MESSAGE_JSON, getOneLineMessage(ex));
  json.put(ERROR_EXCEPTION_JSON, ex.getClass().getSimpleName());
  json.put(ERROR_CLASSNAME_JSON, ex.getClass().getName());
  Map<String, Object> jsonResponse = new LinkedHashMap<String, Object>();
  jsonResponse.put(ERROR_JSON, json);
  ObjectMapper jsonMapper = new ObjectMapper();
  Writer writer = response.getWriter();
  jsonMapper.writerWithDefaultPrettyPrinter().writeValue(writer, jsonResponse);
  writer.flush();
}
 
Example 9
Project: hadoop   File: StateDeserializer.java   Source Code and License 6 votes vote down vote up
@Override
public StatePair deserialize(JsonParser parser, 
                             DeserializationContext context)
throws IOException, JsonProcessingException {
  ObjectMapper mapper = (ObjectMapper) parser.getCodec();
  // set the state-pair object tree
  ObjectNode statePairObject = (ObjectNode) mapper.readTree(parser);
  Class<?> stateClass = null;
  
  try {
    stateClass = 
      Class.forName(statePairObject.get("className").getTextValue().trim());
  } catch (ClassNotFoundException cnfe) {
    throw new RuntimeException("Invalid classname!", cnfe);
  }
  
  String stateJsonString = statePairObject.get("state").toString();
  State state = (State) mapper.readValue(stateJsonString, stateClass);
  
  return new StatePair(state);
}
 
Example 10
Project: AppCoins-ethereumj   File: DifficultyTestSuite.java   Source Code and License 6 votes vote down vote up
public DifficultyTestSuite(String json) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    JavaType type = mapper.getTypeFactory().
            constructMapType(HashMap.class, String.class, DifficultyTestCase.class);

    Map<String, DifficultyTestCase> caseMap = new ObjectMapper().readValue(json, type);

    for (Map.Entry<String, DifficultyTestCase> e : caseMap.entrySet()) {
        e.getValue().setName(e.getKey());
        testCases.add(e.getValue());
    }

    Collections.sort(testCases, new Comparator<DifficultyTestCase>() {
        @Override
        public int compare(DifficultyTestCase t1, DifficultyTestCase t2) {
            return t1.getName().compareTo(t2.getName());
        }
    });
}
 
Example 11
Project: hadoop   File: FSImageLoader.java   Source Code and License 6 votes vote down vote up
/**
 * Return the JSON formatted list of the files in the specified directory.
 * @param path a path specifies a directory to list
 * @return JSON formatted file list in the directory
 * @throws IOException if failed to serialize fileStatus to JSON.
 */
String listStatus(String path) throws IOException {
  StringBuilder sb = new StringBuilder();
  ObjectMapper mapper = new ObjectMapper();
  List<Map<String, Object>> fileStatusList = getFileStatusList(path);
  sb.append("{\"FileStatuses\":{\"FileStatus\":[\n");
  int i = 0;
  for (Map<String, Object> fileStatusMap : fileStatusList) {
    if (i++ != 0) {
      sb.append(',');
    }
    sb.append(mapper.writeValueAsString(fileStatusMap));
  }
  sb.append("\n]}}\n");
  return sb.toString();
}
 
Example 12
Project: hadoop   File: JsonUtil.java   Source Code and License 6 votes vote down vote up
public static List<String> toXAttrNames(final Map<?, ?> json)
    throws IOException {
  if (json == null) {
    return null;
  }

  final String namesInJson = (String) json.get("XAttrNames");
  ObjectReader reader = new ObjectMapper().reader(List.class);
  final List<Object> xattrs = reader.readValue(namesInJson);
  final List<String> names =
    Lists.newArrayListWithCapacity(json.keySet().size());

  for (Object xattr : xattrs) {
    names.add((String) xattr);
  }
  return names;
}
 
Example 13
Project: pyroclast-java   File: BulkProduceEventsParser.java   Source Code and License 6 votes vote down vote up
@Override
public ProducedEventsResult parseResponse(HttpResponse response, ObjectMapper mapper) throws IOException, PyroclastAPIException {
    int status = response.getStatusLine().getStatusCode();

    switch (status) {
        case 200:
            HttpEntity entity = response.getEntity();
            StringWriter writer = new StringWriter();
            IOUtils.copy(entity.getContent(), writer, "UTF-8");
            String json = writer.toString();

            return mapper.readValue(json, ProducedEventsResult.class);
        case 400:
            throw new MalformedEventException();

        case 401:
            throw new UnauthorizedAccessException();

        default:
            throw new UnknownAPIException(response.getStatusLine().toString());
    }
}
 
Example 14
Project: hadoop   File: TestHttpExceptionUtils.java   Source Code and License 6 votes vote down vote up
@Test
public void testValidateResponseJsonErrorUnknownException()
    throws IOException {
  Map<String, Object> json = new HashMap<String, Object>();
  json.put(HttpExceptionUtils.ERROR_EXCEPTION_JSON, "FooException");
  json.put(HttpExceptionUtils.ERROR_CLASSNAME_JSON, "foo.FooException");
  json.put(HttpExceptionUtils.ERROR_MESSAGE_JSON, "EX");
  Map<String, Object> response = new HashMap<String, Object>();
  response.put(HttpExceptionUtils.ERROR_JSON, json);
  ObjectMapper jsonMapper = new ObjectMapper();
  String msg = jsonMapper.writeValueAsString(response);
  InputStream is = new ByteArrayInputStream(msg.getBytes());
  HttpURLConnection conn = Mockito.mock(HttpURLConnection.class);
  Mockito.when(conn.getErrorStream()).thenReturn(is);
  Mockito.when(conn.getResponseMessage()).thenReturn("msg");
  Mockito.when(conn.getResponseCode()).thenReturn(
      HttpURLConnection.HTTP_BAD_REQUEST);
  try {
    HttpExceptionUtils.validateResponse(conn, HttpURLConnection.HTTP_CREATED);
    Assert.fail();
  } catch (IOException ex) {
    Assert.assertTrue(ex.getMessage().contains("EX"));
    Assert.assertTrue(ex.getMessage().contains("foo.FooException"));
  }
}
 
Example 15
Project: devops-cstack   File: JsonConverter.java   Source Code and License 6 votes vote down vote up
public static List<Message> getMessage( String response )
{
    ObjectMapper mapper = new ObjectMapper();
    List<Message> messages = null;
    try
    {
        messages = mapper.readValue( response, new TypeReference<List<Message>>()
        {
        } );
    }
    catch ( IOException e )
    {
        e.printStackTrace();
    }
    return messages;
}
 
Example 16
Project: talchain   File: DifficultyTestSuite.java   Source Code and License 6 votes vote down vote up
public DifficultyTestSuite(String json) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    JavaType type = mapper.getTypeFactory().
            constructMapType(HashMap.class, String.class, DifficultyTestCase.class);

    Map<String, DifficultyTestCase> caseMap = new ObjectMapper().readValue(json, type);

    for (Map.Entry<String, DifficultyTestCase> e : caseMap.entrySet()) {
        e.getValue().setName(e.getKey());
        testCases.add(e.getValue());
    }

    Collections.sort(testCases, new Comparator<DifficultyTestCase>() {
        @Override
        public int compare(DifficultyTestCase t1, DifficultyTestCase t2) {
            return t1.getName().compareTo(t2.getName());
        }
    });
}
 
Example 17
Project: hadoop   File: JobHistoryEventHandler.java   Source Code and License 6 votes vote down vote up
@Private
public JsonNode countersToJSON(Counters counters) {
  ObjectMapper mapper = new ObjectMapper();
  ArrayNode nodes = mapper.createArrayNode();
  if (counters != null) {
    for (CounterGroup counterGroup : counters) {
      ObjectNode groupNode = nodes.addObject();
      groupNode.put("NAME", counterGroup.getName());
      groupNode.put("DISPLAY_NAME", counterGroup.getDisplayName());
      ArrayNode countersNode = groupNode.putArray("COUNTERS");
      for (Counter counter : counterGroup) {
        ObjectNode counterNode = countersNode.addObject();
        counterNode.put("NAME", counter.getName());
        counterNode.put("DISPLAY_NAME", counter.getDisplayName());
        counterNode.put("VALUE", counter.getValue());
      }
    }
  }
  return nodes;
}
 
Example 18
Project: tokenapp-backend   File: Etherscan.java   Source Code and License 6 votes vote down vote up
public BigInteger getBalance(String address) throws IOException {
    String s = "https://"+url+"/api" +
            "?module=account" +
            "&action=balance" +
            "&address=" + address +
            "&tag=latest" +
            "&apikey="+apiKey;

    HttpHeaders headers = new HttpHeaders();
    headers.set("User-Agent", options.getUserAgent());

    ResponseEntity<String> res = restTemplate.exchange(s, HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    ObjectMapper objectMapper = new ObjectMapper();
    ReturnSingleValue retVal = objectMapper.readValue(res.getBody(), ReturnSingleValue.class);
    return new BigInteger(retVal.result);
}
 
Example 19
Project: hadoop   File: WebHdfsFileSystem.java   Source Code and License 6 votes vote down vote up
static Map<?, ?> jsonParse(final HttpURLConnection c, final boolean useErrorStream
    ) throws IOException {
  if (c.getContentLength() == 0) {
    return null;
  }
  final InputStream in = useErrorStream? c.getErrorStream(): c.getInputStream();
  if (in == null) {
    throw new IOException("The " + (useErrorStream? "error": "input") + " stream is null.");
  }
  try {
    final String contentType = c.getContentType();
    if (contentType != null) {
      final MediaType parsed = MediaType.valueOf(contentType);
      if (!MediaType.APPLICATION_JSON_TYPE.isCompatible(parsed)) {
        throw new IOException("Content-Type \"" + contentType
            + "\" is incompatible with \"" + MediaType.APPLICATION_JSON
            + "\" (parsed=\"" + parsed + "\")");
      }
    }
    ObjectMapper mapper = new ObjectMapper();
    return mapper.reader(Map.class).readValue(in);
  } finally {
    in.close();
  }
}
 
Example 20
Project: tokenapp-backend   File: Etherscan.java   Source Code and License 6 votes vote down vote up
/**
 * Can process up to 20 contracts
 */
public BigInteger get20Balances(List<String> contract) throws IOException {

    String addresses = String.join(",", contract);
    String s = "https://"+url+"/api" +
            "?module=account" +
            "&action=balancemulti" +
            "&address=" + addresses +
            "&tag=latest" +
            "&apikey="+apiKey;

    HttpHeaders headers = new HttpHeaders();
    headers.set("User-Agent", options.getUserAgent());

    ResponseEntity<String> res = restTemplate.exchange(s, HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    ObjectMapper objectMapper = new ObjectMapper();
    ReturnValues retVal = objectMapper.readValue(res.getBody(), ReturnValues.class);

    BigInteger result = BigInteger.ZERO;
    for(ReturnValues.Result res1: retVal.result) {
        result = result.add(new BigInteger(res1.balance));
    }
    return result;
}
 
Example 21
Project: pyroclast-java   File: ReadAggregatesParser.java   Source Code and License 6 votes vote down vote up
@Override
public ReadAggregatesResult parseResponse(HttpResponse response, ObjectMapper mapper) throws IOException, PyroclastAPIException {
    int status = response.getStatusLine().getStatusCode();

    switch (status) {
        case 200:
            HttpEntity entity = response.getEntity();
            StringWriter writer = new StringWriter();
            IOUtils.copy(entity.getContent(), writer, "UTF-8");
            String json = writer.toString();

            return mapper.readValue(json, ReadAggregatesResult.class);
        case 400:
            throw new MalformedEventException();

        case 401:
            throw new UnauthorizedAccessException();

        default:
            throw new UnknownAPIException(response.getStatusLine().toString());
    }
}
 
Example 22
Project: Mastering-Apache-Storm   File: BingMapsLookup.java   Source Code and License 6 votes vote down vote up
/**
 * Gets the State of the Tweet by checking the InputStream.
 * For a sample Bing Maps API response, please check the snippet at the end of this file.
 *
 * @param inputStream Bing Maps API response.
 * @return State of the Tweet as got from Bing Maps API reponse.
 */
@SuppressWarnings("unchecked")
private final static Optional<String> getStateFromJSONResponse(InputStream inputStream) {
	final ObjectMapper mapper = new ObjectMapper();
	try {
		//final Map<String,Object> bingResponse = (Map<String, Object>) mapper.readValue(new File("C:/BingMaps_JSON_Response.json"), Map.class);
		final Map<String,Object> bingResponse = (Map<String, Object>) mapper.readValue(inputStream, Map.class);
		if(200 == Integer.parseInt(String.valueOf(bingResponse.get("statusCode")))) {
			final List<Map<String, Object>> resourceSets = (List<Map<String, Object>>) bingResponse.get("resourceSets");
			if(resourceSets != null && resourceSets.size() > 0){
				final List<Map<String, Object>> resources = (List<Map<String, Object>>) resourceSets.get(0).get("resources");
				if(resources != null && resources.size() > 0){
					final Map<String, Object> address = (Map<String, Object>) resources.get(0).get("address");
					LOGGER.debug("State==>{}", address.get("adminDistrict"));
					return Optional.of((String) address.get("adminDistrict"));
				}
			}
		}
	} catch (final IOException ioException) {
		LOGGER.error(ioException.getMessage(), ioException);
		ioException.printStackTrace();
	}
	return Optional.absent();
}
 
Example 23
Project: personium-core   File: JSONManifestTest.java   Source Code and License 6 votes vote down vote up
/**
 * manifest_jsonのschemaの指定がない場合falseが返却されること.
 * @throws IOException IOException
 */
@SuppressWarnings("unchecked")
@Test
public void manifest_jsonのschemaの指定がない場合falseが返却されること() throws IOException {
    JsonFactory f = new JsonFactory();
    JSONObject json = new JSONObject();
    json.put("bar_version", "1");
    json.put("box_version", "1");
    json.put("DefaultPath", "boxName");
    JsonParser jp = f.createJsonParser(json.toJSONString());
    ObjectMapper mapper = new ObjectMapper();
    jp.nextToken();

    JSONManifest manifest = mapper.readValue(jp, JSONManifest.class);

    assertFalse(manifest.checkSchema());
}
 
Example 24
Project: ethereum-bytecode-analyzer   File: Report.java   Source Code and License 6 votes vote down vote up
private static StringWriter buildStringWriter(List<Node> nodes, List<Edge> edges, Map<EVMEnvironment, SymExecutor> executions) throws ReportException {

        VelocityEngine velocityEngine = new VelocityEngine();
        Properties p = new Properties();
        p.setProperty("resource.loader", "class");
        p.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        velocityEngine.init(p);
        Template template = velocityEngine.getTemplate(TEMPLATE_FILE);
        VelocityContext velocityContext = new VelocityContext();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            velocityContext.put("nodes", objectMapper.writeValueAsString(nodes));
            velocityContext.put("edges", objectMapper.writeValueAsString(edges));
            velocityContext.put("executions", executions);
        } catch (IOException e) {
            logger.error("Error building the report: " + e);
            throw new ReportException("Failed creating ReportItem");
        }
        StringWriter stringWriter = new StringWriter();
        template.merge(velocityContext, stringWriter);
        return stringWriter;
    }
 
Example 25
Project: ureport   File: JsonFunction.java   Source Code and License 6 votes vote down vote up
@Override
public Object execute(List<ExpressionData<?>> dataList, Context context,Cell currentCell){
	if(dataList.size()!=2){
		return null;
	}
	String obj = buildData(dataList.get(0));
	String property=buildData(dataList.get(1));
	
	if(obj==null || property==null || obj.equals("") || property.equals("")){
		return null;
	}
	ObjectMapper mapper=new ObjectMapper();
	try{
		Map<?,?> map=mapper.readValue(obj, HashMap.class);
		return Utils.getProperty(map, property);
	}catch(Exception ex){
		throw new ReportException(ex);
	}
}
 
Example 26
Project: guacamole-auth-callback   File: CallbackAuthenticationProviderModule.java   Source Code and License 6 votes vote down vote up
@Override
protected void configure() {

    // Bind core implementations of guacamole-ext classes
    bind(AuthenticationProvider.class).toInstance(authProvider);
    bind(Environment.class).toInstance(environment);

    // Bind services
    bind(ConfigurationService.class);
    bind(UserDataService.class);

    // Bind singleton ObjectMapper for JSON serialization/deserialization
    bind(ObjectMapper.class).in(Scopes.SINGLETON);

    // Bind singleton Jersey REST client
    bind(Client.class).toInstance(Client.create(CLIENT_CONFIG));

}
 
Example 27
Project: urule   File: PackageServletHandler.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private List<GeneralEntity> buildList(String value){
	try {
		List<GeneralEntity> result=new ArrayList<GeneralEntity>();
		ObjectMapper mapper=new ObjectMapper();
		Map<String,Object> map=mapper.readValue(value, HashMap.class);
		if(map.containsKey("rows")){
			List<Object> list=(List<Object>)map.get("rows");
			for(Object obj:list){
				if(obj instanceof Map){
					GeneralEntity entity=new GeneralEntity((String)map.get("type"));
					entity.putAll((Map)obj);
					result.add(entity);
				}
			}
			return result;
		}else{
			return null;
		}
	} catch (Exception e) {
		throw new RuleException(e);
	}
}
 
Example 28
Project: urule   File: PackageServletHandler.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private Set<GeneralEntity> buildSet(String value){
	try {
		Set<GeneralEntity> result=new HashSet<GeneralEntity>();
		ObjectMapper mapper=new ObjectMapper();
		Map<String,Object> map=mapper.readValue(value, HashMap.class);
		if(map.containsKey("rows")){
			List<Object> list=(List<Object>)map.get("rows");
			for(Object obj:list){
				if(obj instanceof Map){
					GeneralEntity entity=new GeneralEntity((String)map.get("type"));
					entity.putAll((Map)obj);
					result.add(entity);
				}
			}
			return result;
		}else{
			return null;
		}
	} catch (Exception e) {
		throw new RuleException(e);
	}
}
 
Example 29
Project: personium-core   File: EventResource.java   Source Code and License 6 votes vote down vote up
/**
 * リクエストボディを解析してEventオブジェクトを取得する.
 * @param reader Http入力ストリーム
 * @return 解析したEventオブジェクト
 */
protected JSONEvent getRequestBody(final Reader reader) {
    JSONEvent event = null;
    JsonParser jp = null;
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory f = new JsonFactory();
    try {
        jp = f.createJsonParser(reader);
        JsonToken token = jp.nextToken(); // JSONルート要素("{")
        if (token == JsonToken.START_OBJECT) {
            event = mapper.readValue(jp, JSONEvent.class);
        } else {
            throw PersoniumCoreException.Event.JSON_PARSE_ERROR;
        }
    } catch (IOException e) {
        throw PersoniumCoreException.Event.JSON_PARSE_ERROR;
    }
    return event;
}
 
Example 30
Project: FolderSync   File: Auth.java   Source Code and License 6 votes vote down vote up
@Override
public boolean signIn(String u, String p) {
	HttpHeaders headers = new HttpHeaders();
   	headers.setContentType(MediaType.APPLICATION_JSON);
	ObjectMapper mapper=ObjectMapperPool.getMapper();

	String json="";
	try {
		json = mapper.writeValueAsString(new LoginRequest(u, p, fingerPrint.getFingerPrint()));
	
		HttpEntity<String> entity = new HttpEntity<String>(json, headers);
		ResponseEntity<String> response=restTemplate.postForEntity(serverPath.concat(Constants.SIGN_IN_SUFFIX), entity, String.class);
		LoginResponse resp=mapper.readValue(response.getBody(), LoginResponse.class);
		logger.debug("Got login response {}",resp.getResult());
		return resp.getResult();
	} catch (Exception e) {
		logger.error("Parse exception", e);
	}
	return false;
}
 
Example 31
Project: FolderSync   File: Auth.java   Source Code and License 6 votes vote down vote up
@Override
public boolean createNewUser(String u, String p) {
	HttpHeaders headers = new HttpHeaders();
   	headers.setContentType(MediaType.APPLICATION_JSON);
	ObjectMapper mapper=ObjectMapperPool.getMapper();

	String json="";
	try {
		json = mapper.writeValueAsString(new LoginRequest(u, p, fingerPrint.getFingerPrint()));
	
		HttpEntity<String> entity = new HttpEntity<String>(json, headers);
		ResponseEntity<String> response=restTemplate.postForEntity(serverPath.concat(Constants.CREATE_USER_SUFFIX), entity, String.class);
		CreateUserResponse resp=mapper.readValue(response.getBody(), CreateUserResponse.class);
		logger.debug("Got create user response {}",resp.getStatus());
		return resp.isResult();
	} catch (Exception e) {
		logger.error("Parse exception", e);
	}
	return false;
}
 
Example 32
Project: pyroclast-java   File: TopicRecordDeserializer.java   Source Code and License 6 votes vote down vote up
@Override
public TopicRecord deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {
    JsonNode node = jp.getCodec().readTree(jp);
    
    String topic = node.get("topic").asText();
    long partition = node.get("partition").asLong();
    long offset = node.get("offset").asLong();
    long timestamp = node.get("timestamp").asLong();
    
    String key = null;
    if (node.has("key")) {
        key = node.get("key").asText();
    }
    
    Map<Object, Object> value = new ObjectMapper().readValue(node.get("value").toString(), Map.class);
    return new TopicRecord(topic, key, partition, offset, timestamp, value);
}
 
Example 33
Project: personium-core   File: JSONManifestTest.java   Source Code and License 6 votes vote down vote up
/**
 * manifest_jsonのschema値がURL形式でない場合falseが返却されること.
 * @throws IOException IOException
 */
@SuppressWarnings("unchecked")
@Test
public void manifest_jsonのschema値がURL形式でない場合falseが返却されること() throws IOException {
    JsonFactory f = new JsonFactory();
    JSONObject json = new JSONObject();
    json.put("bar_version", "1");
    json.put("box_version", "1");
    json.put("DefaultPath", "boxName");
    json.put("schema", "test");
    JsonParser jp = f.createJsonParser(json.toJSONString());
    ObjectMapper mapper = new ObjectMapper();
    jp.nextToken();

    JSONManifest manifest = mapper.readValue(jp, JSONManifest.class);

    assertFalse(manifest.checkSchema());
}
 
Example 34
Project: jwala   File: JsonCreateJvmDeserializerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testDeserializeJsonCreateJvm() throws Exception {
    final InputStream in = this.getClass().getResourceAsStream("/json-create-jvm-data.json");
    final String jsonData = IOUtils.toString(in, Charset.defaultCharset());

    final ObjectMapper mapper = new ObjectMapper();

    final JsonCreateJvm jsonCreateJvm = mapper.readValue(jsonData, JsonCreateJvm.class);
    assertEquals("my-jvm", jsonCreateJvm.getJvmName());
    assertEquals("some-host", jsonCreateJvm.getHostName());
    assertEquals("jwala", jsonCreateJvm.getUserName());
    assertEquals("/manager", jsonCreateJvm.getStatusPath());
    assertEquals("1", jsonCreateJvm.getJdkMediaId());
    assertTrue(StringUtils.isNotEmpty(jsonCreateJvm.getEncryptedPassword()));
    assertNotEquals("password", jsonCreateJvm.getEncryptedPassword());
    assertEquals("8893", jsonCreateJvm.getAjpPort());
    assertEquals("8889", jsonCreateJvm.getHttpPort());
    assertEquals("8890", jsonCreateJvm.getHttpsPort());
    assertEquals("8891", jsonCreateJvm.getRedirectPort());
    assertEquals("8892", jsonCreateJvm.getShutdownPort());
    assertEquals("1", jsonCreateJvm.getGroupIds().get(0).getGroupId());
}
 
Example 35
Project: hadoop   File: FSNamesystem.java   Source Code and License 6 votes vote down vote up
@Override // FSNamesystemMBean
public String getTopUserOpCounts() {
  if (!topConf.isEnabled) {
    return null;
  }

  Date now = new Date();
  final List<RollingWindowManager.TopWindow> topWindows =
      topMetrics.getTopWindows();
  Map<String, Object> topMap = new TreeMap<String, Object>();
  topMap.put("windows", topWindows);
  topMap.put("timestamp", DFSUtil.dateToIso8601String(now));
  ObjectMapper mapper = new ObjectMapper();
  try {
    return mapper.writeValueAsString(topMap);
  } catch (IOException e) {
    LOG.warn("Failed to fetch TopUser metrics", e);
  }
  return null;
}
 
Example 36
Project: SHIKSHAK   File: SignupService.java   Source Code and License 6 votes vote down vote up
@PUT
@Path("/validate")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response userValidation(User userData) {
	try {
		int flag = 0;
		String emailRcvd = "";

		final ObjectNode node = new ObjectMapper().readValue(userData.toString(), ObjectNode.class);

		if (node.has("email")) {
			emailRcvd = node.get("email").toString().replace("\"", "").trim();
		}

		ResultSet rs = dbobj.openConnection("select email from user");
		while (rs.next()) {
			String userEmail = rs.getString("email");
			if (emailRcvd.equals(userEmail)) {
				flag = 1;
				break;
			}
		}
		if (flag == 1) {
			resp.put("response", "false");
			return Response.ok(resp.toJSONString()).build();
		}
		dbobj.closeConnection(rs);
	} catch (SQLException | IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	resp.put("response", "true");
	return Response.ok(resp.toJSONString()).build();
}
 
Example 37
Project: personium-core   File: BarFileReadRunner.java   Source Code and License 6 votes vote down vote up
/**
 * manifest.jsonのバリデート.
 * @param jp Jsonパーサー
 * @param mapper ObjectMapper
 * @return JSONManifestオブジェクト
 * @throws IOException データの読み込みに失敗した場合
 */
protected JSONManifest manifestJsonValidate(JsonParser jp, ObjectMapper mapper) throws IOException {
    // TODO BARファイルのバージョンチェック
    JSONManifest manifest = null;
    try {
        manifest = mapper.readValue(jp, JSONManifest.class);
    } catch (UnrecognizedPropertyException ex) {
        throw PersoniumCoreException.BarInstall.JSON_FILE_FORMAT_ERROR.params(
                "manifest.json unrecognized property");
    }
    if (manifest.getBarVersion() == null) {
        throw PersoniumCoreException.BarInstall.JSON_FILE_FORMAT_ERROR.params("manifest.json#barVersion");
    }
    if (manifest.getBoxVersion() == null) {
        throw PersoniumCoreException.BarInstall.JSON_FILE_FORMAT_ERROR.params("manifest.json#boxVersion");
    }
    if (manifest.getDefaultPath() == null) {
        throw PersoniumCoreException.BarInstall.JSON_FILE_FORMAT_ERROR.params("manifest.json#DefaultPath");
    }
    return manifest;
}
 
Example 38
Project: hadoop   File: TestHistograms.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws IOException {
  final Configuration conf = new Configuration();
  final FileSystem lfs = FileSystem.getLocal(conf);

  for (String arg : args) {
    Path filePath = new Path(arg).makeQualified(lfs);
    String fileName = filePath.getName();
    if (fileName.startsWith("input")) {
      LoggedDiscreteCDF newResult = histogramFileToCDF(filePath, lfs);
      String testName = fileName.substring("input".length());
      Path goldFilePath = new Path(filePath.getParent(), "gold"+testName);

      ObjectMapper mapper = new ObjectMapper();
      JsonFactory factory = mapper.getJsonFactory();
      FSDataOutputStream ostream = lfs.create(goldFilePath, true);
      JsonGenerator gen = factory.createJsonGenerator(ostream,
          JsonEncoding.UTF8);
      gen.useDefaultPrettyPrinter();
      
      gen.writeObject(newResult);
      
      gen.close();
    } else {
      System.err.println("Input file not started with \"input\". File "+fileName+" skipped.");
    }
  }
}
 
Example 39
Project: hadoop   File: DecayRpcScheduler.java   Source Code and License 5 votes vote down vote up
public String getSchedulingDecisionSummary() {
  Map<Object, Integer> decisions = scheduleCacheRef.get();
  if (decisions == null) {
    return "{}";
  } else {
    try {
      ObjectMapper om = new ObjectMapper();
      return om.writeValueAsString(decisions);
    } catch (Exception e) {
      return "Error: " + e.getMessage();
    }
  }
}
 
Example 40
Project: AppCoins-ethereumj   File: BlockTestSuite.java   Source Code and License 5 votes vote down vote up
public BlockTestSuite(String json) throws IOException {

        ObjectMapper mapper = new ObjectMapper();
        JavaType type = mapper.getTypeFactory().
                constructMapType(HashMap.class, String.class, BlockTestCase.class);

        testCases = new ObjectMapper().readValue(json, type);
    }
 
Example 41
Project: sunbird-lms-service   File: LearnerControllerTest.java   Source Code and License 5 votes vote down vote up
private static String mapToJson(Map map){
  ObjectMapper mapperObj = new ObjectMapper();
  String jsonResp = "";
  try {
    jsonResp = mapperObj.writeValueAsString(map);
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
  return jsonResp;
}
 
Example 42
Project: wherehowsX   File: AzJobChecker.java   Source Code and License 5 votes vote down vote up
/**
 *  Parse the json of flow_data field from execution_flows. Use recursion to handle the nested case.
 * @param flowJson
 * @param flowExecId
 * @return
 * @throws IOException
 */
public List<AzkabanJobExecRecord> parseJson(String flowJson, long flowExecId)
  throws IOException {

  ObjectMapper mapper = new ObjectMapper();
  JsonNode wholeFlow = mapper.readTree(flowJson);
  JsonNode allJobs = wholeFlow.get("nodes");
  String flowPath = wholeFlow.get("projectName").asText() + ":" + wholeFlow.get("flowId").asText();
  List<AzkabanJobExecRecord> results = parseJsonHelper(allJobs, flowExecId, flowPath);
  AzkabanJobExecUtil.sortAndSet(results);
  return results;
}
 
Example 43
Project: DailyReader   File: CacheHelper.java   Source Code and License 5 votes vote down vote up
private CacheHelper(String rootPath) {
    mRootDir = new File(rootPath);
    if (!mRootDir.exists()) {
        mRootDir.mkdir();
    }

    mMapper = new ObjectMapper();
}
 
Example 44
Project: hadoop-oss   File: DecayRpcScheduler.java   Source Code and License 5 votes vote down vote up
public String getCallVolumeSummary() {
  try {
    ObjectMapper om = new ObjectMapper();
    return om.writeValueAsString(callCounts);
  } catch (Exception e) {
    return "Error: " + e.getMessage();
  }
}
 
Example 45
Project: hadoop   File: TestJsonUtil.java   Source Code and License 5 votes vote down vote up
@Test
public void testGetXAttrFromJson() throws IOException {
  String jsonString = 
      "{\"XAttrs\":[{\"name\":\"user.a1\",\"value\":\"0x313233\"}," +
      "{\"name\":\"user.a2\",\"value\":\"0x313131\"}]}";
  ObjectReader reader = new ObjectMapper().reader(Map.class);
  Map<?, ?> json = reader.readValue(jsonString);

  // Get xattr: user.a2
  byte[] value = JsonUtil.getXAttr(json, "user.a2");
  Assert.assertArrayEquals(XAttrCodec.decodeValue("0x313131"), value);
}
 
Example 46
Project: hadoop-oss   File: KMSJSONReader.java   Source Code and License 5 votes vote down vote up
@Override
public Map readFrom(Class<Map> type, Type genericType,
    Annotation[] annotations, MediaType mediaType,
    MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
    throws IOException, WebApplicationException {
  ObjectMapper mapper = new ObjectMapper();
  return mapper.readValue(entityStream, type);
}
 
Example 47
Project: hadoop   File: TestRMNMInfo.java   Source Code and License 5 votes vote down vote up
@Test
public void testRMNMInfo() throws Exception {
  if (!(new File(MiniMRYarnCluster.APPJAR)).exists()) {
    LOG.info("MRAppJar " + MiniMRYarnCluster.APPJAR
         + " not found. Not running test.");
    return;
  }
  
  RMContext rmc = mrCluster.getResourceManager().getRMContext();
  ResourceScheduler rms = mrCluster.getResourceManager()
                                                 .getResourceScheduler();
  RMNMInfo rmInfo = new RMNMInfo(rmc,rms);
  String liveNMs = rmInfo.getLiveNodeManagers();
  ObjectMapper mapper = new ObjectMapper();
  JsonNode jn = mapper.readTree(liveNMs);
  Assert.assertEquals("Unexpected number of live nodes:",
                                             NUMNODEMANAGERS, jn.size());
  Iterator<JsonNode> it = jn.iterator();
  while (it.hasNext()) {
    JsonNode n = it.next();
    Assert.assertNotNull(n.get("HostName"));
    Assert.assertNotNull(n.get("Rack"));
    Assert.assertTrue("Node " + n.get("NodeId") + " should be RUNNING",
            n.get("State").asText().contains("RUNNING"));
    Assert.assertNotNull(n.get("NodeHTTPAddress"));
    Assert.assertNotNull(n.get("LastHealthUpdate"));
    Assert.assertNotNull(n.get("HealthReport"));
    Assert.assertNotNull(n.get("NodeManagerVersion"));
    Assert.assertNotNull(n.get("NumContainers"));
    Assert.assertEquals(
            n.get("NodeId") + ": Unexpected number of used containers",
            0, n.get("NumContainers").asInt());
    Assert.assertEquals(
            n.get("NodeId") + ": Unexpected amount of used memory",
            0, n.get("UsedMemoryMB").asInt());
    Assert.assertNotNull(n.get("AvailableMemoryMB"));
  }
}
 
Example 48
Project: personium-core   File: BarFileValidateTest.java   Source Code and License 5 votes vote down vote up
/**
 * 正しいJSONデータを与えてJSONmanifestオブジェクトが返却される.
 */
@Test
@SuppressWarnings({"unchecked" })
public void 正しいJSONデータを与えてJSONManifestオブジェクトが返却される() {
    JsonFactory f = new JsonFactory();
    JSONObject json = new JSONObject();
    json.put("bar_version", "1");
    json.put("box_version", "1");
    json.put("DefaultPath", "boxName");
    json.put("schema", "http://app1.example.com");

    try {
        JsonParser jp = f.createJsonParser(json.toJSONString());
        ObjectMapper mapper = new ObjectMapper();
        jp.nextToken();

        TestBarRunner testBarRunner = new TestBarRunner();
        JSONManifest manifest = testBarRunner.manifestJsonValidate(jp, mapper);

        assertNotNull(manifest);
        assertEquals("1", manifest.getBarVersion());
        assertEquals("1", manifest.getBoxVersion());
        assertEquals("boxName", manifest.getDefaultPath());
        assertEquals("http://app1.example.com", manifest.getSchema());
    } catch (IOException e) {
        fail(e.getMessage());
    }
}
 
Example 49
Project: wechat-mall   File: JsonUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 输入和输出都有可能为null, 注意null检查
 */
@Nullable
public static <E> String bean2Json(ObjectMapper m, E e) {
    try {
        return m.writeValueAsString(e);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    return null;
}
 
Example 50
Project: wechat-mall   File: JsonUtil.java   Source Code and License 5 votes vote down vote up
public static JsonNode jsonTree(ObjectMapper m, String json) {
    try {
        JsonParser jp = factory.createJsonParser(new StringReader(json));
        m.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
        return m.readTree(jp);
    } catch (Exception e) {
        System.out.println(e);
    }
    return NULL_NODE;
}
 
Example 51
Project: cf-java-client-sap   File: CloudControllerClientImpl.java   Source Code and License 5 votes vote down vote up
private HttpEntity<MultiValueMap<String, ?>> generatePartialResourceRequest(UploadApplicationPayload application,
    CloudResources knownRemoteResources) throws IOException {
    MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>(2);
    body.add("application", application);
    ObjectMapper mapper = new ObjectMapper();
    String knownRemoteResourcesPayload = mapper.writeValueAsString(knownRemoteResources);
    body.add("resources", knownRemoteResourcesPayload);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    return new HttpEntity<MultiValueMap<String, ?>>(body, headers);
}
 
Example 52
Project: jwala   File: MediaServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
@Transactional
public JpaMedia create(final Map<String, String> mediaDataMap, final Map<String, Object> mediaFileDataMap) {
    final ObjectMapper objectMapper = new ObjectMapper();
    final JpaMedia media = objectMapper.convertValue(mediaDataMap, JpaMedia.class);

    // filename can be the full path or just the name that is why we need to convert it to Paths
    // to extract the base name e.g. c:/jdk.zip -> jdk.zip or jdk.zip -> jdk.zip
    final String filename = FilenameUtils.getName((String) mediaFileDataMap.get("filename"));

    try {
        mediaDao.findByNameAndType(media.getName(), media.getType());
        final String msg = MessageFormat.format("Media already exists with name {0} and type {1}", media.getName(), media.getType());
        LOGGER.error(msg);
        throw new MediaServiceException(msg);
    } catch (NoResultException e) {
        LOGGER.debug("No Media name conflict, ignoring not found exception for creating media ", e);
    }

    final String uploadedFilePath = repositoryService.upload(filename, (BufferedInputStream) mediaFileDataMap.get("content"));
    final List<String> binariesByBasename = repositoryService.getBinariesByBasename(FilenameUtils.removeExtension(filename));
    final String dest = getPathForExistingBinary(uploadedFilePath, binariesByBasename);

    final Set<String> zipRootDirSet = fileUtility.getZipRootDirs(dest);
    if (!zipRootDirSet.isEmpty()) {
        media.setRootDir(Paths.get(StringUtils.join(zipRootDirSet, ",")));
        media.setLocalPath(Paths.get(dest));
        return mediaDao.create(media);
    }
    repositoryService.delete(dest);
    throw new MediaServiceException(MessageFormat.
            format("{0} does not have any root directories! It may not be a valid media file.", filename));
}
 
Example 53
Project: devops-cstack   File: JsonConverter.java   Source Code and License 5 votes vote down vote up
public static Image getImage(String response )
{
    Image image = new Image();
    ObjectMapper mapper = new ObjectMapper();
    try
    {
        image = mapper.readValue( response, Image.class );
    }
    catch ( IOException e )
    {
        e.printStackTrace();
    }
    return image;
}
 
Example 54
Project: hadoop   File: FSImageLoader.java   Source Code and License 5 votes vote down vote up
/**
 * Return the JSON formatted FileStatus of the specified file.
 * @param path a path specifies a file
 * @return JSON formatted FileStatus
 * @throws IOException if failed to serialize fileStatus to JSON.
 */
String getFileStatus(String path) throws IOException {
  ObjectMapper mapper = new ObjectMapper();
  FsImageProto.INodeSection.INode inode = fromINodeId(lookup(path));
  return "{\"FileStatus\":\n"
      + mapper.writeValueAsString(getFileStatus(inode, false)) + "\n}\n";
}
 
Example 55
Project: sunbird-lms-service   File: TenantPreferenceControllerTest.java   Source Code and License 5 votes vote down vote up
private static String mapToJson(Map map){
  ObjectMapper mapperObj = new ObjectMapper();
  String jsonResp = "";
  try {
    jsonResp = mapperObj.writeValueAsString(map);
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
  return jsonResp;
}
 
Example 56
Project: jwala   File: ResourceServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public ResourceTemplateMetaData getMetaData(final String jsonMetaData) throws IOException {
    if (StringUtils.isNotEmpty(jsonMetaData)) {
        final ResourceTemplateMetaData metaData = new ObjectMapper().readValue(jsonMetaData.replace("\\", "\\\\"),
                ResourceTemplateMetaData.class);
        metaData.setJsonData(jsonMetaData);
        return metaData;
    }
    return null;
}
 
Example 57
Project: devops-cstack   File: JsonConverter.java   Source Code and License 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 58
Project: devops-cstack   File: JsonConverter.java   Source Code and License 5 votes vote down vote up
public static List<String> getTags( String response )
{
    List<String> tags = new ArrayList<>();
    ObjectMapper mapper = new ObjectMapper();
    try
    {
        tags = mapper.readValue( response, new TypeReference<List<String>>()
        {
        } );
    }
    catch ( IOException e )
    {
        e.printStackTrace();
    }
    return tags;
}
 
Example 59
Project: pyroclast-java   File: ReadAggregateGroupResponseDeserializer.java   Source Code and License 5 votes vote down vote up
@Override
public ReadAggregateGroupResult deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {
    JsonNode node = jp.getCodec().readTree(jp);
    ObjectMapper mapper = new ObjectMapper();

    String id = node.get("id").asText();
    String name = node.get("name").asText();
    String type = node.get("type").asText();      
    String group = node.get("group").asText();
    boolean isGrouped = node.get("grouped?").asBoolean();
    JsonNode contents = node.get("contents");

    List<Window> parsedWindows = new ArrayList<>();
    Iterator<JsonNode> it = contents.iterator();

    while (it.hasNext()) {
        JsonNode n = it.next();
        Window window = mapper.readValue(n.toString(), Window.class);
        parsedWindows.add(window);
    }
    
    Map<String, List<Window>> result = new HashMap<>();
    result.put(group, parsedWindows);

    DeploymentAggregate da = new DeploymentAggregate(id, type, isGrouped)
            .withName(name)
            .withGroupedContents(result);
    return new ReadAggregateGroupResult(true, da);
}
 
Example 60
Project: hadoop   File: KMSJSONWriter.java   Source Code and License 5 votes vote down vote up
@Override
public void writeTo(Object obj, Class<?> aClass, Type type,
    Annotation[] annotations, MediaType mediaType,
    MultivaluedMap<String, Object> stringObjectMultivaluedMap,
    OutputStream outputStream) throws IOException, WebApplicationException {
  Writer writer = new OutputStreamWriter(outputStream, Charset
      .forName("UTF-8"));
  ObjectMapper jsonMapper = new ObjectMapper();
  jsonMapper.writerWithDefaultPrettyPrinter().writeValue(writer, obj);
}