public static Object gsonToPrimitive(JsonElement element) {
   if (element.isJsonPrimitive()) {
     JsonPrimitive prim = element.getAsJsonPrimitive();
     if (prim.isString()) {
       return prim.getAsString();
     } else if (prim.isBoolean()) {
       return prim.getAsBoolean();
     } else if (prim.isNumber()) {
       return prim.getAsNumber();
     } else {
       throw new IllegalArgumentException("Unknown Gson primitive: " + prim);
     }
   } else if (element.isJsonArray()) {
     JsonArray array = element.getAsJsonArray();
     List<Object> list = new ArrayList<Object>();
     for (int i = 0; i < array.size(); i++) {
       list.add(gsonToPrimitive(array.get(i)));
     }
     return list;
   } else if (element.isJsonNull()) {
     return null;
   } else if (element.isJsonObject()) {
     Map<String, Object> map = new HashMap<String, Object>();
     for (Map.Entry<String, JsonElement> entry : element.getAsJsonObject().entrySet()) {
       map.put(entry.getKey(), gsonToPrimitive(entry.getValue()));
     }
     return map;
   } else {
     throw new IllegalArgumentException("Unknown Gson value: " + element);
   }
 }
 @Override
 public Object deserialize(JsonElement element, Type type, JsonDeserializationContext jdc)
     throws JsonParseException {
   if (element.isJsonPrimitive()) {
     JsonPrimitive primitive = element.getAsJsonPrimitive();
     if (primitive.isBoolean()) {
       return primitive.getAsBoolean();
     } else if (primitive.isNumber()) {
       return primitive.getAsNumber();
     } else {
       return primitive.getAsString();
     }
   } else if (element.isJsonArray()) {
     Object[] array = jdc.deserialize(element, Object[].class);
     return new ArrayList<Object>(Arrays.asList(array));
   } else if (element.isJsonObject()) {
     Set<Entry<String, JsonElement>> entrySet = element.getAsJsonObject().entrySet();
     Map<String, Object> map = new HashMap<String, Object>();
     for (Entry<String, JsonElement> entry : entrySet) {
       map.put(entry.getKey(), jdc.deserialize(entry.getValue(), Object.class));
     }
     return map;
   }
   throw new IllegalArgumentException(
       "Illegal pipeline format, expecting either a primitive type or an array or an object");
 }
示例#3
0
        @Override
        public void write(JsonWriter out, JsonElement value) throws IOException {
          if (value == null || value.isJsonNull()) {
            out.nullValue();
          } else if (value.isJsonPrimitive()) {
            JsonPrimitive primitive = value.getAsJsonPrimitive();
            if (primitive.isNumber()) {
              out.value(primitive.getAsNumber());
            } else if (primitive.isBoolean()) {
              out.value(primitive.getAsBoolean());
            } else {
              out.value(primitive.getAsString());
            }

          } else if (value.isJsonArray()) {
            out.beginArray();
            for (JsonElement e : value.getAsJsonArray()) {
              write(out, e);
            }
            out.endArray();

          } else if (value.isJsonObject()) {
            out.beginObject();
            for (Map.Entry<String, JsonElement> e : value.getAsJsonObject().entrySet()) {
              out.name(e.getKey());
              write(out, e.getValue());
            }
            out.endObject();

          } else {
            throw new IllegalArgumentException("Couldn't write " + value.getClass());
          }
        }
 /*
  * (non-Javadoc)
  *
  * @see
  * com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement,
  * java.lang.reflect.Type, com.google.gson.JsonDeserializationContext)
  */
 public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
     throws JsonParseException {
   if (json.isJsonNull()) {
     return null;
   } else if (json.isJsonPrimitive()) {
     JsonPrimitive primitive = json.getAsJsonPrimitive();
     if (primitive.isString()) {
       return primitive.getAsString();
     } else if (primitive.isNumber()) {
       return primitive.getAsNumber();
     } else if (primitive.isBoolean()) {
       return primitive.getAsBoolean();
     }
   } else if (json.isJsonArray()) {
     JsonArray array = json.getAsJsonArray();
     Object[] result = new Object[array.size()];
     int i = 0;
     for (JsonElement element : array) {
       result[i] = deserialize(element, null, context);
       ++i;
     }
     return result;
   } else if (json.isJsonObject()) {
     JsonObject object = json.getAsJsonObject();
     Map<String, Object> result = new HashMap<String, Object>();
     for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
       Object value = deserialize(entry.getValue(), null, context);
       result.put(entry.getKey(), value);
     }
     return result;
   } else {
     throw new JsonParseException("Unknown JSON type for JsonElement " + json.toString());
   }
   return null;
 }
