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

The following examples show how to use com.alibaba.fastjson.JSON#toJSONBytes() . 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: JSonSerializer.java    From jvm-sandbox-repeater with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] serialize(Object object, ClassLoader classLoader) throws SerializeException {
    ClassLoader swap = Thread.currentThread().getContextClassLoader();
    try {
        if (classLoader != null) {
            Thread.currentThread().setContextClassLoader(classLoader);
        }
        return JSON.toJSONBytes(object, features);
    } catch (Throwable t) {
        // may produce sof exception
        throw new SerializeException("[Error-1001]-json-serialize-error", t);
    } finally {
        if (classLoader != null) {
            Thread.currentThread().setContextClassLoader(swap);
        }
    }
}
 
Example 2
Source File: TaskStatusServiceImpl.java    From DataLink with Apache License 2.0 6 votes vote down vote up
@Override
public void addStatus(TaskStatus status) throws TaskConflictException {
    DLinkZkUtils zkUtils = DLinkZkUtils.get();
    String statusPath = DLinkZkPathDef.getTaskStatusNode(status.getId());

    byte[] bytes = JSON.toJSONBytes(status);
    try {
        zkUtils.zkClient().createPersistent(DLinkZkPathDef.getTaskNode(status.getId()), true);
        zkUtils.zkClient().create(statusPath, bytes, CreateMode.EPHEMERAL);
    } catch (ZkNodeExistsException e) {
        byte[] data = zkUtils.zkClient().readData(statusPath, true);
        if (data != null) {
            TaskStatus otherTaskStatus = JSON.parseObject(data, TaskStatus.class);
            throw new TaskConflictException(status.getId(), status.getWorkerId(), otherTaskStatus.getWorkerId(),
                    status.getExecutionId(), otherTaskStatus.getExecutionId());
        } else {
            addStatus(status);
        }
    }
}
 
Example 3
Source File: JsonPerfTest.java    From hermes with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	StringBuilder sb = new StringBuilder();
	for (int i = 0; i < 1000; i++) {
		sb.append("x");
	}
	String str = sb.toString();

	JSON.toJSONString(str);

	long start = System.currentTimeMillis();
	for (int i = 0; i < 10000; i++) {
		// JSON.toJSONString(str);
		 JSON.toJSONBytes(str);
		str.getBytes(Charsets.UTF_8);
	}
	System.out.println(System.currentTimeMillis() - start);
}
 
Example 4
Source File: SenderRequest.java    From zabbix-sender with Apache License 2.0 6 votes vote down vote up
public byte[] toBytes() {
	// https://www.zabbix.org/wiki/Docs/protocols/zabbix_sender/2.0
	// https://www.zabbix.org/wiki/Docs/protocols/zabbix_sender/1.8/java_example

	byte[] jsonBytes = JSON.toJSONBytes(this);

	byte[] result = new byte[header.length + 4 + 4 + jsonBytes.length];

	System.arraycopy(header, 0, result, 0, header.length);

	result[header.length] = (byte) (jsonBytes.length & 0xFF);
	result[header.length + 1] = (byte) ((jsonBytes.length >> 8) & 0x00FF);
	result[header.length + 2] = (byte) ((jsonBytes.length >> 16) & 0x0000FF);
	result[header.length + 3] = (byte) ((jsonBytes.length >> 24) & 0x000000FF);

	System.arraycopy(jsonBytes, 0, result, header.length + 4 + 4, jsonBytes.length);
	return result;
}
 
Example 5
Source File: NameServiceCacheDoubleCopy.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
@Override
protected byte[] serialize() {
    try {
        byte[] json = JSON.toJSONBytes(entry, SerializerFeature.DisableCircularReferenceDetect);
        json = ZipUtil.compress(json);

        if (logger.isDebugEnabled()) {
            logger.debug("save nameservice cache, value: {}, file: {}", new String(json), file);
        }

        return json;
    } catch (Exception e) {
        logger.error("serialize cache exception", e);
        return new byte[0];
    }
}
 
Example 6
Source File: RdbEventRecordHandler.java    From DataLink with Apache License 2.0 6 votes vote down vote up
private static void submitToKafka(DBTableRowVO rowVO, String topic, KafkaWriterParameter kafkaWriterParameter, KafkaFactory.KafkaClientModel kafkaClientModel) {

        topic = KafkaUtils.getTopic(topic, rowVO.getDatabaseName(), rowVO.getTableName());
        byte[] data;
        if (kafkaWriterParameter.getSerializeMode() == SerializeMode.Hessian) {
            data = HessianUtil.serialize(rowVO);
        } else if (kafkaWriterParameter.getSerializeMode() == SerializeMode.Json) {
            data = JSON.toJSONBytes(rowVO);
        } else {
            throw new UnsupportedOperationException("Invalid SerializeMode " + kafkaWriterParameter.getSerializeMode());
        }

        //兼容老数据,为空时为id方式
        String haseKey = rowVO.getDatabaseName() + rowVO.getTableName() + rowVO.getId();
        if (kafkaWriterParameter.getPartitionMode() == PartitionMode.TABLE) {
            haseKey = rowVO.getDatabaseName() + rowVO.getTableName();
        }

        try {
            kafkaClientModel.getKafkaProducer().send(new ProducerRecord(topic, haseKey, data));
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RuntimeException(e);
        }
    }
 
