Search in sources :

Example 1 with StaticValue

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

the class BatchExpression method evaluate.

@Override
public Object evaluate(final ActionContext ctx, final GraphObject entity) throws FrameworkException, UnlicensedException {
    if (batchExpression == null || sizeExpression == null) {
        return ERROR_MESSAGE_SLICE;
    }
    final Object value = sizeExpression.evaluate(ctx, entity);
    if (value != null && value instanceof Number) {
        // store batch size for children to use
        this.batchSize = ((Number) value).intValue();
        // initialize holders to store results from worker thread (must be final)
        final StaticValue<FrameworkException> exception = new StaticValue<>(null);
        final StaticValue result = new StaticValue(null);
        final Thread workerThread = new Thread(() -> {
            try {
                result.set(null, batchExpression.evaluate(ctx, entity));
            } catch (FrameworkException fex) {
                exception.set(null, fex);
            }
        });
        workerThread.start();
        try {
            workerThread.join();
        } catch (Throwable t) {
            t.printStackTrace();
        }
        if (exception.get(null) != null) {
            throw exception.get(null);
        }
        // result holder
        return result.get(null);
    } else {
        throw new FrameworkException(422, "Error in batch(): invalid batch size, expecting number.");
    }
}
Also used : FrameworkException(org.structr.common.error.FrameworkException) StaticValue(org.structr.core.StaticValue) GraphObject(org.structr.core.GraphObject)

Example 2 with StaticValue

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

the class WrappedRestCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) throws FrameworkException {
    final Map<String, Object> nodeData = webSocketData.getNodeData();
    final String method = (String) nodeData.get("method");
    if (method == null || !(method.equals("POST") || method.equals("PUT"))) {
        logger.warn("Method not supported: {}", method);
        getWebSocket().send(MessageBuilder.wrappedRest().code(422).message("Method not supported: " + method).build(), true);
        return;
    }
    ResourceProvider resourceProvider;
    try {
        resourceProvider = UiResourceProvider.class.newInstance();
    } catch (Throwable t) {
        logger.error("Couldn't establish a resource provider", t);
        getWebSocket().send(MessageBuilder.wrappedRest().code(422).message("Couldn't establish a resource provider").build(), true);
        return;
    }
    final Map<Pattern, Class<? extends Resource>> resourceMap = new LinkedHashMap<>();
    resourceMap.putAll(resourceProvider.getResources());
    final StructrWebSocket socket = this.getWebSocket();
    final String url = (String) nodeData.get("url");
    // mimic HTTP request
    final HttpServletRequest wrappedRequest = new HttpServletRequestWrapper(socket.getRequest()) {

        @Override
        public Enumeration<String> getParameterNames() {
            return new IteratorEnumeration(getParameterMap().keySet().iterator());
        }

        @Override
        public String getParameter(String key) {
            String[] p = getParameterMap().get(key);
            return p != null ? p[0] : null;
        }

        @Override
        public Map<String, String[]> getParameterMap() {
            String[] parts = StringUtils.split(getQueryString(), "&");
            Map<String, String[]> parameterMap = new HashMap();
            for (String p : parts) {
                String[] kv = StringUtils.split(p, "=");
                if (kv.length > 1) {
                    parameterMap.put(kv[0], new String[] { kv[1] });
                }
            }
            return parameterMap;
        }

        @Override
        public String getQueryString() {
            return StringUtils.substringAfter(url, "?");
        }

        @Override
        public String getPathInfo() {
            return StringUtils.substringBefore(url, "?");
        }

        @Override
        public StringBuffer getRequestURL() {
            return new StringBuffer(url);
        }
    };
    Resource resource;
    final StaticValue fakePropertyView = new StaticValue(PropertyView.Public);
    try {
        resource = ResourceHelper.applyViewTransformation(wrappedRequest, socket.getSecurityContext(), ResourceHelper.optimizeNestedResourceChain(socket.getSecurityContext(), wrappedRequest, resourceMap, fakePropertyView), fakePropertyView);
    } catch (IllegalPathException | NotFoundException e) {
        logger.warn("Illegal path for REST query");
        getWebSocket().send(MessageBuilder.wrappedRest().code(422).message("Illegal path for REST query").build(), true);
        return;
    }
    final String data = (String) nodeData.get("data");
    final Gson gson = new GsonBuilder().create();
    final Map<String, Object> jsonData = gson.fromJson(data, Map.class);
    RestMethodResult result = null;
    switch(method) {
        case "PUT":
            // we want to update data
            result = resource.doPut(jsonData);
            break;
        case "POST":
            // we either want to create data or call a method on an object
            result = resource.doPost(jsonData);
            break;
    }
    // right now we do not send messages
    if (result != null) {
    // getWebSocket().send(MessageBuilder.wrappedRest().code(result.getResponseCode()).message(result.jsonMessage()).build(), true);
    }
}
Also used : IllegalPathException(org.structr.rest.exception.IllegalPathException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) StructrWebSocket(org.structr.websocket.StructrWebSocket) NotFoundException(org.structr.rest.exception.NotFoundException) Gson(com.google.gson.Gson) LinkedHashMap(java.util.LinkedHashMap) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) ResourceProvider(org.structr.rest.ResourceProvider) UiResourceProvider(org.structr.web.common.UiResourceProvider) Pattern(java.util.regex.Pattern) IteratorEnumeration(org.apache.commons.collections.iterators.IteratorEnumeration) GsonBuilder(com.google.gson.GsonBuilder) Resource(org.structr.rest.resource.Resource) StaticValue(org.structr.core.StaticValue) UiResourceProvider(org.structr.web.common.UiResourceProvider) RestMethodResult(org.structr.rest.RestMethodResult)

