Exemple #1
0
  @Override
  public void deleteData(final int offset, final int count) throws DOMException {

    checkWriteAccess();

    // finally, set content to concatenated left and right parts
    try {

      Services.command(securityContext, TransactionCommand.class)
          .execute(
              new StructrTransaction() {

                @Override
                public Object execute() throws FrameworkException {

                  String text = getProperty(content);

                  String leftPart = text.substring(0, offset);
                  String rightPart = text.substring(offset + count);

                  setProperty(content, leftPart.concat(rightPart));

                  return null;
                }
              });

    } catch (FrameworkException fex) {

      throw new DOMException(DOMException.INVALID_STATE_ERR, fex.toString());
    }
  }
  private void setPermission(
      final AbstractNode obj,
      final Principal principal,
      final String action,
      final String permission,
      final boolean rec)
      throws FrameworkException {

    Services.command(getWebSocket().getSecurityContext(), TransactionCommand.class)
        .execute(
            new StructrTransaction() {

              @Override
              public Object execute() throws FrameworkException {

                switch (action) {
                  case "grant":
                    principal.grant(Permission.valueOf(permission), obj);
                    break;
                  case "revoke":
                    principal.revoke(Permission.valueOf(permission), obj);
                    break;
                }

                return null;
              };
            });
  }
Exemple #3
0
  @Override
  public void appendData(final String data) throws DOMException {

    checkWriteAccess();

    // set content to concatenated text and data
    try {

      Services.command(securityContext, TransactionCommand.class)
          .execute(
              new StructrTransaction() {

                @Override
                public Object execute() throws FrameworkException {

                  String text = getProperty(content);
                  setProperty(content, text.concat(data));

                  return null;
                }
              });

    } catch (FrameworkException fex) {

      throw new DOMException(DOMException.INVALID_STATE_ERR, fex.toString());
    }
  }
Exemple #4
0
  private void setOwner(final AbstractNode node, final AbstractNode user)
      throws FrameworkException {

    // Create outer transaction to bundle inner transactions
    Services.command(securityContext, TransactionCommand.class)
        .execute(
            new StructrTransaction() {

              @Override
              public Object execute() throws FrameworkException {

                DeleteRelationshipCommand delRel =
                    Services.command(securityContext, DeleteRelationshipCommand.class);

                // Remove any existing OWNS relationships
                for (AbstractRelationship s :
                    node.getRelationships(RelType.OWNS, Direction.INCOMING)) {

                  delRel.execute(s);
                }

                // Create new relationship to user and grant permissions to user or group
                Services.command(securityContext, CreateRelationshipCommand.class)
                    .execute(user, node, RelType.OWNS);

                return null;
              }
            });
  }
Exemple #5
0
  @Override
  protected void setUp() throws Exception {

    init();

    securityContext = SecurityContext.getSuperUserInstance();
    createNodeCommand = Services.command(securityContext, CreateNodeCommand.class);
    createRelationshipCommand = Services.command(securityContext, CreateRelationshipCommand.class);
    deleteNodeCommand = Services.command(securityContext, DeleteNodeCommand.class);
    transactionCommand = Services.command(securityContext, TransactionCommand.class);
    graphDbCommand = Services.command(securityContext, GraphDatabaseCommand.class);
    findNodeCommand = Services.command(securityContext, FindNodeCommand.class);
  }
