Search in sources :

Example 61 with GraphObject

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

the class PushNodesCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) {
    final Map<String, Object> properties = webSocketData.getNodeData();
    final String sourceId = webSocketData.getId();
    final Object recursiveSource = properties.get("recursive");
    final String username = (String) properties.get("username");
    final String password = (String) properties.get("password");
    final String host = (String) properties.get("host");
    final Long port = (Long) properties.get("port");
    final String key = (String) properties.get("key");
    if (sourceId != null && host != null && port != null && username != null && password != null && key != null) {
        final App app = StructrApp.getInstance();
        try (final Tx tx = app.tx()) {
            final GraphObject root = app.getNodeById(sourceId);
            if (root != null) {
                boolean recursive = false;
                if (recursiveSource != null) {
                    recursive = "true".equals(recursiveSource.toString());
                }
                CloudService.doRemote(webSocket.getSecurityContext(), new PushTransmission(root, recursive), new HostInfo(username, password, host, port.intValue()), new WebsocketProgressListener(getWebSocket(), key, callback));
            } else {
                getWebSocket().send(MessageBuilder.status().code(404).message("Entity with ID " + sourceId + " not found").build(), true);
            }
            tx.success();
        } catch (FrameworkException fex) {
            logger.warn("", fex);
            getWebSocket().send(MessageBuilder.status().code(400).message(fex.getMessage()).build(), true);
        }
    } else {
        getWebSocket().send(MessageBuilder.status().code(400).message("The PUSH command needs id, username, password, host, port and key!").build(), true);
    }
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) PushTransmission(org.structr.cloud.transmission.PushTransmission) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) GraphObject(org.structr.core.GraphObject) WebsocketProgressListener(org.structr.cloud.WebsocketProgressListener) GraphObject(org.structr.core.GraphObject) HostInfo(org.structr.cloud.HostInfo)

Example 62 with GraphObject

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

the class PullNodeRequestContainer method onRequest.

@Override
public void onRequest(CloudConnection serverConnection) throws IOException, FrameworkException {
    try {
        final App app = serverConnection.getApplicationContext();
        // try node first, then relationship
        GraphObject syncable = app.nodeQuery().and(GraphObject.id, rootNodeId).includeDeletedAndHidden().getFirst();
        if (syncable == null) {
            syncable = app.relationshipQuery().and(GraphObject.id, rootNodeId).includeDeletedAndHidden().getFirst();
        }
        if (syncable != null) {
            final ExportSet exportSet = ExportSet.getInstance(syncable, recursive);
            // collect export set
            numNodes = exportSet.getNodes().size();
            numRels = exportSet.getRelationships().size();
            key = NodeServiceCommand.getNextUuid();
            serverConnection.storeValue(key + "Nodes", new ArrayList<>(exportSet.getNodes()));
            serverConnection.storeValue(key + "Rels", new ArrayList<>(exportSet.getRelationships()));
            // send this back
            serverConnection.send(this);
        }
    } catch (FrameworkException fex) {
        logger.warn("", fex);
    }
}
Also used : App(org.structr.core.app.App) ExportSet(org.structr.cloud.ExportSet) FrameworkException(org.structr.common.error.FrameworkException) GraphObject(org.structr.core.GraphObject)

Example 63 with GraphObject

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

the class RDFItem method setProperty.

protected Object setProperty(final Class nodeType, final GraphObject instance, final String propertyName, final Object value) throws FrameworkException {
    final ConfigurationProvider config = StructrApp.getConfiguration();
    Object convertedValue = value;
    if (convertedValue != null) {
        final PropertyKey key = StructrApp.key(nodeType, propertyName);
        if (key != null) {
            final PropertyConverter inputConverter = key.inputConverter(SecurityContext.getSuperUserInstance());
            if (inputConverter != null) {
                convertedValue = inputConverter.convert(convertedValue);
            }
            if (convertedValue == null) {
                OWLParserv2.logger.println("Invalid converted value " + convertedValue + ", source was " + value);
            }
            return instance.setProperty(key, convertedValue);
        } else {
            System.out.println("Key " + propertyName + " not found on " + nodeType.getSimpleName());
        }
    }
    return null;
}
Also used : ConfigurationProvider(org.structr.schema.ConfigurationProvider) PropertyConverter(org.structr.core.converter.PropertyConverter) GraphObject(org.structr.core.GraphObject) PropertyKey(org.structr.core.property.PropertyKey)

Example 64 with GraphObject

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

the class UploadServlet method doPut.

