@Test
  public void should_init_default_object_factory_mapper() throws Exception {
    doCallRealMethod().when(extractor).initObjectMapperFactory(configMap);
    ObjectMapperFactory actual = extractor.initObjectMapperFactory(configMap);

    assertThat(actual).isNotNull();

    ObjectMapper mapper = actual.getMapper(Integer.class);

    assertThat(mapper).isNotNull();
    assertThat(mapper.getSerializationConfig().getSerializationInclusion())
        .isEqualTo(Inclusion.NON_NULL);
    assertThat(
            mapper
                .getDeserializationConfig()
                .isEnabled(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES))
        .isFalse();
    Collection<AnnotationIntrospector> ais =
        mapper.getSerializationConfig().getAnnotationIntrospector().allIntrospectors();

    assertThat(ais).hasSize(2);
    Iterator<AnnotationIntrospector> iterator = ais.iterator();

    assertThat(iterator.next())
        .isInstanceOfAny(JacksonAnnotationIntrospector.class, JaxbAnnotationIntrospector.class);
    assertThat(iterator.next())
        .isInstanceOfAny(JacksonAnnotationIntrospector.class, JaxbAnnotationIntrospector.class);
  }
Example #2
0
 public static String getJSON(Object obj) throws IOException {
   ObjectMapper mapper = new ObjectMapper();
   mapper.getSerializationConfig().disable(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS);
   mapper.getSerializationConfig().disable(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES);
   mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
   Writer sw = new StringWriter();
   mapper.writeValue(sw, obj);
   sw.flush();
   sw.close();
   return sw.toString();
 }
Example #3
0
 /** 设置转换日期类型的format pattern,如果不设置默认打印Timestamp毫秒数. */
 public void setDateFormat(String pattern) {
   if (StringUtils.isNotBlank(pattern)) {
     DateFormat df = new SimpleDateFormat(pattern);
     mapper.getSerializationConfig().setDateFormat(df);
     mapper.getDeserializationConfig().setDateFormat(df);
   }
 }
  private Set<Class<?>> filterInputClasses(Set<Class<?>> referencedClasses) {
    Set<Class<?>> typesToUse = Sets.newHashSet();
    for (Class<?> beanClass : referencedClasses) {
      if (beanClass.isEnum()) {
        typesToUse.add(beanClass);
        continue;
      }
      if (beanClass.equals(void.class)) {
        continue;
      }
      if (beanClass instanceof Class && beanClass.isEnum()) {
        typesToUse.add(beanClass);
        continue;
      }
      if (beanClass == URI.class) {
        continue;
      }

      // Classes directly passed in to typescript-generator need to be directly serializable, so
      // filter out the ones that serializers
      // exist for.
      SerializationConfig serializationConfig = OBJECT_MAPPER.getSerializationConfig();
      final JavaType simpleType = OBJECT_MAPPER.constructType(beanClass);
      try {
        final JsonSerializer<?> jsonSerializer =
            BeanSerializerFactory.instance.createSerializer(serializationConfig, simpleType, null);
        if (jsonSerializer == null || jsonSerializer instanceof BeanSerializer) {
          typesToUse.add(beanClass);
        }
      } catch (Exception e) {

      }
    }
    return typesToUse;
  }
Example #5
0
  static {
    PRETTY_JSON_OBJECT_MAPPER.configure(Feature.INDENT_OUTPUT, true);
    PRETTY_JSON_OBJECT_MAPPER.configure(Feature.SORT_PROPERTIES_ALPHABETICALLY, true);
    PRETTY_JSON_OBJECT_MAPPER
        .getSerializationConfig()
        .setSerializationInclusion(Inclusion.NON_NULL);

    try {
      ERROR_RESULT_JAXB_CONTEXT = JAXBContext.newInstance(ErrorResult.class);
      XML_DATATYPE_FACTORY = DatatypeFactory.newInstance();
      MIMETYPES_FILETYPE_MAP.addMimeTypes(
          Constants.JSON_CONTENT_TYPE
              + " json\n"
              + Constants.XML_CONTENT_TYPE
              + " xml\n"
              + Constants.TEXT_CONTENT_TYPE
              + " txt\n"
              + Constants.PDF_CONTENT_TYPE
              + " pdf\n"
              + Constants.ZIP_CONTENT_TYPE
              + " zip");
    } catch (final Exception e) {
      throw new IllegalStateException(e);
    }

    DEFAULT_FILE_EXTENSIONS.put(Constants.JSON_CONTENT_TYPE, "json");
    DEFAULT_FILE_EXTENSIONS.put(Constants.XML_CONTENT_TYPE, "xml");
    DEFAULT_FILE_EXTENSIONS.put(Constants.TEXT_CONTENT_TYPE, "txt");
    DEFAULT_FILE_EXTENSIONS.put(Constants.PDF_CONTENT_TYPE, "pdf");
    DEFAULT_FILE_EXTENSIONS.put(Constants.ZIP_CONTENT_TYPE, "zip");
  }
 public JpaPortalEventStore() {
   mapper = new ObjectMapper();
   final AnnotationIntrospector pair =
       new AnnotationIntrospector.Pair(
           new JacksonAnnotationIntrospector(), new JaxbAnnotationIntrospector());
   mapper.getDeserializationConfig().withAnnotationIntrospector(pair);
   mapper.getSerializationConfig().withAnnotationIntrospector(pair);
 }
 public JSONSerializer() {
   mapper = new ObjectMapper(); // can reuse, share globally
   mapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
   mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
   DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
   prettyPrinter.indentArraysWith(new DefaultPrettyPrinter.Lf2SpacesIndenter());
   mapper.prettyPrintingWriter(prettyPrinter);
   mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
 }
