Example #1
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();
    }
  }
 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;
 }
  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;
  }
 /*
  * (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;
 }
 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);
   }
 }
Example #6
0
  @Test
  public void testSerializesId() {
    IdTypeAdapter typeAdapter = new IdTypeAdapter();

    JsonElement element = typeAdapter.serialize(new Id("foo"), Id.class, null);

    assertThat(element).isInstanceOf(JsonPrimitive.class);
    assertThat(((JsonPrimitive) element).getAsString()).isEqualTo("foo");
  }
 private Object deserializeValue(
     JsonPrimitive val, org.eclipse.leshan.core.model.ResourceModel.Type expectedType) {
   switch (expectedType) {
     case BOOLEAN:
       return val.getAsBoolean();
     case STRING:
       return val.getAsString();
     case INTEGER:
       return val.getAsLong();
     case FLOAT:
       return val.getAsDouble();
     case TIME:
     case OPAQUE:
     default:
       // TODO we need to better handle this.
       return val.getAsString();
   }
 }
Example #8
0
  /**
   * This private operation creates an instance of the Message class from a string using a JSON
   * parser.
   *
   * <p>This operation is synchronized so that the core can't be overloaded.
   *
   * @param messageString The original message, as a string
   * @return list list of built messages.
   */
  private ArrayList<Message> buildMessagesFromString(String messageString) {

    // Create the ArrayList of messages
    ArrayList<Message> messages = new ArrayList<Message>();

    // Create the parser and gson utility
    JsonParser parser = new JsonParser();
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();

    // Catch any exceptions and return the empty list
    try {

      // Make the string a json string
      JsonElement messageJson = parser.parse(messageString);
      JsonObject messageJsonObject = messageJson.getAsJsonObject();

      // Get the Item id from the json
      JsonPrimitive itemIdJson = messageJsonObject.getAsJsonPrimitive("item_id");
      int itemId = itemIdJson.getAsInt();

      // Get the array of posts from the message
      JsonArray jsonMessagesList = messageJsonObject.getAsJsonArray("posts");

      // Load the list
      for (int i = 0; i < jsonMessagesList.size(); i++) {
        // Get the message as a json element
        JsonElement jsonMessage = jsonMessagesList.get(i);
        // Marshal it into a message
        Message tmpMessage = gson.fromJson(jsonMessage, Message.class);
        // Set the item id
        tmpMessage.setItemId(itemId);
        // Put it in the list
        messages.add(tmpMessage);
      }
    } catch (JsonParseException e) {
      // Log the message
      String err = "Core Message: " + "JSON parsing failed for message " + messageString;
      logger.error(getClass().getName() + " Exception!", e);
      logger.error(err);
    }

    return messages;
  }
 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();
   }
 }
 @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");
 }
  /**
   * Parse response to a wait-container request.
   *
   * @return Status code upon exit
   */
  public static int waitFor(HttpResponse response) throws DockerException {
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode != 200) {
      switch (statusCode) {
        case 404:
          throw new DockerException("Container not found");

        case 500:
          throw new DockerException("Server error");

        default:
          throw new DockerException("Unknown status code");
      }
    }

    JsonElement jsonResult = null;

    // Obtain resulting JSON object
    try {
      jsonResult = new JsonParser().parse(new InputStreamReader(response.getEntity().getContent()));
    } catch (Exception e) {
      throw new DockerException(e);
    }

    if (jsonResult == null || !jsonResult.isJsonObject())
      throw new DockerException("Unexpected result type");

    JsonObject object = jsonResult.getAsJsonObject();

    if (!object.has("StatusCode")) throw new DockerException("Unexpected result schema");

    JsonElement statusElem = object.get("StatusCode");

    if (!statusElem.isJsonPrimitive())
      throw new DockerException("Expected status code to be a JSON primitive");

    JsonPrimitive statusPrim = statusElem.getAsJsonPrimitive();

    return statusPrim.getAsInt();
  }
