Search in sources :

Example 1 with Result

use of org.structr.core.Result in project structr by structr.

the class Factory method page.

protected Result page(final QueryResult<S> input, final int offset, final int pageSize) throws FrameworkException {
    final SecurityContext securityContext = factoryProfile.getSecurityContext();
    final boolean dontCheckCount = securityContext.ignoreResultCount();
    final List<T> nodes = new ArrayList<>();
    int overallCount = 0;
    int position = 0;
    int count = 0;
    try (final QueryResult<S> tmp = input) {
        for (final S item : tmp) {
            final T n = instantiate(item);
            if (n != null) {
                overallCount++;
                position++;
                if (disablePaging || (position > offset && position <= offset + pageSize)) {
                    nodes.add(n);
                    // stop if we got enough nodes
                    if (++count == pageSize && dontCheckCount && !disablePaging) {
                        break;
                    }
                }
            }
        }
    } catch (NetworkException nex) {
        throw new FrameworkException(503, nex.getMessage());
    }
    // The overall count may be inaccurate
    return new Result(nodes, overallCount, true, false);
}
Also used : FrameworkException(org.structr.common.error.FrameworkException) SecurityContext(org.structr.common.SecurityContext) ArrayList(java.util.ArrayList) NetworkException(org.structr.api.NetworkException) QueryResult(org.structr.api.QueryResult) Result(org.structr.core.Result)

Example 2 with Result

use of org.structr.core.Result in project structr by structr.

the class SearchCommand method doSearch.

