Java 类org.codehaus.jackson.map.annotate.JsonSerialize 实例源码

项目:artifactory    文件:AqlJsonStreamer.java   
public byte[] getNewRowFromDb() {
    boolean isFirstElement = mainId == null;
    Row row = inflateRow();
    if (row != null) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.getSerializationConfig().withSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
            mapper.setVisibility(JsonMethod.ALL, JsonAutoDetect.Visibility.NONE);
            mapper.setVisibility(JsonMethod.FIELD, JsonAutoDetect.Visibility.ANY);
            String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(row);
            json = isFirstElement ? "" + json : "," + json;
            return json.getBytes();
        } catch (Exception e) {
            throw new AqlException("Failed to convert Aql Result to JSON", e);
        }
    }
    return null;
}
项目:GitHub    文件:Jackson1Annotator.java   
public Jackson1Annotator(GenerationConfig generationConfig) {
    super(generationConfig);
    switch (generationConfig.getInclusionLevel()) {
        case ALWAYS:
            inclusionLevel = JsonSerialize.Inclusion.ALWAYS;
            break;
        case NON_ABSENT:
            inclusionLevel = JsonSerialize.Inclusion.NON_NULL;
            break;
        case NON_DEFAULT:
            inclusionLevel = JsonSerialize.Inclusion.NON_DEFAULT;
            break;
        case NON_EMPTY:
            inclusionLevel = JsonSerialize.Inclusion.NON_EMPTY;
            break;
        case NON_NULL:
            inclusionLevel = JsonSerialize.Inclusion.NON_NULL;
            break;
        case USE_DEFAULTS:
            inclusionLevel = JsonSerialize.Inclusion.NON_NULL;
            break;
        default:
            inclusionLevel = JsonSerialize.Inclusion.NON_NULL;
            break;
    }
}
项目:SAP-cloud-dqm-sample-java    文件:CustomObjectMapper.java   
/**
 * {@inheritDoc}
 */
   public CustomObjectMapper()
{
    super();
    this.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    this.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
    this.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);

    this.setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT); 
    this.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    this.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);

    final AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();

    // make deserializer use JAXB annotations (only)
    this.setAnnotationIntrospector(introspector);

    // TODO leverage NamingStrategy to make reponse attributes more Java-like
    //this.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
}
项目:artifactory    文件:JsonUtil.java   
/**
 * jsonToString exclude null data end edit fields
 *
 * @param model - model data to String
 * @return - model data with json format
 */
public static String jsonToStringIgnoreSpecialFields(RestModel model) {
    String[] ExcludedFieldsFromView = getExcludedFields(model);
    ObjectMapper specialMapper = new ObjectMapper();
    specialMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    String data = null;
    FilterProvider filters = new SimpleFilterProvider()
            .addFilter("exclude fields",
                    SimpleBeanPropertyFilter.serializeAllExcept(
                            (ExcludedFieldsFromView)));
    ObjectWriter writer = specialMapper.writer(filters);
    try {
        data = writer.writeValueAsString(model);
    } catch (IOException e) {
        log.debug(e.getMessage());
    }
    return data;
}
项目:jrs-rest-java-client    文件:BatchJobsOperationsAdapter.java   
private String buildJson(Object object) {

        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);

        try {
            return mapper.writeValueAsString(object);
        } catch (IOException e) {
            log.warn("Can't marshal search criteria.");
            throw new RuntimeException("Failed inFolder build criteria json.", e);
        }
    }
