Ejemplo n.º 1
0
  private static OrderedMap<Long, Double[]> _MergeDataSets(boolean F, TemperatureSet TSList[]) {

    /* merge temperature data sets */
    OrderedMap<Long, Double[]> rowMap = new OrderedMap<Long, Double[]>();
    if (!ListTools.isEmpty(TSList)) {
      for (int d = 0; d < TSList.length; d++) {
        TemperatureSet TS = TSList[d];
        if (TS != null) {
          Collection<Temperature> TList = TS.getTemperatures();
          for (Temperature T : TList) {
            Long ts = new Long(T.getTimestamp());
            Double tmp = new Double(T.getTemperature(F));
            Double row[] = rowMap.get(ts);
            if (row == null) {
              row = new Double[TSList.length];
              rowMap.put(ts, row);
            }
            row[d] = tmp;
          }
        }
      }
    }

    /* sort by timestamp */
    rowMap.sortKeys(new ListTools.NumberComparator<Long>());

    /* return */
    return rowMap;
  }
Ejemplo n.º 2
0
 public void readFields(Object object, Object jsonData) {
   OrderedMap<String, Object> jsonMap = (OrderedMap) jsonData;
   Class type = object.getClass();
   ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
   if (fields == null) fields = cacheFields(type);
   for (Entry<String, Object> entry : jsonMap.entries()) {
     FieldMetadata metadata = fields.get(entry.key);
     if (metadata == null) {
       if (ignoreUnknownFields) {
         if (debug)
           System.out.println(
               "Ignoring unknown field: " + entry.key + " (" + type.getName() + ")");
         continue;
       } else
         throw new SerializationException(
             "Field not found: " + entry.key + " (" + type.getName() + ")");
     }
     Field field = metadata.field;
     if (entry.value == null) continue;
     try {
       field.set(object, readValue(field.getType(), metadata.elementType, entry.value));
     } 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;
     }
   }
 }
Ejemplo n.º 3
0
  private static String CreateGoogleDataTableJSON(boolean F, TemperatureSet... TSList) {

    /* merge temperature data sets */
    OrderedMap<Long, Double[]> rowMap = _MergeDataSets(F, TSList);

    /* create JSON "cols" Object */
    JSON._Array dataTable_cols = new JSON._Array();
    // -- DateTime
    JSON._Object col_dateTime = (new JSON._Object()).setFormatIndent(false);
    col_dateTime.addKeyValue("id", "date");
    col_dateTime.addKeyValue("label", "Date/Time");
    col_dateTime.addKeyValue("type", "datetime");
    dataTable_cols.addValue(col_dateTime);
    // -- data set titles
    if (!ListTools.isEmpty(TSList)) {
      for (int d = 0; d < TSList.length; d++) {
        TemperatureSet TS = TSList[d];
        JSON._Object col_temp = (new JSON._Object()).setFormatIndent(false);
        col_temp.addKeyValue("id", "temp" + (d + 1));
        col_temp.addKeyValue("label", "Temp-" + (d + 1));
        col_temp.addKeyValue("type", "number");
        dataTable_cols.addValue(col_temp);
      }
    }

    /* create JSON "rows" Object */
    JSON._Array dataTable_rows = new JSON._Array();
    for (Long ts : rowMap.keySet()) {
      JSON._Object col = new JSON._Object();
      // TODO
    }

    /* return */
    return null; // TODO:
  }
