Search in sources :

Example 26 with Result

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

the class SearchAndSortingTest method test11SearchByEmptyIntField.

@Test
public void test11SearchByEmptyIntField() {
    try {
        PropertyMap props = new PropertyMap();
        AbstractNode node = createTestNode(TestOne.class, props);
        try (final Tx tx = app.tx()) {
            Result result = app.nodeQuery(TestOne.class).and(TestOne.anInt, null).includeDeletedAndHidden().getResult();
            assertTrue(result.size() == 1);
            assertTrue(result.get(0).equals(node));
        }
    } catch (Throwable ex) {
        logger.warn("", ex);
        logger.error(ex.toString());
        fail("Unexpected exception");
    }
}
Also used : PropertyMap(org.structr.core.property.PropertyMap) Tx(org.structr.core.graph.Tx) AbstractNode(org.structr.core.entity.AbstractNode) TestOne(org.structr.core.entity.TestOne) Result(org.structr.core.Result) Test(org.junit.Test)

Example 27 with Result

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

the class CsvServlet method doGet.

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws UnsupportedEncodingException {
    Authenticator authenticator = null;
    Result result = null;
    Resource resource = null;
    try {
        // isolate request authentication in a transaction
        try (final Tx tx = StructrApp.getInstance().tx()) {
            authenticator = config.getAuthenticator();
            securityContext = authenticator.initializeAndExamineRequest(request, response);
            tx.success();
        }
        final App app = StructrApp.getInstance(securityContext);
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/csv; charset=utf-8");
        // set default value for property view
        propertyView.set(securityContext, defaultPropertyView);
        // evaluate constraints and measure query time
        double queryTimeStart = System.nanoTime();
        // isolate resource authentication
        try (final Tx tx = app.tx()) {
            resource = ResourceHelper.optimizeNestedResourceChain(securityContext, request, resourceMap, propertyView);
            authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(), propertyView.get(securityContext));
            tx.success();
        }
        try (final Tx tx = app.tx()) {
            String resourceSignature = resource.getResourceSignature();
            // let authenticator examine request again
            authenticator.checkResourceAccess(securityContext, request, resourceSignature, propertyView.get(securityContext));
            // add sorting & paging
            String pageSizeParameter = request.getParameter(JsonRestServlet.REQUEST_PARAMETER_PAGE_SIZE);
            String pageParameter = request.getParameter(JsonRestServlet.REQUEST_PARAMETER_PAGE_NUMBER);
            String sortOrder = request.getParameter(JsonRestServlet.REQUEST_PARAMETER_SORT_ORDER);
            String sortKeyName = request.getParameter(JsonRestServlet.REQUEST_PARAMETER_SORT_KEY);
            boolean sortDescending = (sortOrder != null && "desc".equals(sortOrder.toLowerCase()));
            int pageSize = Services.parseInt(pageSizeParameter, NodeFactory.DEFAULT_PAGE_SIZE);
            int page = Services.parseInt(pageParameter, NodeFactory.DEFAULT_PAGE);
            PropertyKey sortKey = null;
            // set sort key
            if (sortKeyName != null) {
                Class<? extends GraphObject> type = resource.getEntityClass();
                sortKey = StructrApp.getConfiguration().getPropertyKeyForDatabaseName(type, sortKeyName, false);
            }
            // Should line breaks be removed?
            removeLineBreaks = StringUtils.equals(request.getParameter(REMOVE_LINE_BREAK_PARAM), "1");
            // Should a leading BOM be written?
            writeBom = StringUtils.equals(request.getParameter(WRITE_BOM), "1");
            // do action
            result = resource.doGet(sortKey, sortDescending, pageSize, page);
            if (result != null) {
                result.setIsCollection(resource.isCollectionResource());
                result.setIsPrimitiveArray(resource.isPrimitiveArray());
                PagingHelper.addPagingParameter(result, pageSize, page);
                // timing..
                final double queryTimeEnd = System.nanoTime();
                // store property view that will be used to render the results
                result.setPropertyView(propertyView.get(securityContext));
                // allow resource to modify result set
                resource.postProcessResultSet(result);
                DecimalFormat decimalFormat = new DecimalFormat("0.000000000", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
                result.setQueryTime(decimalFormat.format((queryTimeEnd - queryTimeStart) / 1000000000.0));
                Writer writer = response.getWriter();
                if (writeBom) {
                    writeUtf8Bom(writer);
                }
                // gson.toJson(result, writer);
                writeCsv(result, writer, propertyView.get(securityContext));
                response.setStatus(HttpServletResponse.SC_OK);
                writer.flush();
                writer.close();
            } else {
                logger.warn("Result was null!");
                int code = HttpServletResponse.SC_NO_CONTENT;
                response.setStatus(code);
                Writer writer = response.getWriter();
                writer.flush();
                writer.close();
            }
            tx.success();
        }
    } catch (FrameworkException frameworkException) {
        // set status
        response.setStatus(frameworkException.getStatus());
    } catch (JsonSyntaxException jsex) {
        logger.warn("JsonSyntaxException in GET", jsex);
        int code = HttpServletResponse.SC_BAD_REQUEST;
        response.setStatus(code);
    } catch (JsonParseException jpex) {
        logger.warn("JsonParseException in GET", jpex);
        int code = HttpServletResponse.SC_BAD_REQUEST;
        response.setStatus(code);
    } catch (Throwable t) {
        logger.warn("Exception in GET", t);
        int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        response.setStatus(code);
    }
}
Also used : App(org.structr.core.app.App) StructrApp(org.structr.core.app.StructrApp) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) DecimalFormat(java.text.DecimalFormat) Resource(org.structr.rest.resource.Resource) JsonParseException(com.google.gson.JsonParseException) Result(org.structr.core.Result) RestMethodResult(org.structr.rest.RestMethodResult) JsonSyntaxException(com.google.gson.JsonSyntaxException) Authenticator(org.structr.core.auth.Authenticator) PropertyKey(org.structr.core.property.PropertyKey) Writer(java.io.Writer)

