@Override
  protected void onAfterDatabaseCreation(final OrientBaseGraph graph) {
    System.out.println("Creating graph schema...");

    // CREATE BASIC SCHEMA
    OrientVertexType personClass = graph.createVertexType("Person");
    personClass.createProperty("id", OType.STRING);
    personClass.createProperty("name", OType.STRING);
    personClass.createProperty("birthday", OType.DATE);
    personClass.createProperty("children", OType.STRING);

    OrientVertexType person = graph.getVertexType("Person");
    person.createIndex("Person.name", OClass.INDEX_TYPE.UNIQUE, "name");

    OrientVertexType customer = graph.createVertexType("Customer", person);
    customer.createProperty("totalSold", OType.DECIMAL);

    OrientVertexType provider = graph.createVertexType("Provider", person);
    provider.createProperty("totalPurchased", OType.DECIMAL);

    factory = new OrientGraphFactory(graph.getRawGraph().getURL(), "admin", "admin", false);
    factory.setStandardElementConstraints(false);

    v = createVertex(graph, 0, 0, 0).getIdentity();
  }
Exemplo n.º 2
0
  /**
   * (Blueprints Extension) Saves current element to a particular cluster. You don't need to call
   * save() unless you're working against Temporary Vertices.
   *
   * @param iClusterName Cluster name or null to use the default "E"
   */
  public void save(final String iClusterName) {
    checkIfAttached();

    final OrientBaseGraph graph = getGraph();
    graph.setCurrentGraphInThreadLocal();

    if (rawElement instanceof ODocument)
      if (iClusterName != null) rawElement = ((ODocument) rawElement).save(iClusterName);
      else rawElement = ((ODocument) rawElement).save();
  }
Exemplo n.º 3
0
  /**
   * Sets a Property value specifying a type. This is useful when you don't have a schema on this
   * property but you want to force the type.
   *
   * @param key Property name
   * @param value Property value
   * @param iType Type to set
   */
  public void setProperty(final String key, final Object value, final OType iType) {
    if (checkDeletedInTx())
      throw new IllegalStateException("The vertex " + getIdentity() + " has been deleted");

    validateProperty(this, key, value);

    final OrientBaseGraph graph = getGraph();
    if (graph != null) graph.autoStartTransaction();
    getRecord().field(key, value, iType);
    if (graph != null) save();
  }
Exemplo n.º 4
0
  protected boolean checkDeletedInTx() {
    OrientBaseGraph curGraph = getGraph();
    if (curGraph == null) return false;

    ORID id;
    if (getRecord() != null) id = getRecord().getIdentity();
    else return false;

    final ORecordOperation oper = curGraph.getRawGraph().getTransaction().getRecordEntry(id);
    if (oper == null) return id.isTemporary();
    else return oper.type == ORecordOperation.DELETED;
  }
Exemplo n.º 5
0
  /**
   * Removes a Property.
   *
   * @param key Property name
   * @return Old value if any
   */
  @Override
  public <T> T removeProperty(final String key) {
    if (checkDeletedInTx())
      throw new IllegalStateException("The vertex " + getIdentity() + " has been deleted");

    final OrientBaseGraph graph = getGraph();

    if (graph != null) graph.autoStartTransaction();

    final Object oldValue = getRecord().removeField(key);
    if (graph != null) save();
    return (T) oldValue;
  }
Exemplo n.º 6
0
  @Override
  public ORID getIdentity() {
    if (rawElement == null) return ORecordId.EMPTY_RECORD_ID;

    final ORID rid = rawElement.getIdentity();
    if (!rid.isValid() && !isDetached()) {
      // SAVE THE RECORD TO OBTAIN A VALID RID
      graph.setCurrentGraphInThreadLocal();
      graph.autoStartTransaction();
      save();
    }
    return rid;
  }
