Java Code Examples for com.alibaba.fastjson.JSON#writeJSONString()

The following examples show how to use com.alibaba.fastjson.JSON#writeJSONString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CaconfDbExporter.java    From xipki with Apache License 2.0 6 votes vote down vote up
public void export() throws Exception {
  CaCertstore.Caconf caconf = new CaCertstore.Caconf();
  caconf.setVersion(VERSION);

  System.out.println("exporting CA configuration from database");

  exportSigner(caconf);
  exportRequestor(caconf);
  exportUser(caconf);
  exportPublisher(caconf);
  exportCa(caconf);
  exportProfile(caconf);
  exportCaalias(caconf);
  exportCaHasRequestor(caconf);
  exportCaHasUser(caconf);
  exportCaHasPublisher(caconf);
  exportCaHasProfile(caconf);

  caconf.validate();
  try (OutputStream os = Files.newOutputStream(Paths.get(baseDir, FILENAME_CA_CONFIGURATION))) {
    JSON.writeJSONString(os, caconf, SerializerFeature.PrettyFormat);
  }
  System.out.println(" exported CA configuration from database");
}
 
Example 2
Source File: ExtensionsConfCreatorDemo.java    From xipki with Apache License 2.0 6 votes vote down vote up
private static void marshall(ExtensionsType extensionsType, String filename) {
  try {
    extensionsType.validate();
    Path path = Paths.get("tmp", filename);
    IoUtil.mkdirsParent(path);
    try (OutputStream out = Files.newOutputStream(path)) {
      JSON.writeJSONString(out, extensionsType,
          SerializerFeature.PrettyFormat, SerializerFeature.SortField,
          SerializerFeature.DisableCircularReferenceDetect);
    }
    System.out.println("marshalled " + path.toString());

    check(path);
  } catch (Exception ex) {
    System.err.println("Error while generating extensions in " + filename);
    ex.printStackTrace();
  }

}
 
Example 3
Source File: MetricsHttpExporter.java    From sofa-lookout with Apache License 2.0 5 votes vote down vote up
private static void sendResponse(HttpExchange exchange, Object bodyEntity) throws IOException {
    exchange.getResponseHeaders().set("Content-Type", "application/json;charset=utf-8");
    exchange.getResponseHeaders().set("Content-Encoding", "gzip");
    exchange.sendResponseHeaders(200, 0);
    OutputStream os = new GZIPOutputStream(exchange.getResponseBody());
    try {
        JSON.writeJSONString(os, UTF8, bodyEntity);
    } finally {
        os.close();
    }
}
 
Example 4
Source File: OcspCertstoreDbExporter.java    From xipki with Apache License 2.0 5 votes vote down vote up
private void finalizeZip(ZipOutputStream zipOutStream, OcspCertstore.Certs certs)
    throws IOException {
  ZipEntry certZipEntry = new ZipEntry("certs.json");
  zipOutStream.putNextEntry(certZipEntry);
  try {
    JSON.writeJSONString(zipOutStream, Charset.forName("UTF-8"), certs);
  } finally {
    zipOutStream.closeEntry();
  }

  zipOutStream.close();
}
 
Example 5
Source File: OcspCertstoreDbExporter.java    From xipki with Apache License 2.0 5 votes vote down vote up
public void export() throws Exception {
  OcspCertstore certstore;
  if (resume) {
    try (InputStream is = Files.newInputStream(Paths.get(baseDir, FILENAME_OCSP_CERTSTORE))) {
      certstore = JSON.parseObject(is, OcspCertstore.class);
    }
    certstore.validate();

    if (certstore.getVersion() > VERSION) {
      throw new Exception("could not continue with Certstore greater than " + VERSION
          + ": " + certstore.getVersion());
    }
  } else {
    certstore = new OcspCertstore();
    certstore.setVersion(VERSION);
  }
  System.out.println("exporting OCSP certstore from database");

  if (!resume) {
    exportHashAlgo(certstore);
    exportIssuer(certstore);
    exportCrlInfo(certstore);
  }

  File processLogFile = new File(baseDir, PROCESS_LOG_FILENAME);
  Exception exception = exportCert(certstore, processLogFile);

  try (OutputStream os = Files.newOutputStream(Paths.get(baseDir, FILENAME_OCSP_CERTSTORE))) {
    JSON.writeJSONString(os, certstore);
  }

  if (exception == null) {
    System.out.println(" exported OCSP certstore from database");
  } else {
    throw exception;
  }
}
 