Example 28 with Result

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

the class JsonRestServlet method doGetOrHead.

private void doGetOrHead(final HttpServletRequest request, final HttpServletResponse response, final boolean returnContent) throws ServletException, IOException {
    SecurityContext securityContext = null;
    Authenticator authenticator = null;
    Result result = null;
    Resource resource = null;
    try {
        // first thing to do!
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        // isolate request authentication in a transaction
        try (final Tx tx = StructrApp.getInstance().tx()) {
            authenticator = config.getAuthenticator();
            securityContext = authenticator.initializeAndExamineRequest(request, response);
            tx.success();
        }
        final App app = StructrApp.getInstance(securityContext);
        // set default value for property view
        propertyView.set(securityContext, config.getDefaultPropertyView());
        // evaluate constraints and measure query time
        double queryTimeStart = System.nanoTime();
        // isolate resource authentication
        try (final Tx tx = app.tx()) {
            resource = ResourceHelper.applyViewTransformation(request, securityContext, ResourceHelper.optimizeNestedResourceChain(securityContext, request, resourceMap, propertyView), propertyView);
            authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(), propertyView.get(securityContext));
            tx.success();
        }
        // add sorting & paging
        String pageSizeParameter = request.getParameter(REQUEST_PARAMETER_PAGE_SIZE);
        String pageParameter = request.getParameter(REQUEST_PARAMETER_PAGE_NUMBER);
        String sortOrder = request.getParameter(REQUEST_PARAMETER_SORT_ORDER);
        String sortKeyName = request.getParameter(REQUEST_PARAMETER_SORT_KEY);
        String outputDepth = request.getParameter(REQUEST_PARAMTER_OUTPUT_DEPTH);
        boolean sortDescending = (sortOrder != null && "desc".equals(sortOrder.toLowerCase()));
        int pageSize = Services.parseInt(pageSizeParameter, NodeFactory.DEFAULT_PAGE_SIZE);
        int page = Services.parseInt(pageParameter, NodeFactory.DEFAULT_PAGE);
        int depth = Services.parseInt(outputDepth, config.getOutputNestingDepth());
        String baseUrl = request.getRequestURI();
        PropertyKey sortKey = null;
        // set sort key
        if (sortKeyName != null) {
            Class<? extends GraphObject> type = resource.getEntityClass();
            if (type == null) {
                // fallback to default implementation
                // if no type can be determined
                type = AbstractNode.class;
            }
            sortKey = StructrApp.getConfiguration().getPropertyKeyForDatabaseName(type, sortKeyName, false);
        }
        // isolate doGet
        boolean retry = true;
        while (retry) {
            try (final Tx tx = app.tx()) {
                result = resource.doGet(sortKey, sortDescending, pageSize, page);
                tx.success();
                retry = false;
            } catch (RetryException ddex) {
                retry = true;
            }
        }
        if (result == null) {
            throw new FrameworkException(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Unable to retrieve result, check database connection");
        }
        if (returnContent) {
            if (!(resource instanceof StaticRelationshipResource) && !result.isPrimitiveArray() && !result.isEmpty()) {
                result.setIsCollection(resource.isCollectionResource());
                result.setIsPrimitiveArray(resource.isPrimitiveArray());
            }
            PagingHelper.addPagingParameter(result, pageSize, page);
            // timing..
            double queryTimeEnd = System.nanoTime();
            // store property view that will be used to render the results
            result.setPropertyView(propertyView.get(securityContext));
            // allow resource to modify result set
            resource.postProcessResultSet(result);
            DecimalFormat decimalFormat = new DecimalFormat("0.000000000", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
            result.setQueryTime(decimalFormat.format((queryTimeEnd - queryTimeStart) / 1000000000.0));
            if (outputDepth != null) {
                result.setOutputNestingDepth(depth);
            }
            String accept = request.getHeader("Accept");
            if (accept != null && accept.contains("text/html")) {
                final StreamingHtmlWriter htmlStreamer = new StreamingHtmlWriter(this.propertyView, indentJson, depth);
                // isolate write output
                try (final Tx tx = app.tx()) {
                    // no trailing semicolon so we dont trip MimeTypes.getContentTypeWithoutCharset
                    response.setContentType("text/html; charset=utf-8");
                    final Writer writer = response.getWriter();
                    htmlStreamer.stream(securityContext, writer, result, baseUrl);
                    // useful newline
                    writer.append("\n");
                    tx.success();
                }
            } else {
                final StreamingJsonWriter jsonStreamer = new StreamingJsonWriter(this.propertyView, indentJson, depth);
                // isolate write output
                try (final Tx tx = app.tx()) {
                    // no trailing semicolon so we dont trip MimeTypes.getContentTypeWithoutCharset
                    response.setContentType("application/json; charset=utf-8");
                    final Writer writer = response.getWriter();
                    jsonStreamer.stream(securityContext, writer, result, baseUrl);
                    // useful newline
                    writer.append("\n");
                    tx.success();
                }
            }
        }
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (FrameworkException frameworkException) {
        // set status & write JSON output
        response.setStatus(frameworkException.getStatus());
        gson.get().toJson(frameworkException, response.getWriter());
        response.getWriter().println();
    } catch (JsonSyntaxException jsex) {
        logger.warn("JsonSyntaxException in GET", jsex);
        int code = HttpServletResponse.SC_BAD_REQUEST;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "Json syntax exception in GET: " + jsex.getMessage()));
    } catch (JsonParseException jpex) {
        logger.warn("JsonParseException in GET", jpex);
        int code = HttpServletResponse.SC_BAD_REQUEST;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "Parser exception in GET: " + jpex.getMessage()));
    } catch (Throwable t) {
        logger.warn("Exception in GET (URI: {})", securityContext != null ? securityContext.getCompoundRequestURI() : "(null SecurityContext)");
        logger.warn(" => Error thrown: ", t);
        int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "Exception in GET: " + t.getMessage()));
    } finally {
        try {
            // response.getWriter().flush();
            response.getWriter().close();
        } catch (Throwable t) {
            logger.warn("Unable to flush and close response: {}", t.getMessage());
        }
    }
}
Also used : App(org.structr.core.app.App) StructrApp(org.structr.core.app.StructrApp) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) DecimalFormat(java.text.DecimalFormat) Resource(org.structr.rest.resource.Resource) StaticRelationshipResource(org.structr.rest.resource.StaticRelationshipResource) StaticRelationshipResource(org.structr.rest.resource.StaticRelationshipResource) StreamingHtmlWriter(org.structr.rest.serialization.StreamingHtmlWriter) RetryException(org.structr.api.RetryException) JsonParseException(com.google.gson.JsonParseException) Result(org.structr.core.Result) RestMethodResult(org.structr.rest.RestMethodResult) JsonSyntaxException(com.google.gson.JsonSyntaxException) StreamingJsonWriter(org.structr.rest.serialization.StreamingJsonWriter) SecurityContext(org.structr.common.SecurityContext) Authenticator(org.structr.core.auth.Authenticator) PropertyKey(org.structr.core.property.PropertyKey) Writer(java.io.Writer) StreamingHtmlWriter(org.structr.rest.serialization.StreamingHtmlWriter) StreamingJsonWriter(org.structr.rest.serialization.StreamingJsonWriter)

