Example #1
0
  @Override
  public boolean delete() {
    final App app = StructrApp.getInstance();

    try (Tx tx = StructrApp.getInstance().tx()) {
      app.delete(this);
      tx.success();
    } catch (FrameworkException ex) {
      logger.log(Level.SEVERE, null, ex);
    }

    return true;
  }
  /**
   * Return list of nodes which are not attached to a page and have no parent element (no incoming
   * CONTAINS rel)
   *
   * @param app
   * @param securityContext
   * @param webSocketData
   * @return
   * @throws FrameworkException
   */
  protected static List<AbstractNode> getUnattachedNodes(
      final App app, final SecurityContext securityContext, final WebSocketMessage webSocketData)
      throws FrameworkException {

    final String sortOrder = webSocketData.getSortOrder();
    final String sortKey = webSocketData.getSortKey();
    final PropertyKey sortProperty =
        StructrApp.getConfiguration().getPropertyKeyForJSONName(DOMNode.class, sortKey);
    final Query query =
        StructrApp.getInstance(securityContext)
            .nodeQuery()
            .includeDeletedAndHidden()
            .sort(sortProperty)
            .order("desc".equals(sortOrder));

    query.orTypes(DOMElement.class);
    query.orType(Content.class);
    query.orType(Template.class);

    // do search
    List<AbstractNode> filteredResults = new LinkedList();
    List<? extends GraphObject> resultList = null;

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

      resultList = query.getAsList();

    } catch (FrameworkException fex) {
      logger.warn("Exception occured", fex);
    }

    // determine which of the nodes have no incoming CONTAINS relationships and no page id
    for (GraphObject obj : resultList) {

      if (obj instanceof AbstractNode) {

        AbstractNode node = (AbstractNode) obj;

        if (!node.hasIncomingRelationships(DOMChildren.class)
            && node.getProperty(DOMNode.ownerDocument) == null
            && !(node instanceof ShadowDocument)) {

          filteredResults.add(node);
        }
      }
    }

    return filteredResults;
  }
  @Override
  public void setTargetNodeId(final String targetIdNode) throws FrameworkException {

    // Do nothing if new id equals old
    if (getTargetNodeId().equals(targetIdNode)) {
      return;
    }

    final App app = StructrApp.getInstance(securityContext);

    final NodeInterface newTargetNode = (NodeInterface) app.get(targetIdNode);
    final NodeInterface startNode = getSourceNode();
    final Class relationType = getClass();
    final PropertyMap _props = getProperties();
    final String type = this.getClass().getSimpleName();

    if (newTargetNode == null) {
      throw new FrameworkException(type, new IdNotFoundToken(targetIdNode));
    }

    // delete this as the new rel will be the container afterwards
    app.delete(this);

    // create new relationship and store here
    app.create(startNode, newTargetNode, relationType, _props);
  }