@Override
protected void doPut(final HttpServletRequest request, final HttpServletResponse response) throws ServletException {
    try (final Tx tx = StructrApp.getInstance().tx(true, false, false)) {
        final String uuid = PathHelper.getName(request.getPathInfo());
        if (uuid == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getOutputStream().write("URL path doesn't end with UUID.\n".getBytes("UTF-8"));
            return;
        }
        Matcher matcher = threadLocalUUIDMatcher.get();
        matcher.reset(uuid);
        if (!matcher.matches()) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getOutputStream().write("ERROR (400): URL path doesn't end with UUID.\n".getBytes("UTF-8"));
            return;
        }
        final SecurityContext securityContext = getConfig().getAuthenticator().initializeAndExamineRequest(request, response);
        // Ensure access mode is frontend
        securityContext.setAccessMode(AccessMode.Frontend);
        request.setCharacterEncoding("UTF-8");
        // Important: Set character encoding before calling response.getWriter() !!, see Servlet Spec 5.4
        response.setCharacterEncoding("UTF-8");
        // don't continue on redirects
        if (response.getStatus() == 302) {
            return;
        }
        uploader.setFileSizeMax(MEGABYTE * Settings.UploadMaxFileSize.getValue());
        uploader.setSizeMax(MEGABYTE * Settings.UploadMaxRequestSize.getValue());
        FileItemIterator fileItemsIterator = uploader.getItemIterator(request);
        while (fileItemsIterator.hasNext()) {
            final FileItemStream fileItem = fileItemsIterator.next();
            try {
                final GraphObject node = StructrApp.getInstance().getNodeById(uuid);
                if (node == null) {
                    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                    response.getOutputStream().write("ERROR (404): File not found.\n".getBytes("UTF-8"));
                }
                if (node instanceof org.structr.web.entity.File) {
                    final File file = (File) node;
                    if (file.isGranted(Permission.write, securityContext)) {
                        try (final InputStream is = fileItem.openStream()) {
                            FileHelper.writeToFile(file, is);
                            file.increaseVersion();
                            // upload trigger
                            file.notifyUploadCompletion();
                        }
                    } else {
                        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                        response.getOutputStream().write("ERROR (403): Write access forbidden.\n".getBytes("UTF-8"));
                    }
                }
            } catch (IOException ex) {
                logger.warn("Could not write to file", ex);
            }
        }
        tx.success();
    } catch (FrameworkException | IOException | FileUploadException t) {
        logger.error("Exception while processing request", t);
        UiAuthenticator.writeInternalServerError(response);
    }
}
Also used : Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) Matcher(java.util.regex.Matcher) ThreadLocalMatcher(org.structr.common.ThreadLocalMatcher) InputStream(java.io.InputStream) IOException(java.io.IOException) GraphObject(org.structr.core.GraphObject) FileItemStream(org.apache.commons.fileupload.FileItemStream) SecurityContext(org.structr.common.SecurityContext) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) AbstractFile(org.structr.web.entity.AbstractFile) File(org.structr.web.entity.File) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 65 with GraphObject

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

the class WebSocketDataGSONAdapter method serialize.

