Search in sources :

Example 56 with AbstractNode

use of org.structr.core.entity.AbstractNode 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 57 with AbstractNode

use of org.structr.core.entity.AbstractNode in project structr by structr.

the class HtmlServlet method doHead.

@Override
protected void doHead(final HttpServletRequest request, final HttpServletResponse response) {
    final Authenticator auth = getConfig().getAuthenticator();
    SecurityContext securityContext;
    List<Page> pages = null;
    boolean requestUriContainsUuids = false;
    final App app;
    try {
        assertInitialized();
        String path = request.getPathInfo();
        // isolate request authentication in a transaction
        try (final Tx tx = StructrApp.getInstance().tx()) {
            securityContext = auth.initializeAndExamineRequest(request, response);
            tx.success();
        }
        app = StructrApp.getInstance(securityContext);
        try (final Tx tx = app.tx()) {
            // 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");
            response.setContentLength(0);
            boolean dontCache = false;
            logger.debug("Path info {}", path);
            // don't continue on redirects
            if (response.getStatus() == 302) {
                tx.success();
                return;
            }
            final Principal user = securityContext.getUser(false);
            if (user != null) {
                // Don't cache if a user is logged in
                dontCache = true;
            }
            final RenderContext renderContext = RenderContext.getInstance(securityContext, request, response);
            renderContext.setResourceProvider(config.getResourceProvider());
            final EditMode edit = renderContext.getEditMode(user);
            DOMNode rootElement = null;
            AbstractNode dataNode = null;
            String[] uriParts = PathHelper.getParts(path);
            if ((uriParts == null) || (uriParts.length == 0)) {
                // find a visible page
                rootElement = findIndexPage(securityContext, pages, edit);
                logger.debug("No path supplied, trying to find index page");
            } else {
                if (rootElement == null) {
                    rootElement = findPage(securityContext, pages, path, edit);
                } else {
                    dontCache = true;
                }
            }
            if (rootElement == null) {
                // No page found
                // Look for a file
                File file = findFile(securityContext, request, path);
                if (file != null) {
                    // streamFile(securityContext, file, request, response, edit);
                    tx.success();
                    return;
                }
                if (uriParts != null) {
                    // store remaining path parts in request
                    Matcher matcher = threadLocalUUIDMatcher.get();
                    for (int i = 0; i < uriParts.length; i++) {
                        request.setAttribute(uriParts[i], i);
                        matcher.reset(uriParts[i]);
                        // set to "true" if part matches UUID pattern
                        requestUriContainsUuids |= matcher.matches();
                    }
                }
                if (!requestUriContainsUuids) {
                    // Try to find a data node by name
                    dataNode = findFirstNodeByName(securityContext, request, path);
                } else {
                    dataNode = findNodeByUuid(securityContext, PathHelper.getName(path));
                }
                if (dataNode != null && !(dataNode instanceof Linkable)) {
                    // Last path part matches a data node
                    // Remove last path part and try again searching for a page
                    // clear possible entry points
                    request.removeAttribute(POSSIBLE_ENTRY_POINTS_KEY);
                    rootElement = findPage(securityContext, pages, StringUtils.substringBeforeLast(path, PathHelper.PATH_SEP), edit);
                    renderContext.setDetailsDataObject(dataNode);
                    // Start rendering on data node
                    if (rootElement == null && dataNode instanceof DOMNode) {
                        rootElement = ((DOMNode) dataNode);
                    }
                }
            }
            // look for pages with HTTP Basic Authentication (must be done as superuser)
            if (rootElement == null) {
                final HttpBasicAuthResult authResult = checkHttpBasicAuth(request, response, path);
                switch(authResult.authState()) {
                    // Element with Basic Auth found and authentication succeeded
                    case Authenticated:
                        final Linkable result = authResult.getRootElement();
                        if (result instanceof Page) {
                            rootElement = (DOMNode) result;
                            renderContext.pushSecurityContext(authResult.getSecurityContext());
                        } else if (result instanceof File) {
                            // streamFile(authResult.getSecurityContext(), (File)result, request, response, EditMode.NONE);
                            tx.success();
                            return;
                        }
                        break;
                    // Page with Basic Auth found but not yet authenticated
                    case MustAuthenticate:
                        tx.success();
                        return;
                    // no Basic Auth for given path, go on
                    case NoBasicAuth:
                        break;
                }
            }
            // Still nothing found, do error handling
            if (rootElement == null) {
                // Check if security context has set an 401 status
                if (response.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) {
                    try {
                        UiAuthenticator.writeUnauthorized(response);
                    } catch (IllegalStateException ise) {
                    }
                } else {
                    rootElement = notFound(response, securityContext);
                }
            }
            if (rootElement == null) {
                // no content
                response.setContentLength(0);
                response.getOutputStream().close();
                tx.success();
                return;
            }
            // check dont cache flag on page (if root element is a page)
            // but don't modify true to false
            dontCache |= rootElement.dontCache();
            if (EditMode.WIDGET.equals(edit) || dontCache) {
                setNoCacheHeaders(response);
            }
            if (!securityContext.isVisible(rootElement)) {
                rootElement = notFound(response, securityContext);
                if (rootElement == null) {
                    tx.success();
                    return;
                }
            }
            if (securityContext.isVisible(rootElement)) {
                if (!EditMode.WIDGET.equals(edit) && !dontCache && notModifiedSince(request, response, rootElement, dontCache)) {
                    response.getOutputStream().close();
                } else {
                    // prepare response
                    response.setCharacterEncoding("UTF-8");
                    String contentType = rootElement.getProperty(StructrApp.key(Page.class, "contentType"));
                    if (contentType == null) {
                        // Default
                        contentType = "text/html;charset=UTF-8";
                    }
                    if (contentType.equals("text/html")) {
                        contentType = contentType.concat(";charset=UTF-8");
                    }
                    response.setContentType(contentType);
                    setCustomResponseHeaders(response);
                    response.getOutputStream().close();
                }
            } else {
                notFound(response, securityContext);
                response.getOutputStream().close();
            }
            tx.success();
        } catch (Throwable fex) {
            logger.error("Exception while processing request", fex);
        }
    } catch (FrameworkException t) {
        logger.error("Exception while processing request", t);
        UiAuthenticator.writeInternalServerError(response);
    }
}
Also used : App(org.structr.core.app.App) StructrApp(org.structr.core.app.StructrApp) RenderContext(org.structr.web.common.RenderContext) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) AbstractNode(org.structr.core.entity.AbstractNode) Matcher(java.util.regex.Matcher) ThreadLocalMatcher(org.structr.common.ThreadLocalMatcher) Page(org.structr.web.entity.dom.Page) SecurityContext(org.structr.common.SecurityContext) EditMode(org.structr.web.common.RenderContext.EditMode) Linkable(org.structr.web.entity.Linkable) DOMNode(org.structr.web.entity.dom.DOMNode) AbstractFile(org.structr.web.entity.AbstractFile) File(org.structr.web.entity.File) UiAuthenticator(org.structr.web.auth.UiAuthenticator) Authenticator(org.structr.core.auth.Authenticator) Principal(org.structr.core.entity.Principal)