Example #8
0
  public static ObjectMapper getObjectMapper() {
    if (om == null) {
      om = new ObjectMapper();
      om.configure(SerializationConfig.Feature.WRITE_NULL_PROPERTIES, false);
      om.getSerializationConfig().withSerializationInclusion(Inclusion.NON_NULL);
    }

    return om;
  }
Example #9
0
 public JsonBinder(Inclusion inclusion) {
   mapper = new ObjectMapper();
   // 设置输出包含的属性
   mapper.getSerializationConfig().setSerializationInclusion(inclusion);
   // 设置输入时忽略JSON字符串中存在而Java对象实际没有的属性
   mapper
       .getDeserializationConfig()
       .set(
           org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
           false);
 }
Example #10
0
  public static String toJsonStr(Object obj) {

    try {
      AnnotationIntrospector primary = new JacksonAnnotationIntrospector();
      AnnotationIntrospector secondary = new JaxbAnnotationIntrospector();
      AnnotationIntrospector pair = new AnnotationIntrospector.Pair(primary, secondary);

      ObjectMapper mapper = new ObjectMapper();

      mapper.getSerializationConfig().setAnnotationIntrospector(pair);

      mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);

      StringWriter sw = new StringWriter();
      mapper.writeValue(sw, obj);
      return sw.toString();
    } catch (Exception e) {
      System.out.println(e.getMessage() + e);
      throw new RuntimeException("Internal Error", e);
    }
  }
Example #11
0
    public JsonContext() {
      ObjectMapper mapper = getObjectMapper();
      mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
      mapper
          .getSerializationConfig()
          .addMixInAnnotations(ProtocolObject.class, StyxClassIdJsonMixIn.class);
      SimpleModule module =
          new SimpleModule("ProtocolDeserializer Module", new Version(1, 0, 0, null));
      module.addDeserializer(
          HashMapMessage.class,
          new StdDeserializer<HashMapMessage>(HashMapMessage.class) {

            @Override
            @SuppressWarnings("unchecked")
            public HashMapMessage deserialize(JsonParser jp, DeserializationContext ctxt)
                throws IOException, JsonProcessingException {
              ObjectMapper mapper = (ObjectMapper) jp.getCodec();
              ObjectNode root = (ObjectNode) mapper.readTree(jp);
              HashMapMessage s = new HashMapMessage();
              if (hasProtocolObjectData(root)) {
                /*
                 * We have a data node with a classId which makes us comfortable
                 * this is a protocol object. So 1) remove the data; 2) find object
                 * class from classId; 3) create object; and 4) put back again...
                 */
                JsonNode node = root.remove("data");
                int classId = node.get("classId").asInt();
                Class<? extends ProtocolObject> cl = factory.create(classId).getClass();
                ProtocolObject p = mapper.readValue(node, cl);
                s.setData(p);
              }
              /*
               * Read the remainder as an ordinary map and put all into the
               * server messages
               */
              HashMap<String, ?> values = mapper.readValue(root, HashMap.class);
              s.putAll(values);
              return s;
            }

            // --- PRIVATE METHODS --- //

            /*
             * Return true if the object has a data field which has a "classId" field
             */
            private boolean hasProtocolObjectData(ObjectNode root) {
              JsonNode dataNode = root.get("data");
              JsonNode idNode = (dataNode == null ? null : dataNode.get(CLASS_ID_PROPERTY));
              return idNode != null;
            }
          });
      mapper.registerModule(module);
    }
