Example #1
0
    @Override
    protected List doInBackground(Void... params) { // 첫번째 인자
      List<Weather> weatherList = null;

      try {
        // HTTP 에서 내용을 String 으로 받아 온다
        String jsonString = getResponse(URL_FORECAST);
        Log.d(TAG, jsonString);
        JSONObject jsonObject = new JSONObject(jsonString);
        JSONArray jsonArray = jsonObject.getJSONArray("list");

        ObjectMapper objectMapper = new ObjectMapper();

        weatherList =
            objectMapper.readValue(
                jsonArray.toString(),
                objectMapper.getTypeFactory().constructCollectionType(List.class, Weather.class));

        Log.d(TAG, weatherList.toString());

      } catch (Exception e) {
        Log.e(TAG, e.getMessage());
      }

      return weatherList;
    }
  public static List<Product> getProducts() {
    List<Product> products = new ArrayList<>();

    try {
      java.net.URL url = new URL(URL);
      final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setRequestProperty("Accept", "application/json");

      int responseCode = conn.getResponseCode();
      Log.e("getProducts", "Codigo de retorno: " + responseCode);
      if (responseCode == HttpURLConnection.HTTP_OK) {
        InputStream inputStream = conn.getInputStream();

        ObjectMapper objectMapper = new ObjectMapper();
        CollectionType collectionType =
            objectMapper.getTypeFactory().constructCollectionType(List.class, Product.class);
        products = objectMapper.readValue(inputStream, collectionType);
      }
    } catch (Exception e) {
      Log.e(ProductService.class.getName(), e.getMessage());
    }

    return products;
  }
Example #3
0
  @Override
  public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner)
      throws HibernateException, SQLException {
    try {
      String value = rs.getString(names[0]);
      if (value == null) {
        return null;
      }

      Object object = null;
      if (isArray) {
        ObjectMapper objectMapper = ObjectMapperBeanFactory.getObjectMapper();

        JavaType type =
            objectMapper.getTypeFactory().constructCollectionType(List.class, targetClass);
        object = objectMapper.readValue(value, type);
      } else {
        ObjectMapper objectMapper = ObjectMapperBeanFactory.getObjectMapper();
        object = objectMapper.readValue(value, targetClass);
      }

      return object;
    } catch (IOException e) {
      throw new HibernateException(e);
    }
  }
Example #4
0
 public static List<LoadTestConfigModel> readJSONConfig() throws IOException {
   InputStream in = LUtil.class.getClassLoader().getResourceAsStream("loadTestConfig.json");
   ObjectMapper mapper = new ObjectMapper();
   List<LoadTestConfigModel> myObjects =
       mapper.readValue(
           in,
           mapper.getTypeFactory().constructCollectionType(List.class, LoadTestConfigModel.class));
   return myObjects;
 }
Example #5
0
  protected <T> Object[] parseIn(Expression<?> path, JsonNode fieldValue)
      throws QueryInfoException {
    Class<?> javaType = path.getJavaType();

    TypeFactory typeFactory = objectMapper.getTypeFactory();
    ArrayType arrayType = typeFactory.constructArrayType(javaType);

    return objectMapper.convertValue(fieldValue, arrayType);
  }
 /*
  * (non-Javadoc)
  *
  * @see
  * com.basho.riak.client.query.MapReduceResult#getResult(java.lang.Class)
  */
 public <T> Collection<T> getResult(Class<T> resultType) throws ConversionException {
   try {
     return objectMapper.readValue(
         getResultRaw(),
         objectMapper.getTypeFactory().constructCollectionType(Collection.class, resultType));
   } catch (IOException e) {
     throw new ConversionException(e);
   }
 }