Exemple #6
0
  private void setOwner(final List<AbstractNode> nodeList, final AbstractNode user)
      throws FrameworkException {

    // Create outer transaction to bundle inner transactions
    Services.command(securityContext, TransactionCommand.class)
        .execute(
            new StructrTransaction() {

              @Override
              public Object execute() throws FrameworkException {

                for (AbstractNode node : nodeList) {
                  setOwner(node, user);
                }

                return null;
              }
            });
  }
  @Override
  public boolean isValid(
      GraphObject object, PropertyKey<String> key, String value, ErrorBuffer errorBuffer) {

    if (key == null) {
      return false;
    }

    if (StringUtils.isBlank(value)) {
      errorBuffer.add(object.getType(), new EmptyPropertyToken(key));
      return false;
    }

    // FIXME: search should be case-sensitive!

    List<SearchAttribute> attrs = new LinkedList<SearchAttribute>();
    attrs.add(Search.andExactName(value));
    attrs.add(Search.andType(type));

    // just check for existance
    try {
      Result nodes = Services.command(securityContext, SearchNodeCommand.class).execute(attrs);
      if (nodes != null && !nodes.isEmpty()) {

        return true;

      } else {

        errorBuffer.add(object.getType(), new PropertyNotFoundToken(key, value));
        return false;
      }

    } catch (FrameworkException fex) {
      // handle error
    }

    return false;
  }
Exemple #8
0
  @Override
  public void insertData(final int offset, final String data) throws DOMException {

    checkWriteAccess();

    try {

      Services.command(securityContext, TransactionCommand.class)
          .execute(
              new StructrTransaction() {

                @Override
                public Object execute() throws FrameworkException {

                  String text = getProperty(content);

                  String leftPart = text.substring(0, offset);
                  String rightPart = text.substring(offset);

                  StringBuilder buf = new StringBuilder(text.length() + data.length() + 1);
                  buf.append(leftPart);
                  buf.append(data);
                  buf.append(rightPart);

                  // finally, set content to concatenated left, data and right parts
                  setProperty(content, buf.toString());

                  return null;
                }
              });

    } catch (FrameworkException fex) {

      throw new DOMException(DOMException.INVALID_STATE_ERR, fex.toString());
    }
  }