// ~--- methods --------------------------------------------------------
@Override
public JsonElement serialize(WebSocketMessage src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject root = new JsonObject();
    JsonObject jsonNodeData = new JsonObject();
    JsonObject jsonRelData = new JsonObject();
    JsonArray removedProperties = new JsonArray();
    JsonArray modifiedProperties = new JsonArray();
    if (src.getCommand() != null) {
        root.add("command", new JsonPrimitive(src.getCommand()));
    }
    if (src.getId() != null) {
        root.add("id", new JsonPrimitive(src.getId()));
    }
    if (src.getPageId() != null) {
        root.add("pageId", new JsonPrimitive(src.getPageId()));
    }
    if (src.getMessage() != null) {
        root.add("message", new JsonPrimitive(src.getMessage()));
    }
    if (src.getJsonErrorObject() != null) {
        root.add("error", src.getJsonErrorObject());
    }
    if (src.getCode() != 0) {
        root.add("code", new JsonPrimitive(src.getCode()));
    }
    if (src.getSessionId() != null) {
        root.add("sessionId", new JsonPrimitive(src.getSessionId()));
    }
    if (src.getCallback() != null) {
        root.add("callback", new JsonPrimitive(src.getCallback()));
    }
    if (src.getButton() != null) {
        root.add("button", new JsonPrimitive(src.getButton()));
    }
    if (src.getParent() != null) {
        root.add("parent", new JsonPrimitive(src.getParent()));
    }
    if (src.getView() != null) {
        root.add("view", new JsonPrimitive(src.getView()));
    }
    if (src.getSortKey() != null) {
        root.add("sort", new JsonPrimitive(src.getSortKey()));
    }
    if (src.getSortOrder() != null) {
        root.add("order", new JsonPrimitive(src.getSortOrder()));
    }
    if (src.getPageSize() > 0) {
        root.add("pageSize", new JsonPrimitive(src.getPageSize()));
    }
    if (src.getPage() > 0) {
        root.add("page", new JsonPrimitive(src.getPage()));
    }
    JsonArray nodesWithChildren = new JsonArray();
    Set<String> nwc = src.getNodesWithChildren();
    if ((nwc != null) && !src.getNodesWithChildren().isEmpty()) {
        for (String nodeId : nwc) {
            nodesWithChildren.add(new JsonPrimitive(nodeId));
        }
        root.add("nodesWithChildren", nodesWithChildren);
    }
    // serialize session valid flag (output only)
    root.add("sessionValid", new JsonPrimitive(src.isSessionValid()));
    // UPDATE only, serialize only removed and modified properties and use the correct values
    if ((src.getGraphObject() != null)) {
        if (!src.getModifiedProperties().isEmpty()) {
            for (PropertyKey modifiedKey : src.getModifiedProperties()) {
                modifiedProperties.add(toJsonPrimitive(modifiedKey));
            }
            root.add("modifiedProperties", modifiedProperties);
        }
        if (!src.getRemovedProperties().isEmpty()) {
            for (PropertyKey removedKey : src.getRemovedProperties()) {
                removedProperties.add(toJsonPrimitive(removedKey));
            }
            root.add("removedProperties", removedProperties);
        }
    }
    // serialize node data
    if (src.getNodeData() != null) {
        for (Entry<String, Object> entry : src.getNodeData().entrySet()) {
            Object value = entry.getValue();
            String key = entry.getKey();
            if (value != null) {
                jsonNodeData.add(key, toJsonPrimitive(value));
            }
        }
        root.add("data", jsonNodeData);
    }
    // serialize relationship data
    if (src.getRelData() != null) {
        for (Entry<String, Object> entry : src.getRelData().entrySet()) {
            Object value = entry.getValue();
            String key = entry.getKey();
            if (value != null) {
                jsonRelData.add(key, toJsonPrimitive(value));
            }
        }
        root.add("relData", jsonRelData);
    }
    // serialize result list
    if (src.getResult() != null) {
        if ("GRAPHQL".equals(src.getCommand())) {
            try {
                if (src.getResult() != null && !src.getResult().isEmpty()) {
                    final GraphObject firstResultObject = src.getResult().get(0);
                    final SecurityContext securityContext = firstResultObject.getSecurityContext();
                    final StringWriter output = new StringWriter();
                    final String query = (String) src.getNodeData().get("query");
                    final Document doc = GraphQLRequest.parse(new Parser(), query);
                    final GraphQLWriter graphQLWriter = new GraphQLWriter(false);
                    graphQLWriter.stream(securityContext, output, new GraphQLRequest(securityContext, doc, query));
                    JsonElement graphQLResult = new JsonParser().parse(output.toString());
                    root.add("result", graphQLResult);
                } else {
                    root.add("result", new JsonArray());
                }
            } catch (IOException | FrameworkException ex) {
                logger.warn("Unable to set process GraphQL query", ex);
            }
        } else {
            if (src.getView() != null) {
                try {
                    propertyView.set(null, src.getView());
                } catch (FrameworkException fex) {
                    logger.warn("Unable to set property view", fex);
                }
            } else {
                try {
                    propertyView.set(null, PropertyView.Ui);
                } catch (FrameworkException fex) {
                    logger.warn("Unable to set property view", fex);
                }
            }
            JsonArray result = new JsonArray();
            for (GraphObject obj : src.getResult()) {
                result.add(graphObjectSerializer.serialize(obj, System.currentTimeMillis()));
            }
            root.add("result", result);
        }
        root.add("rawResultCount", toJsonPrimitive(src.getRawResultCount()));
    }
    return root;
}
Also used : FrameworkException(org.structr.common.error.FrameworkException) JsonPrimitive(com.google.gson.JsonPrimitive) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) GraphObject(org.structr.core.GraphObject) Document(graphql.language.Document) JsonParser(com.google.gson.JsonParser) Parser(graphql.parser.Parser) JsonArray(com.google.gson.JsonArray) GraphQLRequest(org.structr.core.graphql.GraphQLRequest) GraphQLWriter(org.structr.rest.serialization.GraphQLWriter) StringWriter(java.io.StringWriter) JsonElement(com.google.gson.JsonElement) SecurityContext(org.structr.common.SecurityContext) JsonObject(com.google.gson.JsonObject) GraphObject(org.structr.core.GraphObject) PropertyKey(org.structr.core.property.PropertyKey) JsonParser(com.google.gson.JsonParser)

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