Example 6
Source File: CaCertstoreDbExporter.java    From xipki with Apache License 2.0 5 votes vote down vote up
private void finalizeZip(ZipOutputStream zipOutStream, String filename, Object container)
    throws IOException {
  ZipEntry certZipEntry = new ZipEntry(filename);
  zipOutStream.putNextEntry(certZipEntry);
  try {
    JSON.writeJSONString(zipOutStream, Charset.forName("UTF-8"), container);
  } finally {
    zipOutStream.closeEntry();
  }

  zipOutStream.close();
}
 
Example 7
Source File: ProfileConfCreatorDemo.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static void marshall(X509ProfileType profile, String filename, boolean validate) {
  try {
    Path path = Paths.get("tmp", filename);
    IoUtil.mkdirsParent(path);
    try (OutputStream out = Files.newOutputStream(path)) {
      JSON.writeJSONString(out, profile,
          SerializerFeature.PrettyFormat, SerializerFeature.SortField,
          SerializerFeature.DisableCircularReferenceDetect);
    }

    if (validate) {
      X509ProfileType profileConf;
      // Test by deserializing
      try (InputStream is = Files.newInputStream(path)) {
        profileConf = X509ProfileType.parse(is);
      }
      XijsonCertprofile profileObj = new XijsonCertprofile();
      profileObj.initialize(profileConf);
      profileObj.close();
      System.out.println("Generated certprofile in " + filename);
    }
  } catch (Exception ex) {
    System.err.println("Error while generating certprofile in " + filename);
    ex.printStackTrace();
  }

}
 
Example 8
Source File: CaConfs.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static void marshal(CaConfType.CaSystem root, OutputStream out)
    throws InvalidConfException, IOException {
  Args.notNull(root, "root");
  Args.notNull(out, "out");
  root.validate();
  JSON.writeJSONString(out, Charset.forName("UTF8"), root, SerializerFeature.PrettyFormat);
}
 
Example 9
Source File: Serialization.java    From java-json-benchmark with MIT License 5 votes vote down vote up
@Benchmark
@Override
public Object fastjson() throws Exception {
    ByteArrayOutputStream baos = JsonUtils.byteArrayOutputStream();
    JSON.writeJSONString(baos, JSON_SOURCE().nextPojo(), SerializerFeature.EMPTY);
    return baos;
}
 
Example 10
Source File: FastJsonJsonView.java    From uavstack with Apache License 2.0 5 votes vote down vote up
@Override
protected void renderMergedOutputModel(Map<String, Object> model, //
                                       HttpServletRequest request, //
                                       HttpServletResponse response) throws Exception {
    Object value = filterModel(model);
    String jsonpParameterValue = getJsonpParameterValue(request);
    if(jsonpParameterValue != null) {
        JSONPObject jsonpObject = new JSONPObject(jsonpParameterValue);
        jsonpObject.addParameter(value);
        value = jsonpObject;
    }

    ByteArrayOutputStream outnew = new ByteArrayOutputStream();

    int len = JSON.writeJSONString(outnew, //
            fastJsonConfig.getCharset(), //
            value, //
            fastJsonConfig.getSerializeConfig(), //
            fastJsonConfig.getSerializeFilters(), //
            fastJsonConfig.getDateFormat(), //
            JSON.DEFAULT_GENERATE_FEATURE, //
            fastJsonConfig.getSerializerFeatures());

    if (this.updateContentLength) {
        // Write content length (determined via byte array).
        response.setContentLength(len);
    }

    // Flush byte array to servlet output stream.
    ServletOutputStream out = response.getOutputStream();
    outnew.writeTo(out);
    outnew.close();
    out.flush();
}
 
