use of org.structr.rest.serialization.GraphQLWriter in project structr by structr.
the class WebSocketDataGSONAdapter method serialize.
// ~--- methods --------------------------------------------------------
@Override
public JsonElement serialize(WebSocketMessage src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject root = new JsonObject();
JsonObject jsonNodeData = new JsonObject();
JsonObject jsonRelData = new JsonObject();
JsonArray removedProperties = new JsonArray();
JsonArray modifiedProperties = new JsonArray();
if (src.getCommand() != null) {
root.add("command", new JsonPrimitive(src.getCommand()));
}
if (src.getId() != null) {
root.add("id", new JsonPrimitive(src.getId()));
}
if (src.getPageId() != null) {
root.add("pageId", new JsonPrimitive(src.getPageId()));
}
if (src.getMessage() != null) {
root.add("message", new JsonPrimitive(src.getMessage()));
}
if (src.getJsonErrorObject() != null) {
root.add("error", src.getJsonErrorObject());
}
if (src.getCode() != 0) {
root.add("code", new JsonPrimitive(src.getCode()));
}
if (src.getSessionId() != null) {
root.add("sessionId", new JsonPrimitive(src.getSessionId()));
}
if (src.getCallback() != null) {
root.add("callback", new JsonPrimitive(src.getCallback()));
}
if (src.getButton() != null) {
root.add("button", new JsonPrimitive(src.getButton()));
}
if (src.getParent() != null) {
root.add("parent", new JsonPrimitive(src.getParent()));
}
if (src.getView() != null) {
root.add("view", new JsonPrimitive(src.getView()));
}
if (src.getSortKey() != null) {
root.add("sort", new JsonPrimitive(src.getSortKey()));
}
if (src.getSortOrder() != null) {
root.add("order", new JsonPrimitive(src.getSortOrder()));
}
if (src.getPageSize() > 0) {
root.add("pageSize", new JsonPrimitive(src.getPageSize()));
}
if (src.getPage() > 0) {
root.add("page", new JsonPrimitive(src.getPage()));
}
JsonArray nodesWithChildren = new JsonArray();
Set<String> nwc = src.getNodesWithChildren();
if ((nwc != null) && !src.getNodesWithChildren().isEmpty()) {
for (String nodeId : nwc) {
nodesWithChildren.add(new JsonPrimitive(nodeId));
}
root.add("nodesWithChildren", nodesWithChildren);
}
// serialize session valid flag (output only)
root.add("sessionValid", new JsonPrimitive(src.isSessionValid()));
// UPDATE only, serialize only removed and modified properties and use the correct values
if ((src.getGraphObject() != null)) {
if (!src.getModifiedProperties().isEmpty()) {
for (PropertyKey modifiedKey : src.getModifiedProperties()) {
modifiedProperties.add(toJsonPrimitive(modifiedKey));
}
root.add("modifiedProperties", modifiedProperties);
}
if (!src.getRemovedProperties().isEmpty()) {
for (PropertyKey removedKey : src.getRemovedProperties()) {
removedProperties.add(toJsonPrimitive(removedKey));
}
root.add("removedProperties", removedProperties);
}
}
// serialize node data
if (src.getNodeData() != null) {
for (Entry<String, Object> entry : src.getNodeData().entrySet()) {
Object value = entry.getValue();
String key = entry.getKey();
if (value != null) {
jsonNodeData.add(key, toJsonPrimitive(value));
}
}
root.add("data", jsonNodeData);
}
// serialize relationship data
if (src.getRelData() != null) {
for (Entry<String, Object> entry : src.getRelData().entrySet()) {
Object value = entry.getValue();
String key = entry.getKey();
if (value != null) {
jsonRelData.add(key, toJsonPrimitive(value));
}
}
root.add("relData", jsonRelData);
}
// serialize result list
if (src.getResult() != null) {
if ("GRAPHQL".equals(src.getCommand())) {
try {
if (src.getResult() != null && !src.getResult().isEmpty()) {
final GraphObject firstResultObject = src.getResult().get(0);
final SecurityContext securityContext = firstResultObject.getSecurityContext();
final StringWriter output = new StringWriter();
final String query = (String) src.getNodeData().get("query");
final Document doc = GraphQLRequest.parse(new Parser(), query);
final GraphQLWriter graphQLWriter = new GraphQLWriter(false);
graphQLWriter.stream(securityContext, output, new GraphQLRequest(securityContext, doc, query));
JsonElement graphQLResult = new JsonParser().parse(output.toString());
root.add("result", graphQLResult);
} else {
root.add("result", new JsonArray());
}
} catch (IOException | FrameworkException ex) {
logger.warn("Unable to set process GraphQL query", ex);
}
} else {
if (src.getView() != null) {
try {
propertyView.set(null, src.getView());
} catch (FrameworkException fex) {
logger.warn("Unable to set property view", fex);
}
} else {
try {
propertyView.set(null, PropertyView.Ui);
} catch (FrameworkException fex) {
logger.warn("Unable to set property view", fex);
}
}
JsonArray result = new JsonArray();
for (GraphObject obj : src.getResult()) {
result.add(graphObjectSerializer.serialize(obj, System.currentTimeMillis()));
}
root.add("result", result);
}
root.add("rawResultCount", toJsonPrimitive(src.getRawResultCount()));
}
return root;
}
use of org.structr.rest.serialization.GraphQLWriter in project structr by structr.
the class GraphQLServlet method handleGraphQLRequest.
// ----- private methods -----
private void handleGraphQLRequest(final HttpServletRequest request, final HttpServletResponse response, final String query) throws IOException, FrameworkException {
final SecurityContext securityContext;
final Authenticator authenticator;
try {
// isolate request authentication in a transaction
try (final Tx tx = StructrApp.getInstance().tx()) {
authenticator = config.getAuthenticator();
securityContext = authenticator.initializeAndExamineRequest(request, response);
tx.success();
}
final App app = StructrApp.getInstance(securityContext);
if (securityContext != null) {
// isolate write output
try (final Tx tx = app.tx()) {
final Document doc = GraphQLRequest.parse(new Parser(), query);
if (doc != null) {
final List<ValidationError> errors = new Validator().validateDocument(SchemaService.getGraphQLSchema(), doc);
if (errors.isEmpty()) {
// no validation errors in query, do request
final GraphQLWriter graphQLWriter = new GraphQLWriter(true);
// no trailing semicolon so we dont trip MimeTypes.getContentTypeWithoutCharset
response.setContentType("application/json; charset=utf-8");
final Writer writer = response.getWriter();
graphQLWriter.stream(securityContext, writer, new GraphQLRequest(securityContext, doc, query));
// useful newline
writer.append("\n");
} else {
final Map<String, Object> map = new LinkedHashMap<>();
final Writer writer = response.getWriter();
final Gson gson = getGson();
map.put("errors", errors);
gson.toJson(map, writer);
// useful newline
writer.append("\n");
// send 422 status
response.setStatus(422);
}
}
tx.success();
}
}
} catch (FrameworkException frameworkException) {
// set status & write JSON output
response.setStatus(frameworkException.getStatus());
getGson().toJson(frameworkException, response.getWriter());
response.getWriter().println();
} catch (IllegalStateException | IllegalArgumentException iex) {
final Map<String, Object> map = new LinkedHashMap<>();
map.put("code", 422);
map.put("message", iex.getMessage());
// set status & write JSON output
response.setStatus(422);
getGson().toJson(map, response.getWriter());
response.getWriter().println();
} catch (UnsupportedOperationException uoe) {
logger.warn("POST not supported");
int code = HttpServletResponse.SC_BAD_REQUEST;
response.setStatus(code);
response.getWriter().append(RestMethodResult.jsonError(code, "POST not supported: " + uoe.getMessage()));
} catch (Throwable t) {
logger.warn("Exception in POST", t);
int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
response.setStatus(code);
response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in POST: " + t.getMessage()));
} finally {
try {
// response.getWriter().flush();
response.getWriter().close();
} catch (Throwable t) {
logger.warn("Unable to flush and close response: {}", t.getMessage());
}
}
}
Aggregations