Пример #1
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);
   }
 }
Пример #2
0
  public Photo(JsonObject attributes, Photo basePhoto) {
    m_identifier = readIdentifier(attributes, KEY_IDENTIFIER);
    m_image = readUri(attributes, KEY_IMAGE, (basePhoto != null) ? basePhoto.getImage() : null);
    m_title = readString(attributes, KEY_TITLE, (basePhoto != null) ? basePhoto.getTitle() : null);
    m_author =
        readString(attributes, KEY_AUTHOR, (basePhoto != null) ? basePhoto.getAuthor() : null);
    m_source =
        readHyperlink(attributes, KEY_SOURCE, (basePhoto != null) ? basePhoto.getSource() : null);
    m_tags = new ArrayList<Tag>();

    // FIXME: "tag" is just a temporary workaround for a server-side bug
    for (JsonElement tagElement :
        readArray(attributes, (attributes.has("tag")) ? "tag" : KEY_TAGS)) {
      if (tagElement.isJsonPrimitive()) {
        JsonPrimitive tagPrimitive = tagElement.getAsJsonPrimitive();
        String tagName = (tagPrimitive.isString()) ? tagPrimitive.getAsString() : null;

        if (tagName != null) {
          Tag tag = Tag.parse(tagName);

          if (tag != Tag.UNKNOWN) {
            m_tags.add(tag);
          }
        }
      }
    }

    if (m_identifier == null || m_image == null) {
      throw new IllegalArgumentException();
    }
  }
 /*
  * (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;
 }
Пример #4
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;
  }
Пример #6
0
 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;
 }
Пример #7
0
  public List<String> getJsonArrayAsString(String key) {
    List<String> arrayList = new ArrayList<>();

    getJsonArrayAsJsonElement(key)
        .forEach(
            element -> {
              JsonPrimitive jsonPrimitive = (JsonPrimitive) element;

              if (jsonPrimitive.isString()) {
                arrayList.add(jsonPrimitive.getAsString());
              }
            });

    return arrayList;
  }
Пример #8
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);
   }
 }
Пример #9
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;
  }
 private Object handlePrimitive(JsonPrimitive json) {
   if (json.isBoolean()) return json.getAsBoolean();
   else if (json.isString()) return json.getAsString();
   else {
     BigDecimal bigDec = json.getAsBigDecimal();
     // Find out if it is an int type
     try {
       bigDec.toBigIntegerExact();
       try {
         return bigDec.intValueExact();
       } catch (ArithmeticException e) {
       }
       return bigDec.longValue();
     } catch (ArithmeticException e) {
     }
     // Just return it as a double
     return bigDec.doubleValue();
   }
 }
Пример #11
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;
 }
Пример #12
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;
 }
  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;
  }