コード例 #1
0
 @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");
 }
コード例 #2
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());
          }
        }
コード例 #3
0
 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);
   }
 }
コード例 #4
0
 /*
  * (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
ファイル: Segment.java プロジェクト: GameModsBR/MyTown2
 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;
 }
コード例 #7
0
  @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;
  }
コード例 #8
0
 @Override
 public boolean equals(Object obj) {
   if (this == obj) {
     return true;
   }
   if (obj == null || getClass() != obj.getClass()) {
     return false;
   }
   JsonPrimitive other = (JsonPrimitive) obj;
   if (value == null) {
     return other.value == null;
   }
   if (isIntegral(this) && isIntegral(other)) {
     return getAsNumber().longValue() == other.getAsNumber().longValue();
   }
   if (isFloatingPoint(this) && isFloatingPoint(other)) {
     double a = getAsNumber().doubleValue();
     // Java standard types other than double return true for two NaN. So, need
     // special handling for double.
     double b = other.getAsNumber().doubleValue();
     return a == b || (Double.isNaN(a) && Double.isNaN(b));
   }
   return value.equals(other.value);
 }
コード例 #9
0
ファイル: ConfigOption.java プロジェクト: secoya/plovr
 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
ファイル: MongoDbUtil.java プロジェクト: hbostic/Infinit.e
 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
コード例 #12
0
  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);
    }
  }
コード例 #13
0
ファイル: RpcClient.java プロジェクト: kevinross/jsonrpc
 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);
 }