@Test
  public void testUpdateLocation() throws Exception {
    LocationRepository repository = container.getInjector().getInstance(LocationRepository.class);

    String id = repository.create(new Location("foo", 0, 0)).getId();

    Map<String, Object> location = new HashMap<String, Object>();
    location.put("id", id);
    location.put("name", "test-location");
    location.put("longitude", -122.4d);
    location.put("latitude", 48.5d);

    ObjectMapper om = new ObjectMapper();
    HttpPut updateRequest = new HttpPut("/location/" + id);
    updateRequest.setEntity(
        new ByteArrayEntity(om.writeValueAsBytes(location), ContentType.APPLICATION_JSON));

    HttpResponse httpResponse = container.execute(updateRequest);
    assertEquals(HttpURLConnection.HTTP_OK, httpResponse.getStatusLine().getStatusCode());

    Map<String, ?> response =
        om.readValue(
            EntityUtils.toString(httpResponse.getEntity()), new TypeReference<Map<String, ?>>() {});
    assertEquals("test-location", response.get("name"));
    assertEquals(-122.4d, response.get("longitude"));
    assertEquals(48.5d, response.get("latitude"));
  }
  // @Override
  public void saveEOD(EndOfDayData[] data) {
    try {

      URL url = new URL("http://localhost:8081/service-ws/api/endofday/bulk");
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setDoOutput(true);
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Content-Type", "application/json");

      ObjectMapper mapper = new ObjectMapper();

      byte[] postdata = mapper.writeValueAsBytes(data);

      OutputStream os = conn.getOutputStream();
      os.write(postdata);
      os.flush();

      if (conn.getResponseCode() != HttpURLConnection.HTTP_ACCEPTED) {
        throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
      }

      conn.disconnect();

    } catch (MalformedURLException e) {

      e.printStackTrace();

    } catch (IOException e) {
      e.printStackTrace();
      System.exit(1);
      throw new RuntimeException();
    }
  }
  @Override
  public String convert(String key, String message) {
    try {
      if (objectMapper == null) objectMapper = new org.codehaus.jackson.map.ObjectMapper();

      // Specific case to extract header from Cookie
      if (key.startsWith(ConfigLoader.getProp(Constants.KEYPREFIXFILTER))) {
        // System.out.println("config :"+ConfigLoader.getProp(Constants.KEYPREFIXFILTER));
        ServerCookieData cookiedata =
            (ServerCookieData) objectMapper.readValue(message, ServerCookieData.class);
        byte[] header = objectMapper.writeValueAsBytes(cookiedata.getHeaders());
        String cookieMsg = StringUtils.newStringUtf8(header);
        return cookieMsg;
      } else {
        // return the String we received. This is applicable for cases like
        // cs_map, analytics document.
        return message;
        // return null;
      }
    } catch (org.codehaus.jackson.JsonParseException e) {
      e.printStackTrace();
      return null;
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
 @Test
 public void jsonTest() throws Exception {
   CommandLineJobInfo jobInfo = createRandom();
   ObjectMapper mapper = new ObjectMapper();
   CommandLineJobInfo other =
       mapper.readValue(mapper.writeValueAsBytes(jobInfo), CommandLineJobInfo.class);
   checkEquality(jobInfo, other);
 }
Example #5
0
 @Override
 protected void map(ImmutableBytesWritable key, Result value, Context context)
     throws IOException, InterruptedException {
   HashMap<String, String> json = new HashMap<>();
   json.put(ID_FIELD, new String(key.get()));
   json.put(
       TEXT_FIELD,
       new String(value.getValue(BulkLoad.HBASE_COL_FAMILY, BulkLoad.HBASE_COL_NAME)));
   context.write(NullWritable.get(), new Text(mapper.writeValueAsBytes(json)));
 }
Example #6
0
  public static byte[] toBytes(final Object all) {

    try {
      return OBJECT_MAPPER.writeValueAsBytes(all);
    } catch (final JsonGenerationException e) {
      LOG.warn("Error generating JSON", e);
    } catch (final JsonMappingException e) {
      LOG.warn("Error generating JSON", e);
    } catch (final IOException e) {
      LOG.warn("Error generating JSON", e);
    }
    return new byte[0];
  }
 public static byte[] writeAsByte(Object obj) {
   try {
     ByteArrayOutputStream bos = new ByteArrayOutputStream();
     mapper.getJsonFactory().createJsonGenerator(bos, JsonEncoding.UTF8);
     return mapper.writeValueAsBytes(obj);
   } catch (JsonGenerationException e) {
     throw new RuntimeException(e);
   } catch (JsonMappingException e) {
     throw new RuntimeException(e);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
  @Test
  public void testUpdateLocation_NotFound() throws Exception {
    Map<String, Object> location = new HashMap<String, Object>();
    location.put("id", "DoesNotExist");
    location.put("name", "test-location");
    location.put("longitude", -122.4d);
    location.put("latitude", 48.5d);

    ObjectMapper om = new ObjectMapper();
    HttpPut updateRequest = new HttpPut("/location/DoesNotExist");
    updateRequest.setEntity(
        new ByteArrayEntity(om.writeValueAsBytes(location), ContentType.APPLICATION_JSON));

    HttpResponse httpResponse = container.execute(updateRequest);
    assertEquals(HttpURLConnection.HTTP_NOT_FOUND, httpResponse.getStatusLine().getStatusCode());
  }
Example #9
0
  public static ByteBuffer toByteBuffer(Object obj) {
    if (obj == null) {
      return null;
    }

    byte[] bytes = null;
    try {
      bytes = smileMapper.writeValueAsBytes(obj);
    } catch (Exception e) {
      logger.error("Error getting SMILE bytes", e);
    }
    if (bytes != null) {
      return ByteBuffer.wrap(bytes);
    }
    return null;
  }
  @Test
  public void testCreateLocation() throws Exception {
    Map<String, Object> location = new HashMap<String, Object>();
    location.put("name", "test-location");
    location.put("longitude", -122.4d);
    location.put("latitude", 48.5d);

    ObjectMapper om = new ObjectMapper();
    HttpPost createRequest = new HttpPost("/location");
    createRequest.setEntity(
        new ByteArrayEntity(om.writeValueAsBytes(location), ContentType.APPLICATION_JSON));

    HttpResponse httpResponse = container.execute(createRequest);
    assertEquals(HttpURLConnection.HTTP_CREATED, httpResponse.getStatusLine().getStatusCode());
    String locationUri = httpResponse.getFirstHeader("Location").getValue();
    assertNotNull(locationUri);
    assertTrue(URI.create(locationUri).isAbsolute());
    Map<String, ?> response =
        om.readValue(
            EntityUtils.toString(httpResponse.getEntity()), new TypeReference<Map<String, ?>>() {});
    assertEquals("test-location", response.get("name"));
    assertEquals(-122.4d, response.get("longitude"));
    assertEquals(48.5d, response.get("latitude"));
  }
 public static byte[] convertObjectToJsonBytes(Object object, JsonSerialize.Inclusion inclusion)
     throws IOException {
   ObjectMapper mapper = new ObjectMapper();
   mapper.setSerializationInclusion(inclusion);
   return mapper.writeValueAsBytes(object);
 }
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String idSchema = request.getParameter("idSchema");
    String start = request.getParameter("start");
    String limit = request.getParameter("limit");
    String fields = request.getParameter("fields");
    String searchValue = request.getParameter("query");

    if (fields != null) {
      fields = fields.replaceAll("\\[", "");
      fields = fields.replaceAll("\\]", "");
      fields = fields.replaceAll("\"", "");
    }

    SchemaEntity schemaEntity = schemasDao.find(Long.parseLong(idSchema));
    ObjectMapper mapper = new ObjectMapper();
    ServletOutputStream out = null;
    response.setContentType("application/json");
    mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    out = response.getOutputStream();

    ReadList readList =
        datastreamsDao.read(
            Long.parseLong(idSchema),
            Integer.parseInt(start),
            Integer.parseInt(limit),
            schemaEntity,
            fields,
            searchValue);
    @SuppressWarnings("unchecked")
    List<DatastreamEntity> listDatastreamDTO = (List<DatastreamEntity>) readList.getResults();
    if (listDatastreamDTO != null && listDatastreamDTO.size() > 0) {
      try {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        for (DatastreamEntity dtoInstance : listDatastreamDTO) {
          if (DomToOtherFormat.isXml(dtoInstance.getDatastream())) {
            try {
              StringReader xmlReader = new StringReader(dtoInstance.getDatastream());
              StringWriter xmlWriter = new StringWriter();
              transformer.transform(new StreamSource(xmlReader), new StreamResult(xmlWriter));
              dtoInstance.setDatastream(xmlWriter.toString());
            } catch (Throwable t) {
              dtoInstance.setDatastream(dtoInstance.getDatastream());
            }
          } else {
            dtoInstance.setDatastream(dtoInstance.getDatastream());
          }
        }
      } catch (Exception exception) {
        log.error("DatastremsReceived - Indenting XML : " + exception);
      }
    }
    out.write(mapper.writeValueAsBytes(readList));
    out.flush();
    out.close();
    return null;
  }
Example #13
0
 public byte[] toBytes() throws IOException {
   ObjectMapper mapper = new ObjectMapper();
   return mapper.writeValueAsBytes(this);
 }
 /**
  * json protocol with jackson
  *
  * @param message message
  * @return chat message
  * @throws Exception exception
  */
 public ChatMessage jackson(ChatMessage message) throws Exception {
   byte[] jsonText = objectMapper.writeValueAsBytes(message);
   ChatMessage msg = objectMapper.readValue(jsonText, ChatMessage.class);
   msg.setContentLength(jsonText.length);
   return msg;
 }