Search in sources :

Example 31 with GraphObjectMap

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

the class FulltextIndexerModule method getContextObject.

@Override
public GraphObjectMap getContextObject(final String searchTerm, final String text, final int contextLength) {
    final GraphObjectMap contextObject = new GraphObjectMap();
    final Set<String> contextValues = new LinkedHashSet<>();
    final String[] searchParts = searchTerm.split("[\\s,;]+");
    final GenericProperty contextKey = new GenericProperty("context");
    for (final String searchString : searchParts) {
        final String lowerCaseSearchString = searchString.toLowerCase();
        final String lowerCaseText = text.toLowerCase();
        final StringBuilder wordBuffer = new StringBuilder();
        final StringBuilder lineBuffer = new StringBuilder();
        final int textLength = text.length();
        /*
				 * we take an average word length of 8 characters, multiply
				 * it by the desired prefix and suffix word count, add 20%
				 * and try to extract up to prefixLength words.
			 */
        // modify these parameters to tune prefix and suffix word extraction
        // loop variables
        int newlineCount = 0;
        // wordCount starts at 1 because we include the matching word
        int wordCount = 0;
        int pos = -1;
        do {
            // find next occurrence
            pos = lowerCaseText.indexOf(lowerCaseSearchString, pos + 1);
            if (pos > 0) {
                lineBuffer.setLength(0);
                wordBuffer.setLength(0);
                wordCount = 0;
                newlineCount = 0;
                // fetch context words before search hit
                for (int i = pos; i >= 0; i--) {
                    final char c = text.charAt(i);
                    if (!Character.isAlphabetic(c) && !Character.isDigit(c) && !FulltextTokenizer.SpecialChars.contains(c)) {
                        wordCount += flushWordBuffer(lineBuffer, wordBuffer, true);
                        // store character in buffer
                        wordBuffer.insert(0, c);
                        if (c == '\n') {
                            // increase newline count
                            newlineCount++;
                        } else {
                            // reset newline count
                            newlineCount = 0;
                        }
                        // paragraph boundary reached
                        if (newlineCount > 1) {
                            break;
                        }
                        // stop if we collected half of the desired word count
                        if (wordCount > contextLength / 2) {
                            break;
                        }
                    } else {
                        // store character in buffer
                        wordBuffer.insert(0, c);
                        // reset newline count
                        newlineCount = 0;
                    }
                }
                wordCount += flushWordBuffer(lineBuffer, wordBuffer, true);
                wordBuffer.setLength(0);
                // fetch context words after search hit
                for (int i = pos + 1; i < textLength; i++) {
                    final char c = text.charAt(i);
                    if (!Character.isAlphabetic(c) && !Character.isDigit(c) && !FulltextTokenizer.SpecialChars.contains(c)) {
                        wordCount += flushWordBuffer(lineBuffer, wordBuffer, false);
                        // store character in buffer
                        wordBuffer.append(c);
                        if (c == '\n') {
                            // increase newline count
                            newlineCount++;
                        } else {
                            // reset newline count
                            newlineCount = 0;
                        }
                        // paragraph boundary reached
                        if (newlineCount > 1) {
                            break;
                        }
                        // stop if we collected enough words
                        if (wordCount > contextLength) {
                            break;
                        }
                    } else {
                        // store character in buffer
                        wordBuffer.append(c);
                        // reset newline count
                        newlineCount = 0;
                    }
                }
                wordCount += flushWordBuffer(lineBuffer, wordBuffer, false);
                // replace single newlines with space
                contextValues.add(lineBuffer.toString().trim());
            }
        } while (pos >= 0);
    }
    contextObject.put(contextKey, contextValues);
    return contextObject;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) GraphObjectMap(org.structr.core.GraphObjectMap) GenericProperty(org.structr.core.property.GenericProperty)

Example 32 with GraphObjectMap

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