Example 7
Source File: FastJsonRedisSerializer.java    From uavstack with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] serialize(T t) throws SerializationException {
    if (t == null) {
        return new byte[0];
    }
    try {
        return JSON.toJSONBytes(t, fastJsonConfig.getSerializeConfig(), fastJsonConfig.getSerializerFeatures());
    } catch (Exception ex) {
        throw new SerializationException("Could not serialize: " + ex.getMessage(), ex);
    }
}
 
Example 8
Source File: DemoCertprofile.java    From xipki with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean initExtraExtension(ExtensionType extn) throws CertprofileException {
  ASN1ObjectIdentifier extnId = extn.getType().toXiOid();
  if (id_demo_without_conf.equals(extnId)) {
    this.addExtraWithoutConf = true;
    return true;
  } else if (id_demo_with_conf.equals(extnId)) {
    Object customObj = extn.getCustom();
    if (customObj == null) {
      throw new CertprofileException("ExtensionType.custom is not specified");
    }

    if (!(customObj instanceof JSONObject)) {
      throw new CertprofileException("ExtensionType.custom is not configured correctly");
    }

    // we need to first serialize the configuration
    byte[] serializedConf = JSON.toJSONBytes(customObj);
    ExtnDemoWithConf conf = JSON.parseObject(serializedConf, ExtnDemoWithConf.class);

    List<String> list = conf.getTexts();
    DERUTF8String[] texts = new DERUTF8String[list.size()];
    for (int i = 0; i < list.size(); i++) {
      texts[i] = new DERUTF8String(list.get(i));
    }

    this.sequence = new DERSequence(texts);

    this.addExtraWithConf = true;
    return true;
  } else {
    return false;
  }
}
 
Example 9
Source File: FastJsonJsonSerializer.java    From phone with Apache License 2.0 5 votes vote down vote up
public byte[] serialize(Object t) throws SerializationException {

		if (t == null) {
			return EMPTY_ARRAY;
		}
		try {
			return JSON.toJSONBytes(t);
		} catch (Exception ex) {
			throw new SerializationException("Could not write JSON: " + ex.getMessage(), ex);
		}
	}
 
Example 10
Source File: HRecordHandler.java    From DataLink with Apache License 2.0 5 votes vote down vote up
void submitToKafka(Map<String, Object> map, String topic, KafkaWriterParameter kafkaWriterParameter, KafkaFactory.KafkaClientModel kafkaClientModel) {
    String namespace = map.get("namespace").toString();
    String tableName = map.get("tableName").toString();

    topic = KafkaUtils.getTopic(namespace, tableName, topic);

    //兼容老数据,为空时为id方式
    String haseKey = namespace + tableName + map.get("rowkey");
    if (kafkaWriterParameter.getPartitionMode() == PartitionMode.TABLE) {
        haseKey = namespace + tableName;
    }

    byte[] data;
    if (kafkaWriterParameter.getSerializeMode() == SerializeMode.Hessian) {
        data = HessianUtil.serialize(map);
    } else if (kafkaWriterParameter.getSerializeMode() == SerializeMode.Json) {
        data = JSON.toJSONBytes(map);
    } else {
        throw new UnsupportedOperationException("Invalid SerializeMode " + kafkaWriterParameter.getSerializeMode());
    }

    try {
        kafkaClientModel.getKafkaProducer().send(new ProducerRecord(topic, haseKey, data));
    } catch (Exception e) {
        logger.error(e.getMessage());
        throw new RuntimeException(e);
    }
}
 
Example 11
Source File: OcspMgmtClient.java    From xipki with Apache License 2.0 4 votes vote down vote up
private byte[] transmit(MgmtAction action, MgmtRequest req, boolean voidReturn)
    throws OcspMgmtException {
  initIfNotDone();

  byte[] reqBytes = req == null ? null : JSON.toJSONBytes(req);
  int size = reqBytes == null ? 0 : reqBytes.length;

  URL url = actionUrlMap.get(action);

  try {
    HttpURLConnection httpUrlConnection = IoUtil.openHttpConn(url);
    if (httpUrlConnection instanceof HttpsURLConnection) {
      if (sslSocketFactory != null) {
        ((HttpsURLConnection) httpUrlConnection).setSSLSocketFactory(sslSocketFactory);
      }
      if (hostnameVerifier != null) {
        ((HttpsURLConnection) httpUrlConnection).setHostnameVerifier(hostnameVerifier);
      }
    }

    httpUrlConnection.setDoOutput(true);
    httpUrlConnection.setUseCaches(false);

    httpUrlConnection.setRequestMethod("POST");
    httpUrlConnection.setRequestProperty("Content-Type", REQUEST_CT);
    httpUrlConnection.setRequestProperty("Content-Length", java.lang.Integer.toString(size));
    OutputStream outputstream = httpUrlConnection.getOutputStream();
    if (size != 0) {
      outputstream.write(reqBytes);
    }
    outputstream.flush();

    if (httpUrlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
      InputStream in = httpUrlConnection.getInputStream();

      boolean inClosed = false;
      try {
        String responseContentType = httpUrlConnection.getContentType();
        if (!RESPONSE_CT.equals(responseContentType)) {
          throw new OcspMgmtException(
              "bad response: mime type " + responseContentType + " not supported!");
        }

        if (voidReturn) {
          return null;
        } else {
          inClosed = true;
          return IoUtil.read(httpUrlConnection.getInputStream());
        }
      } finally {
        if (in != null & !inClosed) {
          in.close();
        }
      }
    } else {
      String errorMessage = httpUrlConnection.getHeaderField(HttpConstants.HEADER_XIPKI_ERROR);
      if (errorMessage == null) {
        StringBuilder sb = new StringBuilder(100);
        sb.append("server returns ").append(httpUrlConnection.getResponseCode());
        String respMsg = httpUrlConnection.getResponseMessage();
        if (StringUtil.isNotBlank(respMsg)) {
          sb.append(" ").append(respMsg);
        }
        throw new OcspMgmtException(sb.toString());
      } else {
        throw new OcspMgmtException(errorMessage);
      }
    }
  } catch (IOException ex) {
    throw new OcspMgmtException(
        "IOException while sending message to the server: " + ex.getMessage(), ex);
  }
}
 