Example #7
0
  public <T> T copy(T input) throws ObjectCopyException {
    try {
      byte[] bytes = mapper.writeValueAsBytes(input);

      TypeFactory tf = mapper.getTypeFactory();
      JavaType type = tf.constructType(input.getClass());

      return mapper.readValue(bytes, type);
    } catch (IOException e) {
      log.error("error in copying input", e);
      throw new ObjectCopyException("error in copying input", e);
    }
  }
  public static JsonHeader deserializeJsonHeader(final String ratJson)
      throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    RATJsonObject ratJsonObject = (RATJsonObject) mapper.readValue(ratJson, RATJsonObject.class);

    TypeFactory typeFactory = mapper.getTypeFactory();
    MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, String.class);
    HashMap<String, String> map = mapper.readValue(ratJsonObject.getHeader(), mapType);
    JsonHeader header = new JsonHeader();
    header.setHeaderProperties(map);

    return header;
  }
Example #9
0
  /**
   * Invokes the given method on the {@code handler} passing the given params (after converting them
   * to beans\objects) to it.
   *
   * @param m the method to invoke
   * @param params the params to pass to the method
   * @return the return value (or null if no return)
   * @throws IOException on error
   * @throws IllegalAccessException on error
   * @throws InvocationTargetException on error
   */
  protected JsonNode invoke(Method m, List<JsonNode> params)
      throws IOException, IllegalAccessException, InvocationTargetException {

    // debug log
    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.log(Level.FINE, "Invoking method: " + m.getName());
    }

    // convert the parameters
    Object[] convertedParams = new Object[params.size()];
    Type[] parameterTypes = m.getGenericParameterTypes();

    for (int i = 0; i < parameterTypes.length; i++) {
      JsonParser paramJsonParser = mapper.treeAsTokens(params.get(i));
      JavaType paramJavaType = TypeFactory.defaultInstance().constructType(parameterTypes[i]);
      convertedParams[i] = mapper.readValue(paramJsonParser, paramJavaType);
    }

    // invoke the method
    Object result = m.invoke(handler, convertedParams);
    Type genericReturnType = m.getGenericReturnType();
    if (genericReturnType != null) {
      if (Collection.class.isInstance(result) && genericReturnType instanceof ParameterizedType) {
        try {
          if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "attempting custom collection serialization");
          }
          TypeFactory typeFactory = mapper.getTypeFactory();
          Type actualTypeInCollection =
              ((ParameterizedType) genericReturnType).getActualTypeArguments()[0];
          if (actualTypeInCollection
              instanceof TypeVariable) { // collection actually has a generic return type
            actualTypeInCollection = ((TypeVariable) actualTypeInCollection).getBounds()[0];
          }
          JavaType rootType =
              typeFactory.constructCollectionType(
                  Collection.class, typeFactory.constructType(actualTypeInCollection));
          return valueToTree(mapper.writerWithType(rootType), result);
        } catch (Exception e) {
          LOGGER.log(
              Level.WARNING,
              "could not do custom collection serialization falling back to default",
              e);
        }
      }
      return mapper.valueToTree(result);
    } else {
      return null;
    }
    // return (genericReturnType!=null) ? mapper.valueToTree(result) : null;
  }
