下面列出了怎么用org.springframework.boot.configurationprocessor.json.JSONObject的API类实例代码及写法,或者点击链接到github查看源代码。
public void write(ResourcesDescriptor metadata, OutputStream outputStream)
throws IOException {
try {
ResourcesJsonConverter converter = new ResourcesJsonConverter();
JSONObject jsonObject = converter.toJsonArray(metadata);
outputStream.write(jsonObject.toString(2).getBytes(StandardCharsets.UTF_8));
}
catch (Exception ex) {
if (ex instanceof IOException) {
throw (IOException) ex;
}
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
}
throw new IllegalStateException(ex);
}
}
private static ClassDescriptor toClassDescriptor(JSONObject object) throws Exception {
ClassDescriptor cd = new ClassDescriptor();
cd.setName(object.getString("name"));
for (Flag f: Flag.values()) {
if (object.optBoolean(f.name())) {
cd.setFlag(f);
}
}
JSONArray fields = object.optJSONArray("fields");
if (fields != null) {
for (int i=0;i<fields.length();i++) {
cd.addFieldDescriptor(toFieldDescriptor(fields.getJSONObject(i)));
}
}
JSONArray methods = object.optJSONArray("methods");
if (methods != null) {
for (int i=0;i<methods.length();i++) {
cd.addMethodDescriptor(toMethodDescriptor(methods.getJSONObject(i)));
}
}
return cd;
}
public void write(InitializationDescriptor metadata, OutputStream outputStream)
throws IOException {
try {
InitializationJsonConverter converter = new InitializationJsonConverter();
JSONObject jsonObject = converter.toJsonArray(metadata);
outputStream.write(jsonObject.toString(2).getBytes(StandardCharsets.UTF_8));
}
catch (Exception ex) {
if (ex instanceof IOException) {
throw (IOException) ex;
}
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
}
throw new IllegalStateException(ex);
}
}
public JSONObject toJsonArray(ResourcesDescriptor metadata) throws Exception {
JSONObject object = new JSONObject();
JSONArray jsonArray = new JSONArray();
for (String p : metadata.getPatterns()) {
jsonArray.put(toJsonObject(p));
}
object.put("resources", jsonArray);
return object;
}
private static ResourcesDescriptor toResourcesDescriptor(JSONObject object) throws Exception {
ResourcesDescriptor rd = new ResourcesDescriptor();
JSONArray array = object.getJSONArray("resources");
for (int i=0;i<array.length();i++) {
rd.add(array.getJSONObject(i).getString("pattern"));
}
return rd;
}
private static ReflectionDescriptor toReflectionDescriptor(JSONArray array) throws Exception {
ReflectionDescriptor rd = new ReflectionDescriptor();
for (int i=0;i<array.length();i++) {
ClassDescriptor cd = toClassDescriptor((JSONObject)array.get(i));
if (rd.hasClassDescriptor(cd.getName())) {
System.out.println("DUPLICATE: "+cd.getName());
}
rd.add(cd);
}
return rd;
}
private static MethodDescriptor toMethodDescriptor(JSONObject object) throws Exception {
String name = object.getString("name");
JSONArray parameterTypes = object.optJSONArray("parameterTypes");
List<String> listOfParameterTypes = null;
if (parameterTypes != null) {
listOfParameterTypes = new ArrayList<>();
for (int i=0;i<parameterTypes.length();i++) {
listOfParameterTypes.add(parameterTypes.getString(i));
}
}
return new MethodDescriptor(name, listOfParameterTypes);
}
@Test
public void json_parse() throws JSONException {
long offset = 789;
long timestampToUse = 987;
String input = "123,456," + offset;
String output = myEnrichAndReformatFn._makeJson(input, timestampToUse);
log.info("{} -> {}", input, output);
assertThat("output", output, not(nullValue()));
JSONObject jsonObject = new JSONObject(output);
String latitudeExtracted = jsonObject.getString("latitude");
assertThat("latitude", latitudeExtracted, not(nullValue()));
assertThat("latitude", latitudeExtracted, is(equalTo("123")));
String longitudeExtracted = jsonObject.getString("longitude");
assertThat("longitude", longitudeExtracted, not(nullValue()));
assertThat("longitude", longitudeExtracted, is(equalTo("456")));
String timestampExtracted = jsonObject.getString("timestamp");
assertThat("timestamp", timestampExtracted, not(nullValue()));
assertThat("timestamp", timestampExtracted, is(equalTo(""+timestampToUse)));
assertThat("timestampToUse", timestampToUse, not(equalTo(offset)));
}
/**
* Set the status indicator
*
* @param token JWT
* @return HTTP Response
*/
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> post(JwtAuthenticationToken token, @RequestBody String content) throws JSONException {
UserContext userContext = (UserContext) token.getPrincipal(); // Check if user is logged
JSONObject jsonObject = new JSONObject(content);
String value = jsonObject.get("status").toString();
boolean result = this.customIndicatorService.update(value);
if (result) {
return new ResponseEntity<>(HttpStatus.CREATED);
}
return new ResponseEntity<>("This status does not exist.", HttpStatus.BAD_REQUEST);
}
public JSONObject toJsonObject(String pattern) throws Exception {
JSONObject object = new JSONObject();
object.put("pattern", pattern);
return object;
// JSONObject jsonObject = new JSONObject();
// jsonObject.put("name", cd.getName());
// Set<Flag> flags = cd.getFlags();
// if (flags != null) {
// for (Flag flag: Flag.values()) {
// if (flags.contains(flag)) {
// putTrueFlag(jsonObject,flag.name());
// }
// }
// }
// List<FieldDescriptor> fds = cd.getFields();
// if (fds != null) {
// JSONArray fieldJsonArray = new JSONArray();
// for (FieldDescriptor fd: fds) {
// JSONObject fieldjo = new JSONObject();
// fieldjo.put("name", fd.getName());
// if (fd.isAllowWrite()) {
// fieldjo.put("allowWrite", "true");
// }
// fieldJsonArray.put(fieldjo);
// }
// jsonObject.put("fields", fieldJsonArray);
// }
// List<MethodDescriptor> mds = cd.getMethods();
// if (mds != null) {
// JSONArray methodsJsonArray = new JSONArray();
// for (MethodDescriptor md: mds) {
// JSONObject methodJsonObject = new JSONObject();
// methodJsonObject.put("name", md.getName());
// List<String> parameterTypes = md.getParameterTypes();
// JSONArray parameterArray = new JSONArray();
// if (parameterTypes != null) {
// for (String pt: parameterTypes) {
// parameterArray.put(pt);
// }
// }
// methodJsonObject.put("parameterTypes",parameterArray);
// methodsJsonArray.put(methodJsonObject);
// }
// jsonObject.put("methods", methodsJsonArray);
// }
// return jsonObject;
}
public static ResourcesDescriptor read(InputStream inputStream) throws Exception {
ResourcesDescriptor metadata = toResourcesDescriptor(new JSONObject(toString(inputStream)));
return metadata;
}
public JSONObject toJsonObject(ClassDescriptor cd) throws Exception {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", cd.getName());
Set<Flag> flags = cd.getFlags();
if (flags != null) {
for (Flag flag: Flag.values()) {
if (flags.contains(flag)) {
putTrueFlag(jsonObject,flag.name());
}
}
}
List<FieldDescriptor> fds = cd.getFields();
if (fds != null) {
JSONArray fieldJsonArray = new JSONArray();
for (FieldDescriptor fd: fds) {
JSONObject fieldjo = new JSONObject();
fieldjo.put("name", fd.getName());
if (fd.isAllowWrite()) {
fieldjo.put("allowWrite", "true");
}
fieldJsonArray.put(fieldjo);
}
jsonObject.put("fields", fieldJsonArray);
}
List<MethodDescriptor> mds = cd.getMethods();
if (mds != null) {
JSONArray methodsJsonArray = new JSONArray();
for (MethodDescriptor md: mds) {
JSONObject methodJsonObject = new JSONObject();
methodJsonObject.put("name", md.getName());
List<String> parameterTypes = md.getParameterTypes();
JSONArray parameterArray = new JSONArray();
if (parameterTypes != null) {
for (String pt: parameterTypes) {
parameterArray.put(pt);
}
}
methodJsonObject.put("parameterTypes",parameterArray);
methodsJsonArray.put(methodJsonObject);
}
jsonObject.put("methods", methodsJsonArray);
}
return jsonObject;
}
private void putTrueFlag(JSONObject jsonObject, String name) throws Exception {
jsonObject.put(name, true);
}
private static FieldDescriptor toFieldDescriptor(JSONObject object) throws Exception {
String name = object.getString("name");
boolean allowWrite = object.optBoolean("allowWrite");
return new FieldDescriptor(name,allowWrite);
}
public static InitializationDescriptor read(InputStream inputStream) throws Exception {
InitializationDescriptor metadata = toDelayInitDescriptor(new JSONObject(toString(inputStream)));
return metadata;
}
public JSONObject toPackageJsonObject(String pattern) throws Exception {
JSONObject object = new JSONObject();
object.put("package", pattern);
return object;
}
public JSONObject toClassJsonObject(String pattern) throws Exception {
JSONObject object = new JSONObject();
object.put("class", pattern);
return object;
}
@Override
public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
return new ClientHttpResponse() {
@Override
public HttpStatus getStatusCode() throws IOException {
return HttpStatus.OK;
}
@Override
public int getRawStatusCode() throws IOException {
return 200;
}
@Override
public String getStatusText() throws IOException {
return "OK";
}
@Override
public void close() {
}
@Override
public InputStream getBody() {
SophiaHttpStatus resultEnum = SophiaHttpStatus.SERVER_TIMEOUT;
String data = "";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("code", resultEnum.getCode());
jsonObject.put("msg", resultEnum.getMessage());
jsonObject.put("data", data);
} catch (JSONException e) {
e.printStackTrace();
}
data = jsonObject.toString();
logger.error(data);
return new ByteArrayInputStream(data.getBytes());
}
@Override
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return headers;
}
};
}
@Override
public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
return new ClientHttpResponse() {
@Override
public HttpStatus getStatusCode() throws IOException {
return HttpStatus.OK;
}
@Override
public int getRawStatusCode() throws IOException {
return 200;
}
@Override
public String getStatusText() throws IOException {
return "OK";
}
@Override
public void close() {
}
@Override
public InputStream getBody() {
SophiaHttpStatus resultEnum = SophiaHttpStatus.SERVER_TIMEOUT;
String data = "";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("code", resultEnum.getCode());
jsonObject.put("msg", resultEnum.getMessage());
jsonObject.put("data", data);
} catch (JSONException e) {
e.printStackTrace();
}
data = jsonObject.toString();
logger.error(data);
return new ByteArrayInputStream(data.getBytes());
}
@Override
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return headers;
}
};
}
@Override
public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
return new ClientHttpResponse() {
@Override
public HttpStatus getStatusCode() throws IOException {
return HttpStatus.OK;
}
@Override
public int getRawStatusCode() throws IOException {
return 200;
}
@Override
public String getStatusText() throws IOException {
return "OK";
}
@Override
public void close() {
}
@Override
public InputStream getBody() {
SophiaHttpStatus resultEnum = SophiaHttpStatus.SERVER_TIMEOUT;
String data = "";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("code", resultEnum.getCode());
jsonObject.put("msg", resultEnum.getMessage());
jsonObject.put("data", data);
} catch (JSONException e) {
e.printStackTrace();
}
data = jsonObject.toString();
logger.error(data);
return new ByteArrayInputStream(data.getBytes());
}
@Override
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return headers;
}
};
}
public static long countDocuments(String indexName, ElasticsearchProperties properties) throws IOException, JSONException {
HttpGet httpRequest = new HttpGet(("http://" + properties.getHost() + ":" + properties.getPort() + "/" + indexName + "/_count"));
HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse httpResponse = httpClient.execute(httpRequest);
return new JSONObject(IOUtils.toString(httpResponse.getEntity().getContent(), Charset.defaultCharset())).getLong("count");
}