项目:sip-servlets    文件:ASCCallControlClient.java   
private CallControlCallResultType parseResult(MultivaluedMap<String, String> queryParams, WebResource resource, boolean returnResult) throws JsonProcessingException, IOException {
    queryParams.add("output", "json");

    Builder builder = resource.queryParams(queryParams).getRequestBuilder();

    builder = builder.accept(javax.ws.rs.core.MediaType.APPLICATION_JSON);
    builder = builder.type(javax.ws.rs.core.MediaType.APPLICATION_JSON);
    builder = builder.cookie(JSESSIONID_WS);

    String resultStr = builder.get(String.class);

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    JsonNode rootNode = mapper.readTree(resultStr);
    if(returnResult)
    {
        JsonNode ccr = rootNode.path("ExtActionResponse").path("structure").path("CallControlCallResult");
        return mapper.readValue(ccr, CallControlCallResultType.class);
    }
    else return null;
}
项目:GitHub    文件:InclusionLevelIT.java   
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void Jackson1InclusionLevelAlways() throws ClassNotFoundException, SecurityException, NoSuchMethodException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/primitiveProperties.json", "com.example",
            config("annotationStyle", "jackson1", "inclusionLevel", "ALWAYS"));

    Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties");

    JsonSerialize jsonSerialize = (JsonSerialize) generatedType.getAnnotation(JsonSerialize.class);

    assertThat(jsonSerialize, is(notNullValue()));
    assertThat(jsonSerialize.include(), is(JsonSerialize.Inclusion.ALWAYS));
}
项目:GitHub    文件:InclusionLevelIT.java   
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void Jackson1InclusionLevelNonAbsent() throws ClassNotFoundException, SecurityException, NoSuchMethodException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/primitiveProperties.json", "com.example",
            config("annotationStyle", "jackson1", "inclusionLevel", "NON_ABSENT"));

    Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties");

    JsonSerialize jsonSerialize = (JsonSerialize) generatedType.getAnnotation(JsonSerialize.class);

    assertThat(jsonSerialize, is(notNullValue()));
    assertThat(jsonSerialize.include(), is(JsonSerialize.Inclusion.NON_NULL));
}
项目:GitHub    文件:InclusionLevelIT.java   
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void Jackson1InclusionLevelNonDefault() throws ClassNotFoundException, SecurityException, NoSuchMethodException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/primitiveProperties.json", "com.example",
            config("annotationStyle", "jackson1", "inclusionLevel", "NON_DEFAULT"));

    Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties");

    JsonSerialize jsonSerialize = (JsonSerialize) generatedType.getAnnotation(JsonSerialize.class);

    assertThat(jsonSerialize, is(notNullValue()));
    assertThat(jsonSerialize.include(), is(JsonSerialize.Inclusion.NON_DEFAULT));
}
项目:GitHub    文件:InclusionLevelIT.java   
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void Jackson1InclusionLevelNonEmpty() throws ClassNotFoundException, SecurityException, NoSuchMethodException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/primitiveProperties.json", "com.example",
            config("annotationStyle", "jackson1", "inclusionLevel", "NON_EMPTY"));

    Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties");

    JsonSerialize jsonSerialize = (JsonSerialize) generatedType.getAnnotation(JsonSerialize.class);

    assertThat(jsonSerialize, is(notNullValue()));
    assertThat(jsonSerialize.include(), is(JsonSerialize.Inclusion.NON_EMPTY));
}
项目:GitHub    文件:InclusionLevelIT.java   
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void Jackson1InclusionLevelNonNull() throws ClassNotFoundException, SecurityException, NoSuchMethodException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/primitiveProperties.json", "com.example",
            config("annotationStyle", "jackson1", "inclusionLevel", "NON_NULL"));

    Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties");

    JsonSerialize jsonSerialize = (JsonSerialize) generatedType.getAnnotation(JsonSerialize.class);

    assertThat(jsonSerialize, is(notNullValue()));
    assertThat(jsonSerialize.include(), is(JsonSerialize.Inclusion.NON_NULL));
}
项目:GitHub    文件:InclusionLevelIT.java   
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void Jackson1InclusionLevelUseDefault() throws ClassNotFoundException, SecurityException, NoSuchMethodException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/primitiveProperties.json", "com.example",
            config("annotationStyle", "jackson1", "inclusionLevel", "USE_DEFAULTS"));

    Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties");

    JsonSerialize jsonSerialize = (JsonSerialize) generatedType.getAnnotation(JsonSerialize.class);

    assertThat(jsonSerialize, is(notNullValue()));
    assertThat(jsonSerialize.include(), is(JsonSerialize.Inclusion.NON_NULL));
}
项目:GitHub    文件:InclusionLevelIT.java   
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void Jackson1InclusionLevelNotSet() throws ClassNotFoundException, SecurityException, NoSuchMethodException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/primitiveProperties.json", "com.example",
            config("annotationStyle", "jackson1"));

    Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties");

    JsonSerialize jsonSerialize = (JsonSerialize) generatedType.getAnnotation(JsonSerialize.class);

    assertThat(jsonSerialize, is(notNullValue()));
    assertThat(jsonSerialize.include(), is(JsonSerialize.Inclusion.NON_NULL));
}
项目:cassandra-fhir-index    文件:JsonSerializer.java   
/** Private constructor to hide the implicit public one. */
private JsonSerializer() {
    jsonMapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false);
    jsonMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    jsonMapper.configure(SerializationConfig.Feature.AUTO_DETECT_IS_GETTERS, false);
    jsonMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    jsonMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
}
项目:venus    文件:ObjectMapperFactory.java   
public static ObjectMapper getNullableObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();

    // mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
    // mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
    // mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    // //mapper.configure(DeserializationConfig.Feature.USE_ANNOTATIONS, false);
    // mapper.configure(Feature.AUTO_CLOSE_SOURCE, false);
    // mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);

    SerializationConfig config = objectMapper.getSerializationConfig();
    config.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);

    return objectMapper;
}
项目:SpringBoot-Oauth2-stater-kit    文件:AbstractTest.java   
@Before
public void setUp() {
    mapper = new ObjectMapper();
    mapper.configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, false);
    mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    mvc = webAppContextSetup(webApplicationContext).addFilter(springSecurityFilterChain).build();
    mockSession = new MockHttpSession(webApplicationContext.getServletContext(), UUID.randomUUID().toString());
}
项目:dingding-app-server    文件:JsonUtil.java   
/**
 * 将对象按照json字符串格式输出
 *
 * @param obj javabean对象实例
 * @return json字符串
 * @throws IOException
 */