Example #10
0
 /**
  * Add new record
  *
  * @param data
  * @return response
  * @throws CimbleException
  */
 @POST
 @Path("/bulk")
 public Response bulkSave(String data) throws CimbleException {
   try {
     ObjectMapper mapper = new ObjectMapper();
     List<T> list =
         mapper.readValue(
             data, mapper.getTypeFactory().constructCollectionType(List.class, getDtoType()));
     return bulkSave(list);
   } catch (Exception e) {
     e.printStackTrace();
     throw new CimbleException("Error in save()", e);
   }
 }
 @Override
 public void process(Exchange exchange) throws Exception {
   String message = exchange.getIn().getBody(String.class);
   ObjectMapper objectMapper = new ObjectMapper();
   TypeFactory typeFactory = objectMapper.getTypeFactory();
   List<Double> values =
       objectMapper.readValue(
           message, typeFactory.constructCollectionType(List.class, Double.class));
   SummaryStatistics summaryStatistics = new SummaryStatistics();
   List<Double> list = new ObjectMapper().readValue(message, List.class);
   for (Double value : list) {
     summaryStatistics.addValue(value);
   }
   String variance = Double.toString(summaryStatistics.getVariance());
   exchange.getOut().setBody(variance);
 }
 public static Map<String, Object> toMap(String json) {
   if (json == null) {
     return new HashMap<String, Object>();
   }
   ObjectMapper mapper = new ObjectMapper();
   try {
     JavaType javaType =
         mapper
             .getTypeFactory()
             .constructParametrizedType(
                 LinkedHashMap.class, Map.class, String.class, Object.class);
     return mapper.readValue(json, javaType);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
 /** Reads data source names from Druid. */
 Set<String> tableNames() {
   final Map<String, String> requestHeaders = ImmutableMap.of("Content-Type", "application/json");
   final String data = null;
   final String url = coordinatorUrl + "/druid/coordinator/v1/metadata/datasources";
   if (CalcitePrepareImpl.DEBUG) {
     System.out.println("Druid: table names" + data + "; " + url);
   }
   try (InputStream in0 = post(url, data, requestHeaders, 10000, 1800000);
       InputStream in = traceResponse(in0)) {
     final ObjectMapper mapper = new ObjectMapper();
     final CollectionType listType =
         mapper.getTypeFactory().constructCollectionType(List.class, String.class);
     final List<String> list = mapper.readValue(in, listType);
     return ImmutableSet.copyOf(list);
   } catch (IOException e) {
     throw Throwables.propagate(e);
   }
 }
  @Test
  public void testDeserializeExchangeRates() throws IOException {

    // Read in the JSON from the example resources
    InputStream is =
        CoinbaseMarketDataJsonTest.class.getResourceAsStream(
            "/marketdata/example-exchange-rate-data.json");

    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    MapLikeType mapType =
        mapper.getTypeFactory().constructMapLikeType(HashMap.class, String.class, BigDecimal.class);
    Map<String, BigDecimal> exchangeRates = mapper.readValue(is, mapType);

    assertThat(exchangeRates.size()).isEqualTo(632);

    BigDecimal exchangeRate = exchangeRates.get("scr_to_btc");
    assertThat(exchangeRate).isEqualByComparingTo("0.000115");
  }
  @Test
  public void testDeserializeCurrencies() throws IOException {

    // Read in the JSON from the example resources
    InputStream is =
        CoinbaseMarketDataJsonTest.class.getResourceAsStream(
            "/marketdata/example-currencies-data.json");

    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    CollectionType collectionType =
        mapper.getTypeFactory().constructCollectionType(List.class, CoinbaseCurrency.class);
    List<CoinbaseCurrency> currencies = mapper.readValue(is, collectionType);

    assertThat(currencies.size()).isEqualTo(161);

    CoinbaseCurrency currency = currencies.get(160);
    assertThat(currency.getIsoCode()).isEqualTo("ZWL");
    assertThat(currency.getName()).isEqualTo("Zimbabwean Dollar (ZWL)");
  }
 /** Reads segment metadata, and populates a list of columns and metrics. */
 void metadata(
     String dataSourceName,
     List<String> intervals,
     Map<String, SqlTypeName> fieldBuilder,
     Set<String> metricNameBuilder) {
   final String url = this.url + "/druid/v2/?pretty";
   final Map<String, String> requestHeaders = ImmutableMap.of("Content-Type", "application/json");
   final String data = DruidQuery.metadataQuery(dataSourceName, intervals);
   if (CalcitePrepareImpl.DEBUG) {
     System.out.println("Druid: " + data);
   }
   try (InputStream in0 = post(url, data, requestHeaders, 10000, 1800000);
       InputStream in = traceResponse(in0)) {
     final ObjectMapper mapper =
         new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
     final CollectionType listType =
         mapper.getTypeFactory().constructCollectionType(List.class, JsonSegmentMetadata.class);
     final List<JsonSegmentMetadata> list = mapper.readValue(in, listType);
     in.close();
     for (JsonSegmentMetadata o : list) {
       for (Map.Entry<String, JsonColumn> entry : o.columns.entrySet()) {
         if (!isSupportedType(entry.getValue().type)) {
           continue;
         }
         fieldBuilder.put(entry.getKey(), entry.getValue().sqlType());
       }
       if (o.aggregators != null) {
         for (Map.Entry<String, JsonAggregator> entry : o.aggregators.entrySet()) {
           if (!fieldBuilder.containsKey(entry.getKey())) {
             continue;
           }
           metricNameBuilder.add(entry.getKey());
         }
       }
     }
   } catch (IOException e) {
     throw Throwables.propagate(e);
   }
 }
public class JsonSerialization {
  /* Constants for XML deserialization */
  private static final String textNodeTag = "#text";
  private static final String commentNodeTag = "#comment";
  private static final String cDataNodeTag = "#cdata-section";
  private static final String whitespaceNodeTag = "#whitespace";
  private static final String significantWhitespaceNodeTag = "#significant-whitespace";

  private static final JsonSerializer<LocalDate> dateSerializer =
      new JsonSerializer<LocalDate>() {
        @Override
        public void serialize(
            final LocalDate value, final JsonGenerator generator, final SerializerProvider x)
            throws IOException, JsonProcessingException {
          generator.writeString(value.toString());
        }
      };

  private static final JsonDeserializer<LocalDate> dateDeserializer =
      new JsonDeserializer<LocalDate>() {
        @Override
        public LocalDate deserialize(final JsonParser parser, final DeserializationContext context)
            throws IOException, JsonProcessingException {
          return new DateTime(parser.getValueAsString()).toLocalDate();
        }
      };

  // -----------------------------------------------------------------------------

  private static final JsonSerializer<DateTime> timestampSerializer =
      new JsonSerializer<DateTime>() {
        @Override
        public void serialize(
            final DateTime value, final JsonGenerator gen, final SerializerProvider sP)
            throws IOException, JsonProcessingException {
          gen.writeString(value.toString());
        }
      };

  private static final JsonDeserializer<DateTime> timestampDeserializer =
      new JsonDeserializer<DateTime>() {
        @Override
        public DateTime deserialize(final JsonParser parser, final DeserializationContext context)
            throws IOException, JsonProcessingException {
          return new DateTime(parser.getValueAsString());
        }
      };

  // -----------------------------------------------------------------------------

  private static final JsonSerializer<Point> pointSerializer =
      new JsonSerializer<Point>() {
        @Override
        public void serialize(
            final Point value, final JsonGenerator gen, final SerializerProvider sP)
            throws IOException, JsonProcessingException {
          gen.writeStartObject();
          gen.writeNumberField("X", value.x);
          gen.writeNumberField("Y", value.y);
          gen.writeEndObject();
        }
      };

  private static final JsonDeserializer<Point> pointDeserializer =
      new JsonDeserializer<Point>() {
        @Override
        public Point deserialize(final JsonParser parser, final DeserializationContext context)
            throws IOException, JsonProcessingException {
          final JsonNode tree = parser.getCodec().readTree(parser);
          return new Point(tree.get("X").asInt(), tree.get("Y").asInt());
        }
      };

  // -----------------------------------------------------------------------------

  private static final JsonSerializer<Point2D> locationSerializer =
      new JsonSerializer<Point2D>() {
        @Override
        public void serialize(
            final Point2D value, final JsonGenerator gen, final SerializerProvider sP)
            throws IOException, JsonProcessingException {
          gen.writeStartObject();
          gen.writeNumberField("X", value.getX());
          gen.writeNumberField("Y", value.getY());
          gen.writeEndObject();
        }
      };

  private static final JsonDeserializer<Point2D> locationDeserializer =
      new JsonDeserializer<Point2D>() {
        @Override
        public Point2D deserialize(final JsonParser parser, final DeserializationContext context)
            throws IOException, JsonProcessingException {
          final JsonNode tree = parser.getCodec().readTree(parser);
          return new Point2D.Double(tree.get("X").asDouble(), tree.get("Y").asDouble());
        }
      };

  // -----------------------------------------------------------------------------

  private static final JsonSerializer<Rectangle2D> rectangleSerializer =
      new JsonSerializer<Rectangle2D>() {
        @Override
        public void serialize(
            final Rectangle2D value, final JsonGenerator gen, final SerializerProvider sP)
            throws IOException, JsonProcessingException {
          gen.writeStartObject();
          gen.writeNumberField("X", value.getX());
          gen.writeNumberField("Y", value.getY());
          gen.writeNumberField("Width", value.getWidth());
          gen.writeNumberField("Height", value.getHeight());
          gen.writeEndObject();
        }
      };

  private static final JsonDeserializer<Rectangle2D> rectangleDeserializer =
      new JsonDeserializer<Rectangle2D>() {
        @Override
        public Rectangle2D deserialize(
            final JsonParser parser, final DeserializationContext context)
            throws IOException, JsonProcessingException {
          final JsonNode tree = parser.getCodec().readTree(parser);
          return new Rectangle2D.Double(
              tree.get("X").asDouble(),
              tree.get("Y").asDouble(),
              tree.get("Width").asDouble(),
              tree.get("Height").asDouble());
        }
      };

  // -----------------------------------------------------------------------------

  private static final JsonSerializer<BufferedImage> imageSerializer =
      new JsonSerializer<BufferedImage>() {
        @Override
        public void serialize(
            final BufferedImage value, final JsonGenerator gen, final SerializerProvider sP)
            throws IOException, JsonProcessingException {
          final ByteArrayOutputStream baos = new ByteArrayOutputStream();
          ImageIO.write(value, "png", baos);
          gen.writeBinary(baos.toByteArray());
        }
      };

  private static final JsonDeserializer<BufferedImage> imageDeserializer =
      new JsonDeserializer<BufferedImage>() {
        @Override
        public BufferedImage deserialize(
            final JsonParser parser, final DeserializationContext context)
            throws IOException, JsonProcessingException {
          final InputStream is = new ByteArrayInputStream(parser.getBinaryValue());
          return ImageIO.read(is);
        }
      };

  // -----------------------------------------------------------------------------

  private static final JsonSerializer<Element> xmlSerializer =
      new JsonSerializer<Element>() {
        @Override
        public void serialize(
            final Element value, final JsonGenerator gen, final SerializerProvider sP)
            throws IOException, JsonProcessingException {
          /*
           * The Xml needs to be cleaned from whitespace text nodes, otherwise the
           * converted document won't match Json.Net's conversion
           */
          trimWhitespaceTextNodes(value);

          /* If the node is null, write nothing */
          if (value == null) return;

          value.getChildNodes();
          final HashMap<String, Object> hm = new HashMap<String, Object>();

          hm.put(value.getNodeName(), buildFromXml(value));

          gen.writeObject(hm);
        }
      };

  private static void trimWhitespaceTextNodes(final org.w3c.dom.Node node) {
    if (node != null && node.hasChildNodes()) {
      for (int i = 0; i < node.getChildNodes().getLength(); i++) {
        final org.w3c.dom.Node child = node.getChildNodes().item(i);
        if (child.getNodeType() == org.w3c.dom.Node.TEXT_NODE
            && child.getNodeValue().trim().length() == 0) {
          node.removeChild(child);
        }
        trimWhitespaceTextNodes(node.getChildNodes().item(i));
      }
    }
  }

  /** Recursively builds a JSON object from the given root element */
  private static Object buildFromXml(final Element el) {
    final NodeList cn = el.getChildNodes();
    final int childLen = cn.getLength();

    final LinkedHashMap<String, LinkedList<Node>> childrenByName =
        new LinkedHashMap<String, LinkedList<Node>>();

    /* Sort the nodes in the hash map by children names */
    for (int i = 0; i < childLen; i++) {
      final Node n = cn.item(i);
      final String name = n.getNodeName();
      if (!childrenByName.containsKey(name)) {
        childrenByName.put(name, new LinkedList<Node>());
      }
      childrenByName.get(name).add(n);
    }

    /*
     * If there are no children, and no attributes, just return the node's text
     * content value
     */
    if (childLen == 0 && el.getAttributes().getLength() == 0)
      return el.getTextContent() != "" ? el.getTextContent() : null;

    /* Put all the element's attributes into a hash map */
    final LinkedHashMap<String, Object> jsonHashMap = new LinkedHashMap<String, Object>();
    final int attLen = el.getAttributes().getLength();
    for (int i = 0; i < attLen; i++) {
      final Node a = el.getAttributes().item(i);
      jsonHashMap.put("@" + a.getNodeName(), a.getNodeValue());
    }

    /*
     * Put the child nodes to the hash map; Nodes are sorted by name, nodes
     * having the same name are put together into an array
     */
    for (final Map.Entry<String, LinkedList<Node>> name_ChildrenHavingName :
        childrenByName.entrySet()) {
      /* For all nodes having the current name */
      final Object[] items = new Object[name_ChildrenHavingName.getValue().size()];
      for (int i = 0; i < items.length; i++) {
        final Node n = name_ChildrenHavingName.getValue().get(i);
        /*
         * If the node is an XML element, recursively convert it's tree to an
         * Object
         */
        if (n instanceof Element) {
          items[i] = buildFromXml((Element) n);
        }
        /* Otherwise use the text value */
        else {
          items[i] = n.getNodeValue() != "" ? n.getNodeValue() : null;
        }
      }
      /* Put the resulting object array / single object to the hash map */
      jsonHashMap.put(name_ChildrenHavingName.getKey(), items.length > 1 ? items : items[0]);
    }

    /* If the element has a single child */
    if (jsonHashMap.size() == 1 && childrenByName.keySet().iterator().hasNext()) {
      /* Get the single child's name */
      final String name = childrenByName.keySet().iterator().next();

      /* If it's a text node, the converted object is it's value */
      if (name.equals(textNodeTag)) return jsonHashMap.get(name);
      else {
        // Cleanup? If the single child has a single child with the same
        // name, return the grandchild?
        final Object parent = jsonHashMap.get(name);
        if (parent instanceof HashMap) {
          @SuppressWarnings("unchecked")
          final HashMap<String, Object> parentHm = (HashMap<String, Object>) parent;
          if (parentHm.size() == 1 && parentHm.containsKey(name)) return parentHm;
        }
      }
    }

    return jsonHashMap;
  }

  /**
   * Recursively builds an XML document subtree
   *
   * @param doc the document to be built up
   * @param subtreeRootElement the root of the subtree
   * @param elementContent the value of the subtree
   */
  @SuppressWarnings("unchecked")
  private static void buildXmlFromHashMap(
      final Document doc, final Element subtreeRootElement, final Object elementContent) {
    if (elementContent instanceof HashMap) {
      final HashMap<String, Object> elementContentMap = (HashMap<String, Object>) elementContent;
      for (final Map.Entry<String, Object> childEntry : elementContentMap.entrySet()) {
        if (childEntry.getKey().startsWith("@")) {
          subtreeRootElement.setAttribute(
              childEntry.getKey().substring(1), childEntry.getValue().toString());
        } else if (childEntry.getKey().startsWith("#")) {
          if (childEntry.getKey().equals(textNodeTag)) {
            if (childEntry.getValue() instanceof List) {
              buildTextNodeList(doc, subtreeRootElement, (List<String>) childEntry.getValue());
            } else {
              final Node textNode = doc.createTextNode(childEntry.getValue().toString());
              subtreeRootElement.appendChild(textNode);
            }
          } else if (childEntry.getKey().equals(cDataNodeTag)) {
            if (childEntry.getValue() instanceof List) {
              buildCDataList(doc, subtreeRootElement, (List<String>) childEntry.getValue());
            } else {
              final Node cDataNode = doc.createCDATASection(childEntry.getValue().toString());
              subtreeRootElement.appendChild(cDataNode);
            }
          } else if (childEntry.getKey().equals(commentNodeTag)) {
            if (childEntry.getValue() instanceof List) {
              buildCommentList(doc, subtreeRootElement, (List<String>) childEntry.getValue());
            } else {
              final Node commentNode = doc.createComment(childEntry.getValue().toString());
              subtreeRootElement.appendChild(commentNode);
            }
          } else if (childEntry.getKey().equals(whitespaceNodeTag)
              || childEntry.getKey().equals(significantWhitespaceNodeTag)) {
            // Ignore
          } else {
            /*
             * All other nodes whose name starts with a '#' are invalid XML
             * nodes, and thus ignored:
             */
          }
        } else {
          final Element newElement = doc.createElement(childEntry.getKey());
          subtreeRootElement.appendChild(newElement);
          buildXmlFromHashMap(doc, newElement, childEntry.getValue());
        }
      }
    } else if (elementContent instanceof List) {
      buildXmlFromJsonArray(doc, subtreeRootElement, (List<Object>) elementContent);
    } else {
      if (elementContent != null) {
        subtreeRootElement.setTextContent(elementContent.toString());
      }
    }
  }

  private static void buildTextNodeList(
      final Document doc, final Node subtreeRoot, final List<String> nodeValues) {

    final StringBuffer singleTextNodeValue = new StringBuffer();

    for (final String nodeValue : nodeValues) {
      singleTextNodeValue.append(nodeValue);
      // subtreeRoot.appendChild(doc.createTextNode(nodeValue));
    }

    subtreeRoot.appendChild(doc.createTextNode(singleTextNodeValue.toString()));
  }

  private static void buildCDataList(
      final Document doc, final Node subtreeRoot, final List<String> nodeValues) {
    for (final String nodeValue : nodeValues) {
      subtreeRoot.appendChild(doc.createCDATASection(nodeValue));
    }
  }

  private static void buildCommentList(
      final Document doc, final Node subtreeRoot, final List<String> nodeValues) {
    for (final String nodeValue : nodeValues) {
      subtreeRoot.appendChild(doc.createComment(nodeValue));
    }
  }

  /**
   * Builds an XML subtree out of a list and a head element. The list elements are serialized into a
   * series of nodes whose title is <code>listHeadElementName</code>. The head element need be
   * created before this method call.
   *
   * @param doc The parent document
   * @param listHeadNode The first node of the list, needs to be created before this method call
   * @param listHeadElementName The name of the list's head element
   * @param elementContentList The actual list contents
   */
  private static void buildXmlFromJsonArray(
      final Document doc, final Node listHeadNode, final List<Object> elementContentList) {

    final Node subtreeRootNode = listHeadNode.getParentNode();
    /* The head node (already exists) */
    buildXmlFromHashMap(doc, (Element) listHeadNode, elementContentList.get(0));
    /* The rest of the list */
    for (final Object elementContent : elementContentList.subList(1, elementContentList.size())) {
      final Element newElement = doc.createElement(listHeadNode.getNodeName());
      subtreeRootNode.appendChild(newElement);
      buildXmlFromHashMap(doc, newElement, elementContent);
    }
  }

  private static final JsonDeserializer<Element> xmlDeserializer =
      new JsonDeserializer<Element>() {
        @Override
        public Element deserialize(final JsonParser parser, final DeserializationContext context)
            throws IOException, JsonProcessingException {

          @SuppressWarnings("unchecked")
          final HashMap<String, Object> hm = parser.readValueAs(HashMap.class);

          if (hm == null) return null;

          /* The root is expected to be a single element */
          final Set<String> xmlRootElementNames = hm.keySet();

          if (xmlRootElementNames.size() > 1)
            throw new IOException("Invalid XML. Expecting root element");

          final String rootName = xmlRootElementNames.iterator().next();

          final Document document;
          final Element rootElement;

          /* Initialise the document with a root element */
          try {
            synchronized (this) {
              final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
              final DocumentBuilder builder = factory.newDocumentBuilder();
              document = builder.newDocument();
              rootElement = document.createElement(rootName);
              document.appendChild(rootElement);
            }
          } catch (final Exception e) {
            throw new IOException(e);
          }

          buildXmlFromHashMap(document, rootElement, hm.get(rootName));
          return rootElement;
        }
      };

  // -----------------------------------------------------------------------------

  private static final SimpleModule serializationModule =
      new SimpleModule(
              "SerializationModule",
              new Version(0, 0, 0, "SNAPSHOT", "com.dslplatform", "dsl-client"))
          .addSerializer(LocalDate.class, dateSerializer)
          .addSerializer(DateTime.class, timestampSerializer)
          .addSerializer(Point.class, pointSerializer)
          .addSerializer(Point2D.class, locationSerializer)
          .addSerializer(Rectangle2D.class, rectangleSerializer)
          .addSerializer(BufferedImage.class, imageSerializer)
          .addSerializer(Element.class, xmlSerializer);

  private static final ObjectMapper serializationMapper =
      new ObjectMapper()
          .registerModule(serializationModule)
          .setSerializationInclusion(Include.NON_NULL)
          .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);

  private static final TypeFactory typeFactory = serializationMapper.getTypeFactory();

  public static JavaType buildType(final Class<?> simple) {
    return typeFactory.constructType(simple);
  }

  public static JavaType buildGenericType(final Class<?> containerType, final Class<?>... element) {
    return typeFactory.constructParametricType(containerType, element);
  }

  @SuppressWarnings("rawtypes")
  public static JavaType buildCollectionType(
      final Class<? extends Collection> collection, final JavaType element) {
    return typeFactory.constructCollectionType(collection, element);
  }

  @SuppressWarnings("rawtypes")
  public static JavaType buildCollectionType(
      final Class<? extends Collection> collection, final Class<?> element) {
    return typeFactory.constructCollectionType(collection, element);
  }

  // -----------------------------------------------------------------------------

  private final ObjectMapper deserializationMapper;

  public JsonSerialization(final ServiceLocator locator) {
    deserializationMapper = makeDeserializationObjectMapper(locator);
  }

  public <T> T deserialize(final JavaType type, final String data) throws IOException {
    return deserializationMapper.readValue(data, type);
  }

  public <T> T deserialize(final JavaType type, final byte[] data) throws IOException {
    return deserializationMapper.readValue(data, type);
  }

  // -----------------------------------------------------------------------------

  public static <T> String serialize(final T data) throws IOException {
    return serializationMapper.writer().writeValueAsString(data);
  }

  private static final SimpleModule deserializationModule =
      new SimpleModule(
              "DeserializationModule",
              new Version(0, 0, 0, "SNAPSHOT", "com.dslplatform", "dsl-client"))
          .addDeserializer(LocalDate.class, dateDeserializer)
          .addDeserializer(DateTime.class, timestampDeserializer)
          .addDeserializer(Point.class, pointDeserializer)
          .addDeserializer(Point2D.class, locationDeserializer)
          .addDeserializer(Rectangle2D.class, rectangleDeserializer)
          .addDeserializer(BufferedImage.class, imageDeserializer)
          .addDeserializer(Element.class, xmlDeserializer);

  private static ObjectMapper makeDeserializationObjectMapper(final ServiceLocator locator) {
    return new ObjectMapper()
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        .registerModule(deserializationModule)
        .setInjectableValues(new InjectableValues.Std().addValue("_serviceLocator", locator));
  }

  public static <T> T deserialize(
      final JavaType type, final String data, final ServiceLocator locator) throws IOException {
    return makeDeserializationObjectMapper(locator).readValue(data, type);
  }
}
Example #18
0
 /** 构造Map类型. */
 public JavaType contructMapType(
     Class<? extends Map> mapClass, Class<?> keyClass, Class<?> valueClass) {
   return mapper.getTypeFactory().constructMapType(mapClass, keyClass, valueClass);
 }
Example #19
0
 public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
   ObjectMapper mapper = getObjectMapper();
   return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
 }
Example #20
0
 /** Returns a new JSON object mapper. */
 private ObjectMapper buildObjectMapper() {
   ObjectMapper result = new ObjectMapper();
   result.setAnnotationIntrospector(new JaxbAnnotationIntrospector(result.getTypeFactory()));
   result.enable(SerializationFeature.INDENT_OUTPUT);
   return result;
 }
Example #21
0
 /** 构造Collection类型. */
 public JavaType contructCollectionType(
     Class<? extends Collection> collectionClass, Class<?> elementClass) {
   return mapper.getTypeFactory().constructCollectionType(collectionClass, elementClass);
 }
 private JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
   return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
 }