示例#5
0
  public static Class<? extends NBTBase> getNBTTypeSmart(JsonElement element) {
    if (element.isJsonArray()) {
      JsonArray array = element.getAsJsonArray();

      if (array.size() == 0) {
        return NBTTagList.class;
      }

      boolean allByte = true;
      boolean allInt = true;
      for (JsonElement arrayElement : array) {
        if (arrayElement.isJsonPrimitive()) {
          JsonPrimitive primitive = arrayElement.getAsJsonPrimitive();
          if (!(primitive.isNumber() && primitive.getAsNumber() instanceof Byte)) {
            allByte = false;
          }
          if (!(primitive.isNumber() && primitive.getAsNumber() instanceof Integer)) {
            allInt = false;
          }
        } else {
          allByte = false;
          allInt = false;
        }
      }

      if (allByte) {
        return NBTTagByteArray.class;
      }
      if (allInt) {
        return NBTTagIntArray.class;
      }

      return NBTTagList.class;
    } else if (element.isJsonObject()) {
      return NBTTagCompound.class;
    } else if (element.isJsonPrimitive()) {
      JsonPrimitive primitive = element.getAsJsonPrimitive();
      if (primitive.isString()) {
        return NBTTagString.class;
      } else if (primitive.isNumber()) {
        return NBTBase.NBTPrimitive.class;
      }
    }

    return null;
  }
示例#6
0
 private Object getObjectFromPrimitive(JsonPrimitive json) {
   if (json.isBoolean()) {
     return json.getAsBoolean();
   } else if (json.isString()) {
     return json.getAsString();
   } else if (json.isNumber()) {
     return json.getAsNumber();
   }
   return null;
 }
  @Override
  public Map<String, Object> readProfile() throws IOException {
    JsonElement parseTree = null;

    try {
      fr = new FileReader(_dir + File.separator + "profile");
      parseTree = _parser.parse(fr);
    } catch (Exception e) {
      _logger.error("Json file problem", e);

      /*SURE !? */
      return null;
    } finally {
      if (fr != null) {
        fr.close();
      }
    }

    Set<Map.Entry<String, JsonElement>> set = null;
    try {
      set = parseTree.getAsJsonObject().entrySet();
    } catch (IllegalStateException e) {
      _logger.error("Bad state of Json input. Node: " + _dir + File.separator + "profile", e);
      return null;
    }

    Map<String, Object> properties = new HashMap<String, Object>(set.size());
    for (Map.Entry<String, JsonElement> entry : set) {
      String tmp = null;
      if (entry.getValue().isJsonPrimitive()) {
        JsonPrimitive primitive = entry.getValue().getAsJsonPrimitive();
        if (primitive.isNumber()) {
          properties.put(entry.getKey(), primitive.getAsNumber().longValue());
        } else if (primitive.isBoolean()) {
          properties.put(entry.getKey(), primitive.getAsBoolean());
        } else if (primitive.isString()) {
          tmp = primitive.toString();
          properties.put(entry.getKey(), tmp.substring(1, tmp.length() - 1));
        } else {
          throw new IllegalStateException("Primitive is in illegal state!");
        }

        /*And we go for next entry!*/
        continue;
      }

      /*If entry is NOT primitive we save it in JSON notation as a String*/
      properties.put(entry.getKey(), entry.getValue().toString());
    }

    return properties;
  }
 private org.eclipse.leshan.core.model.ResourceModel.Type getTypeFor(JsonPrimitive val) {
   if (val.isBoolean()) return org.eclipse.leshan.core.model.ResourceModel.Type.BOOLEAN;
   if (val.isString()) return org.eclipse.leshan.core.model.ResourceModel.Type.STRING;
   if (val.isNumber()) {
     if (val.getAsDouble() == (long) val.getAsLong()) {
       return org.eclipse.leshan.core.model.ResourceModel.Type.BOOLEAN;
     } else {
       return org.eclipse.leshan.core.model.ResourceModel.Type.BOOLEAN;
     }
   }
   // use string as default value
   return org.eclipse.leshan.core.model.ResourceModel.Type.STRING;
 }
