Example #1
0
  JsonValue getJsonValueAt(Iterator<FieldSegment> iter) {
    FieldSegment field = iter.next();
    if (field == null) return null;

    int index = field.getIndexSegment().getIndex();

    JsonValue kv = getJsonValueAt(index);
    // if value doesn't exist in map then return null
    if (kv == null) {
      return null;
    }

    // if this is the last path then return the value at this index
    if (field.isLastPath()) {
      return kv;
    }

    if (field.isMap()) {
      if (kv.getType() != Type.MAP) {
        return null;
      }
      return ((JsonDocument) kv).getKeyValueAt(iter);
    }
    if (kv.getType() != Type.ARRAY) {
      return null;
    }
    return ((JsonList) kv).getJsonValueAt(iter);
  }
 @Test
 public void shouldShowFirstStageApproverNameInBuildCauseBy() throws Exception {
   JsonMap jsonMap = presenter.toJson();
   JsonValue jsonValue = JsonUtils.from(jsonMap);
   String revision = jsonValue.getString("groups", 0, "history", 0, "buildCauseBy");
   assertThat(revision, is("Triggered by " + GoConstants.DEFAULT_APPROVED_BY));
 }
 private static void readJsonFile() {
   try (JsonReader jsonReader =
       Json.createReader(
           new FileReader(
               Paths.get(System.getProperty("user.dir"), "target/myData.json").toString()))) {
     JsonStructure jsonStructure = jsonReader.read();
     JsonValue.ValueType valueType = jsonStructure.getValueType();
     if (valueType == JsonValue.ValueType.OBJECT) {
       JsonObject jsonObject = (JsonObject) jsonStructure;
       JsonValue firstName = jsonObject.get("firstName");
       LOGGER.info("firstName=" + firstName);
       JsonValue emailAddresses = jsonObject.get("phoneNumbers");
       if (emailAddresses.getValueType() == JsonValue.ValueType.ARRAY) {
         JsonArray jsonArray = (JsonArray) emailAddresses;
         for (int i = 0; i < jsonArray.size(); i++) {
           JsonValue jsonValue = jsonArray.get(i);
           LOGGER.info("emailAddress(" + i + "): " + jsonValue);
         }
       }
     } else {
       LOGGER.warning("First object is not of type " + JsonValue.ValueType.OBJECT);
     }
   } catch (FileNotFoundException e) {
     LOGGER.severe("Failed to open file: " + e.getMessage());
   }
 }
Example #4
0
 public void characters(char[] characters) {
   if (current.isObject()) {
     current.addElement(key, parseCharacters(characters));
   } else if (current.isArray()) {
     current.addElement(parseCharacters(characters));
   }
 }
 @Test
 public void shouldContainPipelineCounterOrLabel() throws Exception {
   JsonMap jsonMap = presenter.toJson();
   JsonValue jsonValue = JsonUtils.from(jsonMap);
   JsonValue pipeline = jsonValue.getObject("groups", 0, "history", 0);
   assertThat(pipeline.getString("counterOrLabel"), is("1"));
 }
Example #6
0
 public static void dumpJSON(JsonValue tree, String key, String depthPrefix) {
   if (key != null) logger.info(depthPrefix + "Key " + key + ": ");
   switch (tree.getValueType()) {
     case OBJECT:
       logger.info(depthPrefix + "OBJECT");
       JsonObject object = (JsonObject) tree;
       for (String name : object.keySet()) dumpJSON(object.get(name), name, depthPrefix + "  ");
       break;
     case ARRAY:
       logger.info(depthPrefix + "ARRAY");
       JsonArray array = (JsonArray) tree;
       for (JsonValue val : array) dumpJSON(val, null, depthPrefix + "  ");
       break;
     case STRING:
       JsonString st = (JsonString) tree;
       logger.info(depthPrefix + "STRING " + st.getString());
       break;
     case NUMBER:
       JsonNumber num = (JsonNumber) tree;
       logger.info(depthPrefix + "NUMBER " + num.toString());
       break;
     case TRUE:
     case FALSE:
     case NULL:
       logger.info(depthPrefix + tree.getValueType().toString());
       break;
   }
 }
