Search in sources :

Example 61 with Result

use of org.structr.core.Result 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 62 with Result

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

the class SchemaDeserializationStrategy method deserialize.

private T deserialize(final SecurityContext securityContext, final Class<T> type, final PropertyMap attributes, final Object context) throws FrameworkException {
    final App app = StructrApp.getInstance(securityContext);
    if (attributes != null) {
        Result<T> result = Result.EMPTY_RESULT;
        // remove attributes that do not belong to the target node
        final PropertyMap foreignProperties = new PropertyMap();
        for (final Iterator<PropertyKey> it = attributes.keySet().iterator(); it.hasNext(); ) {
            final PropertyKey key = it.next();
            if (foreignPropertyKeys.contains(key)) {
                // move entry to foreign map and remove from attributes
                foreignProperties.put(key, attributes.get(key));
                it.remove();
            }
        }
        // retrieve and remove source type name (needed for foreign properties)
        final String sourceTypeName = (String) ((Map) context).get("name");
        // Check if properties contain the UUID attribute
        if (attributes.containsKey(GraphObject.id)) {
            result = new Result(app.getNodeById(attributes.get(GraphObject.id)), false);
        } else {
            boolean attributesComplete = true;
            // Check if all property keys of the PropertySetNotion are present
            for (PropertyKey key : identifyingPropertyKeys) {
                attributesComplete &= attributes.containsKey(key);
            }
            if (attributesComplete) {
                // collect only those key-value pairs that are needed to
                // identify the correct schema node (do not use related
                // attributes to search for nodes)
                final PropertyMap identifyingKeyValues = new PropertyMap();
                for (final PropertyKey key : identifyingPropertyKeys) {
                    identifyingKeyValues.put(key, attributes.get(key));
                }
                result = app.nodeQuery(type).and(identifyingKeyValues).getResult();
            }
        }
        // test set notion attributes for relationship creation
        Map<String, PropertyMap> notionPropertyMap = (Map<String, PropertyMap>) securityContext.getAttribute("notionProperties");
        if (notionPropertyMap == null) {
            notionPropertyMap = new HashMap<>();
            securityContext.setAttribute("notionProperties", notionPropertyMap);
        }
        // just check for existance
        String errorMessage = null;
        final int size = result.size();
        switch(size) {
            case 0:
                if (createIfNotExisting) {
                    // create node and return it
                    T newNode = app.create(type, attributes);
                    if (newNode != null) {
                        notionPropertyMap.put(getStorageKey(relationProperty, newNode, sourceTypeName), foreignProperties);
                        return newNode;
                    }
                }
                errorMessage = "No node found for the given properties and auto-creation not enabled";
                break;
            case 1:
                final T typedResult = getTypedResult(result, type);
                notionPropertyMap.put(getStorageKey(relationProperty, typedResult, sourceTypeName), foreignProperties);
                // set properties on existing node (relationships)
                for (final Entry<PropertyKey, Object> entry : attributes.entrySet()) {
                    typedResult.setProperty(entry.getKey(), entry.getValue());
                }
                return typedResult;
            default:
                errorMessage = "Found " + size + " nodes for given type and properties, property set is ambiguous";
                logger.error("Found {} nodes for given type and properties, property set is ambiguous!\n" + "This is often due to wrong modeling, or you should consider creating a uniquness constraint for " + type.getName(), size);
                break;
        }
        throw new FrameworkException(404, errorMessage, new PropertiesNotFoundToken(type.getSimpleName(), AbstractNode.base, attributes));
    }
    return null;
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) FrameworkException(org.structr.common.error.FrameworkException) PropertiesNotFoundToken(org.structr.common.error.PropertiesNotFoundToken) Result(org.structr.core.Result) PropertyMap(org.structr.core.property.PropertyMap) GraphObject(org.structr.core.GraphObject) PropertyMap(org.structr.core.property.PropertyMap) PropertyKey(org.structr.core.property.PropertyKey)

Example 63 with Result

use of org.structr.core.Result 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 64 with Result

use of org.structr.core.Result 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)

Example 65 with Result

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

the class HtmlServlet method findPossibleEntryPointsByUuid.

private List<Linkable> findPossibleEntryPointsByUuid(final SecurityContext securityContext, final HttpServletRequest request, final String uuid) throws FrameworkException {
    final List<Linkable> possibleEntryPoints = (List<Linkable>) request.getAttribute(POSSIBLE_ENTRY_POINTS_KEY);
    if (CollectionUtils.isNotEmpty(possibleEntryPoints)) {
        return possibleEntryPoints;
    }
    if (uuid.length() > 0) {
        logger.debug("Requested id: {}", uuid);
        final Query query = StructrApp.getInstance(securityContext).nodeQuery();
        query.and(GraphObject.id, uuid);
        query.and().orType(Page.class).orTypes(File.class);
        // Searching for pages needs super user context anyway
        Result results = query.getResult();
        logger.debug("{} results", results.size());
        request.setAttribute(POSSIBLE_ENTRY_POINTS_KEY, results.getResults());
        return (List<Linkable>) results.getResults();
    }
    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) Page(org.structr.web.entity.dom.Page) Result(org.structr.core.Result)

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