private Result<T> doSearch() throws FrameworkException {
    if (page == 0 || pageSize <= 0) {
        return Result.EMPTY_RESULT;
    }
    final Factory<S, T> factory = getFactory(securityContext, includeDeletedAndHidden, publicOnly, pageSize, page);
    boolean hasGraphSources = false;
    boolean hasSpatialSource = false;
    if (securityContext.getUser(false) == null && !isRelationshipSearch()) {
        rootGroup.add(new PropertySearchAttribute(GraphObject.visibleToPublicUsers, true, Occurrence.REQUIRED, true));
    } else if (securityContext.getUser(false) == null && isRelationshipSearch()) {
        rootGroup.add(new RelationshipVisibilitySearchAttribute());
    }
    // special handling of deleted and hidden flags
    if (!includeDeletedAndHidden && !isRelationshipSearch()) {
        rootGroup.add(new PropertySearchAttribute(NodeInterface.hidden, true, Occurrence.FORBIDDEN, true));
        rootGroup.add(new PropertySearchAttribute(NodeInterface.deleted, true, Occurrence.FORBIDDEN, true));
    }
    // At this point, all search attributes are ready
    final List<SourceSearchAttribute> sources = new ArrayList<>();
    boolean hasEmptySearchFields = false;
    boolean hasRelationshipVisibilitySearch = false;
    Result intermediateResult = null;
    // (some query types seem to allow no MUST occurs)
    for (final Iterator<SearchAttribute> it = rootGroup.getSearchAttributes().iterator(); it.hasNext(); ) {
        final SearchAttribute attr = it.next();
        if (attr instanceof SearchAttributeGroup) {
            // fixme: this needs to be done recursively, but how?
            for (final Iterator<SearchAttribute> groupIterator = ((SearchAttributeGroup) attr).getSearchAttributes().iterator(); groupIterator.hasNext(); ) {
                final SearchAttribute item = groupIterator.next();
                if (item instanceof SourceSearchAttribute) {
                    sources.add((SourceSearchAttribute) item);
                    // remove attribute from filter list
                    groupIterator.remove();
                    hasGraphSources = true;
                }
                if (item instanceof EmptySearchAttribute) {
                    hasEmptySearchFields = true;
                }
            }
        }
        // check for distance search and initialize
        if (attr instanceof DistanceSearchAttribute) {
            final DistanceSearchAttribute distanceSearch = (DistanceSearchAttribute) attr;
            if (distanceSearch.needsGeocding()) {
                final GeoCodingResult coords = GeoHelper.geocode(distanceSearch);
                if (coords != null) {
                    distanceSearch.setCoords(coords.toArray());
                }
            }
            hasSpatialSource = true;
        }
        // store source attributes for later use
        if (attr instanceof SourceSearchAttribute) {
            sources.add((SourceSearchAttribute) attr);
            hasGraphSources = true;
        }
        if (attr instanceof EmptySearchAttribute) {
            hasEmptySearchFields = true;
        }
        if (attr instanceof RelationshipVisibilitySearchAttribute) {
            hasRelationshipVisibilitySearch = true;
        }
    }
    // use filters to filter sources otherwise
    if (!hasSpatialSource && !sources.isEmpty()) {
        intermediateResult = new Result(new ArrayList<>(), null, false, false);
    } else {
        // apply sorting
        if (sortKey != null && !doNotSort) {
            rootGroup.setSortKey(sortKey);
            rootGroup.sortDescending(sortDescending);
        }
        final Index<S> index = getIndex();
        if (index != null) {
            // paging needs to be done AFTER instantiating all nodes
            if (hasEmptySearchFields || comparator != null) {
                factory.disablePaging();
            }
            // do query
            final QueryResult hits = index.query(getQueryContext(), rootGroup);
            intermediateResult = factory.instantiate(hits);
            if (comparator != null) {
                final List<T> rawResult = intermediateResult.getResults();
                Collections.sort(rawResult, comparator);
                return new Result(PagingHelper.subList(rawResult, pageSize, page), rawResult.size(), true, false);
            }
        }
    }
    if (intermediateResult != null && (hasEmptySearchFields || hasGraphSources || hasSpatialSource || hasRelationshipVisibilitySearch)) {
        // sorted result set
        final Set<GraphObject> intermediateResultSet = new LinkedHashSet<>(intermediateResult.getResults());
        final List<GraphObject> finalResult = new ArrayList<>();
        int resultCount = 0;
        if (hasGraphSources) {
            // merge sources according to their occur flag
            final Set<GraphObject> mergedSources = mergeSources(sources);
            if (hasSpatialSource) {
                // CHM 2014-02-24: preserve sorting of intermediate result, might be sorted by distance which we cannot reproduce easily
                intermediateResultSet.retainAll(mergedSources);
            } else {
                intermediateResultSet.addAll(mergedSources);
            }
        }
        // Filter intermediate result
        for (final GraphObject obj : intermediateResultSet) {
            boolean addToResult = true;
            // check all attributes before adding a node
            for (SearchAttribute attr : rootGroup.getSearchAttributes()) {
                // check all search attributes
                addToResult &= attr.includeInResult(obj);
            }
            if (addToResult) {
                finalResult.add(obj);
                resultCount++;
            }
        }
        // sort list
        Collections.sort(finalResult, new GraphObjectComparator(sortKey, sortDescending));
        // return paged final result
        return new Result(PagingHelper.subList(finalResult, pageSize, page), resultCount, true, false);
    } else {
        // no filtering
        return intermediateResult;
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ArrayList(java.util.ArrayList) GraphObject(org.structr.core.GraphObject) GeoCodingResult(org.structr.common.geo.GeoCodingResult) Result(org.structr.core.Result) QueryResult(org.structr.api.QueryResult) GeoCodingResult(org.structr.common.geo.GeoCodingResult) QueryResult(org.structr.api.QueryResult) GraphObjectComparator(org.structr.common.GraphObjectComparator)

Example 3 with Result

use of org.structr.core.Result in project structr by structr.

the class ODSExporter method exportAttributes.

public static void exportAttributes(final ODSExporter thisNode, final String uuid) throws FrameworkException {
    final SecurityContext securityContext = thisNode.getSecurityContext();
    final File output = thisNode.getResultDocument();
    final VirtualType transformation = thisNode.getTransformationProvider();
    try {
        final App app = StructrApp.getInstance();
        final Result result = app.nodeQuery(AbstractNode.class).and(GraphObject.id, uuid).getResult();
        final Result transformedResult = transformation.transformOutput(securityContext, AbstractNode.class, result);
        Map<String, Object> nodeProperties = new HashMap<>();
        GraphObjectMap node = (GraphObjectMap) transformedResult.get(0);
        node.getPropertyKeys(null).forEach(p -> nodeProperties.put(p.dbName(), node.getProperty(p)));
        OdfSpreadsheetDocument spreadsheet = OdfSpreadsheetDocument.loadDocument(output.getFileOnDisk().getAbsolutePath());
        OdfTable sheet = spreadsheet.getTableList().get(0);
        Iterator<Entry<String, Object>> it = nodeProperties.entrySet().iterator();
        while (it.hasNext()) {
            Entry<String, Object> currentEntry = it.next();
            String address = currentEntry.getKey();
            Object val = currentEntry.getValue();
            if (val instanceof Collection) {
                Collection col = (Collection) val;
                writeCollectionToCells(sheet, sheet.getCellByPosition(address), col);
            } else if (val instanceof String[]) {
                String[] arr = (String[]) val;
                List<String> list = new ArrayList<>(Arrays.asList(arr));
                writeCollectionToCells(sheet, sheet.getCellByPosition(address), list);
            } else {
                writeObjectToCell(sheet.getCellByPosition(address), val);
            }
        }
        spreadsheet.save(output.getFileOnDisk().getAbsolutePath());
        spreadsheet.close();
    } catch (Exception e) {
        logger.error("Error while exporting to ODS", e);
    }
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) HashMap(java.util.HashMap) OdfSpreadsheetDocument(org.odftoolkit.odfdom.doc.OdfSpreadsheetDocument) VirtualType(org.structr.transform.VirtualType) FrameworkException(org.structr.common.error.FrameworkException) Result(org.structr.core.Result) Entry(java.util.Map.Entry) GraphObjectMap(org.structr.core.GraphObjectMap) SecurityContext(org.structr.common.SecurityContext) Collection(java.util.Collection) GraphObject(org.structr.core.GraphObject) OdfTable(org.odftoolkit.odfdom.doc.table.OdfTable) ArrayList(java.util.ArrayList) List(java.util.List) File(org.structr.web.entity.File)

Example 4 with Result

use of org.structr.core.Result in project structr by structr.

the class ODTExporter method exportAttributes.

static void exportAttributes(final ODTExporter thisNode, final String uuid) throws FrameworkException {
    final SecurityContext securityContext = thisNode.getSecurityContext();
    final File output = thisNode.getResultDocument();
    final VirtualType transformation = thisNode.getTransformationProvider();
    try {
        final App app = StructrApp.getInstance();
        final Result result = app.nodeQuery(AbstractNode.class).and(GraphObject.id, uuid).getResult();
        final Result transformedResult = transformation.transformOutput(securityContext, AbstractNode.class, result);
        Map<String, Object> nodeProperties = new HashMap<>();
        GraphObjectMap node = (GraphObjectMap) transformedResult.get(0);
        node.getPropertyKeys(null).forEach(p -> nodeProperties.put(p.dbName(), node.getProperty(p)));
        TextDocument text = TextDocument.loadDocument(output.getFileOnDisk().getAbsolutePath());
        NodeList nodes = text.getContentRoot().getElementsByTagName(ODT_FIELD_TAG_NAME);
        for (int i = 0; i < nodes.getLength(); i++) {
            Node currentNode = nodes.item(i);
            NamedNodeMap attrs = currentNode.getAttributes();
            Node fieldName = attrs.getNamedItem(ODT_FIELD_ATTRIBUTE_NAME);
            Object nodeFieldValue = nodeProperties.get(fieldName.getNodeValue());
            Node currentContent = attrs.getNamedItem(ODT_FIELD_ATTRIBUTE_VALUE);
            if (nodeFieldValue != null) {
                if (nodeFieldValue instanceof String[]) {
                    String[] arr = (String[]) nodeFieldValue;
                    List<String> list = new ArrayList<>(Arrays.asList(arr));
                    StringBuilder sb = new StringBuilder();
                    list.forEach(s -> sb.append(s + "\n"));
                    currentContent.setNodeValue(sb.toString());
                } else if (nodeFieldValue instanceof Collection) {
                    Collection col = (Collection) nodeFieldValue;
                    StringBuilder sb = new StringBuilder();
                    col.forEach(s -> sb.append(s + "\n"));
                    currentContent.setNodeValue(sb.toString());
                } else {
                    currentContent.setNodeValue(nodeFieldValue.toString());
                }
            }
        }
        text.save(output.getFileOnDisk().getAbsolutePath());
        text.close();
    } catch (Exception e) {
        logger.error("Error while exporting to ODT", e);
    }
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) StructrApp(org.structr.core.app.StructrApp) JsonObjectType(org.structr.schema.json.JsonObjectType) Arrays(java.util.Arrays) NodeList(org.w3c.dom.NodeList) Collection(java.util.Collection) SecurityContext(org.structr.common.SecurityContext) GraphObject(org.structr.core.GraphObject) HashMap(java.util.HashMap) TextDocument(org.odftoolkit.simple.TextDocument) ArrayList(java.util.ArrayList) File(org.structr.web.entity.File) List(java.util.List) JsonSchema(org.structr.schema.json.JsonSchema) FrameworkException(org.structr.common.error.FrameworkException) App(org.structr.core.app.App) Map(java.util.Map) Node(org.w3c.dom.Node) NamedNodeMap(org.w3c.dom.NamedNodeMap) URI(java.net.URI) GraphObjectMap(org.structr.core.GraphObjectMap) Result(org.structr.core.Result) AbstractNode(org.structr.core.entity.AbstractNode) VirtualType(org.structr.transform.VirtualType) SchemaService(org.structr.schema.SchemaService) TextDocument(org.odftoolkit.simple.TextDocument) NamedNodeMap(org.w3c.dom.NamedNodeMap) HashMap(java.util.HashMap) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) AbstractNode(org.structr.core.entity.AbstractNode) ArrayList(java.util.ArrayList) VirtualType(org.structr.transform.VirtualType) FrameworkException(org.structr.common.error.FrameworkException) Result(org.structr.core.Result) GraphObjectMap(org.structr.core.GraphObjectMap) SecurityContext(org.structr.common.SecurityContext) Collection(java.util.Collection) GraphObject(org.structr.core.GraphObject) File(org.structr.web.entity.File)

Example 5 with Result

use of org.structr.core.Result in project structr by structr.

the class RelationshipResource method doGet.

@Override
public Result doGet(final PropertyKey sortKey, final boolean sortDescending, final int pageSize, final int page) throws FrameworkException {
    // fetch all results, paging is applied later
    final List<? extends GraphObject> results = wrappedResource.doGet(null, false, NodeFactory.DEFAULT_PAGE_SIZE, NodeFactory.DEFAULT_PAGE).getResults();
    final App app = StructrApp.getInstance();
    if (results != null && !results.isEmpty()) {
        try {
            final List<GraphObject> resultList = new LinkedList<>();
            for (GraphObject obj : results) {
                if (obj instanceof AbstractNode) {
                    final List<? extends RelationshipInterface> relationships = Direction.INCOMING.equals(direction) ? Iterables.toList(((AbstractNode) obj).getIncomingRelationships()) : Iterables.toList(((AbstractNode) obj).getOutgoingRelationships());
                    if (relationships != null) {
                        boolean filterInternalRelationshipTypes = false;
                        if (securityContext != null && securityContext.getRequest() != null) {
                            final String filterInternal = securityContext.getRequest().getParameter(REQUEST_PARAMETER_FILTER_INTERNAL_RELATIONSHIP_TYPES);
                            if (filterInternal != null) {
                                filterInternalRelationshipTypes = "true".equals(filterInternal);
                            }
                        }
                        // the result set using the request parameter "filterInternal=true"
                        if (filterInternalRelationshipTypes) {
                            for (final RelationshipInterface rel : relationships) {
                                if (!rel.isInternal()) {
                                    resultList.add(rel);
                                }
                            }
                        } else {
                            resultList.addAll(relationships);
                        }
                    }
                }
            }
            final int rawResultCount = resultList.size();
            return new Result(PagingHelper.subList(resultList, pageSize, page), rawResultCount, true, false);
        } catch (Throwable t) {
            logger.warn("Exception while fetching relationships", t);
        }
    } else {
        logger.info("No results from parent..");
    }
    throw new IllegalPathException(getResourceSignature() + " can only be applied to a non-empty resource");
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) IllegalPathException(org.structr.rest.exception.IllegalPathException) AbstractNode(org.structr.core.entity.AbstractNode) GraphObject(org.structr.core.GraphObject) LinkedList(java.util.LinkedList) Result(org.structr.core.Result) RelationshipInterface(org.structr.core.graph.RelationshipInterface)

Aggregations

Result (org.structr.core.Result)66 FrameworkException (org.structr.common.error.FrameworkException)45 Tx (org.structr.core.graph.Tx)36 Test (org.junit.Test)34 TestOne (org.structr.core.entity.TestOne)31 PropertyKey (org.structr.core.property.PropertyKey)28 PropertyMap (org.structr.core.property.PropertyMap)21 NodeInterface (org.structr.core.graph.NodeInterface)18 GraphObject (org.structr.core.GraphObject)14 AbstractNode (org.structr.core.entity.AbstractNode)12 RestMethodResult (org.structr.rest.RestMethodResult)12 Random (java.util.Random)11 SecurityContext (org.structr.common.SecurityContext)11 GraphObjectMap (org.structr.core.GraphObjectMap)10 LinkedList (java.util.LinkedList)9 Query (org.structr.core.app.Query)9 App (org.structr.core.app.App)8 StructrApp (org.structr.core.app.StructrApp)8 List (java.util.List)7 Principal (org.structr.core.entity.Principal)7