Search in sources :

Example 11 with Query

use of org.structr.core.app.Query in project structr by structr.

the class FindRelationshipFunction method apply.

@Override
public Object apply(final ActionContext ctx, final Object caller, final Object[] sources) throws FrameworkException {
    try {
        if (sources == null) {
            throw new IllegalArgumentException();
        }
        final SecurityContext securityContext = ctx.getSecurityContext();
        final ConfigurationProvider config = StructrApp.getConfiguration();
        final Query query = StructrApp.getInstance(securityContext).relationshipQuery().sort(GraphObject.createdDate).order(false);
        // the type to query for
        Class type = null;
        if (sources.length >= 1 && sources[0] != null) {
            final String typeString = sources[0].toString();
            type = config.getRelationshipEntityClass(typeString);
            if (type != null) {
                query.andTypes(type);
            } else {
                logger.warn("Error in find_relationship(): type \"{}\" not found.", typeString);
                return ERROR_MESSAGE_FIND_RELATIONSHIP_TYPE_NOT_FOUND + typeString;
            }
        }
        // exit gracefully instead of crashing..
        if (type == null) {
            logger.warn("Error in find_relationship(): no type specified. Parameters: {}", getParametersAsString(sources));
            return ERROR_MESSAGE_FIND_RELATIONSHIP_NO_TYPE_SPECIFIED;
        }
        // experimental: disable result count, prevents instantiation
        // of large collections just for counting all the objects..
        securityContext.ignoreResultCount(true);
        // extension for native javascript objects
        if (sources.length == 2 && sources[1] instanceof Map) {
            query.and(PropertyMap.inputTypeToJavaType(securityContext, type, (Map) sources[1]));
        } else if (sources.length == 2) {
            if (sources[1] == null) {
                throw new IllegalArgumentException();
            }
            // special case: second parameter is a UUID
            final PropertyKey key = StructrApp.key(type, "id");
            query.and(key, sources[1].toString());
            return query.getFirst();
        } else {
            final int parameter_count = sources.length;
            if (parameter_count % 2 == 0) {
                throw new FrameworkException(400, "Invalid number of parameters: " + parameter_count + ". Should be uneven: " + ERROR_MESSAGE_FIND_RELATIONSHIP);
            }
            for (int c = 1; c < parameter_count; c += 2) {
                if (sources[c] == null) {
                    throw new IllegalArgumentException();
                }
                final PropertyKey key = StructrApp.key(type, sources[c].toString());
                if (key != null) {
                    final PropertyConverter inputConverter = key.inputConverter(securityContext);
                    Object value = sources[c + 1];
                    if (inputConverter != null) {
                        value = inputConverter.convert(value);
                    }
                    query.and(key, value);
                }
            }
        }
        return query.getAsList();
    } catch (final IllegalArgumentException e) {
        logParameterError(caller, sources, ctx.isJavaScriptContext());
        return usage(ctx.isJavaScriptContext());
    }
}
Also used : Query(org.structr.core.app.Query) FrameworkException(org.structr.common.error.FrameworkException) ConfigurationProvider(org.structr.schema.ConfigurationProvider) SecurityContext(org.structr.common.SecurityContext) PropertyConverter(org.structr.core.converter.PropertyConverter) GraphObject(org.structr.core.GraphObject) PropertyMap(org.structr.core.property.PropertyMap) Map(java.util.Map) PropertyKey(org.structr.core.property.PropertyKey)

Example 12 with Query

use of org.structr.core.app.Query in project structr by structr.

the class FindFunction method apply.