Ejemplo n.º 4
0
 /**
  * @param type 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(
     String name, Class<T> type, Class elementType, T defaultValue, Object jsonData) {
   OrderedMap jsonMap = (OrderedMap) jsonData;
   Object jsonValue = jsonMap.get(name);
   if (jsonValue == null) return defaultValue;
   return (T) readValue(type, elementType, jsonValue);
 }
Ejemplo n.º 5
0
 /** @param elementType May be null if the type is unknown. */
 public void readField(
     Object object, String fieldName, String jsonName, Class elementType, Object jsonData) {
   OrderedMap jsonMap = (OrderedMap) jsonData;
   Class type = 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;
   Object jsonValue = jsonMap.get(jsonName);
   if (jsonValue == null) return;
   if (elementType == null) elementType = metadata.elementType;
   try {
     field.set(object, readValue(field.getType(), 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;
   }
 }
Ejemplo n.º 6
0
 /**
  * ** Gets an <code>OrderedMap</code> of the argument key/value pairs indexed ** by their keys
  * ** @return An <code>OrderedMap</code> of the argument key/value pairs
  */
 protected OrderedMap<String, KeyVal> getKeyValMap() {
   OrderedMap<String, KeyVal> kvMap = new OrderedMap<String, KeyVal>();
   for (KeyVal kv : this.getKeyValList()) {
     // only the first occurance is retained
     String kn = kv.getKey();
     if (!kvMap.containsKey(kn)) {
       kvMap.put(kn, kv);
     }
   }
   return kvMap;
 }
Ejemplo n.º 7
0
 /* write mapping support JS to stream */
 public static void writePushpinArray(PrintWriter out, RequestProperties reqState)
     throws IOException {
   MapProvider mapProv = reqState.getMapProvider();
   out.write("// Icon URLs\n");
   out.write("var jsvPushpinIcon = new Array(\n");
   OrderedMap<String, PushpinIcon> iconMap = mapProv.getPushpinIconMap(reqState);
   for (Iterator<String> k = iconMap.keyIterator(); k.hasNext(); ) {
     String key = k.next();
     PushpinIcon ppi = iconMap.get(key);
     String I = ppi.getIconURL();
     boolean iE = ppi.getIconEval();
     int iW = ppi.getIconWidth();
     int iH = ppi.getIconHeight();
     int iX = ppi.getIconHotspotX();
     int iY = ppi.getIconHotspotY();
     String S = ppi.getShadowURL();
     int sW = ppi.getShadowWidth();
     int sH = ppi.getShadowHeight();
     String B = ppi.getBackgroundURL();
     int bW = ppi.getBackgroundWidth();
     int bH = ppi.getBackgroundHeight();
     int bX = ppi.getBackgroundOffsetX();
     int bY = ppi.getBackgroundOffsetY();
     out.write("    {");
     out.write(" key:\"" + key + "\",");
     if (iE) {
       out.write(" iconEval:\"" + I + "\",");
     } else {
       out.write(" iconURL:\"" + I + "\",");
     }
     out.write(" iconSize:[" + iW + "," + iH + "],");
     out.write(" iconOffset:[" + iX + "," + iY + "],");
     out.write(" iconHotspot:[" + iX + "," + iY + "],");
     out.write(" shadowURL:\"" + S + "\",");
     out.write(" shadowSize:[" + sW + "," + sH + "]");
     if (!StringTools.isBlank(B)) {
       out.write(",");
       out.write(" bgURL:\"" + B + "\",");
       out.write(" bgSize:[" + bW + "," + bH + "],");
       out.write(" bgOffset:[" + bX + "," + bY + "]");
     }
     out.write(" }");
     if (k.hasNext()) {
       out.write(",");
     }
     out.write("\n");
   }
   out.write("    );\n");
 }
Ejemplo n.º 8
0
  /**
   * ** Creates a Google DataTable containing the specified TemperatureSet Data ** @param F True for
   * Fahrenheit, false for Celsius ** @param TSList The TemperatureSet data array ** @return The
   * "DataTable" String.
   */
  public static String CreateGoogleDataTableJavaScript(boolean F, TemperatureSet... TSList) {
    // {
    //   cols: [
    //       { id: "date" , label: "Date/Time", type: "datetime" },
    //       { id: "temp1", label: "Temp-1"   , type: "number"   },
    //       { id: "temp2", label: "Temp-2"   , type: "number"   }
    //   ],
    //   rows: [
    //       { c: [ { v: new Date(1383914237000) }, { v: -12.6 }, { v: -18.1 } ] },
    //       { c: [ { v: new Date(1384914237000) }, { v:  -5.1 }, { v:  -7.3 } ] },
    //       { c: [ { v: new Date(1385914345000) }, { v:  null }, { v:  -2.1 } ] },
    //       { c: [ { v: new Date(1386924683000) }, { v:  -2.0 }, { v:  null } ] },
    //       { c: [ { v: new Date(1387934245000) }, { v:   5.8 }, { v:   6.7 } ] }
    //   ]
    // }

    /* merge temperature data sets */
    OrderedMap<Long, Double[]> rowMap = _MergeDataSets(F, TSList);

    /* init */
    StringBuffer sb = new StringBuffer();
    sb.append("{").append("\n");

    /* "cols" */
    sb.append("  cols: [").append("\n");
    // --
    sb.append("    { id:\"date\", label:\"Date/Time\", type:\"datetime\" },").append("\n");
    // --
    for (int d = 0; d < TSList.length; d++) {
      String id = "temp" + (d + 1);
      String label = "Temp-" + (d + 1);
      String type = "number";
      sb.append("    { id:\"" + id + "\", label:\"" + label + "\", type:\"" + type + "\" },")
          .append("\n");
    }
    // --
    sb.append("  ],").append("\n");

    /* "rows" */
    // { c: [ { v: new Date(1383914237000) }, { v: -12.6 }, { v: -18.1 } ] },
    sb.append("  rows: [").append("\n");
    int rows = 0, rowCnt = rowMap.size();
    for (Long ts : rowMap.keySet()) {
      sb.append("    { c: [ ");
      sb.append("{v:new Date(" + (ts.longValue() * 1000L) + ")}, ");
      Double tmp[] = rowMap.get(ts);
      for (int t = 0; t < tmp.length; t++) {
        Double D = tmp[t];
        if (t > 0) {
          sb.append(", ");
        }
        String Ds = (D != null) ? StringTools.format(D, "0.0") : "null";
        sb.append("{v:" + Ds + "}");
      }
      sb.append(" ]}");
      if (rows < (rowCnt - 1)) {
        sb.append(",");
      }
      sb.append("\n");
      rows++;
    }
    sb.append("  ]").append("\n");

    /* return */
    sb.append("}");
    return sb.toString();
  }
Ejemplo n.º 9
0
  /**
   * @param type 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> type, Class elementType, Object jsonData) {
    if (jsonData == null) return null;

    if (jsonData instanceof OrderedMap) {
      OrderedMap<String, Object> jsonMap = (OrderedMap) jsonData;

      String className = typeName == null ? null : (String) jsonMap.remove(typeName);
      if (className != null) {
        try {
          type = (Class<T>) Class.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, jsonMap, type);

        object = newInstance(type);

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

        if (object instanceof HashMap) {
          HashMap result = (HashMap) object;
          for (Entry entry : jsonMap.entries())
            result.put(entry.key, readValue(elementType, null, entry.value));
          return (T) result;
        }
      } else object = new OrderedMap();

      if (object instanceof ObjectMap) {
        ObjectMap result = (ObjectMap) object;
        for (String key : jsonMap.orderedKeys())
          result.put(key, readValue(elementType, null, jsonMap.get(key)));
        return (T) result;
      }

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

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

    if (jsonData instanceof Array) {
      Array array = (Array) jsonData;
      if (type == null || Array.class.isAssignableFrom(type)) {
        Array newArray = type == null ? new Array() : (Array) newInstance(type);
        newArray.ensureCapacity(array.size);
        for (int i = 0, n = array.size; i < n; i++)
          newArray.add(readValue(elementType, null, array.get(i)));
        return (T) newArray;
      }
      if (ArrayList.class.isAssignableFrom(type)) {
        ArrayList newArray = type == null ? new ArrayList() : (ArrayList) newInstance(type);
        newArray.ensureCapacity(array.size);
        for (int i = 0, n = array.size; i < n; i++)
          newArray.add(readValue(elementType, null, array.get(i)));
        return (T) newArray;
      }
      if (type.isArray()) {
        Class componentType = type.getComponentType();
        if (elementType == null) elementType = componentType;
        Object newArray = java.lang.reflect.Array.newInstance(componentType, array.size);
        for (int i = 0, n = array.size; i < n; i++)
          java.lang.reflect.Array.set(newArray, i, readValue(elementType, null, array.get(i)));
        return (T) newArray;
      }
      throw new SerializationException(
          "Unable to convert value to required type: " + jsonData + " (" + type.getName() + ")");
    }

    if (jsonData instanceof Float) {
      Float floatValue = (Float) jsonData;
      try {
        if (type == null || type == float.class || type == Float.class)
          return (T) (Float) floatValue;
        if (type == int.class || type == Integer.class) return (T) (Integer) floatValue.intValue();
        if (type == long.class || type == Long.class) return (T) (Long) floatValue.longValue();
        if (type == double.class || type == Double.class)
          return (T) (Double) floatValue.doubleValue();
        if (type == short.class || type == Short.class) return (T) (Short) floatValue.shortValue();
        if (type == byte.class || type == Byte.class) return (T) (Byte) floatValue.byteValue();
      } catch (NumberFormatException ignored) {
      }
      jsonData = String.valueOf(jsonData);
    }

    if (jsonData instanceof Boolean) jsonData = String.valueOf(jsonData);

    if (jsonData instanceof String) {
      String string = (String) jsonData;
      if (type == null || type == String.class) return (T) jsonData;
      try {
        if (type == int.class || type == Integer.class) return (T) Integer.valueOf(string);
        if (type == float.class || type == Float.class) return (T) Float.valueOf(string);
        if (type == long.class || type == Long.class) return (T) Long.valueOf(string);
        if (type == double.class || type == Double.class) return (T) Double.valueOf(string);
        if (type == short.class || type == Short.class) return (T) Short.valueOf(string);
        if (type == byte.class || type == Byte.class) return (T) Byte.valueOf(string);
      } catch (NumberFormatException ignored) {
      }
      if (type == boolean.class || type == Boolean.class) return (T) Boolean.valueOf(string);
      if (type == char.class || type == 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 (type == CharSequence.class) return (T) string;
      throw new SerializationException(
          "Unable to convert value to required type: " + jsonData + " (" + type.getName() + ")");
    }

    return null;
  }
Ejemplo n.º 10
0
 /**
  * @param type 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(String name, Class<T> type, Class elementType, Object jsonData) {
   OrderedMap jsonMap = (OrderedMap) jsonData;
   return (T) readValue(type, elementType, jsonMap.get(name));
 }
Ejemplo n.º 11
0
  /**
   * @param value May be null.
   * @param knownType May be null if the type is unknown.
   * @param elementType May be null if the type is unknown.
   */
  public void writeValue(Object value, Class knownType, Class elementType) {
    try {
      if (value == null) {
        writer.value(null);
        return;
      }

      Class actualType = value.getClass();

      if (actualType.isPrimitive()
          || actualType == String.class
          || actualType == Integer.class
          || actualType == Boolean.class
          || actualType == Float.class
          || actualType == Long.class
          || actualType == Double.class
          || actualType == Short.class
          || actualType == Byte.class
          || actualType == Character.class) {
        writer.value(value);
        return;
      }

      if (value instanceof Serializable) {
        writeObjectStart(actualType, knownType);
        ((Serializable) value).write(this);
        writeObjectEnd();
        return;
      }

      Serializer serializer = classToSerializer.get(actualType);
      if (serializer != null) {
        serializer.write(this, value, knownType);
        return;
      }

      if (value instanceof Array) {
        if (knownType != null && actualType != knownType)
          throw new SerializationException(
              "Serialization of an Array other than the known type is not supported.\n"
                  + "Known type: "
                  + knownType
                  + "\nActual type: "
                  + actualType);
        writeArrayStart();
        Array array = (Array) value;
        for (int i = 0, n = array.size; i < n; i++) writeValue(array.get(i), elementType, null);
        writeArrayEnd();
        return;
      }

      if (value instanceof Collection) {
        if (knownType != null && actualType != knownType && actualType != ArrayList.class)
          throw new SerializationException(
              "Serialization of a Collection other than the known type is not supported.\n"
                  + "Known type: "
                  + knownType
                  + "\nActual type: "
                  + actualType);
        writeArrayStart();
        for (Object item : (Collection) value) writeValue(item, elementType, null);
        writeArrayEnd();
        return;
      }

      if (actualType.isArray()) {
        if (elementType == null) elementType = actualType.getComponentType();
        int length = java.lang.reflect.Array.getLength(value);
        writeArrayStart();
        for (int i = 0; i < length; i++)
          writeValue(java.lang.reflect.Array.get(value, i), elementType, null);
        writeArrayEnd();
        return;
      }

      if (value instanceof OrderedMap) {
        if (knownType == null) knownType = OrderedMap.class;
        writeObjectStart(actualType, knownType);
        OrderedMap map = (OrderedMap) value;
        for (Object key : map.orderedKeys()) {
          writer.name(convertToString(key));
          writeValue(map.get(key), elementType, null);
        }
        writeObjectEnd();
        return;
      }

      if (value instanceof ArrayMap) {
        if (knownType == null) knownType = ArrayMap.class;
        writeObjectStart(actualType, knownType);
        ArrayMap map = (ArrayMap) value;
        for (int i = 0, n = map.size; i < n; i++) {
          writer.name(convertToString(map.keys[i]));
          writeValue(map.values[i], elementType, null);
        }
        writeObjectEnd();
        return;
      }

      if (value instanceof ObjectMap) {
        if (knownType == null) knownType = OrderedMap.class;
        writeObjectStart(actualType, knownType);
        for (Entry entry : ((ObjectMap<?, ?>) value).entries()) {
          writer.name(convertToString(entry.key));
          writeValue(entry.value, elementType, null);
        }
        writeObjectEnd();
        return;
      }

      if (value instanceof Map) {
        if (knownType == null) knownType = OrderedMap.class;
        writeObjectStart(actualType, knownType);
        for (Map.Entry entry : ((Map<?, ?>) value).entrySet()) {
          writer.name(convertToString(entry.getKey()));
          writeValue(entry.getValue(), elementType, null);
        }
        writeObjectEnd();
        return;
      }

      if (actualType.isEnum()) {
        writer.value(value);
        return;
      }

      writeObjectStart(actualType, knownType);
      writeFields(value);
      writeObjectEnd();
    } catch (IOException ex) {
      throw new SerializationException(ex);
    }
  }
Ejemplo n.º 12
0
 private void prettyPrint(Object object, StringBuilder buffer, int indent, int singleLineColumns) {
   if (object instanceof OrderedMap) {
     OrderedMap<String, ?> map = (OrderedMap) object;
     if (map.size == 0) {
       buffer.append("{}");
     } else {
       boolean newLines = !isFlat(map);
       int start = buffer.length();
       outer:
       while (true) {
         buffer.append(newLines ? "{\n" : "{ ");
         int i = 0;
         for (String key : map.orderedKeys()) {
           if (newLines) indent(indent, buffer);
           buffer.append(outputType.quoteName(key));
           buffer.append(": ");
           prettyPrint(map.get(key), buffer, indent + 1, singleLineColumns);
           if (i++ < map.size - 1) buffer.append(",");
           buffer.append(newLines ? '\n' : ' ');
           if (!newLines && buffer.length() - start > singleLineColumns) {
             buffer.setLength(start);
             newLines = true;
             continue outer;
           }
         }
         break;
       }
       if (newLines) indent(indent - 1, buffer);
       buffer.append('}');
     }
   } else if (object instanceof Array) {
     Array array = (Array) object;
     if (array.size == 0) {
       buffer.append("[]");
     } else {
       boolean newLines = !isFlat(array);
       int start = buffer.length();
       outer:
       while (true) {
         buffer.append(newLines ? "[\n" : "[ ");
         for (int i = 0, n = array.size; i < n; i++) {
           if (newLines) indent(indent, buffer);
           prettyPrint(array.get(i), buffer, indent + 1, singleLineColumns);
           if (i < array.size - 1) buffer.append(",");
           buffer.append(newLines ? '\n' : ' ');
           if (!newLines && buffer.length() - start > singleLineColumns) {
             buffer.setLength(start);
             newLines = true;
             continue outer;
           }
         }
         break;
       }
       if (newLines) indent(indent - 1, buffer);
       buffer.append(']');
     }
   } else if (object instanceof String) {
     buffer.append(outputType.quoteValue((String) object));
   } else if (object instanceof Float) {
     Float floatValue = (Float) object;
     int intValue = floatValue.intValue();
     buffer.append(floatValue - intValue == 0 ? intValue : object);
   } else if (object instanceof Boolean) {
     buffer.append(object);
   } else if (object == null) {
     buffer.append("null");
   } else throw new SerializationException("Unknown object type: " + object.getClass());
 }