Example #4
0
  @Override
  public T instantiateDummy(final Relationship entity, final String entityType)
      throws FrameworkException {

    Map<String, Class<? extends RelationshipInterface>> entities =
        StructrApp.getConfiguration().getRelationshipEntities();
    Class<T> relClass = (Class<T>) entities.get(entityType);
    T newRel = null;

    if (relClass != null) {

      try {

        newRel = relClass.newInstance();
        newRel.init(factoryProfile.getSecurityContext(), entity);

        // let rel. know of its instantiation so it can cache its start- and end node ID.
        newRel.onRelationshipInstantiation();

      } catch (Throwable t) {

        newRel = null;
      }
    }

    return newRel;
  }
  @Override
  public void processMessage(final WebSocketMessage webSocketData) {

    final String type = (String) webSocketData.getNodeData().get("type");

    if (type == null) {
      logger.log(Level.WARNING, "Node type given not found");
      getWebSocket().send(MessageBuilder.status().code(400).build(), true);
    }

    final SecurityContext securityContext = getWebSocket().getSecurityContext();
    final App app = StructrApp.getInstance(securityContext);

    final SchemaNode typeNode;
    try {
      typeNode = app.nodeQuery(SchemaNode.class).andName(type).getFirst();

      if (typeNode != null) {

        webSocketData.setResult(Arrays.asList(typeNode));

        // send only over local connection (no broadcast)
        getWebSocket().send(webSocketData, true);
      }
    } catch (FrameworkException ex) {
      logger.log(Level.SEVERE, null, ex);
      getWebSocket().send(MessageBuilder.status().code(500).build(), true);
    }
  }
  @Override
  public void processMessage(final WebSocketMessage webSocketData) {

    final SecurityContext securityContext = getWebSocket().getSecurityContext();
    final int pageSize = webSocketData.getPageSize();
    final int page = webSocketData.getPage();

    final App app = StructrApp.getInstance(securityContext);

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

      // do search
      List<AbstractNode> filteredResults = getUnattachedNodes(app, securityContext, webSocketData);

      // save raw result count
      int resultCountBeforePaging = filteredResults.size();

      // set full result list
      webSocketData.setResult(PagingHelper.subList(filteredResults, pageSize, page, null));
      webSocketData.setRawResultCount(resultCountBeforePaging);

      // send only over local connection
      getWebSocket().send(webSocketData, true);

      tx.success();

    } catch (FrameworkException fex) {

      logger.warn("Exception occured", fex);
      getWebSocket()
          .send(
              MessageBuilder.status().code(fex.getStatus()).message(fex.getMessage()).build(),
              true);
    }
  }
Example #7
0
  @Override
  public void ensureCardinality(
      final SecurityContext securityContext,
      final NodeInterface sourceNode,
      final NodeInterface targetNode)
      throws FrameworkException {

    final App app = StructrApp.getInstance();
    final Class<? extends ManyToOne> clazz = this.getClass();
    final Class<T> targetType = getTargetType();

    if (sourceNode != null) {

      // check existing relationships
      final Relation<?, T, ?, ?> outgoingRel = sourceNode.getOutgoingRelationship(clazz);
      if (outgoingRel != null && targetType.isAssignableFrom(outgoingRel.getTargetType())) {

        try {

          app.beginTx();
          app.delete(outgoingRel);
          app.commitTx();

        } finally {

          app.finishTx();
        }
      }
    }
  }
Example #8
0
  @Override
  public void execute(final StructrShellCommand parent) throws IOException {

    final App app = StructrApp.getInstance();

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

      final Folder currentFolder = parent.getCurrentFolder();
      if (currentFolder != null) {

        listFolder(parent, currentFolder.getProperty(AbstractFile.children));

      } else {

        listFolder(
            parent, app.nodeQuery(AbstractFile.class).and(AbstractFile.parent, null).getAsList());
      }

      tx.success();

    } catch (FrameworkException fex) {

      logger.warn("", fex);
    }
  }
Example #9
0
  @Override
  public String getGroupName() {

    String name = "";

    try (Tx tx = StructrApp.getInstance().tx()) {

      Principal owner = getOwner();

      if (owner != null) {
        List<Principal> parents = owner.getParents();
        if (!parents.isEmpty()) {

          name = parents.get(0).getProperty(AbstractNode.name);
        }
      }

      tx.success();

    } catch (FrameworkException fex) {
      logger.log(Level.SEVERE, "Error while getting group name of " + this, fex);
    }

    return name;
  }