Example #12
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());
          }
        }
 /**
  * Returns a Json element as a string
  *
  * @param object json Object
  * @param key element key
  * @return Element value
  */
 private static String getChildElementText(JsonObject object, String key) {
   JsonElement element = object.get(key);
   if (element != null && element.isJsonArray()) {
     if (((JsonArray) element).size() == 1) {
       return object.get(key).getAsString();
     } else {
       StringBuffer sb = new StringBuffer();
       JsonArray elements = (JsonArray) object.get(key);
       for (int i = 0; i < elements.size(); i++) {
         JsonPrimitive ob = (JsonPrimitive) elements.get(i);
         sb.append(ob.getAsString());
         if (i < elements.size() - 1) {
           sb.append(",");
         }
       }
       return sb.toString();
     }
   } else if (element != null && (element.isJsonObject() || element.isJsonPrimitive())) {
     return object.get(key).getAsString();
   }
   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;
  }
Example #15
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;
  }
 @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);
 }
Example #17
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;
 }
Example #18
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);
   }
 }
Example #19
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
Example #20
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;
 }
  @Override
  public void onDataChanged(String s, String s1, String s2, String s3) {
    System.out.println("Data changed to <" + s + "> in document <" + s1 + ">");
    System.out.println("    Changed: " + s2);

    JsonObject jsonAlarmSettings = _parser.parse(s2).getAsJsonObject();

    JsonPrimitive jsonPS = jsonAlarmSettings.getAsJsonPrimitive("power_switch");
    JsonPrimitive jsonTS = jsonAlarmSettings.getAsJsonPrimitive("trigger_switch");
    JsonPrimitive jsonDuration = jsonAlarmSettings.getAsJsonPrimitive("duration");

    if (jsonPS != null) {
      int powerSwitch = jsonPS.getAsInt();
      _model.setPowerSwitch((powerSwitch == 1));
    } else if (jsonTS != null) {
      int triggerSwitch = jsonTS.getAsInt();
      _model.setTriggerSwitch((triggerSwitch == 1));
    } else if (jsonDuration != null) {
      int duration = jsonDuration.getAsInt();
      _model.setDurationSeconds(duration);
    }

    _callback.callback(null, _model);
  }
 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;
 }
Example #23
0
 @Override
 public Cat deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
     throws JsonParseException {
   JsonPrimitive prim = json.getAsJsonPrimitive();
   return new Cat(prim.getAsString());
 }
    @Nullable
    public ChatModifier a(
        JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext)
        throws JsonParseException {
      if (jsonelement.isJsonObject()) {
        ChatModifier chatmodifier = new ChatModifier();
        JsonObject jsonobject = jsonelement.getAsJsonObject();

        if (jsonobject == null) {
          return null;
        } else {
          if (jsonobject.has("bold")) {
            chatmodifier.c = Boolean.valueOf(jsonobject.get("bold").getAsBoolean());
          }

          if (jsonobject.has("italic")) {
            chatmodifier.d = Boolean.valueOf(jsonobject.get("italic").getAsBoolean());
          }

          if (jsonobject.has("underlined")) {
            chatmodifier.e = Boolean.valueOf(jsonobject.get("underlined").getAsBoolean());
          }

          if (jsonobject.has("strikethrough")) {
            chatmodifier.f = Boolean.valueOf(jsonobject.get("strikethrough").getAsBoolean());
          }

          if (jsonobject.has("obfuscated")) {
            chatmodifier.g = Boolean.valueOf(jsonobject.get("obfuscated").getAsBoolean());
          }

          if (jsonobject.has("color")) {
            chatmodifier.b =
                (EnumChatFormat)
                    jsondeserializationcontext.deserialize(
                        jsonobject.get("color"), EnumChatFormat.class);
          }

          if (jsonobject.has("insertion")) {
            chatmodifier.j = jsonobject.get("insertion").getAsString();
          }

          JsonObject jsonobject1;
          JsonPrimitive jsonprimitive;

          if (jsonobject.has("clickEvent")) {
            jsonobject1 = jsonobject.getAsJsonObject("clickEvent");
            if (jsonobject1 != null) {
              jsonprimitive = jsonobject1.getAsJsonPrimitive("action");
              ChatClickable.EnumClickAction chatclickable_enumclickaction =
                  jsonprimitive == null
                      ? null
                      : ChatClickable.EnumClickAction.a(jsonprimitive.getAsString());
              JsonPrimitive jsonprimitive1 = jsonobject1.getAsJsonPrimitive("value");
              String s = jsonprimitive1 == null ? null : jsonprimitive1.getAsString();

              if (chatclickable_enumclickaction != null
                  && s != null
                  && chatclickable_enumclickaction.a()) {
                chatmodifier.h = new ChatClickable(chatclickable_enumclickaction, s);
              }
            }
          }

          if (jsonobject.has("hoverEvent")) {
            jsonobject1 = jsonobject.getAsJsonObject("hoverEvent");
            if (jsonobject1 != null) {
              jsonprimitive = jsonobject1.getAsJsonPrimitive("action");
              ChatHoverable.EnumHoverAction chathoverable_enumhoveraction =
                  jsonprimitive == null
                      ? null
                      : ChatHoverable.EnumHoverAction.a(jsonprimitive.getAsString());
              IChatBaseComponent ichatbasecomponent =
                  (IChatBaseComponent)
                      jsondeserializationcontext.deserialize(
                          jsonobject1.get("value"), IChatBaseComponent.class);

              if (chathoverable_enumhoveraction != null
                  && ichatbasecomponent != null
                  && chathoverable_enumhoveraction.a()) {
                chatmodifier.i =
                    new ChatHoverable(chathoverable_enumhoveraction, ichatbasecomponent);
              }
            }
          }

          return chatmodifier;
        }
      } else {
        return null;
      }
    }