Example #12
0
 public String toJSON(T object) throws IOException {
   JsonFactory jsonFactory = new JsonFactory();
   ObjectMapper mapper = new ObjectMapper(jsonFactory);
   mapper.getSerializationConfig().setAnnotationIntrospector(new JacksonAnnotationIntrospector());
   mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
   jsonFactory.setCodec(mapper);
   StringWriter writer = new StringWriter();
   JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(writer);
   jsonGenerator.useDefaultPrettyPrinter();
   jsonGenerator.writeObject(object);
   return writer.getBuffer().toString();
 }
  @Override
  public ObjectMapper get() {
    ObjectMapper objectMapper = new ObjectMapper();

    // ignore unknown fields (for backwards compatibility)
    objectMapper.getDeserializationConfig().disable(FAIL_ON_UNKNOWN_PROPERTIES);

    // use ISO dates
    objectMapper.getSerializationConfig().disable(WRITE_DATES_AS_TIMESTAMPS);

    // skip fields that are null instead of writing an explicit json null value
    objectMapper.getSerializationConfig().setSerializationInclusion(NON_NULL);

    // disable auto detection of json properties... all properties must be explicit
    objectMapper
        .getDeserializationConfig()
        .disable(DeserializationConfig.Feature.AUTO_DETECT_FIELDS);
    objectMapper.getDeserializationConfig().disable(AUTO_DETECT_SETTERS);
    objectMapper.getSerializationConfig().disable(SerializationConfig.Feature.AUTO_DETECT_FIELDS);
    objectMapper.getSerializationConfig().disable(AUTO_DETECT_GETTERS);
    objectMapper.getSerializationConfig().disable(AUTO_DETECT_IS_GETTERS);

    if (jsonSerializers != null || jsonDeserializers != null) {
      SimpleModule module = new SimpleModule(getClass().getName(), new Version(1, 0, 0, null));
      if (jsonSerializers != null) {
        for (Entry<Class<?>, JsonSerializer<?>> entry : jsonSerializers.entrySet()) {
          addSerializer(module, entry.getKey(), entry.getValue());
        }
      }
      if (jsonDeserializers != null) {
        for (Entry<Class<?>, JsonDeserializer<?>> entry : jsonDeserializers.entrySet()) {
          addDeserializer(module, entry.getKey(), entry.getValue());
        }
      }
      objectMapper.registerModule(module);
    }

    return objectMapper;
  }
  private String prepareJsonForUpdate(Organization clientTenant) {
    ObjectMapper mapper = new ObjectMapper();
    SerializationConfig serializationConfig = mapper.getSerializationConfig();
    serializationConfig =
        serializationConfig.withSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
    mapper.setSerializationConfig(serializationConfig);
    mapper.setAnnotationIntrospector(introspector);

    String json;
    try {
      json = mapper.writeValueAsString(clientTenant);
    } catch (IOException e) {
      log.error("Cannot marshal organization object.");
      throw new JSClientException("Cannot marshal organization object.");
    }
    return json;
  }
Example #15
0
  @Override
  public void render(Map<String, ?> map, HttpServletRequest req, HttpServletResponse resp)
      throws Exception {
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
    mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);
    mapper.getSerializationConfig().setAnnotationIntrospector(introspector);

    // resp.setHeader("Content-Type", "text/html; charset=UTF-8"); // "application/json");

    JsonGenerator generator =
        mapper.getJsonFactory().createJsonGenerator(resp.getOutputStream(), JsonEncoding.UTF8);

    ObjectNode json = mapper.valueToTree(map);
    // json.put("success", true);
    mapper.writeTree(generator, json);
    // mapper.writeValue(generator, ret);
    generator.flush();
  }
  @Override
  public void writeTo(
      Object value,
      Class<?> type,
      Type genericType,
      Annotation[] annotations,
      MediaType mediaType,
      MultivaluedMap<String, Object> httpHeaders,
      OutputStream entityStream)
      throws IOException {
    ObjectMapper mapper = locateMapper(type, mediaType);

    SerializationConfig newSerializerConfig =
        mapper
            .getSerializationConfig()
            .without(Feature.FAIL_ON_EMPTY_BEANS)
            .without(Feature.WRITE_DATES_AS_TIMESTAMPS);

    mapper.setSerializationConfig(newSerializerConfig);
    mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);

    super.writeTo(value, type, genericType, annotations, mediaType, httpHeaders, entityStream);
  }
