private GraphObject extractActiveElement(
      final DOMNode node,
      final Set<String> dataKeys,
      final String parentId,
      final ActiveElementState state,
      final int depth) {

    final GraphObjectMap activeElement = new GraphObjectMap();

    activeElement.put(GraphObject.id, node.getUuid());
    activeElement.put(GraphObject.type, node.getType());
    activeElement.put(DOMElement.dataKey, StringUtils.join(dataKeys, ","));
    activeElement.put(Content.content, node.getProperty(Content.content));

    switch (state) {
      case Button:
        activeElement.put(actionProperty, node.getProperty(DOMElement._action));
        break;

      case Link:
        activeElement.put(actionProperty, node.getProperty(Link._href));
        break;

      case Query:
        extractQueries(activeElement, node);
        break;
    }

    activeElement.put(stateProperty, state.name());
    activeElement.put(recursionDepthProperty, depth);
    activeElement.put(parentIdProperty, parentId);

    return activeElement;
  }
  private boolean extractQuery(
      final GraphObjectMap activeElement, final DOMNode node, final Property<String> queryKey) {

    if (!StringUtils.isEmpty(node.getProperty(queryKey))) {

      activeElement.put(queryProperty, node.getProperty(queryKey));
      return true;
    }

    return false;
  }
  // ----- private methods -----
  private void collectActiveElements(
      final List<GraphObject> resultList,
      final DOMNode root,
      final Set<String> parentDataKeys,
      final String parent,
      final int depth) {

    final String childDataKey = root.getProperty(DOMElement.dataKey);
    final Set<String> dataKeys = new LinkedHashSet<>(parentDataKeys);
    String parentId = parent;
    int dataCentricDepth = depth;

    if (!StringUtils.isEmpty(childDataKey)) {

      dataKeys.add(childDataKey);
      dataCentricDepth++;
    }

    final ActiveElementState state = isActive(root, dataKeys);
    if (!state.equals(ActiveElementState.None)) {

      resultList.add(extractActiveElement(root, dataKeys, parentId, state, depth));
      if (state.equals(ActiveElementState.Query)) {

        parentId = root.getUuid();
      }
    }

    for (final DOMChildren children : root.getChildRelationships()) {

      final DOMNode child = children.getTargetNode();
      collectActiveElements(resultList, child, dataKeys, parentId, dataCentricDepth);
    }
  }