Example #10
0
  @Override
  public void processMessage(final WebSocketMessage webSocketData) {

    final GraphObject obj = getGraphObject(webSocketData.getId());
    String key = (String) webSocketData.getNodeData().get("key");

    if (obj != null) {

      PropertyKey propertyKey =
          StructrApp.getConfiguration().getPropertyKeyForJSONName(obj.getClass(), key);
      PropertyConverter converter = propertyKey.inputConverter(getWebSocket().getSecurityContext());

      Object value = obj.getProperty(propertyKey);
      if (converter != null) {

        try {
          value = converter.revert(value);

        } catch (FrameworkException ex) {

          getWebSocket()
              .send(MessageBuilder.status().code(400).message(ex.getMessage()).build(), true);
        }
      }

      webSocketData.setNodeData(key, value);

      // send only over local connection (no broadcast)
      getWebSocket().send(webSocketData, true);

    } else {

      getWebSocket().send(MessageBuilder.status().code(404).build(), true);
    }
  }
Example #11
0
  @Override
  public DocumentFragment createDocumentFragment() {

    final App app = StructrApp.getInstance(securityContext);

    try {

      // create new content element
      org.structr.web.entity.dom.DocumentFragment fragment =
          app.create(org.structr.web.entity.dom.DocumentFragment.class);

      // create relationship from ownerDocument to new text element
      ((RelationProperty<DOMNode>) Page.elements)
          .addSingleElement(securityContext, Page.this, fragment);
      // Page.elements.createRelationship(securityContext, Page.this, fragment);

      return fragment;

    } catch (FrameworkException fex) {

      // FIXME: what to do with the exception here?
      logger.log(Level.WARNING, "", fex);
    }

    return null;
  }
Example #12
0
  private List<Linkable> findPossibleEntryPointsByName(
      final SecurityContext securityContext, HttpServletRequest request, final String name)
      throws FrameworkException {

    List<Linkable> possibleEntryPoints =
        (List<Linkable>) request.getAttribute(POSSIBLE_ENTRY_POINTS);

    if (CollectionUtils.isNotEmpty(possibleEntryPoints)) {
      return possibleEntryPoints;
    }

    if (name.length() > 0) {

      logger.log(Level.FINE, "Requested name: {0}", name);

      final Query query = StructrApp.getInstance(securityContext).nodeQuery();

      query.and(AbstractNode.name, name);
      query.and().orType(Page.class).orTypes(File.class);

      // Searching for pages needs super user context anyway
      Result results = query.getResult();

      logger.log(Level.FINE, "{0} results", results.size());
      request.setAttribute(POSSIBLE_ENTRY_POINTS, results.getResults());

      return (List<Linkable>) results.getResults();
    }

    return Collections.EMPTY_LIST;
  }
Example #13
0
  /**
   * Find the page with the lowest position value which is visible in the current securit context
   *
   * @param securityContext
   * @return
   * @throws FrameworkException
   */
  private Page findIndexPage(final SecurityContext securityContext) throws FrameworkException {

    Result<Page> results =
        StructrApp.getInstance(securityContext)
            .nodeQuery(Page.class)
            .sort(Page.position)
            .order(false)
            .getResult();
    Collections.sort(
        results.getResults(),
        new GraphObjectComparator(Page.position, GraphObjectComparator.ASCENDING));

    // Find first visible page
    Page page = null;

    if (!results.isEmpty()) {

      int i = 0;

      while (page == null || (i < results.size() && !securityContext.isVisible(page))) {

        page = results.get(i++);
      }
    }

    return page;
  }
Example #14
0
  @Override
  public CDATASection createCDATASection(String string) throws DOMException {

    try {

      // create new content element
      Cdata content =
          (Cdata)
              StructrApp.getInstance(securityContext)
                  .command(CreateNodeCommand.class)
                  .execute(new NodeAttribute(AbstractNode.type, Cdata.class.getSimpleName()));

      // create relationship from ownerDocument to new text element
      ((RelationProperty<DOMNode>) Page.elements)
          .addSingleElement(securityContext, Page.this, content);
      // Page.elements.createRelationship(securityContext, Page.this, content);

      return content;

    } catch (FrameworkException fex) {

      // FIXME: what to do with the exception here?
      logger.log(Level.WARNING, "", fex);
    }

    return null;
  }