Example 58 with AbstractNode

use of org.structr.core.entity.AbstractNode in project structr by structr.

the class AbstractCommand method getNode.

/**
 * Returns the node with the given id.
 *
 * @param id
 * @return the node
 */
public AbstractNode getNode(final String id) {
    final SecurityContext securityContext = getWebSocket().getSecurityContext();
    final App app = StructrApp.getInstance(securityContext);
    try (final Tx tx = app.tx()) {
        final AbstractNode node = (AbstractNode) app.getNodeById(id);
        tx.success();
        return node;
    } catch (FrameworkException fex) {
        logger.warn("Unable to get node", fex);
    }
    return null;
}
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) SecurityContext(org.structr.common.SecurityContext)

Example 59 with AbstractNode

use of org.structr.core.entity.AbstractNode in project structr by structr.

the class AppendChildCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) {
    String id = webSocketData.getId();
    Map<String, Object> nodeData = webSocketData.getNodeData();
    String parentId = (String) nodeData.get("parentId");
    // check node to append
    if (id == null) {
        getWebSocket().send(MessageBuilder.status().code(422).message("Cannot append node, no id is given").build(), true);
        return;
    }
    // check for parent ID
    if (parentId == null) {
        getWebSocket().send(MessageBuilder.status().code(422).message("Cannot add node without parentId").build(), true);
        return;
    }
    // check if parent node with given ID exists
    AbstractNode parentNode = getNode(parentId);
    if (parentNode == null) {
        getWebSocket().send(MessageBuilder.status().code(404).message("Parent node not found").build(), true);
        return;
    }
    if (parentNode instanceof DOMNode) {
        DOMNode parentDOMNode = getDOMNode(parentId);
        if (parentDOMNode == null) {
            getWebSocket().send(MessageBuilder.status().code(422).message("Parent node is no DOM node").build(), true);
            return;
        }
        DOMNode node = (DOMNode) getDOMNode(id);
        // append node to parent
        if (node != null) {
            parentDOMNode.appendChild(node);
        }
    } else {
        // send exception
        getWebSocket().send(MessageBuilder.status().code(422).message("Cannot use given node, not instance of DOMNode").build(), true);
    }
}
Also used : AbstractNode(org.structr.core.entity.AbstractNode) DOMNode(org.structr.web.entity.dom.DOMNode)