Example 3 with StaticValue

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

the class SetPermissionCommand method processMessage.

// ~--- methods --------------------------------------------------------
@Override
public void processMessage(final WebSocketMessage webSocketData) {
    AbstractNode obj = getNode(webSocketData.getId());
    boolean rec = (Boolean) webSocketData.getNodeData().get("recursive");
    String principalId = (String) webSocketData.getNodeData().get("principalId");
    String permission = (String) webSocketData.getNodeData().get("permission");
    String action = (String) webSocketData.getNodeData().get("action");
    if (principalId == null) {
        logger.error("This command needs a principalId");
        getWebSocket().send(MessageBuilder.status().code(400).build(), true);
    }
    Principal principal = (Principal) getNode(principalId);
    if (principal == null) {
        logger.error("No principal found with id {}", new Object[] { principalId });
        getWebSocket().send(MessageBuilder.status().code(400).build(), true);
    }
    webSocketData.getNodeData().remove("recursive");
    if (obj != null) {
        final App app = StructrApp.getInstance(getWebSocket().getSecurityContext());
        try (final Tx nestedTx = app.tx()) {
            if (!((AbstractNode) obj).isGranted(Permission.accessControl, getWebSocket().getSecurityContext())) {
                logger.warn("No access control permission for {} on {}", new Object[] { getWebSocket().getCurrentUser().toString(), obj.toString() });
                getWebSocket().send(MessageBuilder.status().message("No access control permission").code(400).build(), true);
                nestedTx.success();
                return;
            }
            nestedTx.success();
        } catch (FrameworkException ex) {
            logger.warn("", ex);
        }
        try {
            final Value<Tx> value = new StaticValue<>(null);
            setPermission(value, app, obj, principal, action, Permissions.valueOf(permission), rec);
            // commit and close transaction
            final Tx tx = value.get(null);
            if (tx != null) {
                tx.success();
                tx.close();
                value.set(null, null);
            }
            webSocketData.setResult(Arrays.asList(principal));
            // send only over local connection (no broadcast)
            getWebSocket().send(webSocketData, true);
        } catch (FrameworkException ex) {
            logger.error("Unable to set permissions: {}", ((FrameworkException) ex).toString());
            getWebSocket().send(MessageBuilder.status().code(400).build(), true);
        }
    } else {
        logger.warn("Graph object with uuid {} not found.", webSocketData.getId());
        getWebSocket().send(MessageBuilder.status().code(404).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) AbstractNode(org.structr.core.entity.AbstractNode) StaticValue(org.structr.core.StaticValue) Principal(org.structr.core.entity.Principal)

Example 4 with StaticValue

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

the class ToGraphObjectFunction method apply.

@Override
public Object apply(final ActionContext ctx, final Object caller, final Object[] sources) {
    if (sources != null && sources.length >= 1 && sources.length <= 3) {
        try {
            final SecurityContext securityContext = ctx.getSecurityContext();
            final Value<String> view = new StaticValue<>("public");
            if (sources.length > 1) {
                view.set(securityContext, sources[1].toString());
            }
            int outputDepth = 3;
            if (sources.length > 2 && sources[2] instanceof Number) {
                outputDepth = ((Number) sources[2]).intValue();
            }
            final Object converted = UiFunction.toGraphObject(sources[0], outputDepth);
            if (converted != null) {
                return converted;
            }
        } catch (Throwable t) {
            logException(caller, t, sources);
        }
        return "";
    } else {
        logParameterError(caller, sources, ctx.isJavaScriptContext());
    }
    return usage(ctx.isJavaScriptContext());
}
Also used : SecurityContext(org.structr.common.SecurityContext) StaticValue(org.structr.core.StaticValue)

Example 5 with StaticValue

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

the class ToJsonFunction method apply.

@Override
public Object apply(final ActionContext ctx, final Object caller, final Object[] sources) {
    if (sources != null && sources.length >= 1 && sources.length <= 3) {
        try {
            final SecurityContext securityContext = ctx.getSecurityContext();
            final Value<String> view = new StaticValue<>("public");
            if (sources.length > 1) {
                view.set(securityContext, sources[1].toString());
            }
            int outputDepth = 3;
            if (sources.length > 2 && sources[2] instanceof Number) {
                outputDepth = ((Number) sources[2]).intValue();
            }
            final StreamingJsonWriter jsonStreamer = new StreamingJsonWriter(view, true, outputDepth);
            final StringWriter writer = new StringWriter();
            if (sources[0] instanceof GraphObject) {
                jsonStreamer.streamSingle(securityContext, writer, (GraphObject) sources[0]);
            } else if (sources[0] instanceof List) {
                final List list = (List) sources[0];
                jsonStreamer.stream(securityContext, writer, new Result(list, list.size(), true, false), null);
            } else if (sources[0] instanceof Map) {
                final GraphObjectMap map = new GraphObjectMap();
                this.recursivelyConvertMapToGraphObjectMap(map, (Map) sources[0], outputDepth);
                jsonStreamer.stream(securityContext, writer, new Result(map, false), null);
            }
            return writer.getBuffer().toString();
        } catch (Throwable t) {
            logException(caller, t, sources);
        }
        return "";
    } else {
        logParameterError(caller, sources, ctx.isJavaScriptContext());
    }
    return usage(ctx.isJavaScriptContext());
}
Also used : StaticValue(org.structr.core.StaticValue) GraphObject(org.structr.core.GraphObject) Result(org.structr.core.Result) StringWriter(java.io.StringWriter) StreamingJsonWriter(org.structr.rest.serialization.StreamingJsonWriter) GraphObjectMap(org.structr.core.GraphObjectMap) SecurityContext(org.structr.common.SecurityContext) List(java.util.List) Map(java.util.Map) GraphObjectMap(org.structr.core.GraphObjectMap)

Aggregations

StaticValue (org.structr.core.StaticValue)5 SecurityContext (org.structr.common.SecurityContext)2 FrameworkException (org.structr.common.error.FrameworkException)2 GraphObject (org.structr.core.GraphObject)2 Gson (com.google.gson.Gson)1 GsonBuilder (com.google.gson.GsonBuilder)1 StringWriter (java.io.StringWriter)1 HashMap (java.util.HashMap)1 LinkedHashMap (java.util.LinkedHashMap)1 List (java.util.List)1 Map (java.util.Map)1 Pattern (java.util.regex.Pattern)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletRequestWrapper (javax.servlet.http.HttpServletRequestWrapper)1 IteratorEnumeration (org.apache.commons.collections.iterators.IteratorEnumeration)1 GraphObjectMap (org.structr.core.GraphObjectMap)1 Result (org.structr.core.Result)1 App (org.structr.core.app.App)1 StructrApp (org.structr.core.app.StructrApp)1 AbstractNode (org.structr.core.entity.AbstractNode)1