use of org.structr.rest.exception.NotFoundException in project structr by structr.
the class CypherQueryResource method doGet.
@Override
public Result doGet(PropertyKey sortKey, boolean sortDescending, int pageSize, int page) throws FrameworkException {
// Admins only
if (!securityContext.isSuperUser()) {
throw new NotAllowedException("Use of the cypher endpoint is restricted to admin users");
}
try {
Object queryObject = securityContext.getRequest().getParameter("query");
if (queryObject != null) {
String query = queryObject.toString();
List<GraphObject> resultList = StructrApp.getInstance(securityContext).command(CypherQueryCommand.class).execute(query, Collections.EMPTY_MAP);
return new Result(resultList, resultList.size(), true, false);
}
} catch (org.structr.api.NotFoundException nfe) {
throw new NotFoundException("Entity not found for the given query");
}
return new Result(Collections.EMPTY_LIST, 0, false, false);
}
use of org.structr.rest.exception.NotFoundException in project structr by structr.
the class ResourceHelper method parsePath.
// ~--- methods --------------------------------------------------------
/**
* Parse the request path and match with possible resource patterns
*
* @param securityContext
* @param request
* @param resourceMap
* @param propertyView
* @return resourceChain
* @throws FrameworkException
*/
public static List<Resource> parsePath(final SecurityContext securityContext, final HttpServletRequest request, final Map<Pattern, Class<? extends Resource>> resourceMap, final Value<String> propertyView) throws FrameworkException {
final String path = request.getPathInfo();
// intercept empty path and send 204 No Content
if (StringUtils.isBlank(path)) {
throw new NoResultsException("No content");
}
// 1.: split request path into URI parts
final String[] pathParts = path.split("[/]+");
// 2.: create container for resource constraints
final Set<String> propertyViews = Services.getInstance().getConfigurationProvider().getPropertyViews();
final List<Resource> resourceChain = new ArrayList<>(pathParts.length);
// 3.: try to assign resource constraints for each URI part
for (int i = 0; i < pathParts.length; i++) {
// eliminate empty strings
final String part = pathParts[i].trim();
if (part.length() > 0) {
boolean found = false;
// check views first
if (propertyViews.contains(part)) {
Resource resource = new ViewFilterResource();
resource.checkAndConfigure(part, securityContext, request);
resource.configurePropertyView(propertyView);
resourceChain.add(resource);
// mark this part as successfully parsed
found = true;
} else {
// look for matching pattern
for (Map.Entry<Pattern, Class<? extends Resource>> entry : resourceMap.entrySet()) {
Pattern pattern = entry.getKey();
Matcher matcher = pattern.matcher(pathParts[i]);
if (matcher.matches()) {
Class<? extends Resource> type = entry.getValue();
Resource resource = null;
try {
// instantiate resource constraint
resource = type.newInstance();
} catch (Throwable t) {
logger.warn("Error instantiating resource class", t);
}
if (resource != null) {
// set security context
resource.setSecurityContext(securityContext);
if (resource.checkAndConfigure(part, securityContext, request)) {
logger.debug("{} matched, adding resource of type {} for part {}", new Object[] { matcher.pattern(), type.getName(), part });
// allow constraint to modify context
resource.configurePropertyView(propertyView);
// add constraint and go on
resourceChain.add(resource);
found = true;
// first match wins, so choose priority wisely ;)
break;
}
}
}
}
}
if (!found) {
throw new NotFoundException("Cannot resolve URL path");
}
}
}
return resourceChain;
}
use of org.structr.rest.exception.NotFoundException in project structr by structr.
the class TypeResource method createNode.
public NodeInterface createNode(final Map<String, Object> propertySet) throws FrameworkException {
if (entityClass != null) {
// experimental: instruct deserialization strategies to set properties on related nodes
securityContext.setAttribute("setNestedProperties", true);
final App app = StructrApp.getInstance(securityContext);
final PropertyMap properties = PropertyMap.inputTypeToJavaType(securityContext, entityClass, propertySet);
return app.create(entityClass, properties);
}
throw new NotFoundException("Type " + rawType + " does not exist");
}
use of org.structr.rest.exception.NotFoundException in project structr by structr.
the class TypedIdResource method getEntity.
// ----- public methods -----
public GraphObject getEntity() throws FrameworkException {
final GraphObject entity = idResource.getEntity();
if (entity != null) {
final String type = SchemaHelper.normalizeEntityName(typeResource.getRawType());
final String entityType = entity.getClass().getSimpleName();
if (GenericNode.class.equals(entity.getClass()) || SearchCommand.getAllSubtypesAsStringSet(type).contains(entityType)) {
return entity;
}
}
throw new NotFoundException("Entity with ID " + idResource.getUuid() + " not found");
}
use of org.structr.rest.exception.NotFoundException in project structr by structr.
the class RestDataSource method getData.
// FIXME: this method is needed by the websocket search command because there is no reference node for the above method
public List<GraphObject> getData(final RenderContext renderContext, final String restQuery) throws FrameworkException {
final Map<Pattern, Class<? extends Resource>> resourceMap = new LinkedHashMap<>();
final SecurityContext securityContext = renderContext.getSecurityContext();
ResourceProvider resourceProvider = renderContext.getResourceProvider();
if (resourceProvider == null) {
try {
resourceProvider = UiResourceProvider.class.newInstance();
} catch (Throwable t) {
logger.error("Couldn't establish a resource provider", t);
return Collections.EMPTY_LIST;
}
}
// inject resources
resourceMap.putAll(resourceProvider.getResources());
Value<String> propertyView = new ThreadLocalPropertyView();
propertyView.set(securityContext, PropertyView.Ui);
HttpServletRequest request = securityContext.getRequest();
if (request == null) {
request = renderContext.getRequest();
}
// initialize variables
// mimic HTTP request
final HttpServletRequest wrappedRequest = new HttpServletRequestWrapper(request) {
@Override
public Enumeration<String> getParameterNames() {
return new IteratorEnumeration(getParameterMap().keySet().iterator());
}
@Override
public String getParameter(final String key) {
String[] p = getParameterMap().get(key);
return p != null ? p[0] : null;
}
@Override
public String[] getParameterValues(final String key) {
return getParameterMap().get(key);
}
@Override
public Map<String, String[]> getParameterMap() {
String[] parts = StringUtils.split(getQueryString(), "&");
Map<String, String[]> parameterMap = new HashMap();
for (String p : parts) {
String[] kv = StringUtils.split(p, "=");
if (kv.length > 1) {
parameterMap.put(kv[0], new String[] { kv[1] });
}
}
return parameterMap;
}
@Override
public String getQueryString() {
return StringUtils.substringAfter(restQuery, "?");
}
@Override
public String getPathInfo() {
return StringUtils.substringBefore(restQuery, "?");
}
@Override
public StringBuffer getRequestURL() {
return new StringBuffer(restQuery);
}
};
// store original request
final HttpServletRequest origRequest = securityContext.getRequest();
// update request in security context
securityContext.setRequest(wrappedRequest);
// HttpServletResponse response = renderContext.getResponse();
Resource resource = null;
try {
resource = ResourceHelper.applyViewTransformation(wrappedRequest, securityContext, ResourceHelper.optimizeNestedResourceChain(securityContext, wrappedRequest, resourceMap, propertyView), propertyView);
} catch (IllegalPathException | NotFoundException e) {
logger.warn("Illegal path for REST query: {}", restQuery);
}
// reset request to old context
securityContext.setRequest(origRequest);
if (resource == null) {
return Collections.EMPTY_LIST;
}
// experimental: disable result count, prevents instantiation
// of large collections just for counting all the objects..
securityContext.ignoreResultCount(true);
// TODO: decide if we need to rest the REST request here
// securityContext.checkResourceAccess(request, resource.getResourceSignature(), resource.getGrant(request, response), PropertyView.Ui);
// add sorting & paging
String pageSizeParameter = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_PAGE_SIZE);
String pageParameter = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_PAGE_NUMBER);
String sortOrder = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_SORT_ORDER);
String sortKeyName = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_SORT_KEY);
boolean sortDescending = (sortOrder != null && "desc".equals(sortOrder.toLowerCase()));
int pageSize = parseInt(pageSizeParameter, NodeFactory.DEFAULT_PAGE_SIZE);
int page = parseInt(pageParameter, NodeFactory.DEFAULT_PAGE);
PropertyKey sortKey = null;
// set sort key
if (sortKeyName != null) {
Class<? extends GraphObject> type = resource.getEntityClass();
if (type == null) {
// fallback to default implementation
// if no type can be determined
type = AbstractNode.class;
}
sortKey = StructrApp.getConfiguration().getPropertyKeyForDatabaseName(type, sortKeyName, false);
}
// do action
Result result = Result.EMPTY_RESULT;
try {
result = resource.doGet(sortKey, sortDescending, pageSize, page);
} catch (NotFoundException nfe) {
logger.warn("No result from internal REST query: {}", restQuery);
}
result.setIsCollection(resource.isCollectionResource());
result.setIsPrimitiveArray(resource.isPrimitiveArray());
// Integer rawResultCount = (Integer) Services.getAttribute(NodeFactory.RAW_RESULT_COUNT + Thread.currentThread().getId());
PagingHelper.addPagingParameter(result, pageSize, page);
List<GraphObject> res = result.getResults();
renderContext.setResult(result);
return res != null ? res : Collections.EMPTY_LIST;
}
Aggregations