@Override
public Object apply(final ActionContext ctx, final Object caller, final Object[] sources) throws FrameworkException {
    try {
        if (sources == null) {
            throw new IllegalArgumentException();
        }
        final SecurityContext securityContext = ctx.getSecurityContext();
        final ConfigurationProvider config = StructrApp.getConfiguration();
        final App app = StructrApp.getInstance(securityContext);
        final Query query = app.nodeQuery().sort(GraphObject.createdDate).order(false);
        // paging applied by surrounding slice() function
        applyRange(securityContext, query);
        // the type to query for
        Class type = null;
        if (sources.length >= 1 && sources[0] != null) {
            final String typeString = sources[0].toString();
            type = config.getNodeEntityClass(typeString);
            if (type != null) {
                query.andTypes(type);
            } else {
                logger.warn("Error in find(): type \"{}\" not found.", typeString);
                return ERROR_MESSAGE_FIND_TYPE_NOT_FOUND + typeString;
            }
        }
        // exit gracefully instead of crashing..
        if (type == null) {
            logger.warn("Error in find(): no type specified. Parameters: {}", getParametersAsString(sources));
            return ERROR_MESSAGE_FIND_NO_TYPE_SPECIFIED;
        }
        // experimental: disable result count, prevents instantiation
        // of large collections just for counting all the objects..
        securityContext.ignoreResultCount(true);
        // extension for native javascript objects
        if (sources.length == 2 && sources[1] instanceof Map) {
            query.and(PropertyMap.inputTypeToJavaType(securityContext, type, (Map) sources[1]));
        } else if (sources.length == 2) {
            if (sources[1] == null) {
                throw new IllegalArgumentException();
            }
            // special case: second parameter is a UUID
            final PropertyKey key = StructrApp.key(type, "id");
            query.and(key, sources[1].toString());
            return query.getFirst();
        } else {
            final int parameter_count = sources.length;
            if (parameter_count % 2 == 0) {
                throw new FrameworkException(400, "Invalid number of parameters: " + parameter_count + ". Should be uneven: " + ERROR_MESSAGE_FIND);
            }
            for (int c = 1; c < parameter_count; c += 2) {
                if (sources[c] == null) {
                    throw new IllegalArgumentException();
                }
                final PropertyKey key = StructrApp.key(type, sources[c].toString());
                if (key != null) {
                    final PropertyConverter inputConverter = key.inputConverter(securityContext);
                    Object value = sources[c + 1];
                    if (inputConverter != null) {
                        value = inputConverter.convert(value);
                    }
                    query.and(key, value);
                }
            }
        }
        return query.getAsList();
    } catch (final IllegalArgumentException e) {
        logParameterError(caller, sources, ctx.isJavaScriptContext());
        return usage(ctx.isJavaScriptContext());
    } finally {
        resetRange();
    }
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) Query(org.structr.core.app.Query) FrameworkException(org.structr.common.error.FrameworkException) ConfigurationProvider(org.structr.schema.ConfigurationProvider) SecurityContext(org.structr.common.SecurityContext) PropertyConverter(org.structr.core.converter.PropertyConverter) GraphObject(org.structr.core.GraphObject) PropertyMap(org.structr.core.property.PropertyMap) Map(java.util.Map) PropertyKey(org.structr.core.property.PropertyKey)

Example 13 with Query

use of org.structr.core.app.Query in project structr by structr.

the class SearchCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) {
    final SecurityContext securityContext = getWebSocket().getSecurityContext();
    final String searchString = (String) webSocketData.getNodeData().get("searchString");
    final Boolean exactSearch = (Boolean) webSocketData.getNodeData().get("exact");
    final String restQuery = (String) webSocketData.getNodeData().get("restQuery");
    final String cypherQuery = (String) webSocketData.getNodeData().get("cypherQuery");
    final String paramString = (String) webSocketData.getNodeData().get("cypherParams");
    final String typeString = (String) webSocketData.getNodeData().get("type");
    final int pageSize = webSocketData.getPageSize();
    final int page = webSocketData.getPage();
    Class type = null;
    if (typeString != null) {
        type = SchemaHelper.getEntityClassForRawType(typeString);
    }
    if (searchString == null) {
        if (cypherQuery != null) {
            try {
                Map<String, Object> obj = null;
                if (StringUtils.isNoneBlank(paramString)) {
                    obj = new Gson().fromJson(paramString, Map.class);
                }
                final List<GraphObject> result = StructrApp.getInstance(securityContext).cypher(cypherQuery, obj);
                int resultCountBeforePaging = result.size();
                webSocketData.setRawResultCount(resultCountBeforePaging);
                if (page != 0 && pageSize != 0) {
                    webSocketData.setResult(result.subList((page - 1) * pageSize, Math.min(page * pageSize, resultCountBeforePaging)));
                } else {
                    webSocketData.setResult(result);
                }
                getWebSocket().send(webSocketData, true);
                return;
            } catch (Exception ex) {
                logger.warn("Exception occured", ex);
                getWebSocket().send(MessageBuilder.status().code(400).message(ex.getMessage()).build(), true);
                return;
            }
        }
        if (restQuery != null) {
            final RestDataSource restDataSource = new RestDataSource();
            try {
                securityContext.setRequest(getWebSocket().getRequest());
                webSocketData.setResult(restDataSource.getData(new RenderContext(securityContext), restQuery));
                getWebSocket().send(webSocketData, true);
                return;
            } catch (FrameworkException ex) {
                logger.error("", ex);
                return;
            }
        }
    }
    final String sortOrder = webSocketData.getSortOrder();
    final String sortKey = webSocketData.getSortKey();
    final PropertyKey sortProperty = StructrApp.key(AbstractNode.class, sortKey);
    final Query query = StructrApp.getInstance(securityContext).nodeQuery().includeDeletedAndHidden().sort(sortProperty).order("desc".equals(sortOrder));
    query.and(AbstractNode.name, searchString, exactSearch);
    if (type != null) {
        query.andType(type);
    }
    try {
        // do search
        final Result result = query.getResult();
        // set full result list
        webSocketData.setResult(result.getResults());
        // send only over local connection
        getWebSocket().send(webSocketData, true);
    } catch (FrameworkException fex) {
        logger.warn("Exception occured", fex);
        getWebSocket().send(MessageBuilder.status().code(fex.getStatus()).message(fex.getMessage()).build(), true);
    }
}
Also used : RenderContext(org.structr.web.common.RenderContext) FrameworkException(org.structr.common.error.FrameworkException) Query(org.structr.core.app.Query) Gson(com.google.gson.Gson) GraphObject(org.structr.core.GraphObject) RestDataSource(org.structr.web.datasource.RestDataSource) FrameworkException(org.structr.common.error.FrameworkException) Result(org.structr.core.Result) SecurityContext(org.structr.common.SecurityContext) GraphObject(org.structr.core.GraphObject) Map(java.util.Map) PropertyKey(org.structr.core.property.PropertyKey)