public static String toString(Object obj) throws IOException {
    if(obj==null){
        return null;
    }
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    return mapper.writeValueAsString(obj);
}
项目:fountain    文件:JsonUtils.java   
public String writeValueAsString(Object value,
        JsonSerialize.Inclusion inc) throws IOException,
        JsonGenerationException, JsonMappingException {
    if (inc == null) {
        return super.writeValueAsString(value);
    }
    // alas, we have to pull the recycler directly here...
    SegmentedStringWriter sw = new SegmentedStringWriter(
            _jsonFactory._getBufferRecycler());
    writeValueWithConf(_jsonFactory.createJsonGenerator(sw), value,
            inc);
    return sw.getAndClear();
}
项目:fountain    文件:JsonUtils.java   
public byte[] writeValueAsBytes(Object value,
        JsonSerialize.Inclusion inc) throws IOException,
        JsonGenerationException, JsonMappingException {
    if (inc == null) {
        return super.writeValueAsBytes(value);
    }
    // alas, we have to pull the recycler directly here...
    ByteArrayBuilder bb = new ByteArrayBuilder(_jsonFactory._getBufferRecycler());
    writeValueWithConf(_jsonFactory.createJsonGenerator(bb, JsonEncoding.UTF8), value,inc);
    byte[] result = bb.toByteArray();
    bb.release();
    return result;
}
项目:fountain    文件:JsonUtils.java   
private void writeValueWithConf(JsonGenerator jgen, Object value,
        JsonSerialize.Inclusion inc) throws IOException,
        JsonGenerationException, JsonMappingException {

    SerializationConfig cfg = copySerializationConfig();
    cfg = cfg.withSerializationInclusion(inc);

    // [JACKSON-96]: allow enabling pretty printing for ObjectMapper
    // directly
    if (cfg.isEnabled(SerializationConfig.Feature.INDENT_OUTPUT)) {
        jgen.useDefaultPrettyPrinter();
    }
    // [JACKSON-282]: consider Closeable
    if (cfg.isEnabled(SerializationConfig.Feature.CLOSE_CLOSEABLE)
            && (value instanceof Closeable)) {
        configAndWriteCloseable(jgen, value, cfg);
        return;
    }
    boolean closed = false;
    try {
        _serializerProvider.serializeValue(cfg, jgen, value,
                _serializerFactory);
        closed = true;
        jgen.close();
    } finally {
        /*
         * won't try to close twice; also, must catch exception (so it
         * will not mask exception that is pending)
         */
        if (!closed) {
            try {
                jgen.close();
            } catch (IOException ioe) {
            }
        }
    }
}
项目:fountain    文件:JsonUtils.java   
public static String toJson(Object object, boolean ignoreEmpty) {
    String jsonString = "";
    try {
        if(ignoreEmpty){
            jsonString = objectMapper.writeValueAsString(object,JsonSerialize.Inclusion.NON_EMPTY);
        }else{
            jsonString = objectMapper.writeValueAsString(object);
        }
        } catch (Exception e) {
        log.warn("json error:" + e.getMessage());
    }
    return jsonString;

}
项目:fountain    文件:JsonUtils.java   
public static byte[] toJsonBytes(Object object, boolean ignoreEmpty) {
    byte[] smileData = null;
    try {
        if(ignoreEmpty){
            smileData = objectMapperByte.writeValueAsBytes(object,JsonSerialize.Inclusion.NON_EMPTY);
        }else{
            smileData = objectMapperByte.writeValueAsBytes(object);
        }
    } catch (Exception e) {
        log.warn("json error:" + e.getMessage());
    }
    return smileData;

}
项目:apex-core    文件:ObjectMapperFactory.java   
public static ObjectMapper getOperatorValueSerializer()
{
  ObjectMapper returnVal = new ObjectMapper();
  returnVal.setVisibilityChecker(new VC());
  returnVal.configure(org.codehaus.jackson.map.SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
  returnVal.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, As.WRAPPER_OBJECT);
  returnVal.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
  return returnVal;
}
项目:Multipath-Hedera-system-in-Floodlight-controller    文件:OFSwitchImpl.java   
@Override
@JsonSerialize(using=DPIDSerializer.class)
@JsonProperty("dpid")
public long getId() {
    if (this.stringId == null)
        throw new RuntimeException("Features reply has not yet been set");
    return this.datapathId;
}
项目:artifactory    文件:AqlJsonStreamer.java   
private String generateRangeJson() throws IOException {
    Range range = new Range(offset, rowsCount, rowsCount, limit);
    ObjectMapper mapper = new ObjectMapper();
    mapper.getSerializationConfig().withSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    mapper.setVisibility(JsonMethod.ALL, JsonAutoDetect.Visibility.NONE);
    mapper.setVisibility(JsonMethod.FIELD, JsonAutoDetect.Visibility.ANY);
    return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(range);
}
项目:artifactory    文件:JsonUtil.java   
/**
 * json to String exclude null data
 *
 * @param model - model data to String
 * @return - model data with json format
 */
