Search in sources :

Example 6 with Query

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

the class FindDuplicateFilesCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) {
    final PropertyKey<String> path = StructrApp.key(AbstractFile.class, "path");
    final SecurityContext securityContext = getWebSocket().getSecurityContext();
    final Query query = StructrApp.getInstance(securityContext).nodeQuery(AbstractFile.class).sort(path);
    try {
        AbstractFile lastFile = null;
        String lastFilepath = null;
        boolean lastWasDupe = false;
        final ArrayList<GraphObject> filesWithSamePath = new ArrayList<>();
        final Iterator it = query.getAsList().iterator();
        while (it.hasNext()) {
            final AbstractNode node = (AbstractNode) it.next();
            try {
                final AbstractFile file = (AbstractFile) node;
                final String currentFilepath = file.getProperty(path);
                // skip the first file as we can not compare it to the previous one
                if (lastFile != null) {
                    if (currentFilepath.equals(lastFilepath)) {
                        if (!lastWasDupe) {
                            // if this is the first duplicate found we need to add both files
                            filesWithSamePath.add(lastFile);
                        }
                        filesWithSamePath.add(file);
                        lastWasDupe = true;
                    } else {
                        lastWasDupe = false;
                    }
                }
                lastFilepath = currentFilepath;
                lastFile = file;
            } catch (ClassCastException cce) {
                logger.warn("Tried casting node '{}' of type '{}' to AbstractFile. Most likely a node type inheriting from File was deleted and an instance remains. Please delete this node or change its type.", node.getUuid(), node.getType());
            }
        }
        // set full result list
        webSocketData.setResult(filesWithSamePath);
        webSocketData.setRawResultCount(filesWithSamePath.size());
        // 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 : AbstractFile(org.structr.web.entity.AbstractFile) Query(org.structr.core.app.Query) FrameworkException(org.structr.common.error.FrameworkException) AbstractNode(org.structr.core.entity.AbstractNode) ArrayList(java.util.ArrayList) GraphObject(org.structr.core.GraphObject) SecurityContext(org.structr.common.SecurityContext) Iterator(java.util.Iterator)

Example 7 with Query

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

the class GetByTypeCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) {
    final SecurityContext securityContext = getWebSocket().getSecurityContext();
    final String rawType = (String) webSocketData.getNodeData().get("type");
    final String properties = (String) webSocketData.getNodeData().get("properties");
    final boolean includeDeletedAndHidden = (Boolean) webSocketData.getNodeData().get("includeDeletedAndHidden");
    final Class type = SchemaHelper.getEntityClassForRawType(rawType);
    if (type == null) {
        getWebSocket().send(MessageBuilder.status().code(404).message("Type " + rawType + " not found").build(), true);
        return;
    }
    if (properties != null) {
        securityContext.setCustomView(StringUtils.split(properties, ","));
    }
    final String sortOrder = webSocketData.getSortOrder();
    final String sortKey = webSocketData.getSortKey();
    final int pageSize = webSocketData.getPageSize();
    final int page = webSocketData.getPage();
    final Query query = StructrApp.getInstance(securityContext).nodeQuery(type).includeDeletedAndHidden(includeDeletedAndHidden);
    if (sortKey != null) {
        final PropertyKey sortProperty = StructrApp.key(type, sortKey);
        if (sortProperty != null) {
            query.sort(sortProperty).order("desc".equals(sortOrder));
        }
    }
    // for image lists, suppress thumbnails
    if (type.equals(Image.class)) {
        query.and(StructrApp.key(Image.class, "isThumbnail"), false);
    }
    try {
        // do search
        Result result = query.getResult();
        // save raw result count
        int resultCountBeforePaging = result.size();
        // set full result list
        webSocketData.setResult(PagingHelper.subList(result.getResults(), pageSize, page));
        webSocketData.setRawResultCount(resultCountBeforePaging);
        // 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 : Query(org.structr.core.app.Query) FrameworkException(org.structr.common.error.FrameworkException) SecurityContext(org.structr.common.SecurityContext) Image(org.structr.web.entity.Image) PropertyKey(org.structr.core.property.PropertyKey) Result(org.structr.core.Result)

Example 8 with Query

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

the class QueryCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) {
    final SecurityContext securityContext = getWebSocket().getSecurityContext();
    final Map<String, Object> nodeData = webSocketData.getNodeData();
    final String rawType = (String) nodeData.get("type");
    final String properties = (String) nodeData.get("properties");
    final Boolean exact = (Boolean) nodeData.get("exact");
    final Class type = SchemaHelper.getEntityClassForRawType(rawType);
    if (type == null) {
        getWebSocket().send(MessageBuilder.status().code(404).message("Type " + rawType + " not found").build(), true);
        return;
    }
    final String sortKey = webSocketData.getSortKey();
    final int pageSize = webSocketData.getPageSize();
    final int page = webSocketData.getPage();
    final Query query = StructrApp.getInstance(securityContext).nodeQuery(type).page(page).pageSize(pageSize);
    if (sortKey != null) {
        final PropertyKey sortProperty = StructrApp.key(type, sortKey);
        final String sortOrder = webSocketData.getSortOrder();
        query.sort(sortProperty).order("desc".equals(sortOrder));
    }
    if (properties != null) {
        try {
            final Gson gson = new GsonBuilder().create();
            final Map<String, Object> querySource = gson.fromJson(properties, new TypeToken<Map<String, Object>>() {
            }.getType());
            final PropertyMap queryMap = PropertyMap.inputTypeToJavaType(securityContext, type, querySource);
            final boolean inexactQuery = exact != null && exact == false;
            // add properties to query
            for (final Entry<PropertyKey, Object> entry : queryMap.entrySet()) {
                query.and(entry.getKey(), entry.getValue(), !inexactQuery);
            }
        } catch (FrameworkException fex) {
            logger.warn("Exception occured", fex);
            getWebSocket().send(MessageBuilder.status().code(fex.getStatus()).message(fex.getMessage()).build(), true);
            return;
        }
    }
    try {
        // do search
        final Result result = query.getResult();
        // save raw result count
        // filteredResults.size();
        int resultCountBeforePaging = result.getRawResultCount();
        // set full result list
        webSocketData.setResult(result.getResults());
        webSocketData.setRawResultCount(resultCountBeforePaging);
        // 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 : Query(org.structr.core.app.Query) FrameworkException(org.structr.common.error.FrameworkException) GsonBuilder(com.google.gson.GsonBuilder) Gson(com.google.gson.Gson) Result(org.structr.core.Result) PropertyMap(org.structr.core.property.PropertyMap) TypeToken(com.google.gson.reflect.TypeToken) SecurityContext(org.structr.common.SecurityContext) PropertyKey(org.structr.core.property.PropertyKey)

Example 9 with Query

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

the class SearchFunction 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).nodeQuery();
        applyRange(securityContext, query);
        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 search(): type {} not found.", typeString);
                return "Error in search(): type " + typeString + " not found.";
            }
        }
        // exit gracefully instead of crashing..
        if (type == null) {
            logger.warn("Error in search(): no type specified. Parameters: {}", getParametersAsString(sources));
            return "Error in search(): 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) {
            final PropertyMap map = PropertyMap.inputTypeToJavaType(securityContext, type, (Map) sources[1]);
            for (final Map.Entry<PropertyKey, Object> entry : map.entrySet()) {
                query.and(entry.getKey(), entry.getValue(), false);
            }
        } 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_SEARCH);
            }
            for (int c = 1; c < parameter_count; c += 2) {
                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, false);
                }
            }
        }
        // return search results
        return query.getAsList();
    } catch (final IllegalArgumentException e) {
        logParameterError(caller, sources, ctx.isJavaScriptContext());
        return usage(ctx.isJavaScriptContext());
    } finally {
        resetRange();
    }
}
Also used : Query(org.structr.core.app.Query) FrameworkException(org.structr.common.error.FrameworkException) ConfigurationProvider(org.structr.schema.ConfigurationProvider) PropertyMap(org.structr.core.property.PropertyMap) SecurityContext(org.structr.common.SecurityContext) PropertyConverter(org.structr.core.converter.PropertyConverter) PropertyMap(org.structr.core.property.PropertyMap) Map(java.util.Map) PropertyKey(org.structr.core.property.PropertyKey)

