Exemplo n.º 1
0
  @Test
  @SuppressWarnings("rawtypes")
  public void wordDelimitersCausesCamelCase()
      throws ClassNotFoundException, IntrospectionException, InstantiationException,
          IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader =
        generateAndCompile(
            "/schema/properties/propertiesWithWordDelimiters.json",
            "com.example",
            config("usePrimitives", true, "propertyWordDelimiters", "_ -"));

    Class generatedType = resultsClassLoader.loadClass("com.example.WordDelimit");

    Object instance = generatedType.newInstance();

    new PropertyDescriptor("propertyWithUnderscores", generatedType)
        .getWriteMethod()
        .invoke(instance, "a_b_c");
    new PropertyDescriptor("propertyWithHyphens", generatedType)
        .getWriteMethod()
        .invoke(instance, "a-b-c");
    new PropertyDescriptor("propertyWithMixedDelimiters", generatedType)
        .getWriteMethod()
        .invoke(instance, "a b_c-d");

    JsonNode jsonified = mapper.valueToTree(instance);

    assertThat(jsonified.has("property_with_underscores"), is(true));
    assertThat(jsonified.has("property-with-hyphens"), is(true));
    assertThat(jsonified.has("property_with mixed-delimiters"), is(true));
  }
Exemplo n.º 2
0
  @Test
  public void testSaveTwoRootObjectsWithNoType() {
    JsonNode expected =
        mapper
            .createArrayNode()
            .add(mapper.createObjectNode().put("userId", "1").put("name", "Paul"))
            .add(
                mapper
                    .createObjectNode()
                    .put("userId", "2")
                    .put("name", "Anna")
                    .put("sex", "FEMALE"));

    User u1 = ModelFactory.eINSTANCE.createUser();
    u1.setUserId("1");
    u1.setName("Paul");

    User u2 = ModelFactory.eINSTANCE.createUser();
    u2.setUserId("2");
    u2.setName("Anna");
    u2.setSex(Sex.FEMALE);

    Resource resource = new JsonResource(URI.createURI("test"), mapper);
    resource.getContents().add(u1);
    resource.getContents().add(u2);

    JsonNode result = mapper.valueToTree(resource);

    assertEquals(expected, result);
  }
Exemplo n.º 3
0
 /**
  * Convenience method for creating an error response.
  *
  * @param jsonRpc the jsonrpc string
  * @param id the id
  * @param code the error code
  * @param httpCode the http error code
  * @param message the error message
  * @param data the error data (if any)
  * @return the error response
  */
 protected JsonRpcServerResponse createErrorResponse(
     String jsonRpc, Object id, int code, int httpCode, String message, Object data) {
   ObjectNode response = mapper.createObjectNode();
   ObjectNode error = mapper.createObjectNode();
   error.put("code", code);
   error.put("message", message);
   if (data != null) {
     error.put("data", mapper.valueToTree(data));
   }
   response.put("jsonrpc", jsonRpc);
   if (Integer.class.isInstance(id)) {
     response.put("id", Integer.class.cast(id).intValue());
   } else if (Long.class.isInstance(id)) {
     response.put("id", Long.class.cast(id).longValue());
   } else if (Float.class.isInstance(id)) {
     response.put("id", Float.class.cast(id).floatValue());
   } else if (Double.class.isInstance(id)) {
     response.put("id", Double.class.cast(id).doubleValue());
   } else if (BigDecimal.class.isInstance(id)) {
     response.put("id", BigDecimal.class.cast(id));
   } else {
     response.put("id", String.class.cast(id));
   }
   response.put("error", error);
   return new JsonRpcServerResponse(response, httpCode);
 }
Exemplo n.º 4
0
  @Test
  public void givenAnObject_whenConvertingIntoNode_thenCorrect() {
    final NodeBean fromValue = new NodeBean(2016, "baeldung.com");

    final JsonNode node = mapper.valueToTree(fromValue);

    assertEquals(2016, node.get("id").intValue());
    assertEquals("baeldung.com", node.get("name").textValue());
  }