Example #17
0
 static {
   indentObjectMapper.getSerializationConfig().set(Feature.INDENT_OUTPUT, true);
 }
  /**
   * Convert the local prefs to server prefs
   *
   * @param serverPrefs
   * @return
   */
  private String localPrefsToServerPrefs(EasitApplicationPreferences localPrefs) throws Exception {

    PreferencesC4A prefsC4A = new PreferencesC4A();
    String term_common = "http://registry.gpii.net/common/";
    String term_prov_common = "http://registry.gpii.net/provisional-common/";

    // Fontsize
    List<PreferencesValue> list1 = new ArrayList<PreferencesValue>();
    PreferencesValue val1 = new PreferencesValue();
    val1.setValue(localPrefs.getTextSize());
    list1.add(val1);
    prefsC4A.set(term_common + "fontSize", list1);

    // foregroundColor
    List<PreferencesValue> list4 = new ArrayList<PreferencesValue>();
    PreferencesValue val4 = new PreferencesValue();
    val4.setValue(getForeGroundColor(localPrefs.getTheme()));
    list4.add(val4);
    prefsC4A.set(term_prov_common + "foregroundColor", list4);

    // backgroundColor
    List<PreferencesValue> list5 = new ArrayList<PreferencesValue>();
    PreferencesValue val5 = new PreferencesValue();
    val5.setValue(getBackgroundColor(localPrefs.getTheme()));
    list5.add(val5);
    prefsC4A.set(term_prov_common + "backgroundColor", list5);

    // fontName
    List<PreferencesValue> list2 = new ArrayList<PreferencesValue>();
    PreferencesValue val2 = new PreferencesValue();
    String[] font = convertFontNameLong(localPrefs.getTextFont());
    val2.setValue(localPrefs.getTextFont());
    list2.add(val2);
    prefsC4A.set(term_prov_common + "fontName", list2);

    // magnification
    List<PreferencesValue> list6 = new ArrayList<PreferencesValue>();
    PreferencesValue val6 = new PreferencesValue();
    val6.setValue((int) Math.round(localPrefs.getMagnification()));
    list6.add(val6);
    prefsC4A.set(term_common + "magnification", list6);

    // tracking
    List<PreferencesValue> list7 = new ArrayList<PreferencesValue>();
    PreferencesValue val7 = new PreferencesValue();
    val7.setValue(localPrefs.getTracking());
    list7.add(val7);
    prefsC4A.set(term_prov_common + "magnifierFollows", list7);

    // invertImages
    List<PreferencesValue> list8 = new ArrayList<PreferencesValue>();
    PreferencesValue val8 = new PreferencesValue();
    val8.setValue(localPrefs.isInvertImages());
    list8.add(val8);
    prefsC4A.set(term_common + "invertColours", list8);

    // links
    List<PreferencesValue> list9 = new ArrayList<PreferencesValue>();
    PreferencesValue val9 = new PreferencesValue();
    val9.setValue(localPrefs.isLinks());
    list9.add(val9);
    prefsC4A.set(term_prov_common + "emphasizeLinks", list9);

    // toc
    List<PreferencesValue> list10 = new ArrayList<PreferencesValue>();
    PreferencesValue val10 = new PreferencesValue();
    val10.setValue(localPrefs.isToc());
    list10.add(val10);
    prefsC4A.set(term_prov_common + "tableOfContents", list10);

    // inputs larger
    List<PreferencesValue> list11 = new ArrayList<PreferencesValue>();
    PreferencesValue val11 = new PreferencesValue();
    val11.setValue(localPrefs.isInputsLarger());
    list11.add(val11);
    prefsC4A.set(term_prov_common + "inputsLarger", list11);

    // layout
    List<PreferencesValue> list12 = new ArrayList<PreferencesValue>();
    PreferencesValue val12 = new PreferencesValue();
    val12.setValue(localPrefs.isLayout());
    list12.add(val12);
    prefsC4A.set(term_prov_common + "simplifyLayout", list12);

    // line spacing
    List<PreferencesValue> list13 = new ArrayList<PreferencesValue>();
    PreferencesValue val13 = new PreferencesValue();
    val13.setValue(localPrefs.getLineSpacing());
    list13.add(val13);
    prefsC4A.set(term_prov_common + "lineSpacing", list13);

    StringWriter strPreferences = new StringWriter();
    ObjectMapper mapper = new ObjectMapper();
    mapper.getSerializationConfig().without(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS);
    mapper.writeValue(strPreferences, prefsC4A);

    return strPreferences.toString();
  }
 {
   mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
   mapper.enableDefaultTyping();
 }