the class WebappDataCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) {
    final Map<String, Object> data = webSocketData.getNodeData();
    final String category = (String) data.get("category");
    final String mode = (String) data.get("mode");
    final String name = (String) data.get("name");
    if (mode != null) {
        final List<GraphObject> result = new LinkedList<>();
        switch(mode) {
            case "list":
                final List<String> values = WebappDataCommand.listValues(category);
                if (values != null) {
                    final GraphObjectMap container = new GraphObjectMap();
                    container.put(namesProperty, values);
                    result.add(container);
                    webSocketData.setResult(result);
                    webSocketData.setRawResultCount(1);
                    getWebSocket().send(webSocketData, true);
                }
                break;
            case "get":
                try {
                    final String content = new String(Files.readAllBytes(locateFile(category, name).toPath()));
                    getWebSocket().send(MessageBuilder.finished().callback(callback).data("value", content).build(), true);
                } catch (IOException | FrameworkException ex) {
                    logger.error("", ex);
                }
                break;
            case "add":
                final String positions = (String) data.get("value");
                try {
                    final File layoutFile = locateFile(category, name);
                    if (layoutFile.exists()) {
                        getWebSocket().send(MessageBuilder.status().code(422).message("Category/name combination already exists!").build(), true);
                    } else {
                        createValue(category, name, positions);
                    }
                    getWebSocket().send(MessageBuilder.finished().callback(callback).build(), true);
                } catch (FrameworkException ex) {
                    logger.error("", ex);
                }
                break;
            case "delete":
                try {
                    deleteValue(category, name);
                    getWebSocket().send(MessageBuilder.finished().callback(callback).build(), true);
                } catch (FrameworkException ex) {
                    logger.error("", ex);
                }
                break;
            default:
                getWebSocket().send(MessageBuilder.status().code(422).message("Mode must be one of list, get, add or delete.").build(), true);
        }
    } else {
        getWebSocket().send(MessageBuilder.status().code(422).message("Mode must be one of list, get, add or delete.").build(), true);
    }
}
Also used : FrameworkException(org.structr.common.error.FrameworkException) GraphObjectMap(org.structr.core.GraphObjectMap) GraphObject(org.structr.core.GraphObject) IOException(java.io.IOException) GraphObject(org.structr.core.GraphObject) File(java.io.File) LinkedList(java.util.LinkedList)

Example 33 with GraphObjectMap

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