Example 14 with Query

use of org.structr.core.app.Query in project structr by structr.

the class HtmlServlet method findFirstNodeByName.

/**
 * Find first node whose name matches the last part of the given path
 *
 * @param securityContext
 * @param request
 * @param path
 * @return node
 * @throws FrameworkException
 */
private AbstractNode findFirstNodeByName(final SecurityContext securityContext, final HttpServletRequest request, final String path) throws FrameworkException {
    final String name = PathHelper.getName(path);
    if (!name.isEmpty()) {
        logger.debug("Requested name: {}", name);
        final Query query = StructrApp.getInstance(securityContext).nodeQuery();
        final ConfigurationProvider config = StructrApp.getConfiguration();
        if (!possiblePropertyNamesForEntityResolving.isEmpty()) {
            query.and();
            resolvePossiblePropertyNamesForObjectResolution(config, query, name);
            query.parent();
        }
        final Result results = query.getResult();
        logger.debug("{} results", results.size());
        request.setAttribute(POSSIBLE_ENTRY_POINTS_KEY, results.getResults());
        return (results.size() > 0 ? (AbstractNode) results.get(0) : null);
    }
    return null;
}
Also used : Query(org.structr.core.app.Query) AbstractNode(org.structr.core.entity.AbstractNode) ConfigurationProvider(org.structr.schema.ConfigurationProvider) Result(org.structr.core.Result)

Example 15 with Query

use of org.structr.core.app.Query in project structr by structr.

the class HtmlServlet method findPossibleEntryPointsByPath.

private List<Linkable> findPossibleEntryPointsByPath(final SecurityContext securityContext, final HttpServletRequest request, final String path) throws FrameworkException {
    final List<Linkable> possibleEntryPoints = (List<Linkable>) request.getAttribute(POSSIBLE_ENTRY_POINTS_KEY);
    if (CollectionUtils.isNotEmpty(possibleEntryPoints)) {
        return possibleEntryPoints;
    }
    if (path.length() > 0) {
        logger.debug("Requested path: {}", path);
        final Query pageQuery = StructrApp.getInstance(securityContext).nodeQuery();
        pageQuery.and(StructrApp.key(Page.class, "path"), path).andType(Page.class);
        final Result pages = pageQuery.getResult();
        final Query fileQuery = StructrApp.getInstance(securityContext).nodeQuery();
        fileQuery.and(StructrApp.key(AbstractFile.class, "path"), path).andTypes(File.class);
        final Result files = fileQuery.getResult();
        logger.debug("Found {} pages and {} files/folders", new Object[] { pages.size(), files.size() });
        final List<Linkable> linkables = (List<Linkable>) pages.getResults();
        linkables.addAll(files.getResults());
        request.setAttribute(POSSIBLE_ENTRY_POINTS_KEY, linkables);
        return linkables;
    }
    return Collections.EMPTY_LIST;
}
Also used : Query(org.structr.core.app.Query) Linkable(org.structr.web.entity.Linkable) List(java.util.List) LinkedList(java.util.LinkedList) Result(org.structr.core.Result)

Aggregations

Query (org.structr.core.app.Query)17 FrameworkException (org.structr.common.error.FrameworkException)11 PropertyKey (org.structr.core.property.PropertyKey)11 SecurityContext (org.structr.common.SecurityContext)10 Result (org.structr.core.Result)9 GraphObject (org.structr.core.GraphObject)8 Map (java.util.Map)5 PropertyMap (org.structr.core.property.PropertyMap)5 ConfigurationProvider (org.structr.schema.ConfigurationProvider)5 LinkedList (java.util.LinkedList)4 PropertyConverter (org.structr.core.converter.PropertyConverter)4 AbstractNode (org.structr.core.entity.AbstractNode)3 NodeInterface (org.structr.core.graph.NodeInterface)3 Gson (com.google.gson.Gson)2 List (java.util.List)2 AbstractFile (org.structr.web.entity.AbstractFile)2 Image (org.structr.web.entity.Image)2 Linkable (org.structr.web.entity.Linkable)2 GsonBuilder (com.google.gson.GsonBuilder)1 TypeToken (com.google.gson.reflect.TypeToken)1