public static String jsonToString(Object model) {
    //        ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    mapper.disableDefaultTyping();
    String jasonString = null;
    try {
        jasonString = mapper.writeValueAsString(model);
    } catch (IOException e) {
        log.error(e.toString());
    }
    return jasonString;
}
项目:artifactory    文件:JacksonFactory.java   
/**
 * Update the generator with a default codec and pretty printer
 *
 * @param jsonFactory   Factory to set as codec
 * @param jsonGenerator Generator to configure
 */
private static void updateGenerator(JsonFactory jsonFactory, JsonGenerator jsonGenerator) {
    ObjectMapper mapper = new ObjectMapper(jsonFactory);

    //Update the annotation interceptor to also include jaxb annotations as a second choice
    AnnotationIntrospector primary = new JacksonAnnotationIntrospector();
    AnnotationIntrospector secondary = new JaxbAnnotationIntrospector() {

        /**
         * BUG FIX:
         * By contract, if findSerializationInclusion didn't encounter any annotations that should change the
         * inclusion value, it should return the default value it has received; but actually returns null, which
         * overrides the NON_NULL option we set.
         * The doc states issue JACKSON-256 which was supposed to be fixed in 1.5.0. *twilight zone theme song*
         */

        @Override
        public JsonSerialize.Inclusion findSerializationInclusion(Annotated a, JsonSerialize.Inclusion defValue) {
            JsonSerialize.Inclusion inclusion = super.findSerializationInclusion(a, defValue);
            if (inclusion == null) {
                return defValue;
            }
            return inclusion;
        }
    };
    AnnotationIntrospector pair = new AnnotationIntrospector.Pair(primary, secondary);
    mapper.getSerializationConfig().setAnnotationIntrospector(pair);
    mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);

    jsonGenerator.setCodec(mapper);
    jsonGenerator.useDefaultPrettyPrinter();
}
项目:artifactory    文件:JsonProvider.java   
public JsonProvider() {
    ObjectMapper mapper = getMapper();
    //Update the annotation interceptor to also include jaxb annotations as a second choice
    AnnotationIntrospector primary = new JacksonAnnotationIntrospector();
    AnnotationIntrospector secondary = new JaxbAnnotationIntrospector();
    AnnotationIntrospector pair = new AnnotationIntrospector.Pair(primary, secondary);

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

    mapper.getDeserializationConfig().setAnnotationIntrospector(pair);
    //Ignore missing properties
    mapper.getDeserializationConfig().disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
}
项目:artifactory    文件:JsonUtil.java   
/**
 * json to String exclude null data
 *
 * @param model - model data to String
 * @return - model data with json format
 */