Example #7
0
  void delete(Iterator<FieldSegment> iter) {
    FieldSegment field = iter.next();
    if (field == null) return;

    int index = field.getIndexSegment().getIndex();
    JsonValue kv = getJsonValueAt(index);

    // if value doesn't exist in array then return null
    if (kv == null) {
      return;
    }

    // if this is the last path then return the value at this key in map
    if (field.isLastPath()) {
      list.remove(kv.key);
    }

    if (field.isMap()) {
      if (kv.getType() != Type.MAP) {
        return;
      }
      ((JsonDocument) kv).delete(iter);
    }

    if (kv.getType() != Type.ARRAY) {
      return;
    }
    JsonList l = (JsonList) kv;
    l.delete(iter);
  }
  @SuppressWarnings("unchecked")
  public Map<?, ?> read(Json json, JsonValue jsonData) {

    Map<K, V> values;

    try {
      values = (Map<K, V>) map.map().newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
      throw new GdxRuntimeException(e);
    }

    JsonValue entry = jsonData.getChild(name);

    while (entry != null) {

      JsonValue keyValue = entry.get("key");
      K key = json.readValue((Class<K>) map.key(), keyValue);

      JsonValue valueValue = entry.get("value");
      V value = json.readValue((Class<V>) map.value(), valueValue);

      values.put(key, value);

      entry = entry.next;
    }

    return values;
  }
Example #9
0
 @Override
 public Object get(int index) {
   JsonValue kv = getJsonValueAt(index);
   if (kv == null) {
     return null;
   }
   return kv.getObject();
 }
Example #10
0
 @Override
 public List<Object> subList(int fromIndex, int toIndex) {
   List<Object> l = new ArrayList<Object>();
   for (JsonValue v : list.subList(fromIndex, toIndex)) {
     l.add(v.getObject());
   }
   return l;
 }
Example #11
0
 @Override
 public Object previous() {
   JsonValue kv = iter.previous();
   if (kv != null) {
     return kv.getObject();
   }
   return null;
 }
Example #12
0
 @Override
 public Object next() {
   JsonValue kv = iter.next();
   if (kv != null) {
     return kv.getObject();
   }
   return null;
 }
 @Test
 public void shouldContainMaterialRevisions() throws Exception {
   JsonMap jsonMap = presenter.toJson();
   JsonValue jsonValue = JsonUtils.from(jsonMap);
   JsonValue revision = jsonValue.getObject("groups", 0, "history", 0, "materialRevisions", 0);
   assertThat(revision.getString("revision"), is("svn.100"));
   assertThat(revision.getString("user"), is("user"));
   assertThat(revision.getString("date"), is(DateUtils.formatISO8601(modificationDate)));
 }
Example #14
0
 @Override
 public Object[] toArray() {
   List<Object> objs = new ArrayList<Object>(list.size());
   // Make a copy from the JsonValue to native objects
   for (JsonValue kv : list) {
     objs.add(kv.getObject());
   }
   return objs.toArray();
 }
Example #15
0
  JsonValue createOrInsert(Iterator<FieldSegment> iter, JsonValue inJsonValue) {
    /* if the field is null then get the next field from the iterator */
    FieldSegment field;
    field = iter.next();

    int index = field.getIndexSegment().getIndex();
    JsonValue oldJsonValue = getJsonValueAt(index);
    /*
     * If this is the last element in the path then just
     * overwrite the previous value for the same key with
     * new value
     */
    if (field.isLastPath()) {
      if (index >= list.size()) {
        list.add(inJsonValue);
      } else {
        list.set(index, inJsonValue);
      }
      return this;
    }

    if (field.isMap()) {
      /*
       * if the new value for the same field is not
       * a map then delete the existing value and write new
       */
      JsonDocument newDocument;
      if ((oldJsonValue == null) || (oldJsonValue.getType() != Type.MAP)) {
        newDocument = new JsonDocument();
        newDocument.createOrInsert(iter, inJsonValue);
        if (index >= list.size()) {
          list.add(newDocument);
        } else {
          list.set(index, newDocument);
        }
        return this;
      }
      newDocument = (JsonDocument) oldJsonValue;
      return newDocument.createOrInsert(iter, inJsonValue);
    }

    /* next field is an array element - like a[3][5] */
    JsonList newList;
    if (oldJsonValue == null || ((oldJsonValue.getType() != Type.ARRAY))) {
      newList = new JsonList();
      newList.createOrInsert(iter, inJsonValue);
      if (index >= list.size()) {
        list.add(newList);
      } else {
        list.set(index, newList);
      }
      return this;
    }
    // Existing element is already an array so insert the element inside it
    newList = (JsonList) oldJsonValue;
    return newList.createOrInsert(iter, inJsonValue);
  }
