#90 Gson implementation. (#106)

Co-authored-by: Artur Kołecki <koleckiartur@icloud.com>
Reviewed-on: R11/release11-tools-web#106
This commit is contained in:
2023-03-08 12:05:19 +01:00
parent 5ef85cb484
commit 715facf35b
9 changed files with 293 additions and 154 deletions

View File

@@ -74,16 +74,6 @@
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- XSLT -->
<dependency>

View File

@@ -1,5 +1,7 @@
package com.r11.tools;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.r11.tools.controller.JsonController;
import com.r11.tools.controller.ProcessorInfoController;
import com.r11.tools.controller.XPathController;
@@ -25,11 +27,16 @@ public class SparkApplication {
Logger logger = LogManager.getLogger(SparkApplication.class);
Gson gson = new GsonBuilder()
.disableHtmlEscaping()
.setPrettyPrinting()
.create();
RestControllerRegistry registry = new RestControllerRegistry();
registry.registerController(new ProcessorInfoController(logger));
registry.registerController(new XsdController(logger));
registry.registerController(new XPathController(logger));
registry.registerController(new XsltController(logger));
registry.registerController(new XsdController(gson, logger));
registry.registerController(new XPathController(gson, logger));
registry.registerController(new XsltController(gson, logger));
registry.registerController(new JsonController());
registry.register();

View File

@@ -24,35 +24,53 @@ public class JsonController implements RestController {
@ScopedControllerManifest(method = HandlerType.POST, path = "/formatting")
public void formatting(Request request, Response response) {
long startProcess = System.currentTimeMillis();
JsonObject responseJson = new JsonObject();
try {
JsonObject jsonObject = this.gson.fromJson(request.body(), JsonObject.class);
JsonObject requestJson = this.gson.fromJson(request.body(), JsonObject.class);
response.status(200);
response.body(this.prettyGson.toJson(jsonObject));
responseJson.addProperty("data", this.prettyGson.toJson(requestJson));
responseJson.addProperty("time", System.currentTimeMillis() - startProcess);
response.body(this.prettyGson.toJson(responseJson));
} catch (Exception e) {
response.status(500);
Throwable cause = e.getCause();
if (cause == null) {
response.body(e.getMessage());
} else {
response.body(cause.getMessage());
}
response.status(500);
responseJson.addProperty("data", cause == null ? e.getMessage() : cause.getMessage());
responseJson.addProperty("time", System.currentTimeMillis() - startProcess);
response.body(this.prettyGson.toJson(responseJson));
}
}
@ScopedControllerManifest(method = HandlerType.POST, path = "/minimize")
public void minimize(Request request, Response response) {
long startProcess = System.currentTimeMillis();
JsonObject responseJson = new JsonObject();
try {
JsonObject jsonObject = this.prettyGson.fromJson(request.body(), JsonObject.class);
JsonObject requestJson = this.prettyGson.fromJson(request.body(), JsonObject.class);
response.status(200);
response.body(this.gson.toJson(jsonObject));
responseJson.addProperty("data", this.gson.toJson(requestJson));
responseJson.addProperty("time", System.currentTimeMillis() - startProcess);
response.body(this.gson.toJson(responseJson));
} catch (Exception e) {
response.status(500);
Throwable cause = e.getCause();
if (cause == null) {
response.body(e.getMessage());
} else {
response.body(cause.getMessage());
}
response.status(500);
responseJson.addProperty("data", cause == null ? e.getMessage() : cause.getMessage());
responseJson.addProperty("time", System.currentTimeMillis() - startProcess);
response.body(this.prettyGson.toJson(responseJson));
}
}
}

View File

@@ -1,15 +1,13 @@
package com.r11.tools.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.r11.tools.controller.internal.GlobalControllerManifest;
import com.r11.tools.controller.internal.HandlerType;
import com.r11.tools.controller.internal.RestController;
import com.r11.tools.controller.internal.ScopedControllerManifest;
import com.r11.tools.xml.Saxon;
import com.r11.tools.xml.Xalan;
import java.util.HashMap;
import java.util.Map;
import org.apache.logging.log4j.Logger;
import spark.Request;
import spark.Response;
@@ -17,36 +15,37 @@ import spark.Response;
@GlobalControllerManifest
public class XPathController implements RestController {
private final Gson gson;
private final Logger logger;
public XPathController(Logger logger) {
public XPathController(Gson gson, Logger logger) {
this.gson = gson;
this.logger = logger;
}
@ScopedControllerManifest(method = HandlerType.POST, path = "/xpath")
public void transform(Request request, Response response) throws JsonProcessingException {
public void transform(Request request, Response response) {
String body = request.body();
ObjectMapper mapper = new ObjectMapper();
Map<String, String> requestMap = new HashMap<>();
Map<String, String> responseMap = new HashMap<>();
JsonObject requestJson;
try {
requestMap = mapper.readValue(body, Map.class);
} catch (JsonProcessingException ex) {
this.logger.error("Request JSON error. " + ex);
responseMap.put("result", ex.getMessage());
responseMap.put("processor", "N/A");
responseMap.put("status", "ERR");
responseMap.put("time", "N/A");
requestJson = this.gson.fromJson(body, JsonObject.class);
} catch (Exception e) {
JsonObject responseJson = new JsonObject();
responseJson.addProperty("result", e.getMessage());
responseJson.addProperty("processor", "N/A");
responseJson.addProperty("status", "ERR");
responseJson.addProperty("time", "N/A");
response.status(400);
response.body(mapper.writeValueAsString(responseMap));
response.body(this.gson.toJson(responseJson));
return;
}
String data = requestMap.get("data");
String query = requestMap.get("process");
String processor = requestMap.get("processor");
String version = requestMap.get("version");
String data = requestJson.get("data").getAsString();
String query = requestJson.get("process").getAsString();
String processor = requestJson.get("processor").getAsString();
String version = requestJson.get("version").getAsString();
String tmp = "";
long timeStart;
@@ -57,45 +56,64 @@ public class XPathController implements RestController {
return;
}
JsonObject responseJson = new JsonObject();
switch (processor) {
case "saxon":
response.header("processor", "Saxon " + Saxon.getVersion() + " " + version + " over s9api");
timeStart = System.currentTimeMillis();
try {
tmp = Saxon.processXPath(data, query, version).trim();
responseMap.put("result", tmp);
responseMap.put("status", "OK");
response.status(200);
responseJson.addProperty("result", tmp);
responseJson.addProperty("status", "OK");
} catch (Exception ex) {
this.logger.error("Error on processing XPath using Saxon. " + ex);
responseMap.put("result", ex.getMessage());
responseMap.put("status", "ERR");
response.status(400);
responseJson.addProperty("result", ex.getMessage());
responseJson.addProperty("status", "ERR");
}
duration = System.currentTimeMillis() - timeStart;
this.logger.info("Request" + body + " processed in " + duration + " ms.");
responseMap.put("processor", "Saxon " + Saxon.getVersion() + " " + version + " over s9api");
responseMap.put("time", "" + duration);
response.body(mapper.writeValueAsString(responseMap));
responseJson.addProperty("processor", "Saxon " + Saxon.getVersion() + " " + version + " over s9api");
responseJson.addProperty("time", duration);
response.body(this.gson.toJson(responseJson));
return;
case "xalan":
response.header("processor", Xalan.getVersion());
timeStart = System.currentTimeMillis();
try {
tmp = Xalan.processXPath(data, query).trim();
responseMap.put("result", tmp);
responseMap.put("status", "OK");
response.status(200);
responseJson.addProperty("result", tmp);
responseJson.addProperty("status", "OK");
} catch (Exception ex) {
this.logger.error("Error on processing XPath using Xalan. " + ex);
responseMap.put("result", ex.getMessage());
responseMap.put("status", "ERR");
response.status(400);
responseJson.addProperty("result", ex.getMessage());
responseJson.addProperty("status", "ERR");
}
duration = System.currentTimeMillis() - timeStart;
this.logger.info("Request: " + body + " processed in " + duration + " ms.");
responseMap.put("processor", Xalan.getVersion());
responseMap.put("time", Long.toString(duration));
response.body(mapper.writeValueAsString(responseMap));
responseJson.addProperty("processor", Xalan.getVersion());
responseJson.addProperty("time", duration);
response.body(this.gson.toJson(responseJson));
return;
default:
response.body("saxon, xalan");

View File

@@ -1,14 +1,12 @@
package com.r11.tools.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.r11.tools.controller.internal.GlobalControllerManifest;
import com.r11.tools.controller.internal.HandlerType;
import com.r11.tools.controller.internal.RestController;
import com.r11.tools.controller.internal.ScopedControllerManifest;
import com.r11.tools.xml.Xalan;
import java.util.HashMap;
import java.util.Map;
import org.apache.logging.log4j.Logger;
import spark.Request;
import spark.Response;
@@ -16,55 +14,65 @@ import spark.Response;
@GlobalControllerManifest
public class XsdController implements RestController {
private final Gson gson;
private final Logger logger;
public XsdController(Logger logger) {
public XsdController(Gson gson, Logger logger) {
this.gson = gson;
this.logger = logger;
}
@ScopedControllerManifest(method = HandlerType.POST, path = "/xsd")
public Response transform(Request req, Response resp) throws JsonProcessingException {
String body = req.body();
ObjectMapper mapper = new ObjectMapper();
Map<String, String> requestMap = new HashMap<>();
Map<String, String> responseMap = new HashMap<>();
public Response transform(Request request, Response response) {
String body = request.body();
JsonObject requestJson;
try {
requestMap = mapper.readValue(body, Map.class);
} catch (JsonProcessingException ex) {
this.logger.error("Request JSON error. " + ex);
responseMap.put("result", ex.getMessage());
responseMap.put("processor", "N/A");
responseMap.put("status", "ERR");
responseMap.put("time", "N/A");
resp.status(400);
resp.body(mapper.writeValueAsString(responseMap));
return resp;
requestJson = this.gson.fromJson(body, JsonObject.class);
} catch (Exception e) {
JsonObject responseJson = new JsonObject();
responseJson.addProperty("result", e.getMessage());
responseJson.addProperty("processor", "N/A");
responseJson.addProperty("status", "ERR");
responseJson.addProperty("time", "N/A");
response.status(400);
response.body(this.gson.toJson(responseJson));
return response;
}
String data = requestMap.get("data");
String xsd = requestMap.get("process");
String data = requestJson.get("data").getAsString();
String xsd = requestJson.get("process").getAsString();
response.header("processor", Xalan.getVersion());
resp.header("processor", Xalan.getVersion());
long timeStart = System.currentTimeMillis();
String tmp;
JsonObject responseJson = new JsonObject();
try {
tmp = Xalan.validate(data, xsd).trim();
responseMap.put("result", tmp);
responseMap.put("status", "OK");
response.status(200);
responseJson.addProperty("result", tmp);
responseJson.addProperty("status", "OK");
} catch (Exception ex) {
this.logger.error("Error on validation against XSD using Xalan. " + ex);
responseMap.put("result", ex.getMessage());
responseMap.put("status", "ERR");
resp.status(400);
response.status(400);
responseJson.addProperty("result", ex.getMessage());
responseJson.addProperty("status", "ERR");
}
long duration = System.currentTimeMillis() - timeStart;
this.logger.info("Request: " + body + " processed in " + duration + " ms.");
responseMap.put("processor", Xalan.getVersion());
responseMap.put("time", "" + duration);
resp.body(mapper.writeValueAsString(responseMap));
return resp;
responseJson.addProperty("processor", Xalan.getVersion());
responseJson.addProperty("time", duration);
response.body(this.gson.toJson(responseJson));
return response;
}
}

View File

@@ -1,17 +1,13 @@
package com.r11.tools.controller;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.r11.tools.controller.internal.GlobalControllerManifest;
import com.r11.tools.controller.internal.HandlerType;
import com.r11.tools.controller.internal.RestController;
import com.r11.tools.controller.internal.ScopedControllerManifest;
import com.r11.tools.xml.Saxon;
import com.r11.tools.xml.Xalan;
import java.util.HashMap;
import java.util.Map;
import org.apache.logging.log4j.Logger;
import spark.Request;
import spark.Response;
@@ -19,35 +15,37 @@ import spark.Response;
@GlobalControllerManifest
public class XsltController implements RestController {
private final Gson gson;
private final Logger logger;
public XsltController(Logger logger) {
public XsltController(Gson gson, Logger logger) {
this.gson = gson;
this.logger = logger;
}
@ScopedControllerManifest(method = HandlerType.POST, path = "/xslt")
public void transform(Request request, Response response) throws JsonProcessingException {
public void transform(Request request, Response response) {
String body = request.body();
ObjectMapper mapper = new ObjectMapper();
Map<String, String> requestMap = new HashMap<>();
Map<String, String> responseMap = new HashMap<>();
JsonObject requestJson;
try {
requestMap = mapper.readValue(body, Map.class);
} catch (JsonMappingException | JsonParseException ex) {
this.logger.error("Request JSON error. " + ex);
responseMap.put("result", ex.getMessage());
responseMap.put("processor", "N/A");
responseMap.put("status", "ERR");
responseMap.put("time", "N/A");
requestJson = this.gson.fromJson(body, JsonObject.class);
} catch (Exception e) {
JsonObject responseJson = new JsonObject();
responseJson.addProperty("result", e.getMessage());
responseJson.addProperty("processor", "N/A");
responseJson.addProperty("status", "ERR");
responseJson.addProperty("time", "N/A");
response.status(400);
response.body(mapper.writeValueAsString(responseMap));
response.body(this.gson.toJson(responseJson));
return;
}
String data = requestMap.get("data");
String query = requestMap.get("process");
String processor = requestMap.get("processor");
String version = requestMap.get("version");
String data = requestJson.get("data").getAsString();
String query = requestJson.get("process").getAsString();
String processor = requestJson.get("processor").getAsString();
String version = requestJson.get("version").getAsString();
if (processor == null) {
response.body("saxon, xalan");
@@ -57,45 +55,61 @@ public class XsltController implements RestController {
String tmp;
long timeStart;
long duration;
JsonObject responseJson = new JsonObject();
switch (processor) {
case "saxon":
timeStart = System.currentTimeMillis();
try {
tmp = Saxon.processXSLT(data, query);
responseMap.put("result", tmp);
responseMap.put("status", "OK");
response.status(200);
responseJson.addProperty("result", tmp);
responseJson.addProperty("status", "OK");
} catch (Exception ex) {
this.logger.error("Error on processing XSLT using Saxon. " + ex);
responseMap.put("result", ex.getMessage());
responseMap.put("status", "ERR");
response.status(400);
responseJson.addProperty("result", ex.getMessage());
responseJson.addProperty("status", "ERR");
}
duration = System.currentTimeMillis() - timeStart;
this.logger.info("Request: " + body + " processed in " + duration + " ms.");
responseMap.put("processor", "Saxon " + Saxon.getVersion() + " " + version);
responseMap.put("time", Long.toString(duration));
response.body(mapper.writeValueAsString(responseMap));
responseJson.addProperty("processor", "Saxon " + Saxon.getVersion() + " " + version);
responseJson.addProperty("time", duration);
response.body(this.gson.toJson(responseJson));
return;
case "xalan":
timeStart = System.currentTimeMillis();
try {
tmp = Xalan.processXSLT(data, query);
responseMap.put("result", tmp);
responseMap.put("status", "OK");
response.status(200);
responseJson.addProperty("result", tmp);
responseJson.addProperty("status", "OK");
} catch (Exception ex) {
this.logger.error("Error on processing XSLT using Xalan. " + ex);
responseMap.put("result", ex.getMessage());
responseMap.put("status", "ERR");
response.status(400);
responseJson.addProperty("result", ex.getMessage());
responseJson.addProperty("status", "ERR");
}
duration = System.currentTimeMillis() - timeStart;
this.logger.info("Request: " + body + " processed in " + duration + " ms.");
responseMap.put("processor", Xalan.getVersion());
responseMap.put("time", Long.toString(duration));
response.body(mapper.writeValueAsString(responseMap));
responseJson.addProperty("processor", Xalan.getVersion());
responseJson.addProperty("time", duration);
response.body(this.gson.toJson(responseJson));
return;
default:

View File

@@ -1,4 +1,69 @@
.json-block {
height: 600px;
width: 100%;
}
width: 97%;
}
.json-border {
border: 2px solid rgba(93, 99, 96, 0.705);
border-radius: 5px;
}
.json-border:focus {
box-shadow: 0 0 5px rgb(81, 203, 238);
border: 2px solid rgba(93, 99, 96, 0.705);
border-radius: 5px;
}
/*! Theme: Default Description: Original highlight.js style Author: (c) Ivan Sagalaev <maniac@softwaremaniacs.org> Maintainer: @highlightjs/core-team Website: https://highlightjs.org/ License: see project LICENSE Touched: 2021 */
pre code.hljs{
display:block;
overflow-x:auto;
padding:1em
}
code.hljs{
padding:3px 5px
}
.hljs{
background:#FFFFFF;
color:#444
}
.hljs-comment{
color:#697070
}
.hljs-punctuation,.hljs-tag{
color:#444a
}
.hljs-tag .hljs-attr,.hljs-tag .hljs-name{
color:#444
}
.hljs-attribute,.hljs-doctag,.hljs-keyword,.hljs-meta .hljs-keyword,.hljs-name,.hljs-selector-tag{
font-weight:700
}
.hljs-deletion,.hljs-number,.hljs-quote,.hljs-selector-class,.hljs-selector-id,.hljs-string,.hljs-template-tag,.hljs-type{
color:#800
}
.hljs-section,.hljs-title{
color:#800;
font-weight:700
}
.hljs-link,.hljs-operator,.hljs-regexp,.hljs-selector-attr,.hljs-selector-pseudo,.hljs-symbol,.hljs-template-variable,.hljs-variable{
color:#ab5656
}
.hljs-literal{
color:#695
}
.hljs-addition,.hljs-built_in,.hljs-bullet,.hljs-code{
color:#397300
}
.hljs-meta{
color:#1f7199
}
.hljs-meta .hljs-string{
color:#38a
}
.hljs-emphasis{
font-style:italic
}
.hljs-strong{
font-weight:700
}

View File

@@ -1,7 +1,6 @@
function formatAndValidateJson(errorElement) {
const input = document.querySelector('#jsonBlock');
const processInfo = document.getElementById(errorElement);
const start = new Date();
const address = window.location.protocol + "//" + window.location.hostname + ":" + 8081 + "/json/formatting"
@@ -10,22 +9,22 @@ function formatAndValidateJson(errorElement) {
body: input.textContent
})
.then(async (response) => {
const promise = response.json();
if (!response.ok) {
throw Error(await response.text());
throw Error(await promise);
}
return response.text();
return promise;
})
.then((data) => {
input.innerText = data;
input.innerText = data.data;
processInfo.innerText = "";
hljs.highlightElement(input);
const end = new Date();
processInfo.innerHTML = "<b style='color: black'>Validation and formatting time:</b> <span style='color: green'>" + (end.getMilliseconds() - start.getMilliseconds()) + "ms</span>";
processInfo.innerHTML = "<b style='color: green'>Computed in </b> <span style='color: green'>" + data.time + "ms</span>";
})
.catch((error) => {
processInfo.innerHTML = "<b style='color: red'>" + error + "</b>";
processInfo.innerHTML = "<b style='color: red'>" + error.data + "</b>";
console.error('Error:', error);
});
}
@@ -34,7 +33,6 @@ function minimizeJson(errorElement) {
const input = document.querySelector('#jsonBlock');
const processInfo = document.getElementById(errorElement);
const start = new Date();
const address = window.location.protocol + "//" + window.location.hostname + ":" + 8081 + "/json/minimize"
fetch(address, {
@@ -42,22 +40,33 @@ function minimizeJson(errorElement) {
body: input.textContent
})
.then(async (response) => {
const promise = response.json();
if (!response.ok) {
throw Error(await response.text());
throw Error(await promise);
}
return response.text();
return promise;
})
.then((data) => {
input.innerText = data;
input.innerText = data.data;
processInfo.innerText = "";
hljs.highlightElement(input);
const end = new Date();
processInfo.innerHTML = "<b style='color: black'>Validation and formatting time:</b> <span style='color: green'>" + (end.getMilliseconds() - start.getMilliseconds()) + "ms</span>";
processInfo.innerHTML = "<b style='color: green'>Computed in </b> <span style='color: green'>" + data.time + "ms</span>";
})
.catch((error) => {
processInfo.innerHTML = "<b style='color: red'>" + error + "</b>";
processInfo.innerHTML = "<b style='color: red'>" + error.data + "</b>";
console.error('Error:', error);
});
}
function clearJsonData() {
const input = document.querySelector('#jsonBlock');
input.textContent = "";
}
function insertDefaultJson() {
const input = document.querySelector('#jsonBlock');
input.textContent = "{\"enter\": \"your\", \"json\": \"here\"}";
hljs.highlightElement(input);
}

View File

@@ -7,7 +7,6 @@
<link rel="stylesheet" href="../assets/css/tools/r11form.css">
<link rel="stylesheet" href="../assets/css/json.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
<script src="../assets/scripts/tools/scripts.js"></script>
<script src="../assets/scripts/tools/json.js"></script>
@@ -22,10 +21,21 @@
<h1>Online JSON Formatter</h1>
</div>
<p style="margin-bottom: -30px" id="processInfo"></p>
<div class="display-space-between">
<div>
<b><span id="processInfo"></span></b><br>
<b>Insert your JSON:</b>
</div>
<div>
<button class="action-button active" id="clearXMLButton" style="padding: 3px 10px;"
onclick="clearJsonData()">Clear</button>
<button class="action-button active" id="defaultXMLButton" style="padding: 3px 10px;"
onclick="insertDefaultJson()">Insert default XML</button>
</div>
</div>
<pre>
<code class="hightlight-json json-block" id="jsonBlock" contenteditable="True">{"enter": "your", "json": "here"}</code>
<code class="hightlight-json json-block bordered-field" id="jsonBlock" contenteditable="True">{"enter": "your", "json": "here"}</code>
</pre>
<button style="margin-top: 20px"