Exemplo n.º 5
0
 /**
  * Returns {@code object} serialized to a JsonNode.
  *
  * @throws RuntimeException if deserialization fails
  */
 public static JsonNode toJsonNode(Object object) {
   try {
     ObjectNode rootNode = mapper.createObjectNode();
     JsonNode node = mapper.valueToTree(object);
     rootNode.put(rootNameFor(Types.deProxy(object.getClass())), node);
     return rootNode;
   } catch (Exception e) {
     throw Exceptions.uncheck(e, "Failed to serialize object: {}", object);
   }
 }
Exemplo n.º 6
0
 // [Issue#232]
 public void testBigDecimalAsPlainStringTreeConversion() throws Exception {
   ObjectMapper mapper = new ObjectMapper();
   mapper.enable(SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN);
   Map<String, Object> map = new HashMap<String, Object>();
   String PI_STR = "3.00000000";
   map.put("pi", new BigDecimal(PI_STR));
   JsonNode tree = mapper.valueToTree(map);
   assertNotNull(tree);
   assertEquals(1, tree.size());
   assertTrue(tree.has("pi"));
 }
Exemplo n.º 7
0
  @Test
  @SuppressWarnings("rawtypes")
  public void propertiesWithNullValuesAreOmittedWhenSerialized()
      throws ClassNotFoundException, IntrospectionException, InstantiationException,
          IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader =
        generateAndCompile("/schema/properties/nullProperties.json", "com.example");

    Class generatedType = resultsClassLoader.loadClass("com.example.NullProperties");
    Object instance = generatedType.newInstance();

    Method setter = new PropertyDescriptor("property", generatedType).getWriteMethod();
    setter.invoke(instance, "value");

    assertThat(mapper.valueToTree(instance).toString(), containsString("property"));

    setter.invoke(instance, (Object) null);

    assertThat(mapper.valueToTree(instance).toString(), not(containsString("property")));
  }
Exemplo n.º 8
0
  @Test
  public void testSaveSingleObjectWithNoType() {
    JsonNode expected = mapper.createObjectNode().put("userId", "1").put("name", "Paul");

    User u1 = ModelFactory.eINSTANCE.createUser();
    u1.setUserId("1");
    u1.setName("Paul");

    JsonNode result = mapper.valueToTree(u1);

    assertEquals(expected, result);
  }
Exemplo n.º 9
0
  /**
   * Invokes the given method on the {@code handler} passing the given params (after converting them
   * to beans\objects) to it.
   *
   * @param m the method to invoke
   * @param params the params to pass to the method
   * @return the return value (or null if no return)
   * @throws IOException on error
   * @throws IllegalAccessException on error
   * @throws InvocationTargetException on error
   */
  protected JsonNode invoke(Method m, List<JsonNode> params)
      throws IOException, IllegalAccessException, InvocationTargetException {

    // debug log
    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.log(Level.FINE, "Invoking method: " + m.getName());
    }

    // convert the parameters
    Object[] convertedParams = new Object[params.size()];
    Type[] parameterTypes = m.getGenericParameterTypes();

    for (int i = 0; i < parameterTypes.length; i++) {
      JsonParser paramJsonParser = mapper.treeAsTokens(params.get(i));
      JavaType paramJavaType = TypeFactory.defaultInstance().constructType(parameterTypes[i]);
      convertedParams[i] = mapper.readValue(paramJsonParser, paramJavaType);
    }

    // invoke the method
    Object result = m.invoke(handler, convertedParams);
    Type genericReturnType = m.getGenericReturnType();
    if (genericReturnType != null) {
      if (Collection.class.isInstance(result) && genericReturnType instanceof ParameterizedType) {
        try {
          if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "attempting custom collection serialization");
          }
          TypeFactory typeFactory = mapper.getTypeFactory();
          Type actualTypeInCollection =
              ((ParameterizedType) genericReturnType).getActualTypeArguments()[0];
          if (actualTypeInCollection
              instanceof TypeVariable) { // collection actually has a generic return type
            actualTypeInCollection = ((TypeVariable) actualTypeInCollection).getBounds()[0];
          }
          JavaType rootType =
              typeFactory.constructCollectionType(
                  Collection.class, typeFactory.constructType(actualTypeInCollection));
          return valueToTree(mapper.writerWithType(rootType), result);
        } catch (Exception e) {
          LOGGER.log(
              Level.WARNING,
              "could not do custom collection serialization falling back to default",
              e);
        }
      }
      return mapper.valueToTree(result);
    } else {
      return null;
    }
    // return (genericReturnType!=null) ? mapper.valueToTree(result) : null;
  }