public static String jsonToString(RestModel model) {
    mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    mapper.disableDefaultTyping();
    String jasonString = null;
    try {
        jasonString = mapper.writeValueAsString(model);
    } catch (IOException e) {
        log.debug(e.toString());
    }
    return jasonString;
}
项目:hops    文件:PluginStoreTestUtils.java   
static ObjectMapper createObjectMapper() {
  ObjectMapper mapper = new ObjectMapper();
  mapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector());
  mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
  mapper.configure(SerializationConfig.Feature.CLOSE_CLOSEABLE, false);
  return mapper;
}
项目:community-edition-old    文件:RestApiUtil.java   
/**
 * Converts the POJO which represents the JSON payload into a JSON string.
 * null values will be ignored.
 */
public static String toJsonAsStringNonNull(Object object) throws IOException
{
    assertNotNull(object);
    ObjectMapper om = new ObjectMapper();
    om.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    return om.writeValueAsString(object);
}
项目:TestRailSDK    文件:TestRailService.java   
/**
 * Posts the given String to the given TestRails end-point
 * @param apiCall The end-point that expects to receive the entities (e.g. "add_result")
 * @param urlParams The remainder of the URL required for the POST. It is up to you to get this part right
 * @param entity The BaseEntity object to use at the POST body
 * @return The Content of the HTTP Response
 */