Example #16
0
 public void startArray() {
   ArrayValue o = new ArrayValue();
   if (current == null) {
     current = o;
   } else if (current.isObject()) {
     current.addElement(key, o);
   } else if (current.isArray()) {
     current.addElement(o);
   }
   values.push(current);
   current = o;
 }
 protected void writeArray(JsonArray array) throws IOException {
   writeBeginArray();
   boolean first = true;
   for (JsonValue value : array) {
     if (!first) {
       writeArrayValueSeparator();
     }
     value.write(this);
     first = false;
   }
   writeEndArray();
 }
Example #18
0
 public void startObject() {
   if (current == null) {
     current = new ObjectValue();
     values.push(current);
     return;
   }
   ObjectValue o = new ObjectValue();
   if (current.isObject()) {
     current.addElement(key, o);
   } else if (current.isArray()) {
     current.addElement(o);
   }
   values.push(current);
   current = o;
 }
Example #19
0
 /** @param elementType May be null if the type is unknown. */
 public void readField(
     Object object, String fieldName, String jsonName, Class elementType, JsonValue jsonMap) {
   Type type = ReflectionCache.getType(object.getClass());
   ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
   if (fields == null) fields = cacheFields(type);
   FieldMetadata metadata = fields.get(fieldName);
   if (metadata == null)
     throw new SerializationException(
         "Field not found: " + fieldName + " (" + type.getName() + ")");
   Field field = metadata.field;
   JsonValue jsonValue = jsonMap.get(jsonName);
   if (jsonValue == null) return;
   if (elementType == null) elementType = metadata.elementType;
   try {
     field.set(object, readValue(field.getType().getClassOfType(), elementType, jsonValue));
   } catch (IllegalAccessException ex) {
     throw new SerializationException(
         "Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex);
   } catch (SerializationException ex) {
     ex.addTrace(field.getName() + " (" + type.getName() + ")");
     throw ex;
   } catch (RuntimeException runtimeEx) {
     SerializationException ex = new SerializationException(runtimeEx);
     ex.addTrace(field.getName() + " (" + type.getName() + ")");
     throw ex;
   }
 }
 @Test
 public void shouldEncodeStageLocator() {
   PipelineConfig pipelineConfig1 =
       PipelineConfigMother.createPipelineConfigWithStages("mingle-%", "stage1-%", "stage2");
   PipelineHistoryJsonPresentationModel presenter =
       new PipelineHistoryJsonPresentationModel(
           pipelinePauseInfo,
           preparePipelineHistoryGroups(pipelineConfig1),
           pipelineConfig1,
           pagination(),
           CAN_FORCE,
           hasForceBuildCause,
           hasModification,
           true);
   JsonValue json = JsonUtils.from(presenter.toJson());
   String stageLocator = json.getString("groups", 0, "history", 0, "stages", 0, "stageLocator");
   assertThat(stageLocator, is("mingle-%25/1/stage1-%25/1"));
 }
Example #21
0
  /* (non-Javadoc)
   * @see org.directwebremoting.json.JsonValue#toExternalRepresentation()
   */
  @Override
  public String toExternalRepresentation() {
    StringBuffer output = new StringBuffer();
    output.append("[ ");

    boolean isFirst = true;
    for (JsonValue value : proxy) {
      if (isFirst) {
        isFirst = false;
      } else {
        output.append(", ");
      }

      output.append(value.toExternalRepresentation());
    }
    output.append(" ]");
    return output.toString();
  }
 @Test
 public void shouldReturnErrorMessageWhenPostOfJobContainsDotForExecWorkingDir() throws Exception {
   configHelper.addPipeline("pipeline", "stage", "build1", "build2");
   String badXml =
       "<job name=\"build3\" >"
           + "<tasks>"
           + "<exec command=\"ant\" workingdir=\".\"/>"
           + "</tasks>"
           + "</job>";
   String md5 = goConfigDao.md5OfConfigFile();
   ModelAndView mav =
       controller.postBuildAsXmlPartial("pipeline", "stage", 0, badXml, md5, response);
   assertThat(response.getStatus(), is(SC_CONFLICT));
   assertThat(response.getContentType(), is(RESPONSE_CHARSET_JSON));
   Map json = (Map) mav.getModel().get("json");
   JsonValue jsonValue = JsonUtils.from(json);
   assertThat(unescapeJavaScript(jsonValue.getString("originalContent")), is(badXml));
   assertThat(
       unescapeJavaScript(jsonValue.getString("result")), containsString("File path is invalid"));
 }
Example #23
0
 public void readFields(Object object, JsonValue jsonMap) {
   Type type = ReflectionCache.getType(object.getClass());
   ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
   if (fields == null) fields = cacheFields(type);
   for (JsonValue child = jsonMap.child(); child != null; child = child.next()) {
     FieldMetadata metadata = fields.get(child.name());
     if (metadata == null) {
       if (ignoreUnknownFields) {
         if (debug)
           System.out.println(
               "Ignoring unknown field: " + child.name() + " (" + type.getName() + ")");
         continue;
       } else
         throw new SerializationException(
             "Field not found: " + child.name() + " (" + type.getName() + ")");
     }
     Field field = metadata.field;
     // if (entry.value == null) continue; // I don't remember what this did. :(
     try {
       field.set(object, readValue(field.getType().getClassOfType(), metadata.elementType, child));
     } catch (IllegalAccessException ex) {
       throw new SerializationException(
           "Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex);
     } catch (SerializationException ex) {
       ex.addTrace(field.getName() + " (" + type.getName() + ")");
       throw ex;
     } catch (RuntimeException runtimeEx) {
       SerializationException ex = new SerializationException(runtimeEx);
       ex.addTrace(field.getName() + " (" + type.getName() + ")");
       throw ex;
     }
   }
 }
  @SuppressWarnings("unchecked")
  public <M> M read(
      Json json, JsonValue jsonData, Supplier<M> newInstance, KeyValueConsumer<M, K, V> put) {

    M values = newInstance.get();

    JsonValue entry = jsonData.getChild(name);

    while (entry != null) {

      JsonValue keyValue = entry.get("key");
      K key = json.readValue((Class<K>) map.key(), keyValue);

      JsonValue valueValue = entry.get("value");
      V value = json.readValue((Class<V>) map.value(), valueValue);

      put.accept(values, key, value);

      entry = entry.next;
    }

    return values;
  }
Example #25
0
  /**
   * http://docs.oracle.com/middleware/1213/wls/WLPRG/java-api-for-json-proc.htm#WLPRG1061
   *
   * @param tree
   * @param key
   */
  public static Object navigateTree(JsonValue tree, String key) {

    Object ret = null;

    if (key != null) System.out.print("Key " + key + ": ");

    switch (tree.getValueType()) {
      case OBJECT:
        System.out.println("OBJECT");
        JsonObject object = (JsonObject) tree;

        for (String name : object.keySet()) navigateTree(object.get(name), name);
        break;
      case ARRAY:
        System.out.println("ARRAY");
        JsonArray array = (JsonArray) tree;
        for (JsonValue val : array) navigateTree(val, null);
        break;
      case STRING:
        JsonString st = (JsonString) tree;
        System.out.println("STRING " + st.getString());
        break;
      case NUMBER:
        JsonNumber num = (JsonNumber) tree;
        System.out.println("NUMBER " + num.toString());
        break;
      case TRUE:
        System.out.println("TRUE");
      case FALSE:
        System.out.println("FALSE");
      case NULL:
        System.out.println(tree.getValueType().toString());
        break;
    }

    return ret;
  }
Example #26
0
 public static int navigateTree(JsonValue tree, String skip) {
   int ret = 0;
   switch (tree.getValueType()) {
     case OBJECT:
       // System.out.println("OBJECT");
       JsonArrayBuilder dirtyResult = Json.createArrayBuilder();
       JsonObject object = (JsonObject) tree;
       for (String name : object.keySet()) {
         if (object.get(name).getValueType() == JsonValue.ValueType.STRING
             && object.getString(name).equals(skip)) {
           return 0;
         }
         dirtyResult.add(object.get(name));
       }
       ret = ret + navigateTree(dirtyResult.build(), skip);
       break;
     case ARRAY:
       // System.out.println("ARRAY");
       JsonArray array = (JsonArray) tree;
       for (JsonValue val : array) ret = ret + navigateTree(val, skip);
       break;
     case STRING:
       JsonString st = (JsonString) tree;
       // System.out.println("STRING " + st.getString());
       break;
     case NUMBER:
       JsonNumber num = (JsonNumber) tree;
       return num.intValue();
     case TRUE:
     case FALSE:
     case NULL:
       // System.out.println(tree.getValueType().toString());
       break;
   }
   return ret;
 }
  @Test
  public void shouldReturnJsonWithModifications() throws Exception {
    StageJsonPresentationModel presenter =
        new StageJsonPresentationModel(pipeline, stage, null, new Agents());
    Map json = presenter.toJson();

    JsonValue jsonValue = JsonUtils.from(json);
    JsonValue revision = jsonValue.getObject("materialRevisions", 0);
    // TODO: TRAINWRECK! WE should fix this when we re-do the JSON. We don't think this test will
    // last long in the new UI
    String expected =
        modifications
            .getMaterialRevisions()
            .getMaterialRevision(0)
            .getModifications()
            .get(0)
            .getRevision();
    assertThat(revision.getString("revision"), is(expected));
    assertThat(revision.getString("user"), is(ModificationsMother.MOD_USER_WITH_HTML_CHAR));
    assertThat(
        revision.getString("date"), is(DateUtils.formatISO8601(ModificationsMother.TODAY_CHECKIN)));
  }
Example #28
0
  /**
   * @param clazz May be null if the type is unknown.
   * @param elementType May be null if the type is unknown.
   * @return May be null.
   */
  public <T> T readValue(Class<T> clazz, Class elementType, JsonValue jsonData) {
    if (jsonData == null) return null;

    Type type = ReflectionCache.getType(clazz);
    if (jsonData.isObject()) {
      String className = typeName == null ? null : jsonData.getString(typeName, null);
      if (className != null) {
        jsonData.remove(typeName);
        try {
          type = ReflectionCache.forName(className);
        } catch (ClassNotFoundException ex) {
          type = tagToClass.get(className);
          if (type == null) throw new SerializationException(ex);
        }
      }

      Object object;
      if (type != null) {
        Serializer serializer = classToSerializer.get(type);
        if (serializer != null) return (T) serializer.read(this, jsonData, type.getClassOfType());

        object = newInstance(type);

        if (object instanceof Serializable) {
          ((Serializable) object).read(this, jsonData);
          return (T) object;
        }

        if (object instanceof HashMap) {
          HashMap result = (HashMap) object;
          for (JsonValue child = jsonData.child(); child != null; child = child.next())
            result.put(child.name(), readValue(elementType, null, child));
          return (T) result;
        }
      } else object = new OrderedMap();

      if (object instanceof ObjectMap) {
        ObjectMap result = (ObjectMap) object;
        for (JsonValue child = jsonData.child(); child != null; child = child.next())
          result.put(child.name(), readValue(elementType, null, child));
        return (T) result;
      }

      readFields(object, jsonData);
      return (T) object;
    }

    if (type != null) {
      Serializer serializer = classToSerializer.get(type);
      if (serializer != null) return (T) serializer.read(this, jsonData, type.getClassOfType());
    }

    if (jsonData.isArray()) {
      if (type == null || type.isAssignableFrom(ReflectionCache.getType(Array.class))) {
        Array newArray = new Array();
        for (JsonValue child = jsonData.child(); child != null; child = child.next())
          newArray.add(readValue(elementType, null, child));
        return (T) newArray;
      }
      if (type.isAssignableFrom(ReflectionCache.getType(ArrayList.class))) {
        ArrayList newArray = new ArrayList();
        for (JsonValue child = jsonData.child(); child != null; child = child.next())
          newArray.add(readValue(elementType, null, child));
        return (T) newArray;
      }
      if (type.isArray()) {
        Class componentType = type.getComponentType();
        if (elementType == null) elementType = componentType;
        Object newArray = ReflectionCache.newArray(componentType, jsonData.size());
        Type arrayType = ReflectionCache.getType(newArray.getClass());
        int i = 0;
        for (JsonValue child = jsonData.child(); child != null; child = child.next())
          arrayType.setArrayElement(newArray, i++, readValue(elementType, null, child));
        return (T) newArray;
      }
      throw new SerializationException(
          "Unable to convert value to required type: " + jsonData + " (" + type.getName() + ")");
    }

    Class t = type == null ? null : type.getClassOfType();
    if (jsonData.isNumber()) {
      try {
        if (type == null || t == float.class || t == Float.class)
          return (T) (Float) jsonData.asFloat();
        if (t == int.class || t == Integer.class) return (T) (Integer) jsonData.asInt();
        if (t == long.class || t == Long.class) return (T) (Long) jsonData.asLong();
        if (t == double.class || t == Double.class) return (T) (Double) (double) jsonData.asFloat();
        if (t == String.class) return (T) Float.toString(jsonData.asFloat());
        if (t == short.class || t == Short.class) return (T) (Short) (short) jsonData.asInt();
        if (t == byte.class || t == Byte.class) return (T) (Byte) (byte) jsonData.asInt();
      } catch (NumberFormatException ignored) {
      }
      jsonData = new JsonValue(jsonData.asString());
    }

    if (jsonData.isBoolean()) {
      try {
        if (type == null || t == boolean.class || t == Boolean.class)
          return (T) (Boolean) jsonData.asBoolean();
      } catch (NumberFormatException ignored) {
      }
      jsonData = new JsonValue(jsonData.asString());
    }

    if (jsonData.isString()) {
      String string = jsonData.asString();
      if (type == null || t == String.class) return (T) string;
      try {
        if (t == int.class || t == Integer.class) return (T) Integer.valueOf(string);
        if (t == float.class || t == Float.class) return (T) Float.valueOf(string);
        if (t == long.class || t == Long.class) return (T) Long.valueOf(string);
        if (t == double.class || t == Double.class) return (T) Double.valueOf(string);
        if (t == short.class || t == Short.class) return (T) Short.valueOf(string);
        if (t == byte.class || t == Byte.class) return (T) Byte.valueOf(string);
      } catch (NumberFormatException ignored) {
      }
      if (t == boolean.class || t == Boolean.class) return (T) Boolean.valueOf(string);
      if (t == char.class || t == Character.class) return (T) (Character) string.charAt(0);
      if (type.isEnum()) {
        Object[] constants = type.getEnumConstants();
        for (int i = 0, n = constants.length; i < n; i++)
          if (string.equals(constants[i].toString())) return (T) constants[i];
      }
      if (t == CharSequence.class) return (T) string;
      throw new SerializationException(
          "Unable to convert value to required type: " + jsonData + " (" + type.getName() + ")");
    }

    return null;
  }
Example #29
0
 /**
  * Reads a JSON array from the given string.
  *
  * @param string the string that contains the JSON array
  * @return the JSON array that has been read
  * @throws ParseException if the input is not valid JSON
  * @throws UnsupportedOperationException if the input does not contain a JSON array
  */
 public static JsonArray readFrom(String string) {
   return JsonValue.readFrom(string).asArray();
 }
Example #30
0
 /**
  * Reads a JSON array from the given reader.
  *
  * @param reader the reader to read the JSON array from
  * @return the JSON array that has been read
  * @throws IOException if an I/O error occurs in the reader
  * @throws ParseException if the input is not valid JSON
  * @throws UnsupportedOperationException if the input does not contain a JSON array
  */
 public static JsonArray readFrom(Reader reader) throws IOException {
   return JsonValue.readFrom(reader).asArray();
 }