Exemple #9
0
  @Override
  public Text splitText(int offset) throws DOMException {

    checkWriteAccess();

    String text = getProperty(content);

    if (text != null) {

      int len = text.length();

      if (offset < 0 || offset > len) {

        throw new DOMException(DOMException.INDEX_SIZE_ERR, INDEX_SIZE_ERR_MESSAGE);

      } else {

        final String firstPart = text.substring(0, offset);
        final String secondPart = text.substring(offset);

        final Document document = getOwnerDocument();
        final Node parent = getParentNode();

        if (document != null && parent != null) {

          try {

            return Services.command(securityContext, TransactionCommand.class)
                .execute(
                    new StructrTransaction<Text>() {

                      @Override
                      public Text execute() throws FrameworkException {

                        // first part goes into existing text element
                        setProperty(content, firstPart);

                        // second part goes into new text element
                        Text newNode = document.createTextNode(secondPart);

                        // make new node a child of old parent
                        parent.appendChild(newNode);

                        return newNode;
                      }
                    });

          } catch (FrameworkException fex) {

            throw new DOMException(DOMException.INVALID_STATE_ERR, fex.toString());
          }

        } else {

          throw new DOMException(DOMException.INVALID_STATE_ERR, CANNOT_SPLIT_TEXT_WITHOUT_PARENT);
        }
      }
    }

    throw new DOMException(DOMException.INDEX_SIZE_ERR, INDEX_SIZE_ERR_MESSAGE);
  }
  @Override
  public Object execute(Object... parameters) throws FrameworkException {

    if (parameters == null || parameters.length < 2) {

      throw new UnsupportedArgumentError("Wrong number of arguments");
    }

    Long csvNodeId = null;
    AbstractNode sourceNode = null;
    Class targetClass = null;
    CsvFile csvFileNode = null;
    String filePath = null;
    Principal user = null;

    for (Object o : parameters) {

      if (o instanceof CsvFile) {

        csvFileNode = (CsvFile) o;
        filePath = Services.getFilesPath() + "/" + csvFileNode.getRelativeFilePath();
      }

      if (o instanceof Long) {

        csvNodeId = (Long) o;
        sourceNode =
            (AbstractNode)
                Services.command(securityContext, FindNodeCommand.class).execute(csvNodeId);

        if (sourceNode instanceof CsvFile) {

          csvFileNode = (CsvFile) sourceNode;
          filePath = Services.getFilesPath() + "/" + csvFileNode.getRelativeFilePath();
        }
      }

      if (o instanceof Class) {

        targetClass = (Class) o;
      }

      if (o instanceof Principal) {

        user = (Principal) o;
      }
    }

    try {

      // TODO: Implement auto-detection for field separator and quote characters
      CSVReader reader = new CSVReader(new FileReader(filePath), '|', '\"');

      // Read first line, these should be the column keys
      String[] keys = reader.readNext();

      // Get the fields of the target node
      Field[] fields = targetClass.getFields();

      // The field index stores the field name of a column
      Map<Integer, String> fieldIndex = new HashMap<Integer, String>();

      // Instantiate object
      AbstractNode o = (AbstractNode) targetClass.newInstance();
      int col = 0;

      // Match with fields
      for (String key : keys) {

        for (Field f : fields) {

          String fieldName = (String) f.get(o);

          if (fieldName.toUpperCase().equals(key.toUpperCase())) {

            fieldIndex.put(col, fieldName);
          }
        }

        col++;
      }

      for (Entry<Integer, String> entry : fieldIndex.entrySet()) {

        Integer i = entry.getKey();
        String v = entry.getValue();

        System.out.println("v: " + v + ", i: " + i);
      }

      //                      List<String[]> lines = reader.readAll();
      final Principal userCopy = user;
      final AbstractNode sourceNodeCopy = csvFileNode;
      final Command transactionCommand =
          Services.command(securityContext, TransactionCommand.class);
      final Command createNode = Services.command(securityContext, CreateNodeCommand.class);
      final Command createRel = Services.command(securityContext, CreateRelationshipCommand.class);
      final NodeList<AbstractNode> nodeListNode =
          (NodeList<AbstractNode>)
              transactionCommand.execute(
                  new StructrTransaction() {

                    @Override
                    public Object execute() throws FrameworkException {

                      // If the node list node doesn't exist, create one
                      NodeList<AbstractNode> result =
                          (NodeList)
                              createNode.execute(
                                  userCopy,
                                  new NodeAttribute(
                                      AbstractNode.Key.type.name(), NodeList.class.getSimpleName()),
                                  new NodeAttribute(
                                      AbstractNode.Key.name.name(),
                                      sourceNodeCopy.getName() + " List"));

                      createRel.execute(sourceNodeCopy, result, RelType.CONTAINS);

                      return result;
                    }
                  });
      final List<List<NodeAttribute>> creationList = new LinkedList<List<NodeAttribute>>();
      String targetClassName = targetClass.getSimpleName();
      String[] line = null;

      do {

        // read line, one at a time
        try {

          line = reader.readNext();

        } catch (Throwable t) {
        }

        if (line != null) {

          // create a new list for each item
          List<NodeAttribute> nodeAttributes = new LinkedList<NodeAttribute>();

          nodeAttributes.add(new NodeAttribute(AbstractNode.Key.type.name(), targetClassName));

          for (int i = 0; i < col; i++) {

            String csvValue = line[i];
            String key = fieldIndex.get(i);

            nodeAttributes.add(new NodeAttribute(key, csvValue));
          }

          // add node attributes to creation list
          creationList.add(nodeAttributes);
        }
      } while (line != null);

      reader.close();

      // everything in one transaction
      transactionCommand.execute(
          new StructrTransaction() {

            @Override
            public Object execute() throws FrameworkException {

              List<AbstractNode> nodesToAdd = new LinkedList<AbstractNode>();

              for (List<NodeAttribute> attrList : creationList) {

                nodesToAdd.add((AbstractNode) createNode.execute(attrList, false)); // don't index
              }

              // use bulk add
              nodeListNode.addAll(nodesToAdd);

              return (null);
            }
          });

      /*
       * final List<NodeAttribute> attrList = new LinkedList<NodeAttribute>();
       *
       * NodeAttribute typeAttr = new NodeAttribute(AbstractNode.Key.type.name(), targetClass.getSimpleName());
       * attrList.add(typeAttr);
       *
       * String[] line = null;
       *
       * do
       * {
       * try
       * {
       * line = reader.readNext();
       *
       * } catch(Throwable t)
       * {
       * line = null;
       * }
       *
       * if(line != null)
       * {
       * for(int i = 0; i < col; i++)
       * {
       *
       * String csvValue = line[i];
       * String key = fieldIndex.get(i);
       *
       * System.out.println("Creating attribute " + key + " = '" + csvValue + "'..");
       *
       * NodeAttribute attr = new NodeAttribute(key, csvValue);
       * attrList.add(attr);
       *
       * logger.log(Level.FINEST, "Created node attribute {0}={1}", new Object[]
       * {
       * attr.getKey(), attr.getValue()
       * });
       * }
       *
       * AbstractNode newNode = (AbstractNode)transactionCommand.execute(new StructrTransaction()
       * {
       * @Override
       * public Object execute() throws Throwable
       * {
       * Command createNode = Services.command(securityContext, CreateNodeCommand.class);
       *
       * // Create new node
       * AbstractNode newNode = (AbstractNode)createNode.execute(userCopy, attrList);
       * transactionCommand.setExitCode(createNode.getExitCode());
       * transactionCommand.setErrorMessage(createNode.getErrorMessage());
       * return newNode;
       * }
       * });
       *
       * nodeListNode.add(newNode);
       * logger.log(Level.INFO, "Node {0} added to node list", newNode.getId());
       * }
       *
       * } while(line != null);
       */
      return nodeListNode;
    } catch (Throwable t) {

      // TODO: use logger
      t.printStackTrace(System.out);
    }

    return null;
  }
  @Override
  public Object execute(Object... parameters) throws FrameworkException {

    Command findRel = Services.command(securityContext, FindRelationshipCommand.class);

    for (Enum indexName : (RelationshipIndex[]) arguments.get("relationshipIndices")) {

      indices.put(indexName.name(), (Index<Relationship>) arguments.get(indexName.name()));
    }

    long id = 0;
    AbstractRelationship rel = null;
    String key = null;

    switch (parameters.length) {
      case 1:

        // index all properties of this relationship
        if (parameters[0] instanceof Long) {

          id = ((Long) parameters[0]).longValue();
          rel = (AbstractRelationship) findRel.execute(id);

          indexRelationship(rel);

        } else if (parameters[0] instanceof String) {

          id = Long.parseLong((String) parameters[0]);
          rel = (AbstractRelationship) findRel.execute(id);

          indexRelationship(rel);

        } else if (parameters[0] instanceof AbstractRelationship) {

          rel = (AbstractRelationship) parameters[0];

          indexRelationship(rel);

        } else if (parameters[0] instanceof List) {

          indexRelationships((List<AbstractRelationship>) parameters[0]);
        }

        break;

      case 2:

        // index a certain property
        if (parameters[0] instanceof Long) {

          id = ((Long) parameters[0]).longValue();
          rel = (AbstractRelationship) findRel.execute(id);

        } else if (parameters[0] instanceof String) {

          id = Long.parseLong((String) parameters[0]);
          rel = (AbstractRelationship) findRel.execute(id);

        } else if (parameters[0] instanceof AbstractRelationship) {

          rel = (AbstractRelationship) parameters[0];

          // id   = node.getId();

        }

        if (parameters[1] instanceof String) {

          key = (String) parameters[1];
        }

        if (rel == null) {

          logger.log(
              Level.SEVERE,
              "Wrong type of parameters for the index relationship command: {0}",
              parameters);
        }

        indexProperty(rel, key);

        break;

      default:
        logger.log(
            Level.SEVERE,
            "Wrong number of parameters for the index relationship command: {0}",
            parameters);

        return null;
    }

    return null;
  }