示例#9
0
 private void apply(JsonElement json, Config.Builder builder) {
   if (json.isJsonPrimitive()) {
     JsonPrimitive primitive = json.getAsJsonPrimitive();
     if (primitive.isString()) {
       apply(primitive.getAsString(), builder);
     } else if (primitive.isBoolean()) {
       apply(primitive.getAsBoolean(), builder);
     } else if (primitive.isNumber()) {
       apply(primitive.getAsNumber(), builder);
     }
   } else if (json.isJsonArray()) {
     apply(json.getAsJsonArray(), builder);
   } else if (json.isJsonObject()) {
     apply(json.getAsJsonObject(), builder);
   }
 }
示例#10
0
 public static Object toPrimitive(JsonPrimitive jsonPrimitive) {
   Object primitive = null;
   if (jsonPrimitive != null) {
     if (jsonPrimitive.isBoolean()) {
       primitive = jsonPrimitive.getAsBoolean();
     } else if (jsonPrimitive.isNumber()) {
       Number primitiveNumber = jsonPrimitive.getAsNumber();
       if (primitiveNumber instanceof Byte) primitive = primitiveNumber.byteValue();
       else if (primitiveNumber instanceof Double) primitive = primitiveNumber.doubleValue();
       else if (primitiveNumber instanceof Float) primitive = primitiveNumber.floatValue();
       else if (primitiveNumber instanceof Integer) primitive = primitiveNumber.intValue();
       else if (primitiveNumber instanceof Long) primitive = primitiveNumber.longValue();
       else if (primitiveNumber instanceof Short) primitive = primitiveNumber.shortValue();
       else primitive = primitiveNumber;
     } else if (jsonPrimitive.isString()) {
       primitive = jsonPrimitive.getAsString();
     }
   }
   return primitive;
 }
示例#11
0
 public static Object encodeUnknown(JsonElement from) {
   if (from.isJsonArray()) { // Array
     return encodeArray(from.getAsJsonArray());
   } // TESTED
   else if (from.isJsonObject()) { // Object
     JsonObject obj = from.getAsJsonObject();
     // Check for OID/Date:
     if (1 == obj.entrySet().size()) {
       if (obj.has("$date")) {
         try {
           return _format.parse(obj.get("$date").getAsString());
         } catch (ParseException e) {
           try {
             return _format2.parse(obj.get("$date").getAsString());
           } catch (ParseException e2) {
             return null;
           }
         }
       } // TESTED
       else if (obj.has("$oid")) {
         return new ObjectId(obj.get("$oid").getAsString());
       } // TESTED
     }
     return encode(obj);
   } // TESTED
   else if (from.isJsonPrimitive()) { // Primitive
     JsonPrimitive val = from.getAsJsonPrimitive();
     if (val.isNumber()) {
       return val.getAsNumber();
     } // TESTED
     else if (val.isBoolean()) {
       return val.getAsBoolean();
     } // TESTED
     else if (val.isString()) {
       return val.getAsString();
     } // TESTED
   } // TESTED
   return null;
 } // TESTED
 private ConfigurationParam makeConfigParam(String key, JsonPrimitive value)
     throws JsonParseException {
   ConfigurationParam param = new ConfigurationParam();
   String valueStr;
   if (value == null && "mail".equals(key)) {
     valueStr =
         ""; // Ghost 0.8.0 gives an empty string instead of null, when no mail transport is set
     // we don't care about the mail transport anyhow
   } else if (value == null) {
     // FIXME temp log to help debug Crashlytics issue #87
     throw new NullPointerException("value for key '" + key + "' is null!");
   } else if (value.isString()) {
     valueStr = value.getAsString();
   } else if (value.isBoolean()) {
     valueStr = String.valueOf(value.getAsBoolean());
   } else if (value.isNumber()) {
     valueStr = String.valueOf(value.getAsDouble());
   } else {
     throw new JsonParseException("unknown value type in Ghost configuration list");
   }
   param.setKey(key);
   param.setValue(valueStr);
   return param;
 }