Example 11
Source File: SystemUtil.java    From sanshanblog with Apache License 2.0 5 votes vote down vote up
/**
 * 设置或刷新系统配置
 * @param setting 设置
 */
public  void setSetting(Setting setting)  {
    try {
        File file = new File(filename);
        OutputStream out = new FileOutputStream(file);
        JSON.writeJSONString(out,setting);
    } catch (IOException e) {
        log.error("read setting error",e);
        e.printStackTrace();
    }
}
 
Example 12
Source File: HttpApiHandler.java    From arthas with Apache License 2.0 5 votes vote down vote up
private void writeResult(DefaultFullHttpResponse response, Object result) throws IOException {
    ByteBufOutputStream out = new ByteBufOutputStream(response.content());
    try {
        JSON.writeJSONString(out, result);
    } catch (IOException e) {
        logger.error("write json to response failed", e);
        throw e;
    }
}
 
Example 13
Source File: FastJsonProcessor.java    From requests with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public void marshal(Writer writer, Object value) {
    JSON.writeJSONString(writer, value);
}
 
Example 14
Source File: FastJsonProvider.java    From uavstack with Apache License 2.0 4 votes vote down vote up
/**
     * Method that JAX-RS container calls to serialize given value.
     */
    public void writeTo(Object obj, //
                        Class<?> type, //
                        Type genericType, //
                        Annotation[] annotations, //
                        MediaType mediaType, //
                        MultivaluedMap<String, Object> httpHeaders, //
                        OutputStream entityStream //
    ) throws IOException, WebApplicationException {

        FastJsonConfig fastJsonConfig = locateConfigProvider(type, mediaType);

        SerializerFeature[] serializerFeatures = fastJsonConfig.getSerializerFeatures();
        if (pretty) {
            if (serializerFeatures == null)
                serializerFeatures = new SerializerFeature[]{SerializerFeature.PrettyFormat};
            else {
                List<SerializerFeature> featureList = new ArrayList<SerializerFeature>(Arrays
                        .asList(serializerFeatures));
                featureList.add(SerializerFeature.PrettyFormat);
                serializerFeatures = featureList.toArray(serializerFeatures);
            }
            fastJsonConfig.setSerializerFeatures(serializerFeatures);
        }

        try {
            int len = JSON.writeJSONString(entityStream, //
                    fastJsonConfig.getCharset(), //
                    obj, //
                    fastJsonConfig.getSerializeConfig(), //
                    fastJsonConfig.getSerializeFilters(), //
                    fastJsonConfig.getDateFormat(), //
                    JSON.DEFAULT_GENERATE_FEATURE, //
                    fastJsonConfig.getSerializerFeatures());

//            // add Content-Length
//            if (fastJsonConfig.isWriteContentLength()) {
//                httpHeaders.add("Content-Length", String.valueOf(len));
//            }

            entityStream.flush();

        } catch (JSONException ex) {

            throw new WebApplicationException("Could not write JSON: " + ex.getMessage(), ex);
        }
    }
 