Example 10 with Query

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

the class StaticRelationshipResource method doGet.

// ~--- methods --------------------------------------------------------
@Override
public Result doGet(final PropertyKey sortKey, final boolean sortDescending, final int pageSize, final int page) throws FrameworkException {
    // ok, source node exists, fetch it
    final GraphObject sourceEntity = typedIdResource.getEntity();
    if (sourceEntity != null) {
        // first try: look through existing relations
        if (propertyKey == null) {
            if (sourceEntity instanceof NodeInterface) {
                if (!typeResource.isNode) {
                    final NodeInterface source = (NodeInterface) sourceEntity;
                    final Node sourceNode = source.getNode();
                    final Class relationshipType = typeResource.entityClass;
                    final Relation relation = AbstractNode.getRelationshipForType(relationshipType);
                    final Class destNodeType = relation.getOtherType(typedIdResource.getEntityClass());
                    final Set partialResult = new LinkedHashSet<>(typeResource.doGet(sortKey, sortDescending, NodeFactory.DEFAULT_PAGE_SIZE, NodeFactory.DEFAULT_PAGE).getResults());
                    // filter list according to end node type
                    final Set<GraphObject> set = Iterables.toSet(Iterables.filter(new OtherNodeTypeRelationFilter(securityContext, sourceNode, destNodeType), source.getRelationships(relationshipType)));
                    // intersect partial result with result list
                    set.retainAll(partialResult);
                    final List<GraphObject> finalResult = new LinkedList<>(set);
                    // sort after merge
                    applyDefaultSorting(finalResult, sortKey, sortDescending);
                    // return result
                    return new Result(PagingHelper.subList(finalResult, pageSize, page), finalResult.size(), isCollectionResource(), isPrimitiveArray());
                } else {
                    // what here?
                    throw new NotFoundException("Cannot access relationship collection " + typeResource.getRawType());
                }
            }
        } else {
            Query query = typeResource.query;
            if (query == null) {
                query = StructrApp.getInstance(securityContext).nodeQuery();
            }
            // use search context from type resource
            typeResource.collectSearchAttributes(query);
            final Predicate<GraphObject> predicate = query.toPredicate();
            final Object value = sourceEntity.getProperty(propertyKey, predicate);
            if (value != null) {
                if (value instanceof Iterable) {
                    final Set<Object> propertyResults = new LinkedHashSet<>();
                    Iterator<Object> iter = ((Iterable<Object>) value).iterator();
                    boolean iterableContainsGraphObject = false;
                    while (iter.hasNext()) {
                        Object obj = iter.next();
                        propertyResults.add(obj);
                        if (obj != null && !iterableContainsGraphObject) {
                            if (obj instanceof GraphObject) {
                                iterableContainsGraphObject = true;
                            }
                        }
                    }
                    int rawResultCount = propertyResults.size();
                    if (rawResultCount > 0 && !iterableContainsGraphObject) {
                        GraphObjectMap gObject = new GraphObjectMap();
                        gObject.setProperty(new ArrayProperty(this.typeResource.rawType, Object.class), propertyResults.toArray());
                        Result r = new Result(gObject, true);
                        r.setRawResultCount(rawResultCount);
                        return r;
                    }
                    final List<GraphObject> finalResult = new LinkedList<>();
                    propertyResults.forEach(v -> finalResult.add((GraphObject) v));
                    applyDefaultSorting(finalResult, sortKey, sortDescending);
                    // return result
                    Result r = new Result(PagingHelper.subList(finalResult, pageSize, page), finalResult.size(), isCollectionResource(), isPrimitiveArray());
                    r.setRawResultCount(rawResultCount);
                    return r;
                } else if (value instanceof GraphObject) {
                    return new Result((GraphObject) value, isPrimitiveArray());
                } else {
                    GraphObjectMap gObject = new GraphObjectMap();
                    PropertyKey key;
                    String keyName = this.typeResource.rawType;
                    int resultCount = 1;
                    // FIXME: Dynamically resolve all property types and their result count
                    if (value instanceof String) {
                        key = new StringProperty(keyName);
                    } else if (value instanceof Integer) {
                        key = new IntProperty(keyName);
                    } else if (value instanceof Long) {
                        key = new LongProperty(keyName);
                    } else if (value instanceof Double) {
                        key = new DoubleProperty(keyName);
                    } else if (value instanceof Boolean) {
                        key = new BooleanProperty(keyName);
                    } else if (value instanceof Date) {
                        key = new DateProperty(keyName);
                    } else if (value instanceof String[]) {
                        key = new ArrayProperty(keyName, String.class);
                        resultCount = ((String[]) value).length;
                    } else {
                        key = new GenericProperty(keyName);
                    }
                    gObject.setProperty(key, value);
                    Result r = new Result(gObject, true);
                    r.setRawResultCount(resultCount);
                    return r;
                }
            }
            // check propertyKey to return the right variant of empty result
            if (!(propertyKey instanceof StartNode || propertyKey instanceof EndNode)) {
                return new Result(Collections.EMPTY_LIST, 1, false, true);
            }
        }
    }
    return new Result(Collections.EMPTY_LIST, 0, false, true);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) LinkedHashSet(java.util.LinkedHashSet) Set(java.util.Set) Query(org.structr.core.app.Query) DateProperty(org.structr.core.property.DateProperty) StartNode(org.structr.core.property.StartNode) EndNode(org.structr.core.property.EndNode) Node(org.structr.api.graph.Node) AbstractNode(org.structr.core.entity.AbstractNode) NotFoundException(org.structr.rest.exception.NotFoundException) StringProperty(org.structr.core.property.StringProperty) GraphObject(org.structr.core.GraphObject) Result(org.structr.core.Result) RestMethodResult(org.structr.rest.RestMethodResult) Relation(org.structr.core.entity.Relation) NodeInterface(org.structr.core.graph.NodeInterface) StartNode(org.structr.core.property.StartNode) ArrayProperty(org.structr.core.property.ArrayProperty) BooleanProperty(org.structr.core.property.BooleanProperty) OtherNodeTypeRelationFilter(org.structr.core.entity.OtherNodeTypeRelationFilter) LinkedList(java.util.LinkedList) Date(java.util.Date) IntProperty(org.structr.core.property.IntProperty) EndNode(org.structr.core.property.EndNode) GraphObjectMap(org.structr.core.GraphObjectMap) LongProperty(org.structr.core.property.LongProperty) GenericProperty(org.structr.core.property.GenericProperty) GraphObject(org.structr.core.GraphObject) DoubleProperty(org.structr.core.property.DoubleProperty) PropertyKey(org.structr.core.property.PropertyKey)

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