use of org.structr.rest.RestMethodResult in project structr by structr.
the class JsonRestServlet method doPut.
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="PUT">
@Override
protected void doPut(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
final SecurityContext securityContext;
final Authenticator authenticator;
final Resource resource;
RestMethodResult result = new RestMethodResult(HttpServletResponse.SC_BAD_REQUEST);
try {
assertInitialized();
// first thing to do!
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
// get reader before initalizing security context
final String input = IOUtils.toString(request.getReader());
// 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);
final IJsonInput jsonInput = cleanAndParseJsonString(app, input);
if (securityContext != null) {
// isolate resource authentication
try (final Tx tx = app.tx()) {
// evaluate constraint chain
resource = ResourceHelper.applyViewTransformation(request, securityContext, ResourceHelper.optimizeNestedResourceChain(securityContext, request, resourceMap, propertyView), propertyView);
authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(), propertyView.get(securityContext));
tx.success();
}
// isolate doPut
boolean retry = true;
while (retry) {
try (final Tx tx = app.tx()) {
result = resource.doPut(convertPropertySetToMap(jsonInput.getJsonInputs().get(0)));
tx.success();
retry = false;
} catch (RetryException ddex) {
retry = true;
}
}
// isolate write output
try (final Tx tx = app.tx()) {
result.commitResponse(gson.get(), response);
tx.success();
}
} else {
// isolate write output
try (final Tx tx = app.tx()) {
result = new RestMethodResult(HttpServletResponse.SC_FORBIDDEN);
result.commitResponse(gson.get(), response);
tx.success();
}
}
} catch (FrameworkException frameworkException) {
// set status & write JSON output
response.setStatus(frameworkException.getStatus());
gson.get().toJson(frameworkException, response.getWriter());
response.getWriter().println();
} catch (JsonSyntaxException jsex) {
logger.warn("PUT: Invalid JSON syntax", jsex.getMessage());
int code = HttpServletResponse.SC_BAD_REQUEST;
response.setStatus(code);
response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in PUT: " + jsex.getMessage()));
} catch (JsonParseException jpex) {
logger.warn("PUT: Unable to parse JSON string", jpex.getMessage());
int code = HttpServletResponse.SC_BAD_REQUEST;
response.setStatus(code);
response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in PUT: " + jpex.getMessage()));
} catch (Throwable t) {
logger.warn("Exception in PUT", t);
logger.warn("", t);
int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
response.setStatus(code);
response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in PUT: " + t.getMessage()));
} finally {
try {
// response.getWriter().flush();
response.getWriter().close();
} catch (Throwable t) {
logger.warn("Unable to flush and close response: {}", t.getMessage());
}
}
}
use of org.structr.rest.RestMethodResult in project structr by structr.
the class JsonRestServlet method doOptions.
// <editor-fold defaultstate="collapsed" desc="OPTIONS">
@Override
protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final SecurityContext securityContext;
final Authenticator authenticator;
final Resource resource;
RestMethodResult result = new RestMethodResult(HttpServletResponse.SC_BAD_REQUEST);
try {
assertInitialized();
// first thing to do!
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
// 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);
// isolate resource authentication
try (final Tx tx = app.tx()) {
resource = ResourceHelper.applyViewTransformation(request, securityContext, ResourceHelper.optimizeNestedResourceChain(securityContext, request, resourceMap, propertyView), propertyView);
authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(), propertyView.get(securityContext));
tx.success();
}
// isolate doOptions
boolean retry = true;
while (retry) {
try (final Tx tx = app.tx()) {
result = resource.doOptions();
tx.success();
retry = false;
} catch (RetryException ddex) {
retry = true;
}
}
// isolate write output
try (final Tx tx = app.tx()) {
result.commitResponse(gson.get(), response);
tx.success();
}
} catch (FrameworkException frameworkException) {
// set status & write JSON output
response.setStatus(frameworkException.getStatus());
gson.get().toJson(frameworkException, response.getWriter());
response.getWriter().println();
} catch (JsonSyntaxException jsex) {
logger.warn("JsonSyntaxException in OPTIONS", jsex);
int code = HttpServletResponse.SC_BAD_REQUEST;
response.setStatus(code);
response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in OPTIONS: " + jsex.getMessage()));
} catch (JsonParseException jpex) {
logger.warn("JsonParseException in OPTIONS", jpex);
int code = HttpServletResponse.SC_BAD_REQUEST;
response.setStatus(code);
response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in OPTIONS: " + jpex.getMessage()));
} catch (Throwable t) {
logger.warn("Exception in OPTIONS", t);
int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
response.setStatus(code);
response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in OPTIONS: " + t.getMessage()));
} finally {
try {
// response.getWriter().flush();
response.getWriter().close();
} catch (Throwable t) {
logger.warn("Unable to flush and close response: {}", t.getMessage());
}
}
}
use of org.structr.rest.RestMethodResult in project structr by structr.
the class SchemaMethodResource method wrapInResult.
public static RestMethodResult wrapInResult(final Object obj) {
RestMethodResult result = null;
if (obj instanceof RestMethodResult) {
result = (RestMethodResult) obj;
} else {
result = new RestMethodResult(200);
// unwrap nested object(s)
SchemaMethodResource.unwrapTo(obj, result);
}
return result;
}
use of org.structr.rest.RestMethodResult in project structr by structr.
the class StaticRelationshipResource method doPost.
@Override
public RestMethodResult doPost(final Map<String, Object> propertySet) throws FrameworkException {
final GraphObject sourceNode = typedIdResource.getEntity();
RestMethodResult result = null;
if (sourceNode != null && propertyKey != null && propertyKey instanceof RelationProperty) {
final RelationProperty relationProperty = (RelationProperty) propertyKey;
final Class sourceNodeType = sourceNode.getClass();
NodeInterface newNode = null;
if (propertyKey.isReadOnly()) {
logger.info("Read-only property on {}: {}", new Object[] { sourceNodeType, typeResource.getRawType() });
return null;
}
// fetch notion
final Notion notion = relationProperty.getNotion();
final PropertyKey primaryPropertyKey = notion.getPrimaryPropertyKey();
// apply notion if the property set contains the ID property as the only element
if (primaryPropertyKey != null && propertySet.containsKey(primaryPropertyKey.jsonName()) && propertySet.size() == 1) {
// FIXME: what happens here?
} else {
// the notion can not deserialize objects with a single key, or the POSTed propertySet did not contain a key to deserialize,
// so we create a new node from the POSTed properties and link the source node to it. (this is the "old" implementation)
newNode = typeResource.createNode(propertySet);
if (newNode != null) {
relationProperty.addSingleElement(securityContext, sourceNode, newNode);
}
}
if (newNode != null) {
result = new RestMethodResult(HttpServletResponse.SC_CREATED);
result.addHeader("Location", buildLocationHeader(newNode));
return result;
}
} else {
final Class entityType = typedIdResource.getTypeResource().getEntityClass();
final String methodName = typeResource.getRawType();
try {
final String source = SchemaMethodResource.findMethodSource(entityType, methodName);
result = SchemaMethodResource.invoke(securityContext, typedIdResource.getEntity(), source, propertySet, methodName);
} catch (IllegalPathException ex) {
// try direct invocation of the schema method on the node type
try {
result = SchemaMethodResource.wrapInResult(typedIdResource.getEntity().invokeMethod(methodName, propertySet, true));
} catch (Throwable t) {
logger.warn("Unable to execute {}.{}: {}", entityType.getSimpleName(), methodName, t.getMessage());
}
}
}
if (result == null) {
throw new IllegalPathException("Illegal path");
} else {
return result;
}
}
use of org.structr.rest.RestMethodResult in project structr by structr.
the class StaticRelationshipResource method doPut.
@Override
public RestMethodResult doPut(final Map<String, Object> propertySet) throws FrameworkException {
final List<? extends GraphObject> results = typedIdResource.doGet(null, false, NodeFactory.DEFAULT_PAGE_SIZE, NodeFactory.DEFAULT_PAGE).getResults();
final App app = StructrApp.getInstance(securityContext);
if (results != null) {
// fetch static relationship definition
if (propertyKey != null && propertyKey instanceof RelationProperty) {
final GraphObject sourceEntity = typedIdResource.getEntity();
if (sourceEntity != null) {
if (propertyKey.isReadOnly()) {
logger.info("Read-only property on {}: {}", new Object[] { sourceEntity.getClass(), typeResource.getRawType() });
return new RestMethodResult(HttpServletResponse.SC_FORBIDDEN);
}
final List<GraphObject> nodes = new LinkedList<>();
// Now add new relationships for any new id: This should be the rest of the property set
for (final Object obj : propertySet.values()) {
nodes.add(app.getNodeById(obj.toString()));
}
// set property on source node
sourceEntity.setProperty(propertyKey, nodes);
}
}
}
return new RestMethodResult(HttpServletResponse.SC_OK);
}
Aggregations