the class ListSchemaPropertiesCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) {
    final String view = (String) webSocketData.getNodeData().get("view");
    final String id = webSocketData.getId();
    final List<GraphObject> result = new LinkedList();
    if (view != null) {
        if (id != null) {
            AbstractNode schemaObject = getNode(id);
            if (schemaObject != null) {
                final ConfigurationProvider config = StructrApp.getConfiguration();
                String typeName = schemaObject.getProperty(AbstractNode.name);
                if (typeName == null && schemaObject instanceof SchemaRelationshipNode) {
                    typeName = ((SchemaRelationshipNode) schemaObject).getClassName();
                }
                Class type = config.getNodeEntityClass(typeName);
                if (type == null || GenericNode.class.equals(type)) {
                    type = config.getRelationshipEntityClass(typeName);
                }
                if (type != null) {
                    final Set<PropertyKey> allProperties = config.getPropertySet(type, PropertyView.All);
                    final Set<PropertyKey> viewProperties = config.getPropertySet(type, view);
                    final Set<PropertyKey> parentProperties = config.getPropertySet(type.getSuperclass(), view);
                    for (final PropertyKey key : allProperties) {
                        final String declaringClass = key.getDeclaringClass() != null ? key.getDeclaringClass().getSimpleName() : "GraphObject";
                        final String propertyName = key.jsonName();
                        final GraphObjectMap property = new GraphObjectMap();
                        final Class valueType = key.valueType();
                        String valueTypeName = "Unknown";
                        boolean _isDisabled = false;
                        if (valueType != null) {
                            valueTypeName = valueType.getSimpleName();
                        }
                        // (since it has to be configured there instead of locally)
                        if (parentProperties.contains(key)) {
                            _isDisabled = true;
                        }
                        property.put(AbstractNode.name, propertyName);
                        property.put(isSelected, viewProperties.contains(key));
                        property.put(isDisabled, _isDisabled);
                        property.put(SchemaProperty.propertyType, valueTypeName);
                        property.put(SchemaProperty.notNull, key.isNotNull());
                        property.put(SchemaProperty.unique, key.isUnique());
                        property.put(SchemaProperty.isDynamic, key.isDynamic());
                        property.put(SchemaProperty.declaringClass, declaringClass);
                        // store in result
                        result.add(property);
                    }
                } else {
                    getWebSocket().send(MessageBuilder.status().code(404).message("Type " + typeName + " not found.").build(), true);
                }
            } else {
                getWebSocket().send(MessageBuilder.status().code(404).message("Schema node with ID " + id + " not found.").build(), true);
            }
        } else {
            getWebSocket().send(MessageBuilder.status().code(422).message("LIST_SCHEMA_PROPERTIES needs an ID.").build(), true);
        }
    } else {
        getWebSocket().send(MessageBuilder.status().code(422).message("LIST_SCHEMA_PROPERTIES needs a view name in nodeData.").build(), true);
    }
    webSocketData.setView(PropertyView.Ui);
    webSocketData.setResult(result);
    webSocketData.setRawResultCount(1);
    // send only over local connection
    getWebSocket().send(webSocketData, true);
}
Also used : AbstractNode(org.structr.core.entity.AbstractNode) ConfigurationProvider(org.structr.schema.ConfigurationProvider) GenericNode(org.structr.core.entity.GenericNode) GraphObject(org.structr.core.GraphObject) SchemaRelationshipNode(org.structr.core.entity.SchemaRelationshipNode) GraphObjectMap(org.structr.core.GraphObjectMap) PropertyKey(org.structr.core.property.PropertyKey)

Example 34 with GraphObjectMap

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

the class CypherQueryCommand method execute.

public List<GraphObject> execute(String query, Map<String, Object> parameters, boolean includeHiddenAndDeleted, boolean publicOnly) throws FrameworkException {
    DatabaseService graphDb = (DatabaseService) arguments.get("graphDb");
    RelationshipFactory relFactory = new RelationshipFactory(securityContext);
    NodeFactory nodeFactory = new NodeFactory(securityContext);
    List<GraphObject> resultList = new LinkedList<>();
    // graphdb can be null..
    if (graphDb != null) {
        try (final NativeResult result = graphDb.execute(query, parameters != null ? parameters : Collections.emptyMap())) {
            while (result.hasNext()) {
                final Map<String, Object> row = result.next();
                for (Entry<String, Object> entry : row.entrySet()) {
                    String key = entry.getKey();
                    Object value = entry.getValue();
                    final Object obj = handleObject(nodeFactory, relFactory, key, value, includeHiddenAndDeleted, publicOnly, 0);
                    if (obj != null) {
                        if (obj instanceof GraphObject) {
                            resultList.add((GraphObject) obj);
                        } else if (obj instanceof Collection) {
                            final List<Object> nonGraphObjectResult = new LinkedList<>();
                            for (final Object item : ((Collection) obj)) {
                                if (item instanceof GraphObject) {
                                    resultList.add((GraphObject) item);
                                } else {
                                    nonGraphObjectResult.add(item);
                                }
                            }
                            if (!nonGraphObjectResult.isEmpty()) {
                                // Wrap non-graph-objects in simple list
                                final GraphObjectMap graphObject = new GraphObjectMap();
                                graphObject.setProperty(new GenericProperty(key), nonGraphObjectResult);
                                resultList.add(graphObject);
                            }
                        } else {
                            logger.warn("Unable to handle Cypher query result object of type {}, ignoring.", obj.getClass().getName());
                        }
                    }
                }
            }
        }
    }
    return resultList;
}
Also used : NativeResult(org.structr.api.NativeResult) DatabaseService(org.structr.api.DatabaseService) GraphObject(org.structr.core.GraphObject) LinkedList(java.util.LinkedList) GraphObjectMap(org.structr.core.GraphObjectMap) GenericProperty(org.structr.core.property.GenericProperty) Collection(java.util.Collection) GraphObject(org.structr.core.GraphObject) List(java.util.List) LinkedList(java.util.LinkedList)