Example 60 with AbstractNode

use of org.structr.core.entity.AbstractNode in project structr by structr.

the class AppendContentItemCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) {
    String id = webSocketData.getId();
    Map<String, Object> nodeData = webSocketData.getNodeData();
    String parentId = (String) nodeData.get("parentId");
    // check node to append
    if (id == null) {
        getWebSocket().send(MessageBuilder.status().code(422).message("Cannot append node, no id is given").build(), true);
        return;
    }
    // check for parent ID
    if (parentId == null) {
        getWebSocket().send(MessageBuilder.status().code(422).message("Cannot append node without parentId").build(), true);
        return;
    }
    // never append to self
    if (parentId.equals(id)) {
        getWebSocket().send(MessageBuilder.status().code(422).message("Cannot append node as its own child.").build(), true);
        return;
    }
    // check if parent node with given ID exists
    AbstractNode parentNode = getNode(parentId);
    if (parentNode == null) {
        getWebSocket().send(MessageBuilder.status().code(404).message("Parent node not found").build(), true);
        return;
    }
    if (parentNode instanceof ContentContainer) {
        ContentContainer container = (ContentContainer) parentNode;
        ContentItem item = (ContentItem) getNode(id);
        if (item != null) {
            try {
                final List<ContentItem> items = container.getItems();
                items.add(item);
                container.setProperty(StructrApp.key(ContentContainer.class, "items"), items);
                TransactionCommand.registerNodeCallback(item, callback);
            } catch (FrameworkException ex) {
                logger.error("", ex);
                getWebSocket().send(MessageBuilder.status().code(422).message("Cannot append content item").build(), true);
            }
        }
    } else {
        // send exception
        getWebSocket().send(MessageBuilder.status().code(422).message("Parent node is not instance of ContentContainer").build(), true);
    }
}
Also used : FrameworkException(org.structr.common.error.FrameworkException) AbstractNode(org.structr.core.entity.AbstractNode) ContentContainer(org.structr.web.entity.ContentContainer) ContentItem(org.structr.web.entity.ContentItem)

Aggregations

AbstractNode (org.structr.core.entity.AbstractNode)62 FrameworkException (org.structr.common.error.FrameworkException)31 Tx (org.structr.core.graph.Tx)20 App (org.structr.core.app.App)18 StructrApp (org.structr.core.app.StructrApp)18 GraphObject (org.structr.core.GraphObject)17 SecurityContext (org.structr.common.SecurityContext)16 PropertyMap (org.structr.core.property.PropertyMap)12 Result (org.structr.core.Result)10 Test (org.junit.Test)9 AbstractRelationship (org.structr.core.entity.AbstractRelationship)9 LinkedList (java.util.LinkedList)8 TestOne (org.structr.core.entity.TestOne)8 DatabaseService (org.structr.api.DatabaseService)7 NodeInterface (org.structr.core.graph.NodeInterface)7 PropertyKey (org.structr.core.property.PropertyKey)7 Principal (org.structr.core.entity.Principal)6 CmisObjectNotFoundException (org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException)5 DOMNode (org.structr.web.entity.dom.DOMNode)5 LinkedHashSet (java.util.LinkedHashSet)4