Example #20
0
 static {
   mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
   mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
   mapper.getSerializationConfig().setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
 }
  /**
   * Makes an HTTP connection to a server.
   *
   * @param url The URL of the server to connect to.
   * @param resource The identifier of the resource on the server to address.
   * @param method The name of the HTTP method. Expected to be "GET", "PUT", "POST", or "DELETE".
   * @param request The message body of the request to send. The object is expected to be an
   *     instance of an NGSI 9 or 10 message body.
   * @param contentType The content type that is announced in the request header. The request object
   *     in the message body will be sent in XML format for contentType "application/xml" and JSON
   *     format otherwise.
   * @param xAuthToken The security token used by this connection in order to connect to a component
   *     secured by the FIWARE security mechanisms.
   * @return Either returns the response body returned by the server (as a String) or an error
   *     message.
   */
  public String initializeConnection(
      URL url,
      String resource,
      String method,
      Object request,
      String contentType,
      String xAuthToken) {

    // initialize variables
    HttpURLConnection connection = null;
    InputStream is = null;
    OutputStream os = null;
    String resp = null;

    try {

      // use the above setConnection method to get a connection from url,
      // resource and the method.
      connection = createConnection(url, resource, method, contentType, xAuthToken);

      // get the OutputStram form the connection
      os = connection.getOutputStream();

      if (contentType.equals("application/xml")) {
        // connect using XML message body

        // logger.info("URL" + url + resource);

        logger.info("Starting connection with: " + url + resource);

        // logger.info("Send the QUERY!");

        if (request instanceof NgsiStructure) {
          String string = ((NgsiStructure) request).toString();
          os.write(string.getBytes(Charset.forName("UTF-8")));
        } else {

          // create a context from the request class
          JAXBContext requestContext = JAXBContext.newInstance(request.getClass());

          // Create a Marshaller from the context
          Marshaller m = requestContext.createMarshaller();

          // Ask the marshaller to marshall the request for you
          // logger.info("Request Class: "
          // + request.getClass().toString());
          m.marshal(request, os);
        }

      } else {
        // connect using JSON message body

        logger.info("Starting connection with: " + url + resource);

        // get the OutputStram form the connection
        os = connection.getOutputStream();

        if (request instanceof NgsiStructure) {
          String string = ((NgsiStructure) request).toJsonString();
          os.write(string.getBytes(Charset.forName("UTF-8")));
        } else {

          ObjectMapper mapper = new ObjectMapper();
          SerializationConfig config = mapper.getSerializationConfig();
          config.setSerializationInclusion(Inclusion.NON_NULL);
          // m.setProperty(Marshaller.JAXB_ENCODING, "Unicode");

          try {
            logger.info("----------------->" + mapper.writeValueAsString(request));
            mapper.writeValue(os, request);
          } catch (JsonGenerationException e) {
            if (logger.isDebugEnabled()) {
              logger.debug("JsonGenerationException", e);
            }
          } catch (JsonMappingException e) {
            if (logger.isDebugEnabled()) {
              logger.debug("JsonMappingException", e);
            }
          } catch (IOException e) {
            if (logger.isDebugEnabled()) {
              logger.debug("IOException", e);
            }
          }
        }
      }
      logger.info("Output Stream to " + url + resource + " : " + os.toString());

      // send Message
      os.flush();
      // close connection again
      os.close();

      // now it is time to receive the response
      // get input stream from the connection
      is = connection.getInputStream();

      StringWriter writer = new StringWriter();
      IOUtils.copy(is, writer, "UTF-8");
      resp = writer.toString();

      is.close();

      logger.info("------------->Response = " + resp);

      if (connection.getResponseCode() == 415) {

        logger.info("Connection Error: Format not supported by " + url);

        return "415";
      }

      return resp;

    } catch (ConnectException e) {

      logger.info(
          "IOException: Impossible to establish a connection with " + url + ":" + e.getMessage());
      if (logger.isDebugEnabled()) {
        logger.debug("ConnectException", e);
      }

      return "500 - Connection Error - the URL: " + url + " create an internal error!";

    } catch (JAXBException e) {
      logger.info("XML Parse Error!", e);
      logger.debug("JAXBException", e);
      return "500 - XML Parse Error! Response from: " + url + " is not correct!";
    } catch (IOException e) {

      try {
        if (connection != null && connection.getResponseCode() == 415) {

          logger.info("Connection Error: Format not supported by " + url);

          return "415";
        }
      } catch (IOException e1) {
        if (logger.isDebugEnabled()) {
          logger.debug("IOException", e);
        }
      }

      logger.info("500 - Error I/O with: " + url);
      logger.info(
          "IOException: Impossible to establish a connection with " + url + ": " + e.getMessage());

      return "500 - Error I/O with: " + url;

    } finally {

      if (connection != null) {

        connection.disconnect();
      }
      logger.info("Connection Closed!");
    }
  }