Example 29 with Result

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

the class TransformationResource method doGet.

@Override
public Result doGet(PropertyKey sortKey, boolean sortDescending, int pageSize, int page) throws FrameworkException {
    if (wrappedResource != null && transformation != null) {
        // allow view transformation to avoid evaluation of wrapped resource
        if (transformation.evaluateWrappedResource()) {
            Result result = wrappedResource.doGet(sortKey, sortDescending, NodeFactory.DEFAULT_PAGE_SIZE, NodeFactory.DEFAULT_PAGE);
            try {
                transformation.apply(securityContext, result.getResults());
                result.setRawResultCount(result.size());
            } catch (Throwable t) {
                logger.warn("", t);
            }
            // apply paging later
            return PagingHelper.subResult(result, pageSize, page);
        } else {
            List<? extends GraphObject> listToTransform = new LinkedList<GraphObject>();
            transformation.apply(securityContext, listToTransform);
            Result result = new Result(listToTransform, listToTransform.size(), wrappedResource.isCollectionResource(), wrappedResource.isPrimitiveArray());
            // apply paging later
            return PagingHelper.subResult(result, pageSize, page);
        }
    }
    List emptyList = Collections.emptyList();
    return new Result(emptyList, null, isCollectionResource(), isPrimitiveArray());
}
Also used : List(java.util.List) LinkedList(java.util.LinkedList) LinkedList(java.util.LinkedList) Result(org.structr.core.Result)