Example 15
Source File: FastJsonHttpMessageConverter.java    From uavstack with Apache License 2.0 4 votes vote down vote up
@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {

    ByteArrayOutputStream outnew = new ByteArrayOutputStream();
    try {
        HttpHeaders headers = outputMessage.getHeaders();

        //获取全局配置的filter
        SerializeFilter[] globalFilters = fastJsonConfig.getSerializeFilters();
        List<SerializeFilter> allFilters = new ArrayList<SerializeFilter>(Arrays.asList(globalFilters));

        boolean isJsonp = false;

        //不知道为什么会有这行代码, 但是为了保持和原来的行为一致,还是保留下来
        Object value = strangeCodeForJackson(object);

        if (value instanceof FastJsonContainer) {
            FastJsonContainer fastJsonContainer = (FastJsonContainer) value;
            PropertyPreFilters filters = fastJsonContainer.getFilters();
            allFilters.addAll(filters.getFilters());
            value = fastJsonContainer.getValue();
        }

        //revise 2017-10-23 ,
        // 保持原有的MappingFastJsonValue对象的contentType不做修改 保持旧版兼容。
        // 但是新的JSONPObject将返回标准的contentType:application/javascript ,不对是否有function进行判断
        if (value instanceof MappingFastJsonValue) {
            if(!StringUtils.isEmpty(((MappingFastJsonValue) value).getJsonpFunction())){
                isJsonp = true;
            }
        } else if (value instanceof JSONPObject) {
            isJsonp = true;
        }


        int len = JSON.writeJSONString(outnew, //
                fastJsonConfig.getCharset(), //
                value, //
                fastJsonConfig.getSerializeConfig(), //
                //fastJsonConfig.getSerializeFilters(), //
                allFilters.toArray(new SerializeFilter[allFilters.size()]),
                fastJsonConfig.getDateFormat(), //
                JSON.DEFAULT_GENERATE_FEATURE, //
                fastJsonConfig.getSerializerFeatures());

        if (isJsonp) {
            headers.setContentType(APPLICATION_JAVASCRIPT);
        }

        if (fastJsonConfig.isWriteContentLength()) {
            headers.setContentLength(len);
        }

        outnew.writeTo(outputMessage.getBody());

    } catch (JSONException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    } finally {
        outnew.close();
    }
}
 
Example 16
Source File: CaCertstoreDbExporter.java    From xipki with Apache License 2.0 4 votes vote down vote up
public void export() throws Exception {
  CaCertstore certstore;
  if (resume) {
    try (InputStream is = Files.newInputStream(Paths.get(baseDir, FILENAME_CA_CERTSTORE))) {
      certstore = JSON.parseObject(is, CaCertstore.class);
    }
    certstore.validate();

    if (certstore.getVersion() > VERSION) {
      throw new Exception("could not continue with CertStore greater than "
          + VERSION + ": " + certstore.getVersion());
    }
  } else {
    certstore = new CaCertstore();
    certstore.setVersion(VERSION);
  }

  Exception exception = null;
  System.out.println("exporting CA certstore from database");
  try {
    if (!resume) {
      exportPublishQueue(certstore);
      exportDeltaCrlCache(certstore);
    }

    File processLogFile = new File(baseDir, DbPorter.EXPORT_PROCESS_LOG_FILENAME);

    Long idProcessedInLastProcess = null;
    CaDbEntryType typeProcessedInLastProcess = null;
    if (processLogFile.exists()) {
      byte[] content = IoUtil.read(processLogFile);
      if (content != null && content.length > 0) {
        String str = new String(content);
        int idx = str.indexOf(':');
        String typeName = str.substring(0, idx).trim();
        typeProcessedInLastProcess = CaDbEntryType.valueOf(typeName);
        idProcessedInLastProcess = Long.parseLong(str.substring(idx + 1).trim());
      }
    }

    if (CaDbEntryType.CRL == typeProcessedInLastProcess || typeProcessedInLastProcess == null) {
      exception = exportEntries(CaDbEntryType.CRL, certstore, processLogFile,
          idProcessedInLastProcess);
      typeProcessedInLastProcess = null;
      idProcessedInLastProcess = null;
    }

    CaDbEntryType[] types = {CaDbEntryType.CERT, CaDbEntryType.REQUEST, CaDbEntryType.REQCERT};

    for (CaDbEntryType type : types) {
      if (exception == null
          && (type == typeProcessedInLastProcess || typeProcessedInLastProcess == null)) {
        exception = exportEntries(type, certstore, processLogFile, idProcessedInLastProcess);
        typeProcessedInLastProcess = null;
        idProcessedInLastProcess = null;
      }
    }

    certstore.validate();
    try (OutputStream os = Files.newOutputStream(Paths.get(baseDir, FILENAME_CA_CERTSTORE))) {
      JSON.writeJSONString(os, Charset.forName("UTF-8"), certstore);
    }
  } catch (Exception ex) {
    System.err.println("could not export CA certstore from database");
    exception = ex;
  }

  if (exception == null) {
    System.out.println(" exported CA certstore from database");
  } else {
    throw exception;
  }
}
 