示例#13
0
  public Link deserialize(
      JsonElement _jsonElement, Type _type, JsonDeserializationContext _jsonDeserializationContext)
      throws JsonParseException {
    LinkBuilder builder = new LinkBuilder();
    final JsonObject root = _jsonElement.getAsJsonObject();
    final String kindString = root.get("kind").getAsString();
    builder.kind(Kind.getFromRedditType(kindString));
    final JsonObject linkObject = root.get("data").getAsJsonObject();
    final String id = linkObject.get("id").getAsString();
    builder.id(id);
    final String name = linkObject.get("name").getAsString();
    builder.name(name);

    final Double created = linkObject.get("created").getAsDouble();
    builder.created(created.longValue());
    final Double createdUTC = linkObject.get("created_utc").getAsDouble();
    builder.createdUTC(createdUTC.longValue());

    final int ups = linkObject.get("ups").getAsInt();
    builder.ups(ups);
    final int downs = linkObject.get("downs").getAsInt();
    builder.downs(downs);

    final String distinguised = JsonHelper.getStringOrNull(linkObject.get("distinguished"));
    builder.distinguised(distinguised);
    final int numComments = linkObject.get("num_comments").getAsInt();
    builder.numComments(numComments);
    final String title = linkObject.get("title").getAsString();
    builder.title(title);
    final String authorFlairText = JsonHelper.getStringOrNull(linkObject.get("author_flair_text"));
    builder.authorFlairCSSText(authorFlairText);
    final String URL = linkObject.get("url").getAsString();
    builder.URL(URL);
    final boolean saved = linkObject.get("saved").getAsBoolean();
    builder.saved(saved);
    final boolean self = linkObject.get("is_self").getAsBoolean();
    builder.self(self);
    final String permalink = linkObject.get("permalink").getAsString();
    builder.permalink(permalink);
    final String domain = linkObject.get("domain").getAsString();
    builder.domain(domain);
    final String subreddit = linkObject.get("subreddit").getAsString();
    builder.subreddit(subreddit);
    final JsonElement selftextHtmlElement = linkObject.get("selftext_html");
    String selftextHtml = null;
    if (!selftextHtmlElement.isJsonNull()) {
      selftextHtml = selftextHtmlElement.getAsString();
    }
    builder.selfTextHTML(selftextHtml);
    final String selftext = linkObject.get("selftext").getAsString();
    builder.selfText(selftext);
    final Boolean likes = JsonHelper.getBooleanOrNull(linkObject.get("likes"));
    builder.likes(likes);
    final String linkFlairText = JsonHelper.getStringOrNull(linkObject.get("link_flair_text"));
    builder.linkFlairText(linkFlairText);
    final String linkFlairCssClass =
        JsonHelper.getStringOrNull(linkObject.get("link_flair_css_class"));
    builder.linkFlairCSSClass(linkFlairCssClass);
    final String authorFlairCssClass =
        JsonHelper.getStringOrNull(linkObject.get("author_flair_css_class"));
    builder.authorFlairCSSClass(authorFlairCssClass);
    final boolean clicked = linkObject.get("clicked").getAsBoolean();
    builder.clicked(clicked);
    final boolean stickied = linkObject.get("stickied").getAsBoolean();
    builder.stickied(stickied);
    final String author = linkObject.get("author").getAsString();
    builder.author(author);
    final int score = linkObject.get("score").getAsInt();
    builder.score(score);
    final boolean over18 = linkObject.get("over_18").getAsBoolean();
    builder.over18(over18);
    final boolean hidden = linkObject.get("hidden").getAsBoolean();
    builder.hidden(hidden);
    final String thumbnail = linkObject.get("thumbnail").getAsString();
    builder.thumbnail(thumbnail);
    final String subredditId = linkObject.get("subreddit_id").getAsString();
    builder.subredditId(subredditId);
    final JsonPrimitive editedPrimitive = linkObject.get("edited").getAsJsonPrimitive();
    if (editedPrimitive.isNumber()) {
      final Double editedTime = editedPrimitive.getAsDouble();
      builder.editedTime(editedTime.longValue());
      builder.edited(true);
    }

    return builder.build();
  }
  public void post(Representation entity) {
    InputStream input = null;

    try {
      input = getRequest().getEntity().getStream();
      final GeoGIG ggit = getGeogig(getRequest()).get();
      final Reader body = new InputStreamReader(input);
      final JsonParser parser = new JsonParser();
      final JsonElement conflictJson = parser.parse(body);

      if (conflictJson.isJsonObject()) {
        final JsonObject conflict = conflictJson.getAsJsonObject();
        String featureId = null;
        RevFeature ourFeature = null;
        RevFeatureType ourFeatureType = null;
        RevFeature theirFeature = null;
        RevFeatureType theirFeatureType = null;
        JsonObject merges = null;
        if (conflict.has("path") && conflict.get("path").isJsonPrimitive()) {
          featureId = conflict.get("path").getAsJsonPrimitive().getAsString();
        }
        Preconditions.checkState(featureId != null);

        if (conflict.has("ours") && conflict.get("ours").isJsonPrimitive()) {
          String ourCommit = conflict.get("ours").getAsJsonPrimitive().getAsString();
          Optional<NodeRef> ourNode = parseID(ObjectId.valueOf(ourCommit), featureId, ggit);
          if (ourNode.isPresent()) {
            Optional<RevObject> object =
                ggit.command(RevObjectParse.class).setObjectId(ourNode.get().objectId()).call();
            Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeature);

            ourFeature = (RevFeature) object.get();

            object =
                ggit.command(RevObjectParse.class)
                    .setObjectId(ourNode.get().getMetadataId())
                    .call();
            Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeatureType);

            ourFeatureType = (RevFeatureType) object.get();
          }
        }

        if (conflict.has("theirs") && conflict.get("theirs").isJsonPrimitive()) {
          String theirCommit = conflict.get("theirs").getAsJsonPrimitive().getAsString();
          Optional<NodeRef> theirNode = parseID(ObjectId.valueOf(theirCommit), featureId, ggit);
          if (theirNode.isPresent()) {
            Optional<RevObject> object =
                ggit.command(RevObjectParse.class).setObjectId(theirNode.get().objectId()).call();
            Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeature);

            theirFeature = (RevFeature) object.get();

            object =
                ggit.command(RevObjectParse.class)
                    .setObjectId(theirNode.get().getMetadataId())
                    .call();
            Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeatureType);

            theirFeatureType = (RevFeatureType) object.get();
          }
        }

        if (conflict.has("merges") && conflict.get("merges").isJsonObject()) {
          merges = conflict.get("merges").getAsJsonObject();
        }
        Preconditions.checkState(merges != null);

        Preconditions.checkState(ourFeatureType != null || theirFeatureType != null);

        SimpleFeatureBuilder featureBuilder =
            new SimpleFeatureBuilder(
                (SimpleFeatureType)
                    (ourFeatureType != null ? ourFeatureType.type() : theirFeatureType.type()));

        ImmutableList<PropertyDescriptor> descriptors =
            (ourFeatureType == null ? theirFeatureType : ourFeatureType).sortedDescriptors();

        for (Entry<String, JsonElement> entry : merges.entrySet()) {
          int descriptorIndex = getDescriptorIndex(entry.getKey(), descriptors);
          if (descriptorIndex != -1 && entry.getValue().isJsonObject()) {
            PropertyDescriptor descriptor = descriptors.get(descriptorIndex);
            JsonObject attributeObject = entry.getValue().getAsJsonObject();
            if (attributeObject.has("ours")
                && attributeObject.get("ours").isJsonPrimitive()
                && attributeObject.get("ours").getAsBoolean()) {
              featureBuilder.set(
                  descriptor.getName(),
                  ourFeature == null ? null : ourFeature.getValues().get(descriptorIndex).orNull());
            } else if (attributeObject.has("theirs")
                && attributeObject.get("theirs").isJsonPrimitive()
                && attributeObject.get("theirs").getAsBoolean()) {
              featureBuilder.set(
                  descriptor.getName(),
                  theirFeature == null
                      ? null
                      : theirFeature.getValues().get(descriptorIndex).orNull());
            } else if (attributeObject.has("value")
                && attributeObject.get("value").isJsonPrimitive()) {
              JsonPrimitive primitive = attributeObject.get("value").getAsJsonPrimitive();
              if (primitive.isString()) {
                try {
                  Object object =
                      valueFromString(
                          FieldType.forBinding(descriptor.getType().getBinding()),
                          primitive.getAsString());
                  featureBuilder.set(descriptor.getName(), object);
                } catch (Exception e) {
                  throw new Exception(
                      "Unable to convert attribute ("
                          + entry.getKey()
                          + ") to required type: "
                          + descriptor.getType().getBinding().toString());
                }
              } else if (primitive.isNumber()) {
                try {
                  Object value =
                      valueFromNumber(
                          FieldType.forBinding(descriptor.getType().getBinding()),
                          primitive.getAsNumber());
                  featureBuilder.set(descriptor.getName(), value);
                } catch (Exception e) {
                  throw new Exception(
                      "Unable to convert attribute ("
                          + entry.getKey()
                          + ") to required type: "
                          + descriptor.getType().getBinding().toString());
                }
              } else if (primitive.isBoolean()) {
                try {
                  Object value =
                      valueFromBoolean(
                          FieldType.forBinding(descriptor.getType().getBinding()),
                          primitive.getAsBoolean());
                  featureBuilder.set(descriptor.getName(), value);
                } catch (Exception e) {
                  throw new Exception(
                      "Unable to convert attribute ("
                          + entry.getKey()
                          + ") to required type: "
                          + descriptor.getType().getBinding().toString());
                }
              } else if (primitive.isJsonNull()) {
                featureBuilder.set(descriptor.getName(), null);
              } else {
                throw new Exception(
                    "Unsupported JSON type for attribute value (" + entry.getKey() + ")");
              }
            }
          }
        }
        SimpleFeature feature = featureBuilder.buildFeature(NodeRef.nodeFromPath(featureId));
        RevFeature revFeature = RevFeatureBuilder.build(feature);
        ggit.getRepository().stagingDatabase().put(revFeature);

        getResponse()
            .setEntity(
                new StringRepresentation(revFeature.getId().toString(), MediaType.TEXT_PLAIN));
      }

    } catch (Exception e) {
      throw new RestletException(e.getMessage(), Status.SERVER_ERROR_INTERNAL, e);
    } finally {
      if (input != null) Closeables.closeQuietly(input);
    }
  }