Exemple #4
0
  @Override
  public String toString() {

    if (existingNode instanceof Content) {

      return "Update Content("
          + existingNode.getIdHashOrProperty()
          + ") with "
          + newNode.getIdHashOrProperty();

    } else {

      return "Update "
          + newNode.getProperty(DOMElement.tag)
          + "("
          + existingNode.getIdHashOrProperty()
          + ") with "
          + newNode.getIdHashOrProperty();
    }
  }
  @Override
  protected void doGet(final HttpServletRequest request, final HttpServletResponse response) {

    final Authenticator auth = config.getAuthenticator();
    final SecurityContext securityContext;
    final App app;

    try {
      String path = request.getPathInfo();

      // check for registration (has its own tx because of write access
      if (checkRegistration(auth, request, response, path)) {

        return;
      }

      // 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");

        boolean dontCache = false;

        logger.log(Level.FINE, "Path info {0}", path);

        // don't continue on redirects
        if (response.getStatus() == 302) {
          return;
        }

        Principal user = securityContext.getUser(false);
        if (user != null) {

          // Don't cache if a user is logged in
          dontCache = true;
        }

        final RenderContext renderContext =
            RenderContext.getInstance(request, response, getEffectiveLocale(request));

        renderContext.setResourceProvider(config.getResourceProvider());

        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);

          logger.log(Level.FINE, "No path supplied, trying to find index page");

        } else {

          if (rootElement == null) {

            rootElement = findPage(securityContext, request, path);

          } 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);
            return;
          }

          // store remaining path parts in request
          Matcher matcher = threadLocalUUIDMatcher.get();
          boolean requestUriContainsUuids = false;

          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) {

            // 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);

            rootElement =
                findPage(
                    securityContext,
                    request,
                    StringUtils.substringBeforeLast(path, PathHelper.PATH_SEP));

            renderContext.setDetailsDataObject(dataNode);

            // Start rendering on data node
            if (rootElement == null && dataNode instanceof DOMNode) {

              rootElement = ((DOMNode) dataNode);
            }
          }
        }

        // 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) {
          return;
        }

        if (EditMode.WIDGET.equals(edit) || dontCache) {

          setNoCacheHeaders(response);
        }

        if (!securityContext.isVisible(rootElement)) {

          rootElement = notFound(response, securityContext);
          if (rootElement == null) {
            return;
          }
        }

        if (securityContext.isVisible(rootElement)) {

          if (!EditMode.WIDGET.equals(edit)
              && !dontCache
              && notModifiedSince(request, response, rootElement, dontCache)) {

            ServletOutputStream out = response.getOutputStream();
            out.flush();
            // response.flushBuffer();
            out.close();

          } else {

            // prepare response
            response.setCharacterEncoding("UTF-8");

            String contentType = rootElement.getProperty(Page.contentType);

            if (contentType != null && contentType.equals("text/html")) {

              contentType = contentType.concat(";charset=UTF-8");
              response.setContentType(contentType);

            } else {

              // Default
              response.setContentType("text/html;charset=UTF-8");
            }

            response.setHeader("Strict-Transport-Security", "max-age=60");
            response.setHeader("X-Content-Type-Options", "nosniff");
            response.setHeader("X-Frame-Options", "SAMEORIGIN");
            response.setHeader("X-XSS-Protection", "1; mode=block");

            // async or not?
            boolean isAsync =
                HttpService.parseBoolean(
                    Services.getBaseConfiguration().getProperty(HttpService.ASYNC), true);
            if (isAsync) {

              final AsyncContext async = request.startAsync();
              final ServletOutputStream out = async.getResponse().getOutputStream();
              final AtomicBoolean finished = new AtomicBoolean(false);
              final DOMNode rootNode = rootElement;

              threadPool.submit(
                  new Runnable() {

                    @Override
                    public void run() {

                      try (final Tx tx = app.tx()) {

                        // final long start = System.currentTimeMillis();

                        // render
                        rootNode.render(securityContext, renderContext, 0);
                        finished.set(true);

                        // final long end = System.currentTimeMillis();
                        // System.out.println("Done in " + (end-start) + " ms");

                        tx.success();

                      } catch (Throwable t) {
                        t.printStackTrace();
                        final String errorMsg = t.getMessage();
                        try {
                          // response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                          response.sendError(
                              HttpServletResponse.SC_INTERNAL_SERVER_ERROR, errorMsg);
                          finished.set(true);
                        } catch (IOException ex) {
                          ex.printStackTrace();
                        }
                      }
                    }
                  });

              // start output write listener
              out.setWriteListener(
                  new WriteListener() {

                    @Override
                    public void onWritePossible() throws IOException {

                      try {

                        final Queue<String> queue = renderContext.getBuffer().getQueue();
                        while (out.isReady()) {

                          String buffer = null;

                          synchronized (queue) {
                            buffer = queue.poll();
                          }

                          if (buffer != null) {

                            out.print(buffer);

                          } else {

                            if (finished.get()) {

                              async.complete();
                              response.setStatus(HttpServletResponse.SC_OK);

                              // prevent this block from being called again
                              break;
                            }

                            Thread.sleep(1);
                          }
                        }

                      } catch (Throwable t) {
                        t.printStackTrace();
                      }
                    }

                    @Override
                    public void onError(Throwable t) {
                      t.printStackTrace();
                    }
                  });

            } else {

              final StringRenderBuffer buffer = new StringRenderBuffer();
              renderContext.setBuffer(buffer);

              // render
              rootElement.render(securityContext, renderContext, 0);

              response.getOutputStream().write(buffer.getBuffer().toString().getBytes("utf-8"));
              response.getOutputStream().flush();
              response.getOutputStream().close();
            }
          }

        } else {

          notFound(response, securityContext);
        }

        tx.success();

      } catch (FrameworkException fex) {
        fex.printStackTrace();
        logger.log(Level.SEVERE, "Exception while processing request", fex);
      }

    } catch (IOException | FrameworkException t) {

      t.printStackTrace();
      logger.log(Level.SEVERE, "Exception while processing request", t);
      UiAuthenticator.writeInternalServerError(response);
    }
  }
  private ActiveElementState isActive(final DOMNode node, final Set<String> dataKeys) {

    if (!StringUtils.isEmpty(node.getProperty(DOMElement.dataKey))) {
      return ActiveElementState.Query;
    }

    if (!StringUtils.isEmpty(node.getProperty(DOMElement.restQuery))) {
      return ActiveElementState.Query;
    }

    if (!StringUtils.isEmpty(node.getProperty(DOMElement.cypherQuery))) {
      return ActiveElementState.Query;
    }

    if (!StringUtils.isEmpty(node.getProperty(DOMElement.xpathQuery))) {
      return ActiveElementState.Query;
    }

    if (!StringUtils.isEmpty(node.getProperty(DOMElement.functionQuery))) {
      return ActiveElementState.Query;
    }

    /*
     attributes to check for !isEmpty:
      - data-structr-action
      - data-structr-attributes
      - data-structr-raw-value
    */
    if (node.getProperty(DOMElement._action) != null
        || node.getProperty(DOMElement._attributes) != null
        || node.getProperty(DOMElement._rawValue) != null) {
      return ActiveElementState.Button;
    }

    if (node.getProperty(Content.content) != null && !dataKeys.isEmpty()) {

      if (containsDataKeyReference(node.getProperty(Content.content), dataKeys)) {
        return ActiveElementState.Content;
      }
    }

    if (node.getProperty(DOMElement._id) != null && !dataKeys.isEmpty()) {

      if (containsDataKeyReference(node.getProperty(DOMElement._id), dataKeys)) {
        return ActiveElementState.Content;
      }
    }

    if (node.getProperty(Link._href) != null && !dataKeys.isEmpty()) {

      if (containsDataKeyReference(node.getProperty(Link._href), dataKeys)) {
        return ActiveElementState.Link;
      }
    }

    if (node.getProperty(Input._value) != null && !dataKeys.isEmpty()) {

      if (containsDataKeyReference(node.getProperty(Input._value), dataKeys)) {

        return ActiveElementState.Input;
      }
    }

    // last option: just some hidden element..
    if (!StringUtils.isEmpty(node.getProperty(DOMNode.hideConditions))) {
      return ActiveElementState.Content;
    }

    if (!StringUtils.isEmpty(node.getProperty(DOMNode.showConditions))) {
      return ActiveElementState.Content;
    }

    if (node.getProperty(DOMNode.hideOnIndex)) {
      return ActiveElementState.Content;
    }

    if (node.getProperty(DOMNode.hideOnDetail)) {
      return ActiveElementState.Content;
    }

    return ActiveElementState.None;
  }