Example #25
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 class_ez a(JsonElement var1, Type var2, JsonDeserializationContext var3)
        throws JsonParseException {
      if (var1.isJsonObject()) {
        class_ez var4 = new class_ez();
        JsonObject var5 = var1.getAsJsonObject();
        if (var5 == null) {
          return null;
        } else {
          if (var5.has("bold")) {
            var4.c = Boolean.valueOf(var5.get("bold").getAsBoolean());
          }

          if (var5.has("italic")) {
            var4.d = Boolean.valueOf(var5.get("italic").getAsBoolean());
          }

          if (var5.has("underlined")) {
            var4.e = Boolean.valueOf(var5.get("underlined").getAsBoolean());
          }

          if (var5.has("strikethrough")) {
            var4.f = Boolean.valueOf(var5.get("strikethrough").getAsBoolean());
          }

          if (var5.has("obfuscated")) {
            var4.g = Boolean.valueOf(var5.get("obfuscated").getAsBoolean());
          }

          if (var5.has("color")) {
            var4.b = (EnumChatFormat) var3.deserialize(var5.get("color"), EnumChatFormat.class);
          }

          if (var5.has("insertion")) {
            var4.j = var5.get("insertion").getAsString();
          }

          JsonObject var6;
          JsonPrimitive var7;
          if (var5.has("clickEvent")) {
            var6 = var5.getAsJsonObject("clickEvent");
            if (var6 != null) {
              var7 = var6.getAsJsonPrimitive("action");
              class_et.class_a_in_class_et var8 =
                  var7 == null ? null : class_et.class_a_in_class_et.a(var7.getAsString());
              JsonPrimitive var9 = var6.getAsJsonPrimitive("value");
              String var10 = var9 == null ? null : var9.getAsString();
              if ((var8 != null) && (var10 != null) && var8.a()) {
                var4.h = new class_et(var8, var10);
              }
            }
          }

          if (var5.has("hoverEvent")) {
            var6 = var5.getAsJsonObject("hoverEvent");
            if (var6 != null) {
              var7 = var6.getAsJsonPrimitive("action");
              class_ew.class_a_in_class_ew var11 =
                  var7 == null ? null : class_ew.class_a_in_class_ew.a(var7.getAsString());
              IChatBaseComponent var12 =
                  (IChatBaseComponent)
                      var3.deserialize(var6.get("value"), IChatBaseComponent.class);
              if ((var11 != null) && (var12 != null) && var11.a()) {
                var4.i = new class_ew(var11, var12);
              }
            }
          }

          return var4;
        }
      } else {
        return null;
      }
    }
Example #27
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;
  }
Example #28
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);
 }
  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);
    }
  }