Exemplo n.º 7
0
  /**
   * (Blueprints Extension) Sets multiple properties in one shot against Vertices and Edges without
   * saving the element. This improves performance avoiding to save the graph element at every
   * property set. Example: <code>
   * vertex.setProperties( "name", "Jill", "age", 33, "city", "Rome", "born", "Victoria, TX" );
   * </code> You can also pass a Map of values as first argument. In this case all the map entries
   * will be set as element properties: <code>
   * Map<String,Object> props = new HashMap<String,Object>();
   * props.put("name", "Jill");
   * props.put("age", 33);
   * props.put("city", "Rome");
   * props.put("born", "Victoria, TX");
   * vertex.setProperties(props);
   * </code>
   *
   * @param fields Odd number of fields to set as repeating pairs of key, value, or if one parameter
   *     is received and it's a Map, the Map entries are used as field key/value pairs.
   * @param <T>
   * @return
   */
  protected <T extends OrientElement> T setPropertiesInternal(final Object... fields) {
    OrientBaseGraph graph = getGraph();
    if (fields != null && fields.length > 0 && fields[0] != null) {
      if (graph != null) graph.autoStartTransaction();

      if (fields.length == 1) {
        Object f = fields[0];
        if (f instanceof Map<?, ?>) {
          for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) f).entrySet())
            setPropertyInternal(
                this,
                (ODocument) rawElement.getRecord(),
                entry.getKey().toString(),
                entry.getValue());

        } else if (f instanceof Collection) {
          for (Object o : (Collection) f) {
            if (!(o instanceof OPair))
              throw new IllegalArgumentException(
                  "Invalid fields: expecting a pairs of fields as String,Object, but found the item: "
                      + o);

            final OPair entry = (OPair) o;
            setPropertyInternal(
                this,
                (ODocument) rawElement.getRecord(),
                entry.getKey().toString(),
                entry.getValue());
          }

        } else
          throw new IllegalArgumentException(
              "Invalid fields: expecting a pairs of fields as String,Object or a single Map<String,Object>, but found: "
                  + f);
      } else {
        if (fields.length % 2 != 0)
          throw new IllegalArgumentException(
              "Invalid fields: expecting a pairs of fields as String,Object or a single Map<String,Object>, but found: "
                  + Arrays.toString(fields));

        // SET THE FIELDS
        for (int i = 0; i < fields.length; i += 2)
          setPropertyInternal(
              this, (ODocument) rawElement.getRecord(), fields[i].toString(), fields[i + 1]);
      }
    }
    return (T) this;
  }
  protected OrientVertex createVertex(OrientBaseGraph graph, int serverId, int threadId, int i) {
    final String uniqueId = serverId + "-" + threadId + "-" + i;

    final Object result =
        graph
            .command(
                new OCommandSQL(
                    "create vertex Provider content {'id': '"
                        + UUID.randomUUID().toString()
                        + "', 'name': 'Billy"
                        + uniqueId
                        + "', 'surname': 'Mayes"
                        + uniqueId
                        + "', 'birthday': '"
                        + ODatabaseRecordThreadLocal.INSTANCE
                            .get()
                            .getStorage()
                            .getConfiguration()
                            .getDateFormatInstance()
                            .format(new Date())
                        + "', 'children': '"
                        + uniqueId
                        + "', 'saved': 0}"))
            .execute();
    return (OrientVertex) result;
  }
Exemplo n.º 9
0
  public <T extends OrientElement> T setProperties(final Object... fields) {
    if (fields != null && fields.length > 0 && fields[0] != null) {
      if (!isDetached()) graph.autoStartTransaction();

      if (fields.length == 1) {
        Object f = fields[0];
        if (f instanceof Map<?, ?>) {
          for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) f).entrySet())
            setPropertyInternal(
                this,
                (ODocument) rawElement.getRecord(),
                entry.getKey().toString(),
                entry.getValue());

        } else
          throw new IllegalArgumentException(
              "Invalid fields: expecting a pairs of fields as String,Object or a single Map<String,Object>, but found: "
                  + f);
      } else
        // SET THE FIELDS
        for (int i = 0; i < fields.length; i += 2)
          setPropertyInternal(
              this, (ODocument) rawElement.getRecord(), fields[i].toString(), fields[i + 1]);
    }
    return (T) this;
  }
Exemplo n.º 10
0
  /**
   * Removes the Element from the Graph. In case the element is a Vertex, all the incoming and
   * outgoing edges are automatically removed too.
   */
  @Override
  public void remove() {
    checkIfAttached();

    final OrientBaseGraph graph = getGraph();
    graph.setCurrentGraphInThreadLocal();
    graph.autoStartTransaction();

    if (checkDeletedInTx())
      throw new IllegalStateException(
          "The elements " + getIdentity() + " has already been deleted");

    try {
      getRecord().load();
    } catch (ORecordNotFoundException e) {
      throw new IllegalStateException(
          "The elements " + getIdentity() + " has already been deleted", e);
    }

    getRecord().delete();
  }
Exemplo n.º 11
0
  @Override
  public void remove() {
    checkIfAttached();
    graph.setCurrentGraphInThreadLocal();
    graph.autoStartTransaction();

    final ORecordOperation oper =
        graph.getRawGraph().getTransaction().getRecordEntry(getIdentity());
    if (oper != null && oper.type == ORecordOperation.DELETED)
      throw new IllegalStateException(
          "The elements " + getIdentity() + " has already been deleted");

    try {
      getRecord().load();
    } catch (ORecordNotFoundException e) {
      throw new IllegalStateException(
          "The elements " + getIdentity() + " has already been deleted");
    }

    getRecord().delete();
  }