Exemplo n.º 10
0
  @Test
  public void propertyCalledClassCanBeSerialized()
      throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {

    ClassLoader resultsClassLoader =
        generateAndCompile("/schema/properties/propertyCalledClass.json", "com.example");

    Class<?> generatedType = resultsClassLoader.loadClass("com.example.PropertyCalledClass");

    String valuesAsJsonString = "{\"class\":\"a\"}";
    Object valuesAsObject = mapper.readValue(valuesAsJsonString, generatedType);
    JsonNode valueAsJsonNode = mapper.valueToTree(valuesAsObject);

    assertThat(valueAsJsonNode.path("class").asText(), is("a"));
  }
 protected DBObject prepareObject(StreamsDatum streamsDatum) {
   DBObject dbObject = null;
   if (streamsDatum.getDocument() instanceof String) {
     dbObject = (DBObject) JSON.parse((String) streamsDatum.getDocument());
   } else {
     try {
       ObjectNode node = mapper.valueToTree(streamsDatum.getDocument());
       dbObject = (DBObject) JSON.parse(node.toString());
     } catch (Exception e) {
       e.printStackTrace();
       LOGGER.error("Unsupported type: " + streamsDatum.getDocument().getClass(), e);
     }
   }
   return dbObject;
 }
Exemplo n.º 12
0
  public static String[] getRootValuesAsString(final Object object) {
    final JsonNode node = mapper.valueToTree(object);

    final String[] fields = Iterators.toArray(node.fieldNames(), String.class);
    final String[] values = new String[fields.length];

    int i = 0;
    for (final String field : fields) {
      final JsonNode valueAsNode = node.get(field);
      values[i++] =
          (valueAsNode != null)
              ? (node.get(field).asText().replaceFirst("^\"(.*)\"$", "$1"))
              : "n/a";
    }

    return values;
  }
  /** Get the activities of a type. */
  @SubjectPresent
  public Result getActivities() {

    JsonNode json = request().body().asJson();
    Long activityTypeId = json.findPath("activityTypeId").asLong();

    List<TimesheetActivity> activities =
        TimesheetDao.getTimesheetActivityAsListByActivityType(activityTypeId);
    List<OptionData> options = new ArrayList<OptionData>();

    for (TimesheetActivity activity : activities) {
      options.add(new OptionData(activity.id, activity.getName()));
    }

    ObjectMapper mapper = new ObjectMapper();

    return ok((JsonNode) mapper.valueToTree(options));
  }
Exemplo n.º 14
0
  @Test
  public void propertyNamesThatAreJavaKeywordsCanBeSerialized()
      throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {

    ClassLoader resultsClassLoader =
        generateAndCompile("/schema/properties/propertiesThatAreJavaKeywords.json", "com.example");

    Class<?> generatedType =
        resultsClassLoader.loadClass("com.example.PropertiesThatAreJavaKeywords");

    String valuesAsJsonString =
        "{\"public\":\"a\",\"void\":\"b\",\"enum\":\"c\",\"abstract\":\"d\"}";
    Object valuesAsObject = mapper.readValue(valuesAsJsonString, generatedType);
    JsonNode valueAsJsonNode = mapper.valueToTree(valuesAsObject);

    assertThat(valueAsJsonNode.path("public").asText(), is("a"));
    assertThat(valueAsJsonNode.path("void").asText(), is("b"));
    assertThat(valueAsJsonNode.path("enum").asText(), is("c"));
    assertThat(valueAsJsonNode.path("abstract").asText(), is("d"));
  }
