Search in sources :

Example 1 with GraphObjectComparator

use of org.structr.common.GraphObjectComparator 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 2 with GraphObjectComparator

use of org.structr.common.GraphObjectComparator in project structr by structr.

the class DataFeed method cleanUp.

/*
	private static final Logger logger = LoggerFactory.getLogger(DataFeed.class.getName());

	public static final Property<List<FeedItem>> items          = new EndNodes<>("items", FeedItems.class);
	public static final Property<String>         url            = new StringProperty("url").indexed();
	public static final Property<String>         feedType       = new StringProperty("feedType").indexed();
	public static final Property<String>         description    = new StringProperty("description").indexed();
	public static final Property<Long>           updateInterval = new LongProperty("updateInterval"); // update interval in milliseconds
	public static final Property<Date>           lastUpdated    = new ISO8601DateProperty("lastUpdated");
	public static final Property<Long>           maxAge         = new LongProperty("maxAge"); // maximum age of the oldest feed entry in milliseconds
	public static final Property<Integer>        maxItems       = new IntProperty("maxItems"); // maximum number of feed entries to retain

	public static final View defaultView = new View(DataFeed.class, PropertyView.Public, id, type, url, items, feedType, description);

	public static final View uiView = new View(DataFeed.class, PropertyView.Ui,
		id, name, owner, type, createdBy, deleted, hidden, createdDate, lastModifiedDate, visibleToPublicUsers, visibleToAuthenticatedUsers, visibilityStartDate, visibilityEndDate,
                url, items, feedType, description, lastUpdated, maxAge, maxItems, updateInterval
	);

        static {

            SchemaService.registerBuiltinTypeOverride("DataFeed", DataFeed.class.getName());
        }


	@Override
	public boolean onCreation(SecurityContext securityContext, ErrorBuffer errorBuffer) throws FrameworkException {
		updateFeed(true);
		return super.onCreation(securityContext, errorBuffer);
	}
	*/
static void cleanUp(final DataFeed thisFeed) {
    final Integer maxItemsToRetain = thisFeed.getMaxItems();
    final Long maxItemAge = thisFeed.getMaxAge();
    int i = 0;
    // Don't do anything if maxItems and maxAge are not set
    if (maxItemsToRetain != null || maxItemAge != null) {
        final List<FeedItem> feedItems = Iterables.toList(thisFeed.getItems());
        final PropertyKey<Date> dateKey = StructrApp.key(FeedItem.class, "pubDate");
        // Sort by publication date, youngest items first
        feedItems.sort(new GraphObjectComparator(dateKey, GraphObjectComparator.DESCENDING));
        for (final FeedItem item : feedItems) {
            i++;
            final Date itemDate = item.getProperty(dateKey);
            if ((maxItemsToRetain != null && i > maxItemsToRetain) || (maxItemAge != null && itemDate.before(new Date(new Date().getTime() - maxItemAge)))) {
                try {
                    StructrApp.getInstance().delete(item);
                } catch (FrameworkException ex) {
                    logger.error("Error while deleting old/surplus feed item " + item, ex);
                }
            }
        }
    }
}
Also used : FrameworkException(org.structr.common.error.FrameworkException) GraphObjectComparator(org.structr.common.GraphObjectComparator) Date(java.util.Date)

Example 3 with GraphObjectComparator

use of org.structr.common.GraphObjectComparator in project structr by structr.

the class SchemaMethod method getActionEntry.

public ActionEntry getActionEntry(final AbstractSchemaNode schemaEntity) throws FrameworkException {
    final ActionEntry entry = new ActionEntry("___" + SchemaHelper.cleanPropertyName(getProperty(AbstractNode.name)), getProperty(SchemaMethod.source), getProperty(SchemaMethod.codeType));
    final List<SchemaMethodParameter> params = getProperty(parameters);
    // Parameters must be sorted by index
    Collections.sort(params, new GraphObjectComparator(SchemaMethodParameter.index, false));
    for (final SchemaMethodParameter parameter : params) {
        entry.addParameter(parameter.getParameterType(), parameter.getName());
    }
    entry.setReturnType(getProperty(returnType));
    entry.setCallSuper(getProperty(callSuper));
    final String[] _exceptions = getProperty(exceptions);
    if (_exceptions != null) {
        for (final String exception : _exceptions) {
            entry.addException(exception);
        }
    }
    // check for overridden methods and determine method signature etc. from superclass(es)
    if (getProperty(overridesExisting)) {
        determineSignature(schemaEntity, entry, getProperty(name));
    }
    // check for overridden methods and determine method signature etc. from superclass(es)
    if (getProperty(doExport)) {
        entry.setDoExport(true);
    }
    return entry;
}
Also used : ActionEntry(org.structr.schema.action.ActionEntry) GraphObjectComparator(org.structr.common.GraphObjectComparator)

Example 4 with GraphObjectComparator

use of org.structr.common.GraphObjectComparator in project structr by structr.

the class HtmlServlet method findIndexPage.

/**
 * Find the page with the lowest non-empty position value which is visible in the
 * current security context and for the given site.
 *
 * @param securityContext
 * @param pages
 * @param edit
 * @return page
 * @throws FrameworkException
 */
private Page findIndexPage(final SecurityContext securityContext, List<Page> pages, final EditMode edit) throws FrameworkException {
    final PropertyKey<Integer> positionKey = StructrApp.key(Page.class, "position");
    if (pages == null) {
        pages = StructrApp.getInstance(securityContext).nodeQuery(Page.class).getAsList();
        Collections.sort(pages, new GraphObjectComparator(positionKey, GraphObjectComparator.ASCENDING));
    }
    for (Page page : pages) {
        if (securityContext.isVisible(page) && page.getProperty(positionKey) != null && ((EditMode.CONTENT.equals(edit) || isVisibleForSite(securityContext.getRequest(), page)) || (page.getEnableBasicAuth() && page.isVisibleToAuthenticatedUsers()))) {
            return page;
        }
    }
    return null;
}
Also used : Page(org.structr.web.entity.dom.Page) GraphObjectComparator(org.structr.common.GraphObjectComparator)

Example 5 with GraphObjectComparator

use of org.structr.common.GraphObjectComparator in project structr by structr.

the class SortFunction method apply.

@Override
public Object apply(final ActionContext ctx, final Object caller, final Object[] sources) throws FrameworkException {
    if (sources == null || sources.length == 0) {
        return null;
    }
    // Default sort key
    String sortKey = "name";
    if (sources.length > 1 && sources[1] instanceof String) {
        sortKey = (String) sources[1];
    }
    if (sources.length >= 1) {
        if (sources[0] instanceof List) {
            final List list = (List) sources[0];
            final Iterator iterator = list.iterator();
            if (iterator.hasNext()) {
                final Object firstElement = iterator.next();
                if (firstElement instanceof GraphObject) {
                    final Class type = firstElement.getClass();
                    final PropertyKey key = StructrApp.key(type, sortKey);
                    final boolean descending = sources.length == 3 && sources[2] != null && "true".equals(sources[2].toString());
                    if (key != null) {
                        List<GraphObject> sortCollection = (List<GraphObject>) list;
                        Collections.sort(sortCollection, new GraphObjectComparator(key, descending));
                        return sortCollection;
                    }
                } else if (firstElement instanceof String) {
                    final String[] stringArray = (String[]) list.toArray(new String[list.size()]);
                    Arrays.sort(stringArray);
                    return Arrays.asList(stringArray);
                }
            }
        }
    } else {
        logParameterError(caller, sources, ctx.isJavaScriptContext());
    }
    return sources[0];
}
Also used : Iterator(java.util.Iterator) List(java.util.List) GraphObject(org.structr.core.GraphObject) GraphObjectComparator(org.structr.common.GraphObjectComparator) GraphObject(org.structr.core.GraphObject) PropertyKey(org.structr.core.property.PropertyKey)

Aggregations

GraphObjectComparator (org.structr.common.GraphObjectComparator)10 GraphObject (org.structr.core.GraphObject)3 Folder (org.structr.web.entity.Folder)3 LinkedList (java.util.LinkedList)2 ObjectInFolderContainer (org.apache.chemistry.opencmis.commons.data.ObjectInFolderContainer)2 FrameworkException (org.structr.common.error.FrameworkException)2 PropertyKey (org.structr.core.property.PropertyKey)2 CMISRootFolder (org.structr.files.cmis.repository.CMISRootFolder)2 Page (org.structr.web.entity.dom.Page)2 Path (java.nio.file.Path)1 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1 Iterator (java.util.Iterator)1 LinkedHashSet (java.util.LinkedHashSet)1 List (java.util.List)1 TreeMap (java.util.TreeMap)1 CmisObjectNotFoundException (org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException)1 ObjectInFolderContainerImpl (org.apache.chemistry.opencmis.commons.impl.dataobjects.ObjectInFolderContainerImpl)1 QueryResult (org.structr.api.QueryResult)1 GeoCodingResult (org.structr.common.geo.GeoCodingResult)1