Example #15
0
  public static ResourceAccess findGrant(
      final SecurityContext securityContext, final String signature) throws FrameworkException {

    ResourceAccess grant = grantCache.get(signature);
    if (grant == null) {

      // grant =
      // StructrApp.getInstance(securityContext).nodeQuery(ResourceAccess.class).and(ResourceAccess.signature, signature).getFirst();
      // ignore security context for now, so ResourceAccess objects don't have to be visible
      grant =
          StructrApp.getInstance()
              .nodeQuery(ResourceAccess.class)
              .and(ResourceAccess.signature, signature)
              .getFirst();
      if (grant != null) {

        grantCache.put(signature, grant);

      } else {

        logger.debug("No resource access object found for {}", signature);
      }
    }

    return grant;
  }
Example #16
0
  @Override
  public void onWebSocketClose(final int closeCode, final String message) {

    logger.log(
        Level.INFO,
        "Connection closed with closeCode {0} and message {1}",
        new Object[] {closeCode, message});

    final App app = StructrApp.getInstance(securityContext);

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

      this.session = null;

      syncController.unregisterClient(this);

      // flush and close open uploads
      for (FileUploadHandler upload : uploads.values()) {

        upload.finish();
      }

      tx.success();
      uploads.clear();

    } catch (FrameworkException fex) {

      logger.log(Level.SEVERE, "Error while closing connection", fex);
    }
  }
  @Override
  public List<GraphObject> getProperty(
      SecurityContext securityContext,
      GraphObject obj,
      boolean applyConverter,
      Predicate<GraphObject> predicate) {

    if (obj instanceof AbstractNode) {

      try {

        final String query =
            Scripting.replaceVariables(new ActionContext(securityContext), obj, this.format);
        final Map<String, Object> parameters = new LinkedHashMap<>();

        parameters.put("id", obj.getUuid());
        parameters.put("type", obj.getType());

        return StructrApp.getInstance(securityContext)
            .command(CypherQueryCommand.class)
            .execute(query, parameters);

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

    return null;
  }
Example #18
0
  @Override
  public Comment createComment(String comment) {

    try {

      // create new content element
      org.structr.web.entity.dom.Comment commentNode =
          (org.structr.web.entity.dom.Comment)
              StructrApp.getInstance(securityContext)
                  .command(CreateNodeCommand.class)
                  .execute(
                      new NodeAttribute(
                          AbstractNode.type,
                          org.structr.web.entity.dom.Comment.class.getSimpleName()),
                      new NodeAttribute(Content.content, comment));

      // create relationship from ownerDocument to new text element
      ((RelationProperty<DOMNode>) Page.elements)
          .addSingleElement(securityContext, Page.this, commentNode);
      // Page.elements.createRelationship(securityContext, Page.this, content);

      return commentNode;

    } catch (FrameworkException fex) {

      // FIXME: what to do with the exception here?
      logger.log(Level.WARNING, "", fex);
    }

    return null;
  }
Example #19
0
  public static void importCypher(final List<String> sources) {

    final App app = StructrApp.getInstance();
    final GraphDatabaseService graphDb = app.command(GraphDatabaseCommand.class).execute();

    // nothing to do
    if (sources.isEmpty()) {
      return;
    }

    // first step: execute cypher queries
    for (final String source : sources) {

      try (final Transaction tx = graphDb.beginTx()) {

        // be very tolerant here, just execute everything
        graphDb.execute(source);
        tx.success();

      } catch (Throwable t) {
        // ignore
        t.printStackTrace();
      }
    }
  }
Example #20
0
  @Override
  public boolean move(FtpFile target) {
    try (Tx tx = StructrApp.getInstance().tx()) {

      logger.log(Level.INFO, "move()");

      final AbstractStructrFtpFile targetFile = (AbstractStructrFtpFile) target;
      final String path = targetFile instanceof StructrFtpFile ? "/" : targetFile.getAbsolutePath();

      try {

        if (!("/".equals(path))) {
          final String newName =
              path.contains("/") ? StringUtils.substringAfterLast(path, "/") : path;
          setProperty(AbstractNode.name, newName);
        }

      } catch (FrameworkException ex) {
        logger.log(Level.SEVERE, "Could not move ftp file", ex);
        return false;
      }

      tx.success();

      return true;
    } catch (FrameworkException ex) {
      logger.log(Level.SEVERE, null, ex);
    }

    return false;
  }
Example #21
0
 private Principal getOwner() {
   try (Tx tx = StructrApp.getInstance().tx()) {
     Principal owner = getProperty(File.owner);
     tx.success();
     return owner;
   } catch (FrameworkException fex) {
     logger.log(Level.SEVERE, "Error while getting owner of " + this, fex);
   }
   return null;
 }
Example #22
0
 // ----- interface FtpFile -----
 @Override
 public String getAbsolutePath() {
   try (Tx tx = StructrApp.getInstance().tx()) {
     final String path = getPath();
     tx.success();
     return path;
   } catch (FrameworkException fex) {
     logger.log(Level.SEVERE, "Error in getPath() of abstract ftp file", fex);
   }
   return null;
 }
Example #23
0
  /**
   * Find node by uuid
   *
   * @param securityContext
   * @param request
   * @param uuid
   * @return
   * @throws FrameworkException
   */
  private AbstractNode findNodeByUuid(final SecurityContext securityContext, final String uuid)
      throws FrameworkException {

    if (!uuid.isEmpty()) {

      logger.log(Level.FINE, "Requested id: {0}", uuid);

      return (AbstractNode) StructrApp.getInstance(securityContext).get(uuid);
    }

    return null;
  }
Example #24
0
  /**
   * Creates a new Page entity with the given name in the database.
   *
   * @param securityContext the security context to use
   * @param name the name of the new ownerDocument, defaults to "ownerDocument" if not set
   * @return the new ownerDocument
   * @throws FrameworkException
   */
  public static Page createNewPage(SecurityContext securityContext, String name)
      throws FrameworkException {

    final App app = StructrApp.getInstance(securityContext);
    final PropertyMap properties = new PropertyMap();

    properties.put(AbstractNode.name, name != null ? name : "page");
    properties.put(AbstractNode.type, Page.class.getSimpleName());
    properties.put(Page.contentType, "text/html");

    return app.create(Page.class, properties);
  }
  @Override
  public void indexPassiveProperties() {

    for (PropertyKey key :
        StructrApp.getConfiguration().getPropertySet(entityType, PropertyView.All)) {

      if (key.isPassivelyIndexed()) {

        key.index(this, this.getPropertyForIndexing(key));
      }
    }
  }
Example #26
0
  @Override
  public boolean setLastModified(long time) {

    try (Tx tx = StructrApp.getInstance().tx()) {
      setProperty(lastModifiedDate, new Date(time));
      tx.success();
    } catch (FrameworkException ex) {
      logger.log(Level.SEVERE, null, ex);
    }

    return true;
  }
Example #27
0
  @Override
  public void set(
      final SecurityContext securityContext,
      final NodeInterface targetNode,
      final Iterable<S> collection)
      throws FrameworkException {

    final App app = StructrApp.getInstance(securityContext);
    final Set<S> toBeDeleted =
        new LinkedHashSet<>(Iterables.toList(get(securityContext, targetNode, null)));
    final Set<S> toBeCreated = new LinkedHashSet<>();

    if (collection != null) {
      Iterables.addAll(toBeCreated, collection);
    }

    // create intersection of both sets
    final Set<S> intersection = new LinkedHashSet<>(toBeCreated);
    intersection.retainAll(toBeDeleted);

    // intersection needs no change
    toBeCreated.removeAll(intersection);
    toBeDeleted.removeAll(intersection);

    // remove existing relationships
    for (S sourceNode : toBeDeleted) {

      for (AbstractRelationship rel : targetNode.getIncomingRelationships()) {

        final String relTypeName = rel.getRelType().name();
        final String desiredRelType = relation.name();

        if (relTypeName.equals(desiredRelType) && rel.getSourceNode().equals(sourceNode)) {

          app.delete(rel);
        }
      }
    }

    // create new relationships
    for (S sourceNode : toBeCreated) {

      relation.ensureCardinality(securityContext, sourceNode, targetNode);

      app.create(
          sourceNode,
          targetNode,
          relation.getClass(),
          getNotionProperties(securityContext, relation.getClass(), sourceNode.getUuid()));
    }
  }
Example #28
0
  public String getJavascriptLibraryCode(String fileName) {

    final StringBuilder buf = new StringBuilder();
    final App app = StructrApp.getInstance();

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

      final List<JavaScriptSource> jsFiles =
          app.nodeQuery(JavaScriptSource.class)
              .and(JavaScriptSource.name, fileName)
              .and(JavaScriptSource.useAsJavascriptLibrary, true)
              .getAsList();

      if (jsFiles.isEmpty()) {
        logger.warn("No JavaScript library found with fileName: {}", fileName);
      }

      for (final JavaScriptSource jsLibraryFile : jsFiles) {

        final String contentType = jsLibraryFile.getContentType();
        if (contentType != null) {

          final String lowerCaseContentType = contentType.toLowerCase();
          if ("text/javascript".equals(lowerCaseContentType)
              || "application/javascript".equals(lowerCaseContentType)) {

            buf.append(jsLibraryFile.getJavascriptLibraryCode());

          } else {

            logger.info(
                "Ignoring file {} for use as a Javascript library, content type {} not allowed. Use text/javascript or application/javascript.",
                new Object[] {jsLibraryFile.getName(), contentType});
          }

        } else {

          logger.info(
              "Ignoring file {} for use as a Javascript library, content type not set. Use text/javascript or application/javascript.",
              new Object[] {jsLibraryFile.getName(), contentType});
        }
      }

      tx.success();

    } catch (FrameworkException fex) {
      logger.warn("", fex);
    }

    return buf.toString();
  }
  @Override
  public void processMessage(WebSocketMessage webSocketData) {

    final App app = StructrApp.getInstance(getWebSocket().getSecurityContext());
    final String id = webSocketData.getId();
    final Map<String, Object> nodeData = webSocketData.getNodeData();
    final String source = (String) nodeData.get("source");
    final String name = (String) nodeData.get("name");

    // check for ID
    if (id == null) {

      getWebSocket()
          .send(
              MessageBuilder.status().code(422).message("Cannot create widget without id").build(),
              true);

      return;
    }

    // check if parent node with given ID exists
    DOMNode node = getDOMNode(id);

    if (node == null) {

      getWebSocket()
          .send(MessageBuilder.status().code(404).message("Node not found").build(), true);

      return;
    }

    try {

      // convertFromInput
      PropertyMap properties = new PropertyMap();

      properties.put(AbstractNode.type, Widget.class.getSimpleName());
      properties.put(AbstractNode.name, name);
      properties.put(Widget.source, source);

      app.create(Widget.class, properties);

    } catch (Throwable t) {

      logger.log(Level.WARNING, t.toString());

      // send exception
      getWebSocket().send(MessageBuilder.status().code(422).message(t.toString()).build(), true);
    }
  }
Example #30
0
  @Override
  public InputStream createInputStream(long offset) throws IOException {

    ByteArrayInputStream bis = null;
    try (Tx tx = StructrApp.getInstance().tx()) {

      bis = new ByteArrayInputStream(getContent(RenderContext.EditMode.RAW).getBytes("UTF-8"));
      tx.success();

    } catch (FrameworkException fex) {
      logger.log(Level.WARNING, "", fex);
    }

    return bis;
  }