private HttpResponse postRESTBody(String apiCall, String urlParams, BaseEntity entity) {
    HttpClient httpClient = new DefaultHttpClient();
    String completeUrl = buildRequestURL( apiCall, urlParams );

    try {
        HttpPost request = new HttpPost( completeUrl );
        String authentication = utils.encodeAuthenticationBase64(username, password);
        request.addHeader("Authorization", "Basic " + authentication);
        request.addHeader("Content-Type", "application/json");

        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
        byte[] body = mapper.writeValueAsBytes(entity);
        request.setEntity(new ByteArrayEntity(body));

        HttpResponse response = executeRequestWithRetry(request, 2);
        if (response.getStatusLine().getStatusCode() != 200) {
            Error error = JSONUtils.getMappedJsonObject(Error.class, utils.getContentsFromHttpResponse(response));
            log.error("Response code: {}", response.getStatusLine().getStatusCode());
            log.error("TestRails reported an error message: {}", error.getError());
            request.addHeader("Encoding", "UTF-8");
        }
        return response;
    }
    catch (IOException e) {
        log.error(String.format("An IOException was thrown while trying to process a REST Request against URL: [%s]", completeUrl), e.toString());
        throw new RuntimeException(String.format("Connection is null, check URL: %s", completeUrl));
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
项目:TestRailSDK    文件:TestRailService.java   
/**
   * Posts the given String to the given TestRails end-point
   *
   * @param apiCall The end-point that expects to receive the entities (e.g. "add_result")
   * @param urlParams The remainder of the URL required for the POST. It is up to you to get this part right
   * @param entity The BaseEntity object to use at the POST body
   * @param returnEntityType The Class of the return type you wish to receive (helps avoid casting from the calling method)
   * @return The Content of the HTTP Response
   */
  private <T extends BaseEntity> T postRESTBodyReturn(String apiCall, String urlParams, BaseEntity entity, Class<T> returnEntityType) {
      HttpClient httpClient = new DefaultHttpClient();
      String completeUrl = buildRequestURL( apiCall, urlParams );

      try {
          HttpPost request = new HttpPost( completeUrl );
          String authentication = utils.encodeAuthenticationBase64(username, password);
          request.addHeader("Authorization", "Basic " + authentication);
          request.addHeader("Content-Type", "application/json");
          request.addHeader("Encoding", "UTF-8");

          ObjectMapper mapper = new ObjectMapper();
          mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
          byte[] body = mapper.writeValueAsBytes(entity);
          request.setEntity(new ByteArrayEntity(body));

          HttpResponse response = executeRequestWithRetry(request, 2);
          int responseStatusCode = response.getStatusLine().getStatusCode();
          if (responseStatusCode == 200) {
              log.info("Returning a JSON mapped object from calling api integration point");
              T mappedJsonObject = JSONUtils.getMappedJsonObject(returnEntityType, utils.getContentsFromHttpResponse(response));
              mappedJsonObject.setTestRailService(this);
              return mappedJsonObject;
          } else {
              Error error = JSONUtils.getMappedJsonObject(Error.class, utils.getContentsFromHttpResponse(response));
              log.error("Response code: {}", responseStatusCode);
              log.error("TestRails reported an error message: {}", error.getError());
          }
      }
      catch (IOException e) {
          log.error(String.format("An IOException was thrown while trying to process a REST Request against URL: [%s]", completeUrl), e);
          throw new RuntimeException(String.format("Connection is null, check URL: %s", completeUrl), e);
      } finally {
          httpClient.getConnectionManager().shutdown();
      }
return null;
  }
项目:jira-rest-client    文件:IssueService.java   
public Issue createIssue(Issue issue) throws IOException {
    ObjectMapper mapper = new ObjectMapper();

    //to ignore a field if its value is null
    mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    String content = mapper.writeValueAsString(issue);

    logger.debug("Content=" + content);

    client.setResourceName(Constants.JIRA_RESOURCE_ISSUE);

    ClientResponse response = client.post(content);

    content = response.getEntity(String.class);

    mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, true);
    TypeReference<Issue> ref = new TypeReference<Issue>() {
    };

    Issue resIssue = mapper.readValue(content, ref);

    if (issue.hasAttachments()) {
        issue.setId(resIssue.getId());
        List<Attachment> attachment = postAttachment(issue);
        resIssue.getFields().setAttachment(attachment);
    }

    return resIssue;
}
项目:ecru    文件:RestObjectMapperProvider.java   
private static ObjectMapper createMapper() {

    final ObjectMapper mapper = new ObjectMapper();
    mapper.configure(Feature.INDENT_OUTPUT, true);
    mapper.configure(Feature.WRITE_NULL_MAP_VALUES, false);
    // the next piece is from http://wiki.fasterxml.com/JacksonFAQDateHandling
    mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.setSerializationConfig(mapper.getSerializationConfig().withSerializationInclusion(JsonSerialize.Inclusion.NON_NULL));
    return mapper;

}
项目:12306-android-Decompile    文件:JacksonAnnotationIntrospector.java   
public Class<? extends JsonSerializer<?>> findContentSerializer(Annotated paramAnnotated)
{
  JsonSerialize localJsonSerialize = (JsonSerialize)paramAnnotated.getAnnotation(JsonSerialize.class);
  if (localJsonSerialize != null)
  {
    Class localClass = localJsonSerialize.contentUsing();
    if (localClass != JsonSerializer.None.class)
      return localClass;
  }
  return null;
}
项目:12306-android-Decompile    文件:JacksonAnnotationIntrospector.java   
public String findGettablePropertyName(AnnotatedMethod paramAnnotatedMethod)
{
  JsonProperty localJsonProperty = (JsonProperty)paramAnnotatedMethod.getAnnotation(JsonProperty.class);
  if (localJsonProperty != null)
    return localJsonProperty.value();
  JsonGetter localJsonGetter = (JsonGetter)paramAnnotatedMethod.getAnnotation(JsonGetter.class);
  if (localJsonGetter != null)
    return localJsonGetter.value();
  if ((paramAnnotatedMethod.hasAnnotation(JsonSerialize.class)) || (paramAnnotatedMethod.hasAnnotation(JsonView.class)))
    return "";
  return null;
}
项目:12306-android-Decompile    文件:JacksonAnnotationIntrospector.java   
public Class<? extends JsonSerializer<?>> findKeySerializer(Annotated paramAnnotated)
{
  JsonSerialize localJsonSerialize = (JsonSerialize)paramAnnotated.getAnnotation(JsonSerialize.class);
  if (localJsonSerialize != null)
  {
    Class localClass = localJsonSerialize.keyUsing();
    if (localClass != JsonSerializer.None.class)
      return localClass;
  }
  return null;
}
项目:12306-android-Decompile    文件:JacksonAnnotationIntrospector.java   
public String findSerializablePropertyName(AnnotatedField paramAnnotatedField)
{
  JsonProperty localJsonProperty = (JsonProperty)paramAnnotatedField.getAnnotation(JsonProperty.class);
  if (localJsonProperty != null)
    return localJsonProperty.value();
  if ((paramAnnotatedField.hasAnnotation(JsonSerialize.class)) || (paramAnnotatedField.hasAnnotation(JsonView.class)))
    return "";
  return null;
}
项目:12306-android-Decompile    文件:JacksonAnnotationIntrospector.java   
public Class<?> findSerializationContentType(Annotated paramAnnotated, JavaType paramJavaType)
{
  JsonSerialize localJsonSerialize = (JsonSerialize)paramAnnotated.getAnnotation(JsonSerialize.class);
  if (localJsonSerialize != null)
  {
    Class localClass = localJsonSerialize.contentAs();
    if (localClass != NoClass.class)
      return localClass;
  }
  return null;
}