示例#15
0
 public Object __parse_response__(String resp) throws RemoteException {
   JsonParser parser = new JsonParser();
   JsonElement main_response = (JsonElement) parser.parse(resp);
   if (main_response.isJsonArray()) {
     List<Object> res = new Vector<Object>();
     for (Object o : main_response.getAsJsonArray()) {
       res.add(__parse_response__(gson.toJson(o)));
     }
     return res;
   }
   JsonObject response = main_response.getAsJsonObject();
   if (response.has("error")) {
     JsonObject e = response.get("error").getAsJsonObject().get("data").getAsJsonObject();
     throw new RemoteException(e.get("exception").getAsString(), e.get("message").getAsString());
   }
   JsonElement value = response.get("result");
   String valuestr = gson.toJson(response.get("result"));
   if (valuestr.contains("hash:")) {
     Class<? extends RpcClient> klass = this.getClass();
     try {
       Constructor<? extends RpcClient> m =
           klass.getDeclaredConstructor(String.class, String.class);
       String new_endpoint = gson.fromJson(value, String.class);
       return m.newInstance(this.base_endpoint, new_endpoint.replace("hash:", ""));
     } catch (NoSuchMethodException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
       return null;
     } catch (IllegalArgumentException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
       return null;
     } catch (InstantiationException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
       return null;
     } catch (IllegalAccessException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
       return null;
     } catch (InvocationTargetException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
       return null;
     }
   } else if (valuestr.contains("funcs")) {
     return gson.fromJson(valuestr, Interface.class);
   }
   if (value.isJsonPrimitive()) {
     JsonPrimitive val = value.getAsJsonPrimitive();
     if (val.isBoolean()) {
       return val.getAsBoolean();
     } else if (val.isNumber()) {
       return val.getAsNumber();
     } else if (val.isString()) {
       DateTimeFormatter dtparser = ISODateTimeFormat.dateHourMinuteSecond();
       try {
         return dtparser.parseDateTime(val.getAsString());
       } catch (Exception ex) {
       }
       return val.getAsString();
     } else {
       return null;
     }
   } else if (value.isJsonNull()) {
     return null;
   } else if (value.isJsonObject() && !value.getAsJsonObject().has("__meta__")) {
     return gson.fromJson(value, HashMap.class);
   } else if (value.isJsonArray()) {
     if (value.getAsJsonArray().size() == 0) return new LinkedList();
     JsonElement obj = value.getAsJsonArray().get(0);
     if (obj.isJsonObject()) {
       if (!obj.getAsJsonObject().has("__meta__")) {
         return gson.fromJson(value, LinkedList.class);
       }
     }
   }
   return __resolve_references__(valuestr);
 }