Example 30 with Result

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

the class ListCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) {
    final SecurityContext securityContext = getWebSocket().getSecurityContext();
    final Map<String, Object> nodeData = webSocketData.getNodeData();
    final String rawType = (String) nodeData.get("type");
    final String properties = (String) webSocketData.getNodeData().get("properties");
    final boolean rootOnly = Boolean.TRUE.equals((Boolean) nodeData.get("rootOnly"));
    Class type = SchemaHelper.getEntityClassForRawType(rawType);
    if (type == null) {
        getWebSocket().send(MessageBuilder.status().code(404).message("Type " + rawType + " not found").build(), true);
        return;
    }
    if (properties != null) {
        securityContext.setCustomView(StringUtils.split(properties, ","));
    }
    final String sortOrder = webSocketData.getSortOrder();
    final String sortKey = webSocketData.getSortKey();
    final int pageSize = webSocketData.getPageSize();
    final int page = webSocketData.getPage();
    final PropertyKey sortProperty = StructrApp.key(type, sortKey);
    final Query query = StructrApp.getInstance(securityContext).nodeQuery(type).sort(sortProperty).order("desc".equals(sortOrder)).page(page).pageSize(pageSize);
    if (File.class.isAssignableFrom(type)) {
        if (rootOnly) {
            query.and(StructrApp.key(File.class, "hasParent"), false);
        }
        // inverted as isThumbnail is not necessarily present in all objects inheriting from FileBase
        query.not().and(StructrApp.key(Image.class, "isThumbnail"), true);
    }
    // important
    if (Folder.class.isAssignableFrom(type) && rootOnly) {
        query.and(StructrApp.key(Folder.class, "hasParent"), false);
    }
    try {
        // do search
        final Result result = query.getResult();
        // save raw result count
        // filteredResults.size();
        int resultCountBeforePaging = result.getRawResultCount();
        // set full result list
        webSocketData.setResult(result.getResults());
        webSocketData.setRawResultCount(resultCountBeforePaging);
        // 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 : Query(org.structr.core.app.Query) FrameworkException(org.structr.common.error.FrameworkException) Image(org.structr.web.entity.Image) Folder(org.structr.web.entity.Folder) Result(org.structr.core.Result) SecurityContext(org.structr.common.SecurityContext) File(org.structr.web.entity.File) PropertyKey(org.structr.core.property.PropertyKey)

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