Exemplo n.º 12
0
  /**
   * Check if a class already exists, otherwise create it at the fly. If a transaction is running
   * commit changes, create the class and begin a new transaction.
   *
   * @param className Class's name
   */
  protected String checkForClassInSchema(final String className) {
    if (className == null) return null;

    OrientBaseGraph graph = getGraph();
    if (graph == null) return className;

    final OSchema schema = graph.getRawGraph().getMetadata().getSchema();

    if (!schema.existsClass(className)) {
      // CREATE A NEW CLASS AT THE FLY
      try {
        graph.executeOutsideTx(
            new OCallable<OClass, OrientBaseGraph>() {

              @Override
              public OClass call(final OrientBaseGraph g) {
                return schema.createClass(className, schema.getClass(getBaseClassName()));
              }
            },
            "Committing the active transaction to create the new type '",
            className,
            "' as subclass of '",
            getBaseClassName(),
            "'. The transaction will be reopen right after that. To avoid this behavior create the classes outside the transaction");

      } catch (OSchemaException e) {
        if (!schema.existsClass(className)) throw e;
      }
    } else {
      // CHECK THE CLASS INHERITANCE
      final OClass cls = schema.getClass(className);
      if (!cls.isSubClassOf(getBaseClassName()))
        throw new IllegalArgumentException(
            "Class '" + className + "' is not an instance of " + getBaseClassName());
    }

    return className;
  }
Exemplo n.º 13
0
  /**
   * Returns a Property value.
   *
   * @param key Property name
   * @return Property value if any, otherwise NULL.
   */
  @Override
  public <T> T getProperty(final String key) {
    if (key == null) return null;

    final OrientBaseGraph graph = getGraph();
    if (key.equals("_class"))
      return (T) ODocumentInternal.getImmutableSchemaClass(getRecord()).getName();
    else if (key.equals("_version")) return (T) new Integer(getRecord().getVersion());
    else if (key.equals("_rid")) return (T) rawElement.getIdentity().toString();

    final Object fieldValue = getRecord().field(key);
    if (graph != null
        && fieldValue instanceof OIdentifiable
        && !(((OIdentifiable) fieldValue).getRecord() instanceof ORecordBytes))
      // CONVERT IT TO VERTEX/EDGE
      return (T) graph.getElement(fieldValue);
    else if (OMultiValue.isMultiValue(fieldValue)
        && OMultiValue.getFirstValue(fieldValue) instanceof OIdentifiable) {
      final OIdentifiable firstValue = (OIdentifiable) OMultiValue.getFirstValue(fieldValue);

      if (firstValue instanceof ODocument) {
        final ODocument document = (ODocument) firstValue;

        if (document.isEmbedded() || ODocumentInternal.getImmutableSchemaClass(document) == null)
          return (T) fieldValue;
      }

      if (graph != null)
        // CONVERT IT TO ITERABLE<VERTEX/EDGE>
        return (T)
            new OrientElementIterable<OrientElement>(
                graph, OMultiValue.getMultiValueIterable(fieldValue));
    }

    return (T) fieldValue;
  }
Exemplo n.º 14
0
 protected OrientBaseGraph setCurrentGraphInThreadLocal() {
   final OrientBaseGraph graph = getGraph();
   if (graph != null) graph.setCurrentGraphInThreadLocal();
   return graph;
 }
Exemplo n.º 15
0
  /**
   * (Blueprints Extension) Returns the Graph instance associated to the current element. On @detach
   * ed elements returns NULL.
   */
  public OrientBaseGraph getGraph() {
    if (classicDetachMode) return graph;

    return OrientBaseGraph.getActiveGraph();
  }
Exemplo n.º 16
0
 public OrientEdgeType(final OrientBaseGraph graph) {
   super(graph.getRawGraph().getMetadata().getSchema().getClass(CLASS_NAME));
   this.graph = graph;
 }
Exemplo n.º 17
0
 public void setProperty(final String key, final Object value) {
   validateProperty(this, key, value);
   if (!isDetached()) graph.autoStartTransaction();
   getRecord().field(key, value);
   if (!isDetached()) save();
 }
Exemplo n.º 18
0
 protected void setCurrentGraphInThreadLocal() {
   if (!isDetached()) graph.setCurrentGraphInThreadLocal();
 }
Exemplo n.º 19
0
 public <T> T removeProperty(final String key) {
   if (!isDetached()) graph.autoStartTransaction();
   final Object oldValue = getRecord().removeField(key);
   if (!isDetached()) save();
   return (T) oldValue;
 }