Example 17
Source File: JsonMessageConverter.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
    try (ByteArrayOutputStream outnew = new ByteArrayOutputStream()) {
        HttpHeaders headers = outputMessage.getHeaders();

        //获取全局配置的filter
        SerializeFilter[] globalFilters = getFastJsonConfig().getSerializeFilters();
        List<SerializeFilter> allFilters = new ArrayList<>(Arrays.asList(globalFilters));

        boolean isJsonp = false;
        Object value = strangeCodeForJackson(object);

        if (value instanceof FastJsonContainer) {
            FastJsonContainer fastJsonContainer = (FastJsonContainer) value;
            PropertyPreFilters filters = fastJsonContainer.getFilters();
            allFilters.addAll(filters.getFilters());
            value = fastJsonContainer.getValue();
        }

        if (value instanceof MappingFastJsonValue) {
            isJsonp = true;
            value = ((MappingFastJsonValue) value).getValue();
        } else if (value instanceof JSONPObject) {
            isJsonp = true;
        }


        int len = writePrefix(outnew, object);
        len += JSON.writeJSONString(outnew, //
                getFastJsonConfig().getCharset(), //
                value, //
                getFastJsonConfig().getSerializeConfig(), //
                allFilters.toArray(new SerializeFilter[allFilters.size()]),
                getFastJsonConfig().getDateFormat(), //
                JSON.DEFAULT_GENERATE_FEATURE, //
                getFastJsonConfig().getSerializerFeatures());
        len += writeSuffix(outnew, object);

        if (isJsonp) {
            headers.setContentType(APPLICATION_JAVASCRIPT);
        }
        if (getFastJsonConfig().isWriteContentLength()) {
            headers.setContentLength(len);
        }

        headers.set("carrera_logid", RequestContext.getLogId());
        RequestContext.sendJsonResponse(outnew.toString());

        outnew.writeTo(outputMessage.getBody());

    } catch (JSONException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    }
}
 
Example 18
Source File: JsonMessageConverter.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
    try (ByteArrayOutputStream outnew = new ByteArrayOutputStream()) {
        HttpHeaders headers = outputMessage.getHeaders();

        //获取全局配置的filter
        SerializeFilter[] globalFilters = getFastJsonConfig().getSerializeFilters();
        List<SerializeFilter> allFilters = new ArrayList<>(Arrays.asList(globalFilters));

        boolean isJsonp = false;
        Object value = strangeCodeForJackson(object);

        if (value instanceof FastJsonContainer) {
            FastJsonContainer fastJsonContainer = (FastJsonContainer) value;
            PropertyPreFilters filters = fastJsonContainer.getFilters();
            allFilters.addAll(filters.getFilters());
            value = fastJsonContainer.getValue();
        }

        if (value instanceof MappingFastJsonValue) {
            isJsonp = true;
            value = ((MappingFastJsonValue) value).getValue();
        } else if (value instanceof JSONPObject) {
            isJsonp = true;
        }


        int len = writePrefix(outnew, object);
        len += JSON.writeJSONString(outnew, //
                getFastJsonConfig().getCharset(), //
                value, //
                getFastJsonConfig().getSerializeConfig(), //
                allFilters.toArray(new SerializeFilter[allFilters.size()]),
                getFastJsonConfig().getDateFormat(), //
                JSON.DEFAULT_GENERATE_FEATURE, //
                getFastJsonConfig().getSerializerFeatures());
        len += writeSuffix(outnew, object);

        if (isJsonp) {
            headers.setContentType(APPLICATION_JAVASCRIPT);
        }
        if (getFastJsonConfig().isWriteContentLength()) {
            headers.setContentLength(len);
        }

        headers.set("carrera_logid", RequestContext.getLogId());
        RequestContext.sendJsonResponse(outnew.toString());

        outnew.writeTo(outputMessage.getBody());

    } catch (JSONException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    }
}