Exemplo n.º 15
0
 private static HttpOperation createPostRequest(HttpOperationClient httpoperationclient, CharSequence charsequence, HashMap hashmap, HttpOperationReader httpoperationreader, VineAPI vineapi)
 {
     charsequence = new HttpPost(charsequence.toString());
     if (hashmap != null)
     {
         try
         {
             ObjectMapper objectmapper = new ObjectMapper();
             hashmap = new StringEntity(objectmapper.writeValueAsString(objectmapper.valueToTree(hashmap)), "UTF-8");
             hashmap.setContentType("application/json");
             hashmap.setContentEncoding("UTF-8");
             charsequence.setEntity(hashmap);
         }
         // Misplaced declaration of an exception variable
         catch (HashMap hashmap)
         {
             SLog.e("Failed to create Post Request.", hashmap);
         }
     }
     return new HttpOperation(httpoperationclient, charsequence, httpoperationreader, vineapi);
 }
Exemplo n.º 16
0
  @Test
  public void testSaveSingleObjectWithNoTypeAndOneContainment() {
    JsonNode expected =
        mapper
            .createObjectNode()
            .put("userId", "1")
            .put("name", "Paul")
            .set("address", mapper.createObjectNode().put("addId", "a1").put("city", "Prague"));

    User u1 = ModelFactory.eINSTANCE.createUser();
    u1.setUserId("1");
    u1.setName("Paul");

    Address add = ModelFactory.eINSTANCE.createAddress();
    add.setAddId("a1");
    add.setCity("Prague");

    u1.setAddress(add);

    JsonNode result = mapper.valueToTree(u1);

    assertEquals(expected, result);
  }
Exemplo n.º 17
0
  @Test
  @SuppressWarnings("rawtypes")
  public void propertiesAreSerializedInCorrectOrder()
      throws ClassNotFoundException, IntrospectionException, InstantiationException,
          IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader =
        generateAndCompile("/schema/properties/orderedProperties.json", "com.example");

    Class generatedType = resultsClassLoader.loadClass("com.example.OrderedProperties");
    Object instance = generatedType.newInstance();

    new PropertyDescriptor("type", generatedType).getWriteMethod().invoke(instance, "1");
    new PropertyDescriptor("id", generatedType).getWriteMethod().invoke(instance, "2");
    new PropertyDescriptor("name", generatedType).getWriteMethod().invoke(instance, "3");
    new PropertyDescriptor("hastickets", generatedType).getWriteMethod().invoke(instance, true);
    new PropertyDescriptor("starttime", generatedType).getWriteMethod().invoke(instance, "4");

    String serialized = mapper.valueToTree(instance).toString();

    assertThat(
        "Properties are not in expected order",
        serialized.indexOf("type"),
        is(lessThan(serialized.indexOf("id"))));
    assertThat(
        "Properties are not in expected order",
        serialized.indexOf("id"),
        is(lessThan(serialized.indexOf("name"))));
    assertThat(
        "Properties are not in expected order",
        serialized.indexOf("name"),
        is(lessThan(serialized.indexOf("hastickets"))));
    assertThat(
        "Properties are not in expected order",
        serialized.indexOf("hastickets"),
        is(lessThan(serialized.indexOf("starttime"))));
  }
Exemplo n.º 18
0
 public static String toJson(Object o, String exclude) {
   final ObjectNode jsonNode = MAPPER.valueToTree(o);
   jsonNode.remove(exclude);
   return jsonNode.toString();
 }
Exemplo n.º 19
0
 public static JsonNode valueToTree(Model<?> o) {
   return JSON_MAPPER.valueToTree(o);
 }
 private JsonNode createJsonElement(Object o) {
   return objectMapper.valueToTree(o);
 }
Exemplo n.º 21
0
 public static String[] getRootFieldNames(final Object object) {
   final JsonNode node = mapper.valueToTree(object);
   return Iterators.toArray(node.fieldNames(), String.class);
 }