Example 12
Source File: FastJsonSerializer.java    From buddha with MIT License 4 votes vote down vote up
public byte[] serialize(Object object) {
    byte[] bytes = JSON.toJSONBytes(object, SerializerFeature.SortField);
    return bytes;
}
 
Example 13
Source File: JsonUtils.java    From feeyo-hlsserver with Apache License 2.0 4 votes vote down vote up
public static byte[] marshalToByte(Object obj) {
    return JSON.toJSONBytes(obj); // 默认为UTF-8
}
 
Example 14
Source File: HealthCheckServlet.java    From xipki with Apache License 2.0 4 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
    throws ServletException, IOException {
  resp.setHeader("Access-Control-Allow-Origin", "*");

  try {
    String caName = null;
    CmpResponder responder = null;

    String path = (String) req.getAttribute(HttpConstants.ATTR_XIPKI_PATH);
    if (path.length() > 1) {
      // skip the first char which is always '/'
      String caAlias = path.substring(1);
      caName = responderManager.getCaNameForAlias(caAlias);
      if (caName == null) {
        caName = caAlias.toLowerCase();
      }
      responder = responderManager.getX509CaResponder(caName);
    }

    if (caName == null || responder == null || !responder.isOnService()) {
      String auditMessage;
      if (caName == null) {
        auditMessage = "no CA is specified";
      } else if (responder == null) {
        auditMessage = "unknown CA '" + caName + "'";
      } else {
        auditMessage = "CA '" + caName + "' is out of service";
      }
      LOG.warn(auditMessage);

      sendError(resp, HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    HealthCheckResult healthResult = responder.healthCheck();
    int status = healthResult.isHealthy()
        ? HttpServletResponse.SC_OK
        : HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    byte[] respBytes = JSON.toJSONBytes(healthResult);
    resp.setStatus(status);
    resp.setContentLength(respBytes.length);
    resp.setContentType(CT_RESPONSE);
    resp.getOutputStream().write(respBytes);
  } catch (Throwable th) {
    if (th instanceof EOFException) {
      LogUtil.warn(LOG, th, "connection reset by peer");
    } else {
      LOG.error("Throwable thrown, this should not happen!", th);
    }
    sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
  } finally {
    resp.flushBuffer();
  }
}
 
Example 15
Source File: JsonSerializer.java    From elephant with Apache License 2.0 4 votes vote down vote up
@Override
public <T> byte[] serializer(T obj) {
	JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
	return JSON.toJSONBytes(obj, SerializerFeature.WriteDateUseDateFormat);
}
 
Example 16
Source File: FastjsonServiceDefinitionSerializer.java    From xian with Apache License 2.0 4 votes vote down vote up
@Override
public byte[] serialize(T payloadBean) {
    return JSON.toJSONBytes(payloadBean);
}
 
Example 17
Source File: JsonUtils.java    From feeyo-hlsserver with Apache License 2.0 4 votes vote down vote up
public static byte[] marshalToByte(Object obj, SerializerFeature... features) {
    return JSON.toJSONBytes(obj, features); // 默认为UTF-8
}
 
Example 18
Source File: DataSource.java    From metrics with Apache License 2.0 4 votes vote down vote up
public byte[] toJsonBytes() {
	return JSON.toJSONBytes(this, SerializerFeature.QuoteFieldNames);
}
 
Example 19
Source File: JsonPayloadCodec.java    From hermes with Apache License 2.0 4 votes vote down vote up
@Override
public byte[] doEncode(String topic, Object input) {
	return JSON.toJSONBytes(input);
}
 
Example 20
Source File: FastJsonServiceInstanceSerializer.java    From xian with Apache License 2.0 4 votes vote down vote up
@Override
public byte[] serialize(ServiceInstance<T> instance) {
    return JSON.toJSONBytes(instance);
}