Example 35 with GraphObjectMap

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

the class ListRemoteSyncablesCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) {
    final Map<String, Object> properties = webSocketData.getNodeData();
    final String username = (String) properties.get("username");
    final String password = (String) properties.get("password");
    final String host = (String) properties.get("host");
    final String key = (String) properties.get("key");
    final String type = (String) properties.get("type");
    final Long port = (Long) properties.get("port");
    if (host != null && port != null && username != null && password != null && key != null) {
        final App app = StructrApp.getInstance();
        try (final Tx tx = app.tx()) {
            final StructrWebSocket webSocket = getWebSocket();
            final List<SyncableInfo> syncables = CloudService.doRemote(webSocket.getSecurityContext(), new SingleTransmission<>(new ListSyncables(type)), new HostInfo(username, password, host, port.intValue()), new WebsocketProgressListener(getWebSocket(), key, callback));
            if (syncables != null) {
                final List<GraphObject> result = new LinkedList<>();
                for (final SyncableInfo info : syncables) {
                    final GraphObjectMap map = new GraphObjectMap();
                    map.put(GraphObject.id, info.getId());
                    map.put(NodeInterface.name, info.getName());
                    map.put(File.size, info.getSize());
                    map.put(GraphObject.type, info.getType());
                    map.put(GraphObject.visibleToPublicUsers, info.isVisibleToPublicUsers());
                    map.put(GraphObject.visibleToAuthenticatedUsers, info.isVisibleToAuthenticatedUsers());
                    map.put(GraphObject.lastModifiedDate, info.getLastModified());
                    // check for existance
                    map.put(isSynchronized, isSynchronized(info));
                    result.add(map);
                }
                webSocketData.setResult(result);
                webSocket.send(webSocketData, true);
            }
            tx.success();
        } catch (FrameworkException fex) {
            getWebSocket().send(MessageBuilder.status().code(400).message(fex.getMessage()).build(), true);
        }
    } else {
        getWebSocket().send(MessageBuilder.status().code(400).message("The PULL command needs sourceId, username, password, host, port and key!").build(), true);
    }
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) ListSyncables(org.structr.cloud.message.ListSyncables) StructrWebSocket(org.structr.websocket.StructrWebSocket) SyncableInfo(org.structr.cloud.message.SyncableInfo) GraphObject(org.structr.core.GraphObject) LinkedList(java.util.LinkedList) GraphObjectMap(org.structr.core.GraphObjectMap) GraphObject(org.structr.core.GraphObject) WebsocketProgressListener(org.structr.cloud.WebsocketProgressListener) HostInfo(org.structr.cloud.HostInfo)

Aggregations

GraphObjectMap (org.structr.core.GraphObjectMap)60 LinkedList (java.util.LinkedList)27 GraphObject (org.structr.core.GraphObject)24 Map (java.util.Map)18 FrameworkException (org.structr.common.error.FrameworkException)16 StringProperty (org.structr.core.property.StringProperty)15 GenericProperty (org.structr.core.property.GenericProperty)13 PropertyKey (org.structr.core.property.PropertyKey)12 List (java.util.List)11 Result (org.structr.core.Result)10 SecurityContext (org.structr.common.SecurityContext)8 IntProperty (org.structr.core.property.IntProperty)8 RestMethodResult (org.structr.rest.RestMethodResult)8 ArrayList (java.util.ArrayList)6 Collection (java.util.Collection)6 Test (org.junit.Test)6 ConfigurationProvider (org.structr.schema.ConfigurationProvider)6 HashMap (java.util.HashMap)5 LinkedHashSet (java.util.LinkedHashSet)5 Tx (org.structr.core.graph.Tx)5