示例#16
0
  private static String compareNodes(String path, JsonElement n1, JsonElement n2) {
    if (n1.getClass() != n2.getClass())
      return "properties differ at "
          + path
          + ": type "
          + n1.getClass().getName()
          + "/"
          + n2.getClass().getName();
    else if (n1 instanceof JsonPrimitive) {
      JsonPrimitive p1 = (JsonPrimitive) n1;
      JsonPrimitive p2 = (JsonPrimitive) n2;
      if (p1.isBoolean() && p2.isBoolean()) {
        if (p1.getAsBoolean() != p2.getAsBoolean())
          return "boolean property values differ at "
              + path
              + ": type "
              + p1.getAsString()
              + "/"
              + p2.getAsString();
      } else if (p1.isString() && p2.isString()) {
        String s1 = p1.getAsString();
        String s2 = p2.getAsString();
        if (!(s1.contains("<div") && s2.contains("<div")))
          if (!s1.equals(s2))
            if (!sameBytes(unBase64(s1), unBase64(s2)))
              return "string property values differ at " + path + ": type " + s1 + "/" + s2;
      } else if (p1.isNumber() && p2.isNumber()) {
        if (!p1.getAsString().equals(p2.getAsString()))
          return "number property values differ at "
              + path
              + ": type "
              + p1.getAsString()
              + "/"
              + p2.getAsString();
      } else
        return "property types differ at "
            + path
            + ": type "
            + p1.getAsString()
            + "/"
            + p2.getAsString();
    } else if (n1 instanceof JsonObject) {
      String s = compareObjects(path, (JsonObject) n1, (JsonObject) n2);
      if (!Utilities.noString(s)) return s;
    } else if (n1 instanceof JsonArray) {
      JsonArray a1 = (JsonArray) n1;
      JsonArray a2 = (JsonArray) n2;

      if (a1.size() != a1.size())
        return "array properties differ at "
            + path
            + ": count "
            + Integer.toString(a1.size())
            + "/"
            + Integer.toString(a2.size());
      for (int i = 0; i < a1.size(); i++) {
        String s = compareNodes(path + "[" + Integer.toString(i) + "]", a1.get(i), a2.get(i));
        if (!Utilities.noString(s)) return s;
      }
    } else if (n1 instanceof JsonNull) {

    } else return "unhandled property " + n1.getClass().getName();
    return null;
  }