Search in sources :

Example 6 with GraphObject

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

the class BulkDeleteCommand method bulkDelete.

public void bulkDelete(final Iterator<GraphObject> iterator) throws FrameworkException {
    final App app = StructrApp.getInstance(securityContext);
    final long count = bulkGraphOperation(securityContext, iterator, 1000, "DeleteObjects", new BulkGraphOperation<GraphObject>() {

        @Override
        public void handleGraphObject(final SecurityContext securityContext, final GraphObject obj) {
            try {
                if (obj.isNode()) {
                    final AbstractNode node = (AbstractNode) obj;
                    if (!node.isGranted(Permission.delete, securityContext)) {
                        logger.warn("Could not delete {} because {} has no delete permission", obj.getUuid(), securityContext.getUser(false));
                    } else {
                        app.delete((NodeInterface) obj);
                    }
                } else {
                    app.delete((RelationshipInterface) obj);
                }
            } catch (FrameworkException fex) {
                logger.warn("Unable to delete node {}: {}", obj.getUuid(), fex.toString());
            }
        }

        @Override
        public void handleThrowable(SecurityContext securityContext, Throwable t, GraphObject node) {
            logger.warn("Unable to delete node {}", node.getUuid());
        }

        @Override
        public void handleTransactionFailure(SecurityContext securityContext, Throwable t) {
            logger.warn("Unable to delete nodes {}", t.toString());
        }
    });
    info("Done with deleting {} nodes", count);
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) FrameworkException(org.structr.common.error.FrameworkException) AbstractNode(org.structr.core.entity.AbstractNode) SecurityContext(org.structr.common.SecurityContext) GraphObject(org.structr.core.GraphObject)

Example 7 with GraphObject

use of org.structr.core.GraphObject 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 8 with GraphObject

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

the class ModificationQueue method updateChangelog.

public void updateChangelog() {
    if (Settings.ChangelogEnabled.getValue() && !modificationEvents.isEmpty()) {
        for (final ModificationEvent ev : modificationEvents) {
            if (!ev.isDeleted()) {
                try {
                    final GraphObject obj = ev.getGraphObject();
                    if (obj != null) {
                        final String existingLog = obj.getProperty(GraphObject.structrChangeLog);
                        final String newLog = ev.getChangeLog();
                        final String newValue = existingLog != null ? existingLog + newLog : newLog;
                        obj.unlockSystemPropertiesOnce();
                        obj.setProperty(GraphObject.structrChangeLog, newValue);
                    }
                } catch (Throwable t) {
                    logger.warn("", t);
                }
            }
        }
    }
}
Also used : GraphObject(org.structr.core.GraphObject)

Example 9 with GraphObject

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

the class SetFunction method apply.

@Override
public Object apply(final ActionContext ctx, final Object caller, final Object[] sources) throws FrameworkException {
    if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) {
        final SecurityContext securityContext = ctx.getSecurityContext();
        final ConfigurationProvider config = StructrApp.getConfiguration();
        Class type = null;
        PropertyMap propertyMap = null;
        if (sources[0] instanceof GraphObject) {
            final GraphObject source = (GraphObject) sources[0];
            type = source.getEntityType();
        }
        if (type == null) {
            throw new FrameworkException(422, "Can't get type of object '" + sources[0].toString() + "' in set() method!");
        }
        final GraphObject sourceObject = (GraphObject) sources[0];
        if (sources.length == 2 && sources[1] instanceof Map) {
            propertyMap = PropertyMap.inputTypeToJavaType(securityContext, type, (Map) sources[1]);
        } else if (sources.length == 2 && sources[1] instanceof GraphObjectMap) {
            propertyMap = PropertyMap.inputTypeToJavaType(securityContext, type, ((GraphObjectMap) sources[1]).toMap());
        } else if (sources.length == 2 && sources[1] instanceof String) {
            final Gson gson = new GsonBuilder().create();
            final Map<String, Object> values = deserialize(gson, sources[1].toString());
            if (values != null) {
                propertyMap = PropertyMap.inputTypeToJavaType(securityContext, type, values);
            }
        } else if (sources.length > 2) {
            propertyMap = new PropertyMap();
            final int parameter_count = sources.length;
            if (parameter_count % 2 == 0) {
                throw new FrameworkException(400, "Invalid number of parameters: " + parameter_count + ". Should be uneven: " + (ctx.isJavaScriptContext() ? ERROR_MESSAGE_SET_JS : ERROR_MESSAGE_SET));
            }
            for (int c = 1; c < parameter_count; c += 2) {
                final PropertyKey key = config.getPropertyKeyForJSONName(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);
                    }
                    propertyMap.put(key, value);
                }
            }
        } else {
            throw new FrameworkException(422, "Invalid use of builtin method set, usage: set(entity, params..)");
        }
        if (propertyMap != null) {
            sourceObject.setProperties(securityContext, propertyMap);
        }
    } else {
        logParameterError(caller, sources, ctx.isJavaScriptContext());
    }
    return "";
}
Also used : FrameworkException(org.structr.common.error.FrameworkException) GsonBuilder(com.google.gson.GsonBuilder) ConfigurationProvider(org.structr.schema.ConfigurationProvider) Gson(com.google.gson.Gson) GraphObject(org.structr.core.GraphObject) PropertyMap(org.structr.core.property.PropertyMap) GraphObjectMap(org.structr.core.GraphObjectMap) 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) GraphObjectMap(org.structr.core.GraphObjectMap) PropertyKey(org.structr.core.property.PropertyKey)

Example 10 with GraphObject

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

the class TemplateFunction method apply.

@Override
public Object apply(final ActionContext ctx, final Object caller, final Object[] sources) throws FrameworkException {
    if (sources == null || sources != null && sources.length != 3) {
        logParameterError(caller, sources, ctx.isJavaScriptContext());
        return usage(ctx.isJavaScriptContext());
    }
    try {
        if (!(arrayHasLengthAndAllElementsNotNull(sources, 3) && sources[2] instanceof GraphObject)) {
            return null;
        }
        final Class type = StructrApp.getConfiguration().getNodeEntityClass("MailTemplate");
        final PropertyKey<String> localeKey = StructrApp.key(type, "locale");
        final PropertyKey<String> textKey = StructrApp.key(type, "text");
        final App app = StructrApp.getInstance(ctx.getSecurityContext());
        final String name = sources[0].toString();
        final String locale = sources[1].toString();
        final GraphObject template = app.nodeQuery(type).andName(name).and(localeKey, locale).getFirst();
        final GraphObject templateInstance = (GraphObject) sources[2];
        if (template != null) {
            final String text = template.getProperty(textKey);
            if (text != null) {
                // recursive replacement call, be careful here
                return Scripting.replaceVariables(ctx, templateInstance, text);
            }
        } else {
            logger.warn("No MailTemplate found for parameters: {}", getParametersAsString(sources));
        }
    } catch (final IllegalArgumentException e) {
        logParameterError(caller, sources, ctx.isJavaScriptContext());
        return usage(ctx.isJavaScriptContext());
    }
    return "";
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) GraphObject(org.structr.core.GraphObject)

Aggregations

GraphObject (org.structr.core.GraphObject)151 FrameworkException (org.structr.common.error.FrameworkException)58 PropertyKey (org.structr.core.property.PropertyKey)39 LinkedList (java.util.LinkedList)35 SecurityContext (org.structr.common.SecurityContext)25 App (org.structr.core.app.App)25 StructrApp (org.structr.core.app.StructrApp)24 Tx (org.structr.core.graph.Tx)23 List (java.util.List)22 PropertyConverter (org.structr.core.converter.PropertyConverter)22 AbstractNode (org.structr.core.entity.AbstractNode)18 GraphObjectMap (org.structr.core.GraphObjectMap)17 NodeInterface (org.structr.core.graph.NodeInterface)17 LinkedHashSet (java.util.LinkedHashSet)15 PropertyMap (org.structr.core.property.PropertyMap)13 Map (java.util.Map)12 RestMethodResult (org.structr.rest.RestMethodResult)11 ConfigurationProvider (org.structr.schema.ConfigurationProvider)10 Result (org.structr.